# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

#' @title Conditional Power for Generic Group Sequential Design
#' @description Obtains the conditional power for specified incremental
#' information given the interim results, parameter values, and
#' data-dependent changes in the error spending function, as well as the
#' number and spacing of interim looks.
#'
#' @param INew The maximum information of the secondary trial.
#' @param L The interim adaptation look of the primary trial.
#' @param zL The z-test statistic at the interim adaptation look of
#'   the primary trial.
#' @param theta A scalar or a vector of parameter values of
#'   length \code{kMax + kMax - L} if \code{MullerSchafer = FALSE} or
#'   length \code{kMax + kNew} if \code{MullerSchafer = TRUE}.
#' @param IMax The maximum information of the primary trial.
#' @param kMax The maximum number of stages of the primary trial.
#' @param informationRates The information rates of the primary trial.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage of the primary trial. Defaults to true
#'   if left unspecified.
#' @param futilityStopping Indicators of whether futility stopping is
#'   allowed at each stage of the primary trial. Defaults to true
#'   if left unspecified.
#' @param criticalValues The upper boundaries on the z-test statistic scale
#'   for efficacy stopping for the primary trial.
#' @param alpha The significance level of the primary trial.
#'   Defaults to 0.025.
#' @param typeAlphaSpending The type of alpha spending for the primary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function,
#'   \code{"user"} for user defined spending, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param userAlphaSpending The user defined alpha spending for the primary
#'   trial. Cumulative alpha spent up to each stage.
#' @param futilityBounds	The lower boundaries on the z-test statistic scale
#'   for futility stopping for the primary trial. Defaults to
#'   \code{rep(-8, kMax-1)} if left unspecified.
#' @param futilityCP The conditional power-based futility bounds for the
#'   primary trial.
#' @param futilityTheta The parameter value-based futility bounds for the
#'   primary trial.
#' @param spendingTime The error spending time of the primary trial.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRates}.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @param kNew The number of looks of the secondary trial.
#' @param informationRatesNew The spacing of looks of the secondary trial.
#' @param efficacyStoppingNew The indicators of whether efficacy stopping is
#'   allowed at each look of the secondary trial. Defaults to true
#'   if left unspecified.
#' @param futilityStoppingNew The indicators of whether futility stopping is
#'   allowed at each look of the secondary trial. Defaults to true
#'   if left unspecified.
#' @param typeAlphaSpendingNew The type of alpha spending for the secondary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param futilityBoundsInt The futility boundaries on the z statistic
#'   scale for new stages of the integrated trial.
#' @param futilityCPInt The conditional power-based futility bounds for
#'   new stages of the integrated trial.
#' @param futilityThetaInt The parameter value-based futility bounds for the
#'   new stages of the integrated trial.
#' @param typeBetaSpendingNew The type of beta spending for the secondary
#'   trial. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @param parameterBetaSpendingNew The parameter value of beta spending
#'   for the secondary trial. Corresponds to \eqn{\rho} for \code{"sfKD"},
#'   and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTimeNew The error spending time of the secondary trial.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRatesNew}.
#' @param varianceRatio The ratio of the variance under H0 to the variance
#'   under H1.
#'
#' @return A vector of two conditional powers given the interim results and
#' parameter values, one without design change and the other with
#' data-dependent design changes.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Cyrus R. Mehta and Stuart J. Pocock.
#' Adaptive increase in sample size when interim results are promising:
#' A practical guide with examples.
#' Stat Med. 2011;30:3267–3284.
#'
#' @seealso \code{\link{adaptDesign}}
#'
#' @examples
#'
#' # Conditional power calculation with delayed treatment effect
#'
#' # Two interim analyses have occurred with 179 and 266 events,
#' # respectively. The observed hazard ratio at the second interim
#' # look is 0.81.
#'
#' trialsdt <- as.Date("2020-03-04")                       # trial start date
#' iadt <- c(as.Date("2022-02-01"), as.Date("2022-11-01")) # interim dates
#' mo1 <- as.numeric(iadt - trialsdt + 1)/30.4375          # interim months
#'
#' # Assume a piecewise Poisson enrollment process with a 8-month ramp-up
#' # and 521 patients were enrolled after 17.94 months
#' N <- 521                   # total number of patients
#' Ta <- 17.94                # enrollment duration
#' Ta1 <- 8                   # assumed end of enrollment ramp-up
#' enrate <- N / (Ta - Ta1/2) # enrollment rate after ramp-up
#'
#' # Assume a median survival of 16.7 months for the control group, a
#' # 5-month delay in treatment effect, and a hazard ratio of 0.7 after
#' # the delay
#' lam1 <- log(2)/16.7  # control group hazard of exponential distribution
#' t1 <- 5              # months of delay in treatment effect
#' hr <- 0.7            # hazard ratio after delay
#' lam2 <- hr*lam1      # treatment group hazard after delay
#'
#' # Assume an annual dropout rate of 5%
#' gam <- -log(1-0.05)/12  # hazard for dropout
#'
#' # The original target number of events was 298 and the new target is 335
#' mo2 <- caltime(
#'   nevents = c(298, 335),
#'   allocationRatioPlanned = 1,
#'   accrualTime = seq(0, Ta1),
#'   accrualIntensity = enrate*seq(1, Ta1+1)/(Ta1+1),
#'   piecewiseSurvivalTime = c(0, t1),
#'   lambda1 = c(lam1, lam2),
#'   lambda2 = c(lam1, lam1),
#'   gamma1 = gam,
#'   gamma2 = gam,
#'   accrualDuration = Ta,
#'   followupTime = 1000)
#'
#' # expected number of events and average hazard ratios
#' (lr1 <- lrstat(
#'   time = c(mo1, mo2),
#'   accrualTime = seq(0, Ta1),
#'   accrualIntensity = enrate*seq(1, Ta1+1)/(Ta1+1),
#'   piecewiseSurvivalTime = c(0, t1),
#'   lambda1 = c(lam1, lam2),
#'   lambda2 = c(lam1, lam1),
#'   gamma1 = gam,
#'   gamma2 = gam,
#'   accrualDuration = Ta,
#'   followupTime = 1000,
#'   predictTarget = 3))
#'
#'
#' hr2 <- 0.81                    # observed hazard ratio at interim 2
#' z2 <- (-log(hr2))*sqrt(266/4)  # corresponding z-test statistic value
#'
#' # expected mean of -log(HR) at the original looks and the new final look
#' theta <- -log(lr1$HR[c(1,2,3,4)])
#'
#' # conditional power with sample size increase
#' getCP(INew = (335 - 266)/4,
#'       L = 2, zL = z2, theta = theta,
#'       IMax = 298/4, kMax = 3,
#'       informationRates = c(179, 266, 298)/298,
#'       alpha = 0.025, typeAlphaSpending = "sfOF")
#'
#' @export
getCP <- function(INew = NA_real_, L = NA_integer_, zL = NA_real_, theta = NA_real_, IMax = NA_real_, kMax = NA_integer_, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityTheta = NULL, spendingTime = NA_real_, MullerSchafer = FALSE, kNew = NA_integer_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, futilityStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, futilityBoundsInt = NULL, futilityCPInt = NULL, futilityThetaInt = NULL, typeBetaSpendingNew = "none", parameterBetaSpendingNew = NA_real_, spendingTimeNew = NA_real_, varianceRatio = 1) {
    .Call(`_lrstat_getCP`, INew, L, zL, theta, IMax, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityTheta, spendingTime, MullerSchafer, kNew, informationRatesNew, efficacyStoppingNew, futilityStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, futilityBoundsInt, futilityCPInt, futilityThetaInt, typeBetaSpendingNew, parameterBetaSpendingNew, spendingTimeNew, varianceRatio)
}

#' @title Conditional Power for Multi-Arm Multi-Stage Design
#' @description Obtains the conditional power for specified incremental
#' information given the interim results, parameter values, and
#' data-dependent changes in the selected treatment(s),
#' the error spending function, as well as the
#' number and spacing of interim looks.
#'
#' @param INew The maximum information for any active arm versus the common
#'   control in the secondary trial.
#' @param M Number of active treatment arms in the primary trial.
#' @param r Randomization ratio of each active arm to the common control
#'   in the primary trial.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is assumed.
#' @param L The interim adaptation look of the primary trial.
#' @param zL The z-test statistics at the interim adaptation look of
#'   the primary trial.
#' @param theta A vector of length \eqn{M} representing the assumed treatment
#'   effects for each active arm versus the common control. The global null
#'   is \eqn{\theta_i = 0} for all \eqn{i}, and alternatives are one-sided:
#'   \eqn{\theta_i > 0} for at least one \eqn{i = 1, \ldots, M}.
#' @param IMax Maximum information for any active arm versus the common
#'   control for the primary trial. Must be provided.
#' @param kMax The maximum number of stages of the primary trial.
#' @param informationRates The information rates of the primary trial.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage of the primary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param futilityStopping Indicators of whether futility stopping is
#'   allowed at each stage of the primary trial.
#' @param criticalValues The upper boundaries on the max z-test statistic
#'   scale for efficacy stopping for the primary trial. If missing, boundaries
#'   will be computed based on the specified alpha spending function.
#' @param alpha The significance level of the primary trial.
#'   Defaults to 0.025.
#' @param typeAlphaSpending The type of alpha spending for the primary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function,
#'   \code{"user"} for user defined spending, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param userAlphaSpending The user-defined alpha spending for the
#'   primary trial. Represents the cumulative alpha spent up to each stage.
#' @param futilityBounds The futility boundaries on the max-z statistic
#'   scale for the primary trial. Defaults to \code{rep(-8, kMax-1)}
#'   if left unspecified.
#' @param futilityCP The conditional power-based futility bounds for the
#'   primary trial.
#' @param futilityTheta The parameter value-based futility bounds for the
#'   primary trial.
#' @param spendingTime The error spending time of the primary trial.
#'   Defaults to missing, in which case it is assumed to be the same as
#'   \code{informationRates}.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @param MNew Number of active treatment arms in the secondary trial.
#' @param selected The indices of the selected active treatment arms for
#'   the secondary trial.
#' @param rNew Randomization ratio of each active arm to the common control
#'   in the secondary trial.
#' @param kNew The number of looks of the secondary trial.
#' @param informationRatesNew The spacing of looks of the secondary trial.
#' @param efficacyStoppingNew The indicators of whether efficacy stopping is
#'   allowed at each look of the secondary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param futilityStoppingNew The indicators of whether futility stopping is
#'   allowed at each look of the secondary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param typeAlphaSpendingNew The type of alpha spending for the secondary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param futilityBoundsInt The futility boundaries on the max-z statistic
#'   scale for new stages of the integrated trial.
#' @param futilityCPInt The conditional power-based futility bounds for
#'   new stages of the integrated trial.
#' @param futilityThetaInt The parameter value-based futility bounds for the
#'   new stages of the integrated trial.
#' @param typeBetaSpendingNew The type of beta spending for the secondary
#'   trial. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function,
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @param parameterBetaSpendingNew The parameter value of beta spending
#'   for the secondary trial. Corresponds to \eqn{\rho} for \code{"sfKD"},
#'   and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTimeNew The error spending time of the secondary trial.
#'   Defaults to missing, in which case it is assumed to be the same as
#'   \code{informationRatesNew}.
#'
#' @return A vector of two conditional powers given the interim results and
#' parameter values, one without design change and the other with
#' data-dependent design changes.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive multiple comparison sequential design (AMCSD) for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2024, 34(3), 424-440.
#'
#' @seealso \code{\link{adaptDesign_mams}}
#'
#' @examples
#'
#' getCP_mams(
#'   INew = 373 / 4, M = 2, r = 1, corr_known = FALSE,
#'   L = 1, zL = c(-log(0.91), -log(0.78)) * sqrt(324 / 4 / 2),
#'   theta = c(-log(0.91), -log(0.78)),
#'   IMax = 324 / 4, kMax = 2, informationRates = c(1/2, 1),
#'   alpha = 0.025, typeAlphaSpending = "OF",
#'   MNew = 1, selected = 2, rNew = 1)
#'
#' @export
getCP_mams <- function(INew = NA_real_, M = NA_integer_, r = 1, corr_known = TRUE, L = NA_integer_, zL = NA_real_, theta = NA_real_, IMax = NA_real_, kMax = NA_integer_, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityTheta = NULL, spendingTime = NA_real_, MullerSchafer = FALSE, MNew = NA_integer_, selected = NA_integer_, rNew = 1, kNew = NA_integer_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, futilityStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, futilityBoundsInt = NULL, futilityCPInt = NULL, futilityThetaInt = NULL, typeBetaSpendingNew = "none", parameterBetaSpendingNew = NA_real_, spendingTimeNew = NA_real_) {
    .Call(`_lrstat_getCP_mams`, INew, M, r, corr_known, L, zL, theta, IMax, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityTheta, spendingTime, MullerSchafer, MNew, selected, rNew, kNew, informationRatesNew, efficacyStoppingNew, futilityStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, futilityBoundsInt, futilityCPInt, futilityThetaInt, typeBetaSpendingNew, parameterBetaSpendingNew, spendingTimeNew)
}

#' @title Conditional Power for Phase 2/3 Seamless Design
#' @description Obtains the conditional power for specified incremental
#' information given the interim results, parameter values, and
#' data-dependent changes in the error spending function, as well as the
#' number and spacing of interim looks.
#'
#' @param INew The maximum information for the active arm versus the common
#'   control in the secondary trial.
#' @param M Number of active treatment arms in Phase 2.
#' @param r Randomization ratio of each active arm to the common control
#'   in Phase 2.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics in Phase 2 is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is used.
#' @param L The interim adaptation look in Phase 3.
#' @param zL The z-test statistic at the interim adaptation look of
#'   Phase 3.
#' @param theta The assumed treatment effect for the selected arm versus the
#'   common control.
#' @param IMax Maximum information for the active arm versus the common
#'   control for the original trial. Must be provided.
#' @param K Number of sequential looks in Phase 3.
#' @param informationRates A numeric vector of information rates fixed
#'   before the trial. If unspecified, defaults to \eqn{(1:(K+1)) / (K+1)}.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage of the primary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param futilityStopping Indicators of whether futility stopping is
#'   allowed at each stage of the primary trial. Defaults to true
#'   if left unspecified.
#' @param criticalValues The upper boundaries on the max z-test statistic
#'   scale for Phase 2 and the z-test statistics for the selected arm
#'   in Phase 3 for the primary trial. If missing, boundaries
#'   will be computed based on the specified alpha spending function.
#' @param alpha The significance level of the primary trial.
#'   Defaults to 0.025.
#' @param typeAlphaSpending The type of alpha spending for the primary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function,
#'   \code{"user"} for user defined spending, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param userAlphaSpending The user-defined alpha spending for the
#'   primary trial. Represents the cumulative alpha spent up to each stage.
#' @param futilityBounds	The lower boundaries on the  max z-test statistic
#'   scale for Phase 2 and the z-test statistics for the selected arm
#'   in Phase 3 for the primary trial.
#' @param futilityCP The conditional power-based futility bounds for the
#'   primary trial.
#' @param futilityTheta The parameter value-based futility bounds for the
#'   primary trial.
#' @param spendingTime The error spending time of the primary trial.
#'   Defaults to missing, in which case it is assumed to be the same as
#'   \code{informationRates}.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @param kNew The number of looks of the secondary trial.
#' @param informationRatesNew The spacing of looks of the secondary trial.
#' @param efficacyStoppingNew The indicators of whether efficacy stopping is
#'   allowed at each look of the secondary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param futilityStoppingNew The indicators of whether futility stopping is
#'   allowed at each look of the secondary trial. Defaults to true
#'   if left unspecified.
#' @param typeAlphaSpendingNew The type of alpha spending for the secondary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param futilityBoundsInt The futility boundaries on the z statistic
#'   scale for new stages of the integrated trial.
#' @param futilityCPInt The conditional power-based futility bounds for
#'   new stages of the integrated trial.
#' @param futilityThetaInt The parameter value-based futility bounds for the
#'   new stages of the integrated trial.
#' @param typeBetaSpendingNew The type of beta spending for the secondary
#'   trial. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @param parameterBetaSpendingNew The parameter value of beta spending
#'   for the secondary trial. Corresponds to \eqn{\rho} for \code{"sfKD"},
#'   and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTimeNew The error spending time of the secondary trial.
#'   Defaults to missing, in which case it is assumed to be the same as
#'   \code{informationRatesNew}.
#'
#' @return A vector of two conditional powers given the interim results and
#' parameter values, one without design change and the other with
#' data-dependent design changes.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive two-stage seamless sequential design for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2025, 35(4), 565-587.
#'
#' @seealso \code{\link{adaptDesign_seamless}}
#'
#' @examples
#'
#' getCP_seamless(
#'   INew = 198 / 4, M = 2, r = 1, corr_known = FALSE,
#'   L = 1, zL = -log(0.67) * sqrt(80 / 4), theta = -log(0.691),
#'   IMax = 120 / 4, K = 2, informationRates = c(1/3, 2/3, 1),
#'   alpha = 0.025, typeAlphaSpending = "OF", kNew = 1)
#'
#' @export
getCP_seamless <- function(INew = NA_real_, M = NA_integer_, r = 1, corr_known = TRUE, L = NA_integer_, zL = NA_real_, theta = NA_real_, IMax = NA_real_, K = NA_integer_, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityTheta = NULL, spendingTime = NA_real_, MullerSchafer = FALSE, kNew = NA_integer_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, futilityStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, futilityBoundsInt = NULL, futilityCPInt = NULL, futilityThetaInt = NULL, typeBetaSpendingNew = "none", parameterBetaSpendingNew = NA_real_, spendingTimeNew = NA_real_) {
    .Call(`_lrstat_getCP_seamless`, INew, M, r, corr_known, L, zL, theta, IMax, K, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityTheta, spendingTime, MullerSchafer, kNew, informationRatesNew, efficacyStoppingNew, futilityStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, futilityBoundsInt, futilityCPInt, futilityThetaInt, typeBetaSpendingNew, parameterBetaSpendingNew, spendingTimeNew)
}

#' @title Confidence Interval After Trial Termination
#' @description Obtains the p-value, median unbiased point estimate, and
#' confidence interval after the end of a group sequential trial.
#'
#' @param L The termination look.
#' @param zL The z-test statistic at the termination look.
#' @param IMax The maximum information of the trial.
#' @param informationRates The information rates up to look \code{L}.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage up to look \code{L}.
#'   Defaults to true if left unspecified.
#' @param criticalValues The upper boundaries on the z-test statistic scale
#'   for efficacy stopping up to look \code{L}.
#' @inheritParams param_alpha
#' @param typeAlphaSpending The type of alpha spending for the trial.
#'   One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @inheritParams param_parameterAlphaSpending
#' @param spendingTime The error spending time up to look \code{L}.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRates}.
#'
#' @return A data frame with the following components:
#'
#' * \code{pvalue}: p-value for rejecting the null hypothesis.
#'
#' * \code{thetahat}: Median unbiased point estimate of the parameter.
#'
#' * \code{cilevel}: Confidence interval level.
#'
#' * \code{lower}: Lower bound of confidence interval.
#'
#' * \code{upper}: Upper bound of confidence interval.
#'
#' @details
#' If \code{typeAlphaSpending} is \code{"OF"}, \code{"P"}, \code{"WT"}, or
#' \code{"none"}, then \code{informationRates}, \code{efficacyStopping},
#' and \code{spendingTime} must be of full length \code{kMax}, and
#' \code{informationRates} and \code{spendingTime} must end with 1.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Anastasios A. Tsiatis, Gary L. Rosner and Cyrus R. Mehta.
#' Exact confidence intervals following a group sequential test.
#' Biometrics 1984;40:797-803.
#'
#' @examples
#'
#' # group sequential design with 90% power to detect delta = 6
#' delta <- 6
#' sigma <- 17
#' n <- 282
#' (des1 <- getDesign(IMax = n/(4*sigma^2), theta = delta, kMax = 3,
#'                    alpha = 0.05, typeAlphaSpending = "sfHSD",
#'                    parameterAlphaSpending = -4))
#'
#' # crossed the boundary at the second look
#' L <- 2
#' n1 <- n*2/3
#' delta1 <- 7
#' sigma1 <- 20
#' zL <- delta1/sqrt(4/n1*sigma1^2)
#'
#' # confidence interval
#' getCI(L = L, zL = zL, IMax = n/(4*sigma1^2),
#'       informationRates = c(1/3, 2/3), alpha = 0.05,
#'       typeAlphaSpending = "sfHSD", parameterAlphaSpending = -4)
#'
#' @export
getCI <- function(L = NA_integer_, zL = NA_real_, IMax = NA_real_, informationRates = NA_real_, efficacyStopping = NA_integer_, criticalValues = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, spendingTime = NA_real_) {
    .Call(`_lrstat_getCI`, L, zL, IMax, informationRates, efficacyStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, spendingTime)
}

#' @title Repeated Confidence Interval for Group Sequential Design
#' @description Obtains the repeated confidence interval
#' for a group sequential trial.
#'
#' @param L The look of interest.
#' @param zL The z-test statistic at the look.
#' @param IMax The maximum information of the trial.
#' @param informationRates The information rates up to look \code{L}.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage up to look \code{L}. Defaults to true
#'   if left unspecified.
#' @param criticalValues The upper boundaries on the z-test statistic scale
#'   for efficacy stopping up to look \code{L}.
#' @inheritParams param_alpha
#' @param typeAlphaSpending The type of alpha spending for the trial.
#'   One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @param spendingTime The error spending time up to look \code{L}.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRates}.
#'
#' @return A data frame with the following components:
#'
#' * \code{pvalue}: Repeated p-value for rejecting the null hypothesis.
#'
#' * \code{thetahat}: Point estimate of the parameter.
#'
#' * \code{cilevel}: Confidence interval level.
#'
#' * \code{lower}: Lower bound of repeated confidence interval.
#'
#' * \code{upper}: Upper bound of repeated confidence interval.
#'
#' If \code{typeAlphaSpending} is \code{"OF"}, \code{"P"}, \code{"WT"}, or
#' \code{"none"}, then \code{informationRates}, \code{efficacyStopping},
#' and \code{spendingTime} must be of full length \code{kMax}, and
#' \code{informationRates} and \code{spendingTime} must end with 1.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Christopher Jennison and Bruce W. Turnbull.
#' Interim analyses: the repeated confidence interval approach
#' (with discussion).
#' J R Stat Soc Series B. 1989;51:305-361.
#'
#' @examples
#'
#' # group sequential design with 90% power to detect delta = 6
#' delta <- 6
#' sigma <- 17
#' n <- 282
#' (des1 <- getDesign(IMax = n/(4*sigma^2), theta = delta, kMax = 3,
#'                    alpha = 0.05, typeAlphaSpending = "sfHSD",
#'                    parameterAlphaSpending = -4))
#'
#' # results at the second look
#' L <- 2
#' n1 <- n*2/3
#' delta1 <- 7
#' sigma1 <- 20
#' zL <- delta1/sqrt(4/n1*sigma1^2)
#'
#' # repeated confidence interval
#' getRCI(L = L, zL = zL, IMax = n/(4*sigma1^2),
#'        informationRates = c(1/3, 2/3), alpha = 0.05,
#'        typeAlphaSpending = "sfHSD", parameterAlphaSpending = -4)
#'
#' @export
getRCI <- function(L = NA_integer_, zL = NA_real_, IMax = NA_real_, informationRates = NA_real_, efficacyStopping = NA_integer_, criticalValues = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, spendingTime = NA_real_) {
    .Call(`_lrstat_getRCI`, L, zL, IMax, informationRates, efficacyStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, spendingTime)
}

#' @title Confidence Interval After Adaptation
#' @description Obtains the p-value, median unbiased point estimate, and
#' confidence interval after the end of an adaptive trial.
#'
#' @param L The interim adaptation look of the primary trial.
#' @param zL The z-test statistic at the interim adaptation look of
#'   the primary trial.
#' @param IMax The maximum information of the primary trial.
#' @param kMax The maximum number of stages of the primary trial.
#' @param informationRates The information rates of the primary trial.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage of the primary trial. Defaults to true
#'   if left unspecified.
#' @param criticalValues The upper boundaries on the z-test statistic scale
#'   for efficacy stopping for the primary trial.
#' @param alpha The significance level of the primary trial.
#'   Defaults to 0.025.
#' @param typeAlphaSpending The type of alpha spending for the primary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTime The error spending time of the primary trial.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRates}.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @param Lc The termination look of the integrated trial.
#' @param zLc The z-test statistic at the termination look of the
#'   integrated trial.
#' @param INew The maximum information of the secondary trial.
#' @param informationRatesNew The spacing of looks of the secondary trial
#'   up to look \code{L2}.
#' @param efficacyStoppingNew The indicators of whether efficacy stopping is
#'   allowed at each look of the secondary trial up to look \code{L2}.
#'   Defaults to true if left unspecified.
#' @param typeAlphaSpendingNew The type of alpha spending for the secondary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTimeNew The error spending time of the secondary trial
#'   up to look \code{L2}. Defaults to missing, in which case, it is
#'   the same as \code{informationRatesNew}.
#'
#' @return A data frame with the following variables:
#'
#' * \code{pvalue}: p-value for rejecting the null hypothesis.
#'
#' * \code{thetahat}: Median unbiased point estimate of the parameter.
#'
#' * \code{cilevel}: Confidence interval level.
#'
#' * \code{lower}: Lower bound of confidence interval.
#'
#' * \code{upper}: Upper bound of confidence interval.
#'
#' @details
#' If \code{typeAlphaSpendingNew} is \code{"OF"}, \code{"P"}, \code{"WT"}, or
#' \code{"none"}, then \code{informationRatesNew}, \code{efficacyStoppingNew},
#' and \code{spendingTimeNew} must be of full length \code{kNew}, and
#' \code{informationRatesNew} and \code{spendingTimeNew} must end with 1.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Lingyun Liu and Cyrus Mehta.
#' Exact inference for adaptive group sequential designs.
#' Stat Med. 2013;32(23):3991-4005.
#'
#' @seealso \code{\link{adaptDesign}}
#'
#' @examples
#' # two-arm randomized clinical trial with a normally distributed endpoint
#' # 90% power to detect mean difference of 15 with a standard deviation of 50
#' # Design the Stage I Trial with 3 looks and Lan-DeMets O'Brien-Fleming type
#' # spending function
#' delta <- 15
#' sigma <- 50
#'
#' (des1 <- getDesignMeanDiff(
#'   beta = 0.1, meanDiff = delta, stDev = sigma,
#'   kMax = 3, alpha = 0.025, typeAlphaSpending = "sfOF"
#' ))
#'
#' s1 <- des1$byStageResults$informationRates
#' b1 <- des1$byStageResults$efficacyBounds
#' n <- des1$overallResults$numberOfSubjects
#'
#' # Monitoring the Stage I Trial
#' L <- 1
#' nL <- des1$byStageResults$numberOfSubjects[L]
#' deltahat <- 8
#' sigmahat <- 55
#' sedeltahat <- sigmahat * sqrt( 4 / nL)
#' zL <- deltahat / sedeltahat
#'
#' # Making an Adaptive Change: Stage I to Stage II
#' # revised clinically meaningful difference downward to 10 power the study
#' # retain the standard deviation at the design stage
#' # Muller & Schafer (2001) method to design the secondary trial
#' # with 2 looks and Lan-DeMets Pocock type spending function
#' # re-estimate sample size to reach 90% conditional power
#' deltaNew <- 10
#'
#' (des2 <- adaptDesign(
#'   betaNew = 0.1, L = L, zL = zL, theta = deltaNew,
#'   IMax = n / (4 * sigma^2), kMax = 3, informationRates = s1,
#'   alpha = 0.025, typeAlphaSpending = "sfOF",
#'   MullerSchafer = TRUE, kNew = 2, typeAlphaSpendingNew = "sfP"
#' ))
#'
#' INew <- des2$secondaryTrial$maxInformation
#' (nNew <- ceiling(INew * 4 * sigma^2))
#' (nTotal <- nL + nNew)
#'
#' # Monitoring the Integrated Trial
#' s2 <- des2$secondaryTrial$informationRates
#'
#' Lc <- 2
#' deltahatc <- 9.5
#' sigmahatc <- 52.759
#' L2 <- Lc - L
#' nL2 <-  nNew * s2[L2]
#' nc <- nL + nL2
#' sedeltahatc <- sigmahatc * sqrt(4 / nc)
#' zLc <- deltahatc / sedeltahatc
#' zL2 <- (zLc * sqrt(nc) - zL * sqrt(nL)) / sqrt(nL2)
#'
#' getADCI(
#'   L = L, zL = zL, IMax = n / (4 * sigmahatc^2), kMax = 3,
#'   informationRates = s1, alpha = 0.025, typeAlphaSpending = "sfOF",
#'   MullerSchafer = TRUE, Lc = Lc, zLc = zLc,
#'   INew = nNew / (4 * sigmahatc^2), informationRatesNew = s2,
#'   typeAlphaSpendingNew = "sfP")
#'
#' @export
getADCI <- function(L = NA_integer_, zL = NA_real_, IMax = NA_real_, kMax = NA_integer_, informationRates = NA_real_, efficacyStopping = NA_integer_, criticalValues = NA_real_, alpha = 0.25, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, spendingTime = NA_real_, MullerSchafer = FALSE, Lc = NA_integer_, zLc = NA_real_, INew = NA_real_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, spendingTimeNew = NA_real_) {
    .Call(`_lrstat_getADCI`, L, zL, IMax, kMax, informationRates, efficacyStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, spendingTime, MullerSchafer, Lc, zLc, INew, informationRatesNew, efficacyStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, spendingTimeNew)
}

#' @title Repeated Confidence Interval After Adaptation
#' @description Obtains the repeated p-value, conservative point estimate,
#' and repeated confidence interval for an adaptive group sequential trial.
#'
#' @param L The interim adaptation look of the primary trial.
#' @param zL The z-test statistic at the interim adaptation look of
#'   the primary trial.
#' @param IMax The maximum information of the primary trial.
#' @param kMax The maximum number of stages of the primary trial.
#' @param informationRates The information rates of the primary trial.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage of the primary trial. Defaults to true
#'   if left unspecified.
#' @param criticalValues The upper boundaries on the z-test statistic scale
#'   for efficacy stopping for the primary trial.
#' @param alpha The significance level of the primary trial.
#'   Defaults to 0.025.
#' @param typeAlphaSpending The type of alpha spending for the primary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTime The error spending time of the primary trial.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRates}.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @param Lc The look of interest in the integrated trial.
#' @param zLc The z-test statistic at the look of the integrated trial.
#' @param INew The maximum information of the secondary trial.
#' @param informationRatesNew The spacing of looks of the secondary trial.
#' @param efficacyStoppingNew The indicators of whether efficacy stopping is
#'   allowed at each look of the secondary trial up to look \code{L2}.
#'   Defaults to true if left unspecified.
#' @param typeAlphaSpendingNew The type of alpha spending for the secondary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTimeNew The error spending time of the secondary trial.
#'   up to look \code{L2}. Defaults to missing, in which case, it is
#'   the same as \code{informationRatesNew}.
#'
#' @return A data frame with the following variables:
#'
#' * \code{pvalue}: Repeated p-value for rejecting the null hypothesis.
#'
#' * \code{thetahat}: Point estimate of the parameter.
#'
#' * \code{cilevel}: Confidence interval level.
#'
#' * \code{lower}: Lower bound of repeated confidence interval.
#'
#' * \code{upper}: Upper bound of repeated confidence interval.
#'
#' @details
#' If \code{typeAlphaSpendingNew} is \code{"OF"}, \code{"P"}, \code{"WT"}, or
#' \code{"none"}, then \code{informationRatesNew}, \code{efficacyStoppingNew},
#' and \code{spendingTimeNew} must be of full length \code{kNew}, and
#' \code{informationRatesNew} and \code{spendingTimeNew} must end with 1.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Cyrus R. Mehta, Peter Bauer, Martin Posch and Werner Brannath.
#' Repeated confidence intervals for adaptive group sequential trials.
#' Stat Med. 2007;26:5422–5433.
#'
#' @seealso \code{\link{adaptDesign}}
#'
#' @examples
#' # two-arm randomized clinical trial with a normally distributed endpoint
#' # 90% power to detect mean difference of 15 with a standard deviation of 50
#' # Design the Stage I Trial with 3 looks and Lan-DeMets O'Brien-Fleming type
#' # spending function
#' delta <- 15
#' sigma <- 50
#'
#' (des1 <- getDesignMeanDiff(
#'   beta = 0.1, meanDiff = delta, stDev = sigma,
#'   kMax = 3, alpha = 0.025, typeAlphaSpending = "sfOF"
#' ))
#'
#' s1 <- des1$byStageResults$informationRates
#' b1 <- des1$byStageResults$efficacyBounds
#' n <- des1$overallResults$numberOfSubjects
#'
#' # Monitoring the Stage I Trial
#' L <- 1
#' nL <- des1$byStageResults$numberOfSubjects[L]
#' deltahat <- 8
#' sigmahat <- 55
#' sedeltahat <- sigmahat * sqrt( 4 / nL)
#' zL <- deltahat / sedeltahat
#'
#' # Making an Adaptive Change: Stage I to Stage II
#' # revised clinically meaningful difference downward to 10 power the study
#' # retain the standard deviation at the design stage
#' # Muller & Schafer (2001) method to design the secondary trial
#' # with 2 looks and Lan-DeMets Pocock type spending function
#' # re-estimate sample size to reach 90% conditional power
#' deltaNew <- 10
#'
#' (des2 <- adaptDesign(
#'   betaNew = 0.1, L = L, zL = zL, theta = deltaNew,
#'   IMax = n / (4 * sigma^2), kMax = 3, informationRates = s1,
#'   alpha = 0.025, typeAlphaSpending = "sfOF",
#'   MullerSchafer = TRUE, kNew = 2, typeAlphaSpendingNew = "sfP"
#' ))
#'
#' INew <- des2$secondaryTrial$maxInformation
#' (nNew <- ceiling(INew * 4 * sigma^2))
#' (nTotal <- nL + nNew)
#'
#' # Monitoring the Integrated Trial
#' s2 <- des2$secondaryTrial$informationRates
#'
#' Lc <- 2
#' deltahatc <- 9.5
#' sigmahatc <- 52.759
#' L2 <- Lc - L
#' nL2 <-  nNew * s2[L2]
#' nc <- nL + nL2
#' sedeltahatc <- sigmahatc * sqrt(4 / nc)
#' zLc <- deltahatc / sedeltahatc
#' zL2 <- (zLc * sqrt(nc) - zL * sqrt(nL)) / sqrt(nL2)
#'
#' getADRCI(
#'   L = L, zL = zL, IMax = n / (4 * sigmahatc^2), kMax = 3,
#'   informationRates = s1, alpha = 0.025, typeAlphaSpending = "sfOF",
#'   MullerSchafer = TRUE, Lc = Lc, zLc = zLc,
#'   INew = nNew / (4 * sigmahatc^2), informationRatesNew = s2,
#'   typeAlphaSpendingNew = "sfP")
#'
#' @export
getADRCI <- function(L = NA_integer_, zL = NA_real_, IMax = NA_real_, kMax = NA_integer_, informationRates = NA_real_, efficacyStopping = NA_integer_, criticalValues = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, spendingTime = NA_real_, MullerSchafer = FALSE, Lc = NA_integer_, zLc = NA_real_, INew = NA_real_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, spendingTimeNew = NA_real_) {
    .Call(`_lrstat_getADRCI`, L, zL, IMax, kMax, informationRates, efficacyStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, spendingTime, MullerSchafer, Lc, zLc, INew, informationRatesNew, efficacyStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, spendingTimeNew)
}

#' @title Confidence Interval After Trial Termination for Multi-Arm
#' Multi-Stage Design
#' @description Obtains the p-value, conservative point estimate, and
#' confidence interval after the end of a multi-arm multi-stage trial.
#'
#' @param M Number of active treatment arms.
#' @param r Randomization ratio of each active arm to the common control.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is used.
#' @param L The termination look.
#' @param zL The vector of z-test statistics at the termination look.
#' @param IMax Maximum information for any active arm versus the common
#'   control.
#' @param informationRates The information rates up to look \code{L}.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage up to look \code{L}.
#'   Defaults to \code{TRUE} if left unspecified.
#' @param criticalValues The matrix of by-level upper boundaries on the
#'   max z-test statistic scale for efficacy stopping up to look \code{L}.
#'   The first column is for level \code{M}, the second column is for
#'   level \code{M - 1}, and so on, with the last column for level 1.
#'   If left unspecified, the critical values will be computed based
#'   on the specified alpha spending function.
#' @inheritParams param_alpha
#' @param typeAlphaSpending The type of alpha spending for the trial.
#'   One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @inheritParams param_parameterAlphaSpending
#' @param spendingTime The error spending time up to look \code{L}.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRates}.
#'
#' @details
#' If \code{typeAlphaSpending} is \code{"OF"}, \code{"P"}, \code{"WT"}, or
#' \code{"none"}, then \code{informationRates}, \code{efficacyStopping},
#' and \code{spendingTime} must be of full length \code{kMax}, and
#' \code{informationRates} and \code{spendingTime} must end with 1.
#'
#' @return A data frame with the following components:
#'
#' * \code{level}: Number of individual hypotheses considered for multiplicity.
#'
#' * \code{index}: The treatment arm with max Z among the active arms.
#'
#' * \code{pvalue}: p-value for rejecting the null hypothesis.
#'
#' * \code{thetahat}: Point estimate of the parameter.
#'
#' * \code{cilevel}: Confidence interval level.
#'
#' * \code{lower}: Lower bound of confidence interval.
#'
#' * \code{upper}: Upper bound of confidence interval.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive multiple comparison sequential design (AMCSD) for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2024, 34(3), 424-440.
#'
#' @examples
#' getCI_mams(
#'   L = 2, zL = c(2.075, 2.264),
#'   M = 2, r = 1, corr_known = FALSE,
#'   IMax = 300 / 4, informationRates = c(1/2, 1),
#'   alpha = 0.025, typeAlphaSpending = "sfOF")
#'
#' @export
getCI_mams <- function(M = NA_integer_, r = 1, corr_known = TRUE, L = NA_integer_, zL = NA_real_, IMax = NA_real_, informationRates = NA_real_, efficacyStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, spendingTime = NA_real_) {
    .Call(`_lrstat_getCI_mams`, M, r, corr_known, L, zL, IMax, informationRates, efficacyStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, spendingTime)
}

#' @title Confidence Interval After Adaptation for Multi-Arm Multi-Stage
#' Design
#' @description Obtains the p-value, conservative point estimate, and
#' confidence interval after the end of an adaptive multi-arm multi-stage trial.
#'
#' @param M Number of active treatment arms in the primary trial.
#' @param r Randomization ratio of each active arm to the common control
#'   in the primary trial.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is assumed.
#' @param L The interim adaptation look of the primary trial.
#' @param zL The z-test statistics at the interim adaptation look of
#'   the primary trial.
#' @param IMax Maximum information for any active arm versus the common
#'   control for the primary trial. Must be provided.
#' @param kMax The maximum number of stages of the primary trial.
#' @param informationRates The information rates of the primary trial.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage of the primary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param criticalValues The matrix of by-level upper boundaries on the
#'   max z-test statistic scale for efficacy stopping up to look \code{L}
#'   for the primary trial.
#'   The first column is for level \code{M}, the second column is for
#'   level \code{M - 1}, and so on, with the last column for level 1.
#'   If left unspecified, the critical values will be computed based
#'   on the specified alpha spending function.
#' @param alpha The significance level of the primary trial.
#'   Defaults to 0.025.
#' @param typeAlphaSpending The type of alpha spending for the primary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTime The error spending time of the primary trial.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRates}.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @param MNew The number of active treatment arms in the secondary trial.
#' @param selected The indices of the selected treatment arms for the
#'   secondary trial among the \code{M} active arms in the primary trial.
#' @param rNew The randomization ratio of each active arm to the common control
#'  in the secondary trial.
#' @param Lc The termination look of the integrated trial.
#' @param zLc The z-test statistics at the termination look of the
#'   integrated trial.
#' @param INew The maximum information for any active arm versus the common
#'   control in the secondary trial.
#' @param informationRatesNew The spacing of looks of the secondary trial.
#' @param efficacyStoppingNew The indicators of whether efficacy stopping is
#'   allowed at each look of the secondary trial.
#'   Defaults to \code{TRUE} if left unspecified.
#' @param typeAlphaSpendingNew The type of alpha spending for the secondary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTimeNew The error spending time of the secondary trial.
#'   Defaults to missing, in which case, it is
#'   the same as \code{informationRatesNew}.
#'
#' @details
#' If typeAlphaSpendingNew is \code{"OF"} or \code{"none"}, then
#' \code{informationRatesNew}, \code{efficacyStoppingNew}, and
#' \code{spendingTimeNew} must be of full length \code{kNew}, and
#' \code{informationRatesNew} and \code{spendingTimeNew} must end with 1.
#'
#' @return A data frame with the following variables:
#'
#' * \code{level}: Number of individual hypotheses considered for multiplicity.
#'
#' * \code{index}: The treatment arm with max Z among the active arms.
#'
#' * \code{pvalue}: p-value for rejecting the null hypothesis.
#'
#' * \code{thetahat}: Point estimate of the parameter.
#'
#' * \code{cilevel}: Confidence interval level.
#'
#' * \code{lower}: Lower bound of confidence interval.
#'
#' * \code{upper}: Upper bound of confidence interval.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive multiple comparison sequential design (AMCSD) for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2024, 34(3), 424-440.
#'
#' @examples
#' getADCI_mams(
#'   M = 2, r = 1, corr_known = FALSE, L = 1, zL = c(2.075, 2.264),
#'   IMax = 300 / 4, kMax = 2, informationRates = c(0.5, 1),
#'   alpha = 0.025, typeAlphaSpending = "sfOF",
#'   MNew = 1, selected = 2, rNew = 1,
#'   Lc = 2, zLc = 1.667, INew = 374 / 4)
#'
#' @export
getADCI_mams <- function(M = NA_integer_, r = 1, corr_known = TRUE, L = NA_integer_, zL = NA_real_, IMax = NA_real_, kMax = NA_integer_, informationRates = NA_real_, efficacyStopping = NA_integer_, criticalValues = NULL, alpha = 0.25, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, spendingTime = NA_real_, MullerSchafer = FALSE, MNew = NA_integer_, selected = NA_integer_, rNew = 1, Lc = NA_integer_, zLc = NA_real_, INew = NA_real_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, spendingTimeNew = NA_real_) {
    .Call(`_lrstat_getADCI_mams`, M, r, corr_known, L, zL, IMax, kMax, informationRates, efficacyStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, spendingTime, MullerSchafer, MNew, selected, rNew, Lc, zLc, INew, informationRatesNew, efficacyStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, spendingTimeNew)
}

#' @title Confidence Interval After Trial Termination for Phase 2/3
#' Seamless Design
#' @description Obtains the p-value, point estimate, and
#' confidence interval after the end of a phase 2/3 seamless trial.
#'
#' @param M Number of active treatment arms in Phase 2.
#' @param r Randomization ratio of each active arm to the common control
#'   in Phase 2.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics in Phase 2 is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is assumed.
#' @param L The termination look in Phase 3.
#' @param zL The z-test statistic at the termination look.
#' @param IMax Maximum information for any active arm versus the common
#'   control.
#' @param informationRates The information rates up to look \code{L}.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage up to look \code{L}.
#'   Defaults to \code{TRUE} if left unspecified.
#' @param criticalValues The upper boundaries on the max z-test statistic
#'   scale for Phase 2 and the z-test statistics for the selected arm
#'   in Phase 3 up to look \code{L}. If missing, boundaries will be
#'   computed based on the specified alpha spending function.
#' @inheritParams param_alpha
#' @param typeAlphaSpending The type of alpha spending for the trial.
#'   One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @inheritParams param_parameterAlphaSpending
#' @param spendingTime The error spending time up to look \code{L}.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRates}.
#'
#' @details
#' If \code{typeAlphaSpending} is \code{"OF"}, \code{"P"}, \code{"WT"}, or
#' \code{"none"}, then \code{informationRates}, \code{efficacyStopping},
#' and \code{spendingTime} must be of full length \eqn{K + 1}, and
#' \code{informationRates} and \code{spendingTime} must end with 1.
#'
#' @return A data frame with the following components:
#'
#' * \code{pvalue}: p-value for rejecting the null hypothesis.
#'
#' * \code{thetahat}: Point estimate of the parameter.
#'
#' * \code{cilevel}: Confidence interval level.
#'
#' * \code{lower}: Lower bound of confidence interval.
#'
#' * \code{upper}: Upper bound of confidence interval.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive two-stage seamless sequential design for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2025, 35(4), 565-587.
#'
#' @examples
#' getCI_seamless(
#'   L = 2, zL = 2.075,
#'   M = 2, r = 1, corr_known = FALSE,
#'   IMax = 300 / 4, informationRates = c(1/3, 2/3, 1),
#'   alpha = 0.025, typeAlphaSpending = "sfOF")
#'
#' @export
getCI_seamless <- function(M = NA_integer_, r = 1, corr_known = TRUE, L = NA_integer_, zL = NA_real_, IMax = NA_real_, informationRates = NA_real_, efficacyStopping = NA_integer_, criticalValues = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, spendingTime = NA_real_) {
    .Call(`_lrstat_getCI_seamless`, M, r, corr_known, L, zL, IMax, informationRates, efficacyStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, spendingTime)
}

#' @title Confidence Interval After Adaptation for Phase 2/3 Seamless
#' Design
#' @description Obtains the p-value, conservative point estimate, and
#' confidence interval after the end of an adaptive phase 2/3 seamless
#' design.
#'
#' @param M Number of active treatment arms in Phase 2.
#' @param r Randomization ratio of each active arm to the common control
#'   in Phase 2.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics in Phase 2 is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is used.
#' @param L The interim adaptation look in Phase 3.
#' @param zL The z-test statistic at the interim adaptation look of
#'   Phase 3.
#' @param IMax Maximum information for the active arm versus the common
#'   control for the original trial. Must be provided.
#' @param K Number of sequential looks in Phase 3.
#' @param informationRates A numeric vector of information rates fixed
#'   before the trial. If unspecified, defaults to \eqn{(1:(K+1)) / (K+1)}.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage of the primary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param criticalValues The upper boundaries on the max z-test statistic
#'   scale for Phase 2 and the z-test statistics for the selected arm
#'   in Phase 3 for the primary trial. If missing, boundaries
#'   will be computed based on the specified alpha spending function.
#' @param alpha The significance level of the primary trial.
#'   Defaults to 0.025.
#' @param typeAlphaSpending The type of alpha spending for the primary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTime The error spending time of the primary trial.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRates}.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @param Lc The termination look of the integrated trial.
#' @param zLc The z-test statistic at the termination look of the
#'   integrated trial.
#' @param INew The maximum information for the active arm versus the common
#'   control in the secondary trial.
#' @param informationRatesNew The spacing of looks of the secondary trial.
#' @param efficacyStoppingNew The indicators of whether efficacy stopping is
#'   allowed at each look of the secondary trial.
#'   Defaults to \code{TRUE} if left unspecified.
#' @param typeAlphaSpendingNew The type of alpha spending for the secondary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param spendingTimeNew The error spending time of the secondary trial.
#'   Defaults to missing, in which case, it is
#'   the same as \code{informationRatesNew}.
#'
#' @details
#' If typeAlphaSpendingNew is \code{"OF"}, \code{"P"}, \code{"WT"},
#' or \code{"none"}, then
#' \code{informationRatesNew}, \code{efficacyStoppingNew}, and
#' \code{spendingTimeNew} must be of full length \code{kNew}, and
#' \code{informationRatesNew} and \code{spendingTimeNew} must end with 1.
#'
#' @return A data frame with the following variables:
#'
#' * \code{pvalue}: p-value for rejecting the null hypothesis.
#'
#' * \code{thetahat}: Point estimate of the parameter.
#'
#' * \code{cilevel}: Confidence interval level.
#'
#' * \code{lower}: Lower bound of confidence interval.
#'
#' * \code{upper}: Upper bound of confidence interval.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive multiple comparison sequential design (AMCSD) for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2024, 34(3), 424-440.
#'
#' @examples
#' getADCI_seamless(
#'   M = 2, r = 1, corr_known = FALSE,
#'   L = 1, zL = -log(0.67) * sqrt(80 / 4),
#'   IMax = 120 / 4, K = 2, informationRates = c(1/3, 2/3, 1),
#'   alpha = 0.025, typeAlphaSpending = "OF",
#'   Lc = 2, zLc = -log(0.677) * sqrt(236 / 4), INew = 236 / 4)
#'
#' @export
getADCI_seamless <- function(M = NA_integer_, r = 1, corr_known = TRUE, L = NA_integer_, zL = NA_real_, IMax = NA_real_, K = NA_integer_, informationRates = NA_real_, efficacyStopping = NA_integer_, criticalValues = NA_real_, alpha = 0.25, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, spendingTime = NA_real_, MullerSchafer = FALSE, Lc = NA_integer_, zLc = NA_real_, INew = NA_real_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, spendingTimeNew = NA_real_) {
    .Call(`_lrstat_getADCI_seamless`, M, r, corr_known, L, zL, IMax, K, informationRates, efficacyStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, spendingTime, MullerSchafer, Lc, zLc, INew, informationRatesNew, efficacyStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, spendingTimeNew)
}

#' @title Number of Enrolled Subjects
#' @description Obtains the number of subjects enrolled by given calendar
#' times.
#'
#' @param time A vector of calendar times at which to calculate the number
#'   of enrolled subjects.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_accrualDuration
#'
#' @return A vector of total number of subjects enrolled by the
#' specified calendar times.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Example 1: Uniform enrollment with 20 patients per month for 12 months.
#'
#' accrual(time = 3, accrualTime = 0, accrualIntensity = 20,
#'         accrualDuration = 12)
#'
#'
#' # Example 2: Piecewise accrual, 10 patients per month for the first
#' # 3 months, and 20 patients per month thereafter. Patient recruitment
#' # ends at 12 months for the study.
#'
#' accrual(time = c(2, 9), accrualTime = c(0, 3),
#'         accrualIntensity = c(10, 20), accrualDuration = 12)
#'
#' @export
accrual <- function(time, accrualTime, accrualIntensity, accrualDuration) {
    .Call(`_lrstat_accrual`, time, accrualTime, accrualIntensity, accrualDuration)
}

#' @title Accrual Duration to Enroll Target Number of Subjects
#' @description Obtains the accrual duration to enroll the target number
#' of subjects.
#'
#' @param nsubjects The vector of target number of subjects.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#'
#' @return A vector of accrual durations.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' getAccrualDurationFromN(nsubjects = c(20, 150), accrualTime = c(0, 3),
#'                         accrualIntensity = c(10, 20))
#'
#' @export
getAccrualDurationFromN <- function(nsubjects, accrualTime, accrualIntensity) {
    .Call(`_lrstat_getAccrualDurationFromN`, nsubjects, accrualTime, accrualIntensity)
}

#' @title Probability of Being at Risk
#' @description Obtains the probability of being at risk at given analysis
#' times.
#'
#' @param time A vector of analysis times at which to calculate the
#'   probability of being at risk.
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda
#' @inheritParams param_gamma
#'
#' @return A vector of probabilities of being at risk at the specified
#' analysis times after enrollment for a patient in a treatment group with
#' specified piecewise exponential survival and dropout distributions.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise exponential survival with hazard 0.0533 in the first 6
#' # months, and hazard 0.0309 thereafter, and 5% dropout by the end of
#' # 1 year.
#'
#' patrisk(time = c(3, 9), piecewiseSurvivalTime = c(0, 6),
#'         lambda = c(0.0533, 0.0309), gamma = -log(1-0.05)/12)
#'
#' @export
patrisk <- function(time, piecewiseSurvivalTime, lambda, gamma) {
    .Call(`_lrstat_patrisk`, time, piecewiseSurvivalTime, lambda, gamma)
}

#' @title Probability of Having an Event
#' @description Obtains the probability of having an event at given analysis
#' times.
#'
#' @param time A vector of analysis times at which to calculate the
#'   probability of having an event.
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda
#' @inheritParams param_gamma
#'
#' @return A vector of probabilities of having an event at the specified
#' analysis times after enrollment for a patient in a treatment group with
#' specified piecewise exponential survival and dropout distributions.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise exponential survival with hazard 0.0533 in the first 6
#' # months, and hazard 0.0309 thereafter, and 5% dropout by the end of
#' # 1 year.
#'
#' pevent(time = c(3, 9), piecewiseSurvivalTime = c(0, 6),
#'        lambda = c(0.0533, 0.0309), gamma = -log(1-0.05)/12)
#'
#' @export
pevent <- function(time, piecewiseSurvivalTime, lambda, gamma) {
    .Call(`_lrstat_pevent`, time, piecewiseSurvivalTime, lambda, gamma)
}

#' @title Number of Subjects at Risk
#' @description Obtains the number of subjects at risk at given analysis
#' times for each treatment group.
#'
#' @param t A vector of analysis times at which to calculate the number
#'   of patients at risk.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda1
#' @inheritParams param_lambda2
#' @inheritParams param_gamma1
#' @inheritParams param_gamma2
#' @inheritParams param_accrualDuration
#' @inheritParams param_maxFollowupTime
#' @param time Calendar time for the analysis.
#'
#' @return A matrix of the number of patients at risk at the specified
#' analysis times (row) for each treatment group (column).
#'
#' @details For a given treatment group \eqn{g} and calendar time \eqn{\tau},
#' the number of patients at risk at analysis time \eqn{t} is calculated as
#' \deqn{\phi_g A(\tau - t) S_g(t) G_g(t),} where \eqn{\phi_g} is the
#' probability of randomization to treatment group \eqn{g},
#' \eqn{A(\tau - t)} is the number of patients enrolled by calendar time
#' \eqn{\tau - t}, \eqn{S_g(t)G_g(t)} is the probability of being at risk at
#' analysis time \eqn{t} for a patient in treatment group \eqn{g}
#' after enrollment. Obviously, \eqn{t < \min(\tau, T_{\rm{fmax}})}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#'
#' natrisk(t = c(9, 24), allocationRatioPlanned = 1,
#'         accrualTime = c(0, 3), accrualIntensity = c(10, 20),
#'         piecewiseSurvivalTime = c(0, 6),
#'         lambda1 = c(0.0533, 0.0309), lambda2 = c(0.0533, 0.0533),
#'         gamma1 = -log(1-0.05)/12, gamma2 = -log(1-0.05)/12,
#'         accrualDuration = 12, maxFollowupTime = 30, time = 30)
#'
#' @export
natrisk <- function(t = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, maxFollowupTime = NA_real_, time = NA_real_) {
    .Call(`_lrstat_natrisk`, t, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, lambda1, lambda2, gamma1, gamma2, accrualDuration, maxFollowupTime, time)
}

#' @title Number of Subjects Having an Event by Calendar Time
#' @description Obtains the number of subjects having an event by given
#' calendar times for each treatment group.
#'
#' @param time A vector of calendar times at which to calculate the number
#'   of patients having an event.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda1
#' @inheritParams param_lambda2
#' @inheritParams param_gamma1
#' @inheritParams param_gamma2
#' @inheritParams param_accrualDuration
#' @inheritParams param_maxFollowupTime
#'
#' @return A matrix of the number of patients having an event at the
#' specified calendar times (row) for each treatment group (column).
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @details For a given treatment group \eqn{g} and calendar time \eqn{\tau},
#' the number of patients having an event by calendar time \eqn{\tau} is
#' calculated as \eqn{I_1 + I_2}, where
#' \deqn{I_1 = \phi_g A(\tau - T_{\rm{fmax}}) P_g(T_{\rm{fmax}}),} and
#' \deqn{I_2 = \phi_g \int_{\tau - T_{\rm{fmax}}}^{\tau} a(u) P_g(\tau - u) du,}
#' where \eqn{\phi_g} is the probability of randomization to treatment group \eqn{g},
#' \eqn{A(\tau - T_{\rm{fmax}})} is the number of patients enrolled by
#' calendar time \eqn{\tau - T_{\rm{fmax}}},
#' \eqn{P_g(T_{\rm{fmax}})} is the probability of having an event by
#' the maximum follow-up time \eqn{T_{\rm{fmax}}} for a patient in
#' treatment group \eqn{g} after enrollment,
#' \eqn{a(u)} is the accrual intensity at calendar time \eqn{u},
#' and \eqn{P_g(\tau - u)} is the probability of having an event by
#' calendar time \eqn{\tau} for a patient in treatment group \eqn{g}
#' enrolled at calendar time \eqn{u}.
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#' nevent(time = c(9, 24), allocationRatioPlanned = 1,
#'        accrualTime = c(0, 3), accrualIntensity = c(10, 20),
#'        piecewiseSurvivalTime = c(0, 6),
#'        lambda1 = c(0.0533, 0.0309), lambda2 = c(0.0533, 0.0533),
#'        gamma1 = -log(1-0.05)/12, gamma2 = -log(1-0.05)/12,
#'        accrualDuration = 12, maxFollowupTime = 30)
#'
#' @export
nevent <- function(time = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, maxFollowupTime = NA_real_) {
    .Call(`_lrstat_nevent`, time, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, lambda1, lambda2, gamma1, gamma2, accrualDuration, maxFollowupTime)
}

#' @title Power for Binomial One-Sample Exact Test
#' @description Obtains the power for binomial one-sample exact test.
#'
#' @param n The sample size.
#' @param piH0 The response probability under the null hypothesis.
#' @param pi The response probability under the alternative hypothesis.
#' @param alpha The one-sided significance level. Defaults to 0.025.
#'
#' @return A data frame containing the critical value of the number of
#' responses for rejecting the null hypothesis, the attained type I
#' error, the power for the exact test, the sample size, the
#' response probabilities under the null and alternative hypotheses,
#' and the direction of the alternative.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' powerOnePropExact(n = 110, piH0 = 0.15, pi = 0.25, alpha = 0.05)
#'
#' @export
powerOnePropExact <- function(n = NA_integer_, piH0 = NA_real_, pi = NA_real_, alpha = 0.025) {
    .Call(`_lrstat_powerOnePropExact`, n, piH0, pi, alpha)
}

#' @title Sample Size for Binomial One-Sample Exact Test
#' @description Obtains the sample size for binomial one-sample exact test.
#'
#' @param beta The type II error.
#' @param piH0 The response probability under the null hypothesis.
#' @param pi The response probability under the alternative hypothesis.
#' @param alpha The one-sided significance level. Defaults to 0.025.
#' @param max_n_search The maximum sample size to search up to. If no
#'   sample size up to this value satisfies the windowed power criterion,
#'   an error is thrown.
#' @param window The number of consecutive sample sizes that must all
#'   satisfy the power criterion to confirm the found sample size.
#'   This is to mitigate non-monotonicity of power in sample size for
#'   the exact test.
#'
#' @return A data frame containing the critical value of the number of
#' responses for rejecting the null hypothesis, the attained type I
#' error, the power for the exact test, the sample size, the
#' response probabilities under the null and alternative hypotheses,
#' and the direction of the alternative.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' samplesizeOnePropExact(beta = 0.2, piH0 = 0.15, pi = 0.25, alpha = 0.025)
#'
#' @export
samplesizeOnePropExact <- function(beta = 0.2, piH0 = NA_real_, pi = NA_real_, alpha = 0.025, max_n_search = 1000L, window = 10L) {
    .Call(`_lrstat_samplesizeOnePropExact`, beta, piH0, pi, alpha, max_n_search, window)
}

#' @title Power for Poisson One-Sample Exact Test
#' @description Obtains the power for Poisson one-sample exact test.
#'
#' @param n The sample size.
#' @param lambdaH0 The Poisson rate under the null hypothesis.
#' @param lambda The Poisson rate under the alternative hypothesis.
#' @param D The average exposure per subject.
#' @param alpha The one-sided significance level. Defaults to 0.025.
#'
#' @return A data frame containing the critical value of the number of
#' events for rejecting the null hypothesis, the attained type I
#' error, the power for the exact test, the sample size,
#' the Poisson rates under the null and alternative hypotheses,
#' the average exposure, and the direction of the alternative.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' powerOneRateExact(n = 525, lambdaH0 = 0.049, lambda = 0.012,
#'                   D = 0.5, alpha = 0.025)
#'
#' @export
powerOneRateExact <- function(n = NA_integer_, lambdaH0 = NA_real_, lambda = NA_real_, D = 1, alpha = 0.025) {
    .Call(`_lrstat_powerOneRateExact`, n, lambdaH0, lambda, D, alpha)
}

#' @title Sample Size for Poisson One-Sample Exact Test
#' @description Obtains the sample size for Poisson one-sample exact test.
#'
#' @param beta The type II error.
#' @param lambdaH0 The Poisson rate under the null hypothesis.
#' @param lambda The Poisson rate under the alternative hypothesis.
#' @param D The average exposure per subject.
#' @param alpha The one-sided significance level. Defaults to 0.025.
#' @param max_n_search The maximum sample size to search up to. If no
#'   sample size up to this value satisfies the windowed power criterion,
#'   an error is thrown.
#' @param window The number of consecutive sample sizes that must all
#'   satisfy the power criterion to confirm the found sample size.
#'   This is to mitigate non-monotonicity of power in sample size for
#'   the exact test.
#'
#' @return A data frame containing the critical value of the number of
#' events for rejecting the null hypothesis, the attained type I
#' error, the power for the exact test, the sample size,
#' the Poisson rates under the null and alternative hypotheses,
#' the average exposure, and the direction of the alternative.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' samplesizeOneRateExact(beta = 0.2, lambdaH0 = 0.2, lambda = 0.3,
#'                        D = 1, alpha = 0.05)
#'
#' @export
samplesizeOneRateExact <- function(beta = 0.2, lambdaH0 = NA_real_, lambda = NA_real_, D = 1, alpha = 0.025, max_n_search = 1000L, window = 10L) {
    .Call(`_lrstat_samplesizeOneRateExact`, beta, lambdaH0, lambda, D, alpha, max_n_search, window)
}

#' @title Power for Fisher's Exact Test for Two Proportions
#' @description Obtains the power given sample size for Fisher's exact
#' test for two proportions.
#'
#' @param n The total sample size.
#' @param pi1 The assumed probability for the active treatment group.
#' @param pi2 The assumed probability for the control group.
#' @param allocationRatioPlanned Allocation ratio for the active treatment
#'   versus control. Defaults to 1 for equal randomization.
#' @param alpha The two-sided significance level. Defaults to 0.05.
#'
#' @return A data frame with the following variables:
#'
#' * \code{alpha}: The two-sided significance level.
#'
#' * \code{power}: The power.
#'
#' * \code{n}: The sample size.
#'
#' * \code{pi1}: The assumed probability for the active treatment group.
#'
#' * \code{pi2}: The assumed probability for the control group.
#'
#' * \code{allocationRatioPlanned}: Allocation ratio for the active
#'   treatment versus control.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @keywords internal
#'
#' @examples
#'
#' (design1 <- powerFisherExact(
#'   n = 136, pi1 = 0.25, pi2 = 0.05, alpha = 0.05))
#'
#' @export
powerFisherExact <- function(n = NA_integer_, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.05) {
    .Call(`_lrstat_powerFisherExact`, n, pi1, pi2, allocationRatioPlanned, alpha)
}

#' @title Sample Size for Fisher's Exact Test for Two Proportions
#' @description Obtains the sample size given power for Fisher's exact
#' test for two proportions.
#'
#' @param beta The type II error.
#' @param pi1 The assumed probability for the active treatment group.
#' @param pi2 The assumed probability for the control group.
#' @param allocationRatioPlanned Allocation ratio for the active treatment
#'   versus control. Defaults to 1 for equal randomization.
#' @param alpha The two-sided significance level. Defaults to 0.05.
#' @param max_n_search The maximum sample size to search up to. If no
#'   sample size up to this value satisfies the windowed power criterion,
#'   an error is thrown.
#' @param window The number of consecutive sample sizes that must all
#'   satisfy the power criterion to confirm the found sample size.
#'   This is to mitigate non-monotonicity of power in sample size for
#'   the exact test.
#'
#' @return A data frame with the following variables:
#'
#' * \code{alpha}: The two-sided significance level.
#'
#' * \code{power}: The power.
#'
#' * \code{n}: The sample size.
#'
#' * \code{pi1}: The assumed probability for the active treatment group.
#'
#' * \code{pi2}: The assumed probability for the control group.
#'
#' * \code{allocationRatioPlanned}: Allocation ratio for the active
#'   treatment versus control.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @keywords internal
#'
#' @examples
#'
#' (design1 <- samplesizeFisherExact(
#'   beta = 0.1, pi1 = 0.25, pi2 = 0.05, alpha = 0.05))
#'
#' @export
samplesizeFisherExact <- function(beta = NA_real_, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.05, max_n_search = 1000L, window = 10L) {
    .Call(`_lrstat_samplesizeFisherExact`, beta, pi1, pi2, allocationRatioPlanned, alpha, max_n_search, window)
}

#' @title Power for Exact Unconditional Test of Risk Difference
#' @description Obtains the power given sample size for exact unconditional
#' test of risk difference.
#'
#' @param n The total sample size.
#' @param riskDiffH0 The risk difference under the null hypothesis.
#'   Defaults to 0.
#' @param pi1 The assumed probability for the active treatment group.
#' @param pi2 The assumed probability for the control group.
#' @param allocationRatioPlanned Allocation ratio for the active treatment
#'   versus control. Defaults to 1 for equal randomization.
#' @param alpha The one-sided significance level. Defaults to 0.025.
#' @param calculateAttainedAlpha Whether to calculate the attained alpha.
#'
#' @return A data frame with the following variables:
#'
#' * \code{alpha}: The specified one-sided significance level.
#'
#' * \code{attainedAlpha}: The attained one-sided significance level if
#'   requested.
#'
#' * \code{power}: The power.
#'
#' * \code{n}: The sample size.
#'
#' * \code{riskDiffH0}: The risk difference under the null hypothesis.
#'
#' * \code{pi1}: The assumed probability for the active treatment group.
#'
#' * \code{pi2}: The assumed probability for the control group.
#'
#' * \code{allocationRatioPlanned}: Allocation ratio for the active
#'   treatment versus control.
#'
#' * \code{zstatRiskDiffBound}: The critical value on the scale of
#'   score test statistic for risk difference.
#'
#' * \code{pi2star}: The response probability in the control group
#'   at which the critical value of the test statistic is attained.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' powerRiskDiffExact(n = 68, pi1 = 0.6, pi2 = 0.25, alpha = 0.05)
#'
#' @export
powerRiskDiffExact <- function(n = NA_integer_, riskDiffH0 = 0, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.025, calculateAttainedAlpha = TRUE) {
    .Call(`_lrstat_powerRiskDiffExact`, n, riskDiffH0, pi1, pi2, allocationRatioPlanned, alpha, calculateAttainedAlpha)
}

#' @title Sample Size for Exact Unconditional Test of Risk Difference
#' @description Obtains the sample size given power for exact unconditional
#' test of risk difference.
#'
#' @param beta The type II error.
#' @param riskDiffH0 The risk difference under the null hypothesis.
#'   Defaults to 0.
#' @param pi1 The assumed probability for the active treatment group.
#' @param pi2 The assumed probability for the control group.
#' @param allocationRatioPlanned Allocation ratio for the active treatment
#'   versus control. Defaults to 1 for equal randomization.
#' @param alpha The one-sided significance level.
#' @param calculateAttainedAlpha Whether to calculate the attained alpha.
#' @param max_n_search The maximum sample size to search up to. If no
#'   sample size up to this value satisfies the windowed power criterion,
#'   an error is thrown.
#' @param window The number of consecutive sample sizes that must all
#'   satisfy the power criterion to confirm the found sample size.
#'   This is to mitigate non-monotonicity of power in sample size for
#'   the exact test.
#'
#' @return A data frame with the following variables:
#'
#' * \code{alpha}: The specified one-sided significance level.
#'
#' * \code{attainedAlpha}: The attained one-sided significance level.
#'
#' * \code{power}: The power.
#'
#' * \code{n}: The sample size.
#'
#' * \code{riskDiffH0}: The risk difference under the null hypothesis.
#'
#' * \code{pi1}: The assumed probability for the active treatment group.
#'
#' * \code{pi2}: The assumed probability for the control group.
#'
#' * \code{allocationRatioPlanned}: Allocation ratio for the active
#'   treatment versus control.
#'
#' * \code{zstatRiskDiffBound}: The critical value on the scale of
#'   score test statistic for risk difference.
#'
#' * \code{pi2star}: The response probability in the control group
#'   at which the critical value of the test statistic is attained.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' samplesizeRiskDiffExact(beta = 0.2, riskDiffH0 = -0.3,
#'                         pi1 = 0.8, pi2 = 0.8, alpha = 0.025)
#'
#' @export
samplesizeRiskDiffExact <- function(beta = NA_real_, riskDiffH0 = 0, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.025, calculateAttainedAlpha = TRUE, max_n_search = 1000L, window = 10L) {
    .Call(`_lrstat_samplesizeRiskDiffExact`, beta, riskDiffH0, pi1, pi2, allocationRatioPlanned, alpha, calculateAttainedAlpha, max_n_search, window)
}

#' @title Power for Exact Unconditional Test of Risk Ratio
#' @description Obtains the power given sample size for exact unconditional
#' test of risk ratio.
#'
#' @param n The total sample size.
#' @param riskRatioH0 The risk ratio under the null hypothesis.
#'   Defaults to 1.
#' @param pi1 The assumed probability for the active treatment group.
#' @param pi2 The assumed probability for the control group.
#' @param allocationRatioPlanned Allocation ratio for the active treatment
#'   versus control. Defaults to 1 for equal randomization.
#' @param alpha The one-sided significance level. Defaults to 0.025.
#' @param calculateAttainedAlpha Whether to calculate the attained alpha.
#'
#' @return A data frame with the following variables:
#'
#' * \code{alpha}: The specified one-sided significance level.
#'
#' * \code{attainedAlpha}: The attained one-sided significance level if
#'   requested.
#'
#' * \code{power}: The power.
#'
#' * \code{n}: The sample size.
#'
#' * \code{riskRatioH0}: The risk ratio under the null hypothesis.
#'
#' * \code{pi1}: The assumed probability for the active treatment group.
#'
#' * \code{pi2}: The assumed probability for the control group.
#'
#' * \code{allocationRatioPlanned}: Allocation ratio for the active
#'   treatment versus control.
#'
#' * \code{zstatRiskRatioBound}: The critical value on the scale of
#'   score test statistic for risk ratio.
#'
#' * \code{pi2star}: The response probability in the control group
#'   at which the critical value of the test statistic is attained.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' powerRiskRatioExact(n = 68, pi1 = 0.6, pi2 = 0.25, alpha = 0.05)
#'
#' @export
powerRiskRatioExact <- function(n = NA_integer_, riskRatioH0 = 1, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.025, calculateAttainedAlpha = TRUE) {
    .Call(`_lrstat_powerRiskRatioExact`, n, riskRatioH0, pi1, pi2, allocationRatioPlanned, alpha, calculateAttainedAlpha)
}

#' @title Sample Size for Exact Unconditional Test of Risk Ratio
#' @description Obtains the sample size given power for exact unconditional
#' test of risk ratio.
#'
#' @param beta The type II error.
#' @param riskRatioH0 The risk ratio under the null hypothesis.
#'   Defaults to 1.
#' @param pi1 The assumed probability for the active treatment group.
#' @param pi2 The assumed probability for the control group.
#' @param allocationRatioPlanned Allocation ratio for the active treatment
#'   versus control. Defaults to 1 for equal randomization.
#' @param alpha The one-sided significance level.
#' @param calculateAttainedAlpha Whether to calculate the attained alpha.
#' @param max_n_search The maximum sample size to search up to. If no
#'   sample size up to this value satisfies the windowed power criterion,
#'   an error is thrown.
#' @param window The number of consecutive sample sizes that must all
#'   satisfy the power criterion to confirm the found sample size.
#'   This is to mitigate non-monotonicity of power in sample size for
#'   the exact test.
#'
#' @return A data frame with the following variables:
#'
#' * \code{alpha}: The specified one-sided significance level.
#'
#' * \code{attainedAlpha}: The attained one-sided significance level.
#'
#' * \code{power}: The power.
#'
#' * \code{n}: The sample size.
#'
#' * \code{riskRatioH0}: The risk ratio under the null hypothesis.
#'
#' * \code{pi1}: The assumed probability for the active treatment group.
#'
#' * \code{pi2}: The assumed probability for the control group.
#'
#' * \code{allocationRatioPlanned}: Allocation ratio for the active
#'   treatment versus control.
#'
#' * \code{zstatRiskRatioBound}: The critical value on the scale of
#'   score test statistic for risk ratio.
#'
#' * \code{pi2star}: The response probability in the control group
#'   at which the critical value of the test statistic is attained.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' samplesizeRiskRatioExact(beta = 0.2, riskRatioH0 = 0.8,
#'                          pi1 = 0.95, pi2 = 0.95, alpha = 0.05)
#'
#' @export
samplesizeRiskRatioExact <- function(beta = NA_real_, riskRatioH0 = 1, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.025, calculateAttainedAlpha = TRUE, max_n_search = 1000L, window = 10L) {
    .Call(`_lrstat_samplesizeRiskRatioExact`, beta, riskRatioH0, pi1, pi2, allocationRatioPlanned, alpha, calculateAttainedAlpha, max_n_search, window)
}

#' @title Power for Exact Unconditional Test of Equivalence in Risk
#' Difference
#' @description Obtains the power given sample size for exact unconditional
#' test of equivalence in risk difference.
#'
#' @param n The total sample size.
#' @param riskDiffLower The lower equivalence limit of risk difference.
#' @param riskDiffUpper The upper equivalence limit of risk difference.
#' @param pi1 The assumed probability for the active treatment group.
#' @param pi2 The assumed probability for the control group.
#' @param allocationRatioPlanned Allocation ratio for the active treatment
#'   versus control. Defaults to 1 for equal randomization.
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @param calculateAttainedAlpha Whether to calculate the attained alpha.
#'
#' @return A data frame with the following variables:
#'
#' * \code{alpha}: The specified significance level for each of the two
#'   one-sided tests.
#'
#' * \code{attainedAlphaH10}: The attained significance level under H10
#'   if requested.
#'
#' * \code{attainedAlphaH20}: The attained significance level under H20
#'   if requested.
#'
#' * \code{power}: The power.
#'
#' * \code{n}: The sample size.
#'
#' * \code{riskDiffLower}: The lower equivalence limit of risk difference.
#'
#' * \code{riskDiffUpper}: The upper equivalence limit of risk difference.
#'
#' * \code{pi1}: The assumed probability for the active treatment group.
#'
#' * \code{pi2}: The assumed probability for the control group.
#'
#' * \code{riskDiff}: The risk difference.
#'
#' * \code{allocationRatioPlanned}: Allocation ratio for the active
#'   treatment versus control.
#'
#' * \code{zstatRiskDiffLower}: The efficacy boundaries on the
#'   z-test statistic scale for the one-sided null hypothesis on the
#'   lower equivalence limit.
#'
#' * \code{zstatRiskDiffUpper}: The efficacy boundaries on the
#'   z-test statistic scale for the one-sided null hypothesis on the
#'   upper equivalence limit.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' powerRiskDiffExactEquiv(
#'   n = 200, riskDiffLower = -0.2, riskDiffUpper = 0.2,
#'   pi1 = 0.775, pi2 = 0.775, alpha = 0.05)
#'
#' @export
powerRiskDiffExactEquiv <- function(n = NA_integer_, riskDiffLower = NA_real_, riskDiffUpper = NA_real_, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.05, calculateAttainedAlpha = TRUE) {
    .Call(`_lrstat_powerRiskDiffExactEquiv`, n, riskDiffLower, riskDiffUpper, pi1, pi2, allocationRatioPlanned, alpha, calculateAttainedAlpha)
}

#' @title Sample Size for Exact Unconditional Test of Equivalence in Risk
#' Difference
#' @description Obtains the sample size given power for exact unconditional
#' test of equivalence in risk difference.
#'
#' @param beta The type II error.
#' @param riskDiffLower The lower equivalence limit of risk difference.
#' @param riskDiffUpper The upper equivalence limit of risk difference.
#' @param pi1 The assumed probability for the active treatment group.
#' @param pi2 The assumed probability for the control group.
#' @param allocationRatioPlanned Allocation ratio for the active treatment
#'   versus control. Defaults to 1 for equal randomization.
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @param calculateAttainedAlpha Whether to calculate the attained alpha.
#' @param max_n_search The maximum sample size to search up to. If no
#'   sample size up to this value satisfies the windowed power criterion,
#'   an error is thrown.
#' @param window The number of consecutive sample sizes that must all
#'   satisfy the power criterion to confirm the found sample size.
#'   This is to mitigate non-monotonicity of power in sample size for
#'   the exact test.
#'
#' @return A data frame with the following variables:
#'
#' * \code{alpha}: The specified significance level for each of the two
#'   one-sided tests.
#'
#' * \code{attainedAlpha}: The attained significance level.
#'
#' * \code{power}: The power.
#'
#' * \code{n}: The sample size.
#'
#' * \code{riskDiffLower}: The lower equivalence limit of risk difference.
#'
#' * \code{riskDiffUpper}: The upper equivalence limit of risk difference.
#'
#' * \code{pi1}: The assumed probability for the active treatment group.
#'
#' * \code{pi2}: The assumed probability for the control group.
#'
#' * \code{riskDiff}: The risk difference.
#'
#' * \code{allocationRatioPlanned}: Allocation ratio for the active
#'   treatment versus control.
#'
#' * \code{zstatRiskDiffLower}: The efficacy boundaries on the
#'   z-test statistic scale for the one-sided null hypothesis on the
#'   lower equivalence limit.
#'
#' * \code{zstatRiskDiffUpper}: The efficacy boundaries on the
#'   z-test statistic scale for the one-sided null hypothesis on the
#'   upper equivalence limit.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' samplesizeRiskDiffExactEquiv(
#'   beta = 0.2, riskDiffLower = -0.3, riskDiffUpper = 0.3,
#'   pi1 = 0.9, pi2 = 0.9, alpha = 0.05)
#'
#' @export
samplesizeRiskDiffExactEquiv <- function(beta = NA_real_, riskDiffLower = NA_real_, riskDiffUpper = NA_real_, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.05, calculateAttainedAlpha = TRUE, max_n_search = 1000L, window = 10L) {
    .Call(`_lrstat_samplesizeRiskDiffExactEquiv`, beta, riskDiffLower, riskDiffUpper, pi1, pi2, allocationRatioPlanned, alpha, calculateAttainedAlpha, max_n_search, window)
}

#' @title Power for Exact Unconditional Test of Equivalence in Risk
#' Ratio
#' @description Obtains the power given sample size for exact unconditional
#' test of equivalence in risk ratio.
#'
#' @param n The total sample size.
#' @param riskRatioLower The lower equivalence limit of risk ratio.
#' @param riskRatioUpper The upper equivalence limit of risk ratio.
#' @param pi1 The assumed probability for the active treatment group.
#' @param pi2 The assumed probability for the control group.
#' @param allocationRatioPlanned Allocation ratio for the active treatment
#'   versus control. Defaults to 1 for equal randomization.
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @param calculateAttainedAlpha Whether to calculate the attained alpha.
#'
#' @return A data frame with the following variables:
#'
#' * \code{alpha}: The specified significance level for each of the two
#'   one-sided tests.
#'
#' * \code{attainedAlphaH10}: The attained significance level under H10
#'   if requested.
#'
#' * \code{attainedAlphaH20}: The attained significance level under H20
#'   if requested.
#'
#' * \code{power}: The power.
#'
#' * \code{n}: The sample size.
#'
#' * \code{riskRatioLower}: The lower equivalence limit of risk ratio.
#'
#' * \code{riskRatioUpper}: The upper equivalence limit of risk ratio.
#'
#' * \code{pi1}: The assumed probability for the active treatment group.
#'
#' * \code{pi2}: The assumed probability for the control group.
#'
#' * \code{riskRatio}: The risk ratio.
#'
#' * \code{allocationRatioPlanned}: Allocation ratio for the active
#'   treatment versus control.
#'
#' * \code{zstatRiskRatioLower}: The efficacy boundaries on the
#'   z-test statistic scale for the one-sided null hypothesis on the
#'   lower equivalence limit.
#'
#' * \code{zstatRiskRatioUpper}: The efficacy boundaries on the
#'   z-test statistic scale for the one-sided null hypothesis on the
#'   upper equivalence limit.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' powerRiskRatioExactEquiv(
#'   n = 200, riskRatioLower = 0.8, riskRatioUpper = 1.25,
#'   pi1 = 0.775, pi2 = 0.775, alpha = 0.05)
#'
#' @export
powerRiskRatioExactEquiv <- function(n = NA_integer_, riskRatioLower = NA_real_, riskRatioUpper = NA_real_, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.05, calculateAttainedAlpha = TRUE) {
    .Call(`_lrstat_powerRiskRatioExactEquiv`, n, riskRatioLower, riskRatioUpper, pi1, pi2, allocationRatioPlanned, alpha, calculateAttainedAlpha)
}

#' @title Sample Size for Exact Unconditional Test of Equivalence in Risk
#' Ratio
#' @description Obtains the sample size given power for exact unconditional
#' test of equivalence in risk ratio.
#'
#' @param beta The type II error.
#' @param riskRatioLower The lower equivalence limit of risk ratio.
#' @param riskRatioUpper The upper equivalence limit of risk ratio.
#' @param pi1 The assumed probability for the active treatment group.
#' @param pi2 The assumed probability for the control group.
#' @param allocationRatioPlanned Allocation ratio for the active treatment
#'   versus control. Defaults to 1 for equal randomization.
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @param calculateAttainedAlpha Whether to calculate the attained alpha.
#' @param max_n_search The maximum sample size to search up to. If no
#'   sample size up to this value satisfies the windowed power criterion,
#'   an error is thrown.
#' @param window The number of consecutive sample sizes that must all
#'   satisfy the power criterion to confirm the found sample size.
#'   This is to mitigate non-monotonicity of power in sample size for
#'   the exact test.
#'
#' @return A data frame with the following variables:
#'
#' * \code{alpha}: The specified significance level for each of the two
#'   one-sided tests.
#'
#' * \code{attainedAlpha}: The attained significance level.
#'
#' * \code{power}: The power.
#'
#' * \code{n}: The sample size.
#'
#' * \code{riskRatioLower}: The lower equivalence limit of risk ratio.
#'
#' * \code{riskRatioUpper}: The upper equivalence limit of risk ratio.
#'
#' * \code{pi1}: The assumed probability for the active treatment group.
#'
#' * \code{pi2}: The assumed probability for the control group.
#'
#' * \code{riskRatio}: The risk ratio.
#'
#' * \code{allocationRatioPlanned}: Allocation ratio for the active
#'   treatment versus control.
#'
#' * \code{zstatRiskRatioLower}: The efficacy boundaries on the
#'   z-test statistic scale for the one-sided null hypothesis on the
#'   lower equivalence limit.
#'
#' * \code{zstatRiskRatioUpper}: The efficacy boundaries on the
#'   z-test statistic scale for the one-sided null hypothesis on the
#'   upper equivalence limit.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' samplesizeRiskRatioExactEquiv(
#'   beta = 0.2, riskRatioLower = 0.7, riskRatioUpper = 1/0.7,
#'   pi1 = 0.95, pi2 = 0.95, alpha = 0.05)
#'
#' @export
samplesizeRiskRatioExactEquiv <- function(beta = NA_real_, riskRatioLower = NA_real_, riskRatioUpper = NA_real_, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.05, calculateAttainedAlpha = TRUE, max_n_search = 1000L, window = 10L) {
    .Call(`_lrstat_samplesizeRiskRatioExactEquiv`, beta, riskRatioLower, riskRatioUpper, pi1, pi2, allocationRatioPlanned, alpha, calculateAttainedAlpha, max_n_search, window)
}

#' @title P-Value for Exact Unconditional Test of Risk Difference
#' @description Obtains the p-value for exact unconditional
#' test of risk difference.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param riskDiffH0 The risk difference under the null hypothesis.
#'   Defaults to 0.
#' @param directionUpper Whether larger values represent better
#'   responses.
#'
#' @return A data frame containing the following variables:
#'
#' * \code{riskDiffH0}: The risk difference under the null hypothesis.
#'
#' * \code{directionUpper}: Whether larger values represent better
#'   responses.
#'
#' * \code{riskDiff}: The observed risk difference.
#'
#' * \code{zstat}: The observed value of the Z test statistic.
#'
#' * \code{pvalue}: The one-sided p-value for the unconditional exact test.
#'
#' * \code{pi2star}: The value of pi2 that yields the p-value.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' riskDiffExactPValue(riskDiffH0 = 0, directionUpper = 1,
#'                     n1 = 68, y1 = 2, n2 = 65, y2 = 1)
#'
#' @export
riskDiffExactPValue <- function(n1 = NA_integer_, y1 = NA_integer_, n2 = NA_integer_, y2 = NA_integer_, riskDiffH0 = 0, directionUpper = TRUE) {
    .Call(`_lrstat_riskDiffExactPValue`, n1, y1, n2, y2, riskDiffH0, directionUpper)
}

#' @title Exact Unconditional Confidence Interval for Risk Difference
#' @description Obtains the exact unconditional confidence interval for
#' risk difference based on the standardized score statistic.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param cilevel The confidence interval level.
#'
#' @return A data frame containing the following variables:
#'
#' * \code{scale}: The scale of treatment effect.
#'
#' * \code{estimate}: The point estimate.
#'
#' * \code{lower}: The lower limit of the confidence interval.
#'
#' * \code{upper}: The upper limit of the confidence interval.
#'
#' * \code{cilevel}: The confidence interval level.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' riskDiffExactCI(n1 = 30, y1 = 2, n2 = 30, y2 = 1, cilevel = 0.95)
#'
#' @export
riskDiffExactCI <- function(n1 = NA_integer_, y1 = NA_integer_, n2 = NA_integer_, y2 = NA_integer_, cilevel = 0.95) {
    .Call(`_lrstat_riskDiffExactCI`, n1, y1, n2, y2, cilevel)
}

#' @title P-Value for Exact Unconditional Test of Risk Ratio
#' @description Obtains the p-value for exact unconditional
#' test of risk ratio.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param riskRatioH0 The risk ratio under the null hypothesis.
#'   Defaults to 1.
#' @param directionUpper Whether larger values represent better
#'   responses.
#'
#' @return A data frame containing the following variables:
#'
#' * \code{riskRatioH0}: The risk ratio under the null hypothesis.
#'
#' * \code{directionUpper}: Whether larger values represent better
#'   responses.
#'
#' * \code{riskRatio}: The observed risk ratio.
#'
#' * \code{zstat}: The observed value of the Z test statistic.
#'
#' * \code{pvalue}: The one-sided p-value for the unconditional exact test.
#'
#' * \code{pi2star}: The value of pi2 that yields the p-value.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' riskRatioExactPValue(riskRatioH0 = 1, directionUpper = 1,
#'                      n1 = 68, y1 = 2, n2 = 65, y2 = 1)
#'
#' @export
riskRatioExactPValue <- function(n1 = NA_integer_, y1 = NA_integer_, n2 = NA_integer_, y2 = NA_integer_, riskRatioH0 = 1, directionUpper = TRUE) {
    .Call(`_lrstat_riskRatioExactPValue`, n1, y1, n2, y2, riskRatioH0, directionUpper)
}

#' @title Exact Unconditional Confidence Interval for Risk Ratio
#' @description Obtains the exact unconditional confidence interval for
#' risk ratio based on the standardized score statistic.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param cilevel The confidence interval level.
#'
#' @return A data frame containing the following variables:
#'
#' * \code{scale}: The scale of treatment effect.
#'
#' * \code{estimate}: The point estimate.
#'
#' * \code{lower}: The lower limit of the confidence interval.
#'
#' * \code{upper}: The upper limit of the confidence interval.
#'
#' * \code{cilevel}: The confidence interval level.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' riskRatioExactCI(n1 = 30, y1 = 2, n2 = 30, y2 = 1, cilevel = 0.95)
#'
#' @export
riskRatioExactCI <- function(n1 = NA_integer_, y1 = NA_integer_, n2 = NA_integer_, y2 = NA_integer_, cilevel = 0.95) {
    .Call(`_lrstat_riskRatioExactCI`, n1, y1, n2, y2, cilevel)
}

#' @title Error Spending
#' @description Obtains the error spent at given spending times
#' for the specified error spending function.
#'
#' @param t A vector of spending times, typically equal to information
#'   fractions.
#' @param error The total error to spend.
#' @param sf The spending function. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function, and
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function.
#'   Defaults to \code{"sfOF"}.
#' @param sfpar The parameter for the spending function. Corresponds to
#'   \eqn{\rho} for \code{"sfKD"} and \eqn{\gamma} for \code{"sfHSD"}.
#'
#' @details
#' This function implements a variety of error spending functions commonly
#' used in group sequential designs, assuming one-sided hypothesis testing.
#'
#' **O'Brien-Fleming-Type Spending Function**
#'
#' This spending function allocates very little alpha early on and more alpha
#' later in the trial. It is defined as:
#' \deqn{
#' \alpha(t) = 2 - 2\Phi\left(\frac{z_{\alpha/2}}{\sqrt{t}}\right),
#' }
#' where \eqn{\Phi} is the standard normal cumulative distribution function,
#' \eqn{z_{\alpha/2}} is the critical value from the standard normal
#' distribution, and \eqn{t \in [0, 1]} denotes the information fraction.
#'
#' **Pocock-Type Spending Function**
#'
#' This function spends alpha more evenly throughout the study:
#' \deqn{
#' \alpha(t) = \alpha \log(1 + (e - 1)t),
#' }
#' where \eqn{e} is Euler's number (approximately 2.718).
#'
#' **Kim and DeMets Power-Type Spending Function**
#'
#' This family of spending functions is defined as:
#' \deqn{
#' \alpha(t) = \alpha t^{\rho}, \quad \rho > 0.
#' }
#' - When \eqn{\rho = 1}, the function mimics Pocock-type boundaries.
#' - When \eqn{\rho = 3}, it approximates O’Brien-Fleming-type boundaries.
#'
#' **Hwang, Shih, and DeCani Spending Function**
#'
#' This flexible family of functions is given by:
#' \deqn{
#' \alpha(t) =
#' \begin{cases}
#' \alpha \frac{1 - e^{-\gamma t}}{1 - e^{-\gamma}}, & \text{if }
#' \gamma \ne 0 \\ \alpha t, & \text{if } \gamma = 0.
#' \end{cases}
#' }
#' - When \eqn{\gamma = -4}, the spending function resembles
#'   O’Brien-Fleming boundaries.
#' - When \eqn{\gamma = 1}, it resembles Pocock boundaries.
#'
#' @return A vector of errors spent up to the interim look.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' errorSpent(t = 0.5, error = 0.025, sf = "sfOF")
#'
#' errorSpent(t = c(0.5, 0.75, 1), error = 0.025, sf = "sfHSD", sfpar = -4)
#'
#' @export
errorSpent <- function(t, error = 0.025, sf = "sfOF", sfpar = NA_real_) {
    .Call(`_lrstat_errorSpent`, t, error, sf, sfpar)
}

#' @title Stagewise Exit Probabilities
#' @description Obtains the stagewise exit probabilities for both efficacy
#' and futility stopping.
#'
#' @param b Upper boundaries on the z-test statistic scale.
#' @param a Lower boundaries on the z-test statistic scale. Defaults to
#'   \code{c(rep(-8.0, kMax-1), b[kMax])} if left unspecified, where
#'   \code{kMax = length(b)}.
#' @param theta Stagewise parameter of interest, e.g., \code{-U/V} for
#'   weighted log-rank test, where \code{U} is the mean and \code{V} is
#'   the variance of the weighted log-rank test score statistic at each
#'   stage. For proportional hazards and conventional log-rank test, use the
#'   scalar input, \code{theta = -log(HR)}. Defaults to 0 corresponding to
#'   the null hypothesis.
#' @param I Stagewise cumulative information, e.g., \code{V}, the variance
#'   of the weighted log-rank test score statistic at each stage. For
#'   conventional log-rank test, information can be approximated by
#'   \code{phi*(1-phi)*D}, where \code{phi} is the probability of being
#'   allocated to the active arm, and \code{D} is the total number of events
#'   at each stage. Defaults to \code{seq(1, kMax)} if left unspecified.
#'
#' @return A list of stagewise exit probabilities:
#'
#' * \code{exitProbUpper}: The vector of efficacy stopping probabilities
#'
#' * \code{exitProbLower}: The vector of futility stopping probabilities.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' exitprob(b = c(3.471, 2.454, 2.004), theta = -log(0.6),
#'          I = c(50, 100, 150)/4)
#'
#' exitprob(b = c(2.963, 2.359, 2.014),
#'          a = c(-0.264, 0.599, 2.014),
#'          theta = c(0.141, 0.204, 0.289),
#'          I = c(81, 121, 160))
#'
#' @export
exitprob <- function(b, a = NA_real_, theta = 0L, I = NA_real_) {
    .Call(`_lrstat_exitprob`, b, a, theta, I)
}

#' @title Efficacy Boundaries for Group Sequential Design
#' @description Obtains the efficacy stopping boundaries for a group
#' sequential design.
#'
#' @param k Look number for the current analysis.
#' @param informationRates Information rates up to the current look. Must be
#'   increasing and less than or equal to 1.
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param spendingTime A vector of length \code{k} for the error spending
#'   time at each analysis. Must be increasing and less than or equal to 1.
#'   Defaults to missing, in which case, it is the same as
#'   \code{informationRates}.
#' @inheritParams param_efficacyStopping
#'
#' @details
#' If \code{typeAlphaSpending} is \code{"OF"}, \code{"P"}, \code{"WT"}, or
#' \code{"none"}, then \code{informationRates}, \code{efficacyStopping},
#' and \code{spendingTime} must be of full length \code{kMax}, and
#' \code{informationRates} and \code{spendingTime} must end with 1.
#'
#' @return A numeric vector of critical values up to the current look.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' getBound(k = 2, informationRates = c(0.5,1),
#'          alpha = 0.025, typeAlphaSpending = "sfOF")
#'
#' @export
getBound <- function(k = NA_integer_, informationRates = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, spendingTime = NA_real_, efficacyStopping = NA_integer_) {
    .Call(`_lrstat_getBound`, k, informationRates, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, spendingTime, efficacyStopping)
}

#' @title Power and Sample Size for a Generic Group Sequential Design
#' @description Obtains the maximum information and stopping boundaries
#' for a generic group sequential design assuming a constant treatment
#' effect, or obtains the power given the maximum information and
#' stopping boundaries.
#'
#' @param beta The type II error.
#' @param IMax The maximum information. Either \code{beta} or \code{IMax}
#'   should be provided while the other one should be missing.
#' @param theta The parameter value. Null hypothesis is at \code{theta = 0},
#'   and the alternative hypothesis is one-sided for \code{theta > 0}.
#' @inheritParams param_kMax
#' @param informationRates The information rates. Fixed prior to the trial.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP The futility bounds on the conditional power scale.
#' @param futilityTheta The futility bounds on the parameter scale.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param varianceRatio The ratio of the variance under H0 to the
#'   variance under H1.
#'
#' @details
#' The function determines efficacy and futility bounds based on the inputs
#' provided, following a clear priority order.
#'
#' \strong{Efficacy bounds:}
#' If \code{criticalValues} are supplied, they take precedence and all
#' alpha-spending parameters are ignored. Otherwise, efficacy bounds are
#' derived from the specified alpha-spending function.
#'
#' \strong{Futility bounds:}
#' Futility inputs are evaluated in the following order of priority:
#' \enumerate{
#'   \item If \code{futilityBounds} are provided, they override all other
#'   futility-related inputs (\code{futilityCP}, \code{futilityTheta},
#'   and beta-spending parameters).
#'
#'   \item If \code{futilityBounds} are not provided but \code{futilityCP}
#'   is specified, then \code{futilityTheta} and beta-spending parameters
#'   are ignored.
#'
#'   \item If only \code{futilityTheta} is provided, beta-spending parameters
#'   are ignored.
#'
#'   \item If none of \code{futilityBounds}, \code{futilityCP},
#'   or \code{futilityTheta} are specified, futility bounds are computed
#'   using the beta-spending approach.
#' }
#'
#' @return An S3 class \code{design} object with three components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{attainedAlpha}: The attained significance level, which is
#'       different from the overall significance level in the presence of
#'       futility stopping.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{theta}: The parameter value.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedInformationH1}: The expected information under H1.
#'
#'     - \code{expectedInformationH0}: The expected information under H0.
#'
#'     - \code{drift}: The drift parameter, equal to
#'       \code{theta*sqrt(information)}.
#'
#'     - \code{inflationFactor}: The inflation factor (relative to the
#'       fixed design).
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale.
#'
#'     - \code{futilityBounds}: The futility boundaries on the Z-scale.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{futilityPerStage}: The probability for futility stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeFutility}: The cumulative probability for futility
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha spent.
#'
#'     - \code{efficacyTheta}: The efficacy boundaries on the parameter
#'       scale.
#'
#'     - \code{futilityTheta}: The futility boundaries on the parameter
#'       scale.
#'
#'     - \code{efficacyP}: The efficacy boundaries on the p-value scale.
#'
#'     - \code{futilityP}: The futility boundaries on the p-value scale.
#'
#'     - \code{information}: The cumulative information.
#'
#'     - \code{efficacyStopping}: Whether to allow efficacy stopping.
#'
#'     - \code{futilityStopping}: Whether to allow futility stopping.
#'
#'     - \code{rejectPerStageH0}: The probability for efficacy stopping
#'       under H0.
#'
#'     - \code{futilityPerStageH0}: The probability for futility stopping
#'       under H0.
#'
#'     - \code{cumulativeRejectionH0}: The cumulative probability for
#'       efficacy stopping under H0.
#'
#'     - \code{cumulativeFutilityH0}: The cumulative probability for
#'       futility stopping under H0.
#'
#' * \code{settings}: A list containing the following input parameters:
#'
#'     - \code{typeAlphaSpending}: The type of alpha spending.
#'
#'     - \code{parameterAlphaSpending}: The parameter value for alpha
#'       spending.
#'
#'     - \code{userAlphaSpending}: The user defined alpha spending.
#'
#'     - \code{typeBetaSpending}: The type of beta spending.
#'
#'     - \code{parameterBetaSpending}: The parameter value for beta
#'       spending.
#'
#'     - \code{userBetaSpending}: The user defined beta spending.
#'
#'     - \code{spendingTime}: The error spending time at each analysis.
#'
#'     - \code{varianceRatio}: The ratio of the variance under H0
#'       to the variance under H1.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Christopher Jennison, Bruce W. Turnbull.
#' Group Sequential Methods with Applications to Clinical Trials.
#' Chapman & Hall/CRC: Boca Raton, 2000, ISBN:0849303168
#'
#' @examples
#'
#' # Example 1: obtain the maximum information given power
#' (design1 <- getDesign(
#'   beta = 0.2, theta = -log(0.7),
#'   kMax = 2, informationRates = c(0.5,1),
#'   alpha = 0.025, typeAlphaSpending = "sfOF",
#'   typeBetaSpending = "sfP"))
#'
#' # Example 2: obtain power given the maximum information
#' (design2 <- getDesign(
#'   IMax = 72.5, theta = -log(0.7),
#'   kMax = 3, informationRates = c(0.5, 0.75, 1),
#'   alpha = 0.025, typeAlphaSpending = "sfOF",
#'   typeBetaSpending = "sfP"))
#'
#' @export
getDesign <- function(beta = NA_real_, IMax = NA_real_, theta = NA_real_, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityTheta = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, spendingTime = NA_real_, varianceRatio = 1) {
    .Call(`_lrstat_getDesign`, beta, IMax, theta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityTheta, typeBetaSpending, parameterBetaSpending, userBetaSpending, spendingTime, varianceRatio)
}

#' @title Power and Sample Size for a Generic Group Sequential Equivalence
#' Design
#'
#' @description Obtains the maximum information and stopping boundaries
#' for a generic group sequential equivalence design assuming a constant
#' treatment effect, or obtains the power given the maximum information
#' and stopping boundaries.
#'
#' @param beta The type II error.
#' @param IMax The maximum information. Either \code{beta} or \code{IMax}
#'   should be provided while the other one should be missing.
#' @param thetaLower The parameter value at the lower equivalence limit.
#' @param thetaUpper The parameter value at the upper equivalence limit.
#' @param theta The parameter value under the alternative hypothesis.
#' @inheritParams param_kMax
#' @param informationRates The information rates. Fixed prior to the trial.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_criticalValues
#' @param alpha The significance level for each of the two one-sided
#'   tests, e.g., 0.05.
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#'
#' @details
#' Consider the equivalence design with two one-sided hypotheses:
#' \deqn{H_{10}: \theta \leq \theta_{10},}
#' \deqn{H_{20}: \theta \geq \theta_{20}.}
#' We reject \eqn{H_{10}} at or before look \eqn{k} if
#' \deqn{Z_{1j} = (\hat{\theta}_j - \theta_{10})\sqrt{I_j}
#' \geq b_j}
#' for some \eqn{j=1,\ldots,k}, where \eqn{\{b_j:j=1,\ldots,K\}} are the
#' critical values associated with the specified alpha-spending function,
#' and \eqn{I_j} is the information for \eqn{\theta} (inverse variance of
#' \eqn{\hat{\theta}}) at the
#' \eqn{j}th look. For example,
#' for estimating the risk difference \eqn{\theta = \pi_1 - \pi_2},
#' \deqn{I_j = \left\{\frac{\pi_1 (1-\pi_1)}{n_{1j}} +
#' \frac{\pi_2(1-\pi_2)}{n_{2j}}\right\}^{-1}.}
#' It follows that
#' \deqn{(Z_{1j} \geq b_j) = (Z_j \geq b_j +
#' \theta_{10}\sqrt{I_j}),}
#' where \eqn{Z_j = \hat{\theta}_j \sqrt{I_j}}.
#'
#' Similarly, we reject \eqn{H_{20}} at or before look \eqn{k} if
#' \deqn{Z_{2j} = (\hat{\theta}_j - \theta_{20})\sqrt{I_j}
#' \leq -b_j} for some \eqn{j=1,\ldots,k}. We have
#' \deqn{(Z_{2j} \leq -b_j) = (Z_j \leq - b_j +
#' \theta_{20}\sqrt{I_j}).}
#'
#' Let \eqn{l_j = b_j + \theta_{10}\sqrt{I_j}},
#' and \eqn{u_j = -b_j + \theta_{20}\sqrt{I_j}}.
#' The cumulative probability to reject \eqn{H_0 = H_{10} \cup H_{20}} at
#' or before look \eqn{k} under the alternative hypothesis \eqn{H_1} is
#' given by
#' \deqn{P_\theta\left(\cup_{j=1}^{k} (Z_{1j} \geq b_j) \cap
#' \cup_{j=1}^{k} (Z_{2j} \leq -b_j)\right) = p_1 + p_2 - p_{12},}
#' where
#' \deqn{p_1 = P_\theta\left(\cup_{j=1}^{k} (Z_{1j} \geq b_j)\right)
#' = P_\theta\left(\cup_{j=1}^{k} (Z_j \geq l_j)\right),}
#' \deqn{p_2 = P_\theta\left(\cup_{j=1}^{k} (Z_{2j} \leq -b_j)\right)
#' = P_\theta\left(\cup_{j=1}^{k} (Z_j \leq u_j)\right),}
#' and
#' \deqn{p_{12} = P_\theta\left(\cup_{j=1}^{k} (Z_j \geq l_j) \cup
#' (Z_j \leq u_j)\right).}
#' Of note, both \eqn{p_1} and \eqn{p_2} can be evaluated using
#' one-sided exit probabilities for group sequential designs.
#' If there exists \eqn{j\leq k} such that \eqn{l_j \leq u_j}, then
#' \eqn{p_{12} = 1}. Otherwise, \eqn{p_{12}} can be evaluated using
#' two-sided exit probabilities for group sequential designs.
#'
#' Since the equivalent hypothesis is tested using two one-sided tests,
#' the type I error is controlled. To evaluate the attained type I error
#' of the equivalence trial under \eqn{H_{10}} (or \eqn{H_{20}}),
#' we simply fix the control group parameters, update the active
#' treatment group parameters according to the null hypothesis, and
#' use the parameters in the power calculation outlined above.
#'
#' @return An S3 class \code{designEquiv} object with three components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{attainedAlphaH10}: The attained significance level under H10.
#'
#'     - \code{attainedAlphaH20}: The attained significance level under H20.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{thetaLower}: The parameter value at the lower equivalence
#'       limit.
#'
#'     - \code{thetaUpper}: The parameter value at the upper equivalence
#'       limit.
#'
#'     - \code{theta}: The parameter value under the alternative hypothesis.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedInformationH1}: The expected information under H1.
#'
#'     - \code{expectedInformationH10}: The expected information under H10.
#'
#'     - \code{expectedInformationH20}: The expected information under H20.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale for
#'       each of the two one-sided tests.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha for each of
#'       the two one-sided tests.
#'
#'     - \code{cumulativeAttainedAlphaH10}: The cumulative probability for
#'       efficacy stopping under H10.
#'
#'     - \code{cumulativeAttainedAlphaH20}: The cumulative probability for
#'       efficacy stopping under H20.
#'
#'     - \code{efficacyThetaLower}: The efficacy boundaries on the
#'       parameter scale for the one-sided null hypothesis at the
#'       lower equivalence limit.
#'
#'     - \code{efficacyThetaUpper}: The efficacy boundaries on the
#'       parameter scale for the one-sided null hypothesis at the
#'       upper equivalence limit.
#'
#'     - \code{efficacyP}: The efficacy bounds on the p-value scale for
#'       each of the two one-sided tests.
#'
#'     - \code{information}: The cumulative information.
#'
#' * \code{settings}: A list containing the following components:
#'
#'     - \code{typeAlphaSpending}: The type of alpha spending.
#'
#'     - \code{parameterAlphaSpending}: The parameter value for alpha
#'       spending.
#'
#'     - \code{userAlphaSpending}: The user defined alpha spending.
#'
#'     - \code{spendingTime}: The error spending time at each analysis.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' # Example 1: obtain the maximum information given power
#' (design1 <- getDesignEquiv(
#'   beta = 0.2, thetaLower = log(0.8), thetaUpper = log(1.25),
#'   kMax = 2, informationRates = c(0.5, 1),
#'   alpha = 0.05, typeAlphaSpending = "sfOF"))
#'
#'
#' # Example 2: obtain power given the maximum information
#' (design2 <- getDesignEquiv(
#'   IMax = 72.5, thetaLower = log(0.7), thetaUpper = -log(0.7),
#'   kMax = 3, informationRates = c(0.5, 0.75, 1),
#'   alpha = 0.05, typeAlphaSpending = "sfOF"))
#'
#' @export
getDesignEquiv <- function(beta = NA_real_, IMax = NA_real_, thetaLower = NA_real_, thetaUpper = NA_real_, theta = 0, kMax = 1L, informationRates = NA_real_, criticalValues = NULL, alpha = 0.05, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, spendingTime = NA_real_) {
    .Call(`_lrstat_getDesignEquiv`, beta, IMax, thetaLower, thetaUpper, theta, kMax, informationRates, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, spendingTime)
}

#' @title Adaptive Design at an Interim Look
#' @description
#' Calculates the conditional power for specified incremental
#' information, given the interim results, parameter value,
#' data-dependent changes in the error spending function, and
#' the number and spacing of interim looks. Conversely,
#' calculates the incremental information required to attain
#' a specified conditional power, given the interim results,
#' parameter value, data-dependent changes in the error
#' spending function, and the number and spacing of interim looks.
#'
#' @param betaNew The type II error for the secondary trial.
#' @param INew The maximum information of the secondary trial. Either
#'   \code{betaNew} or \code{INew} should be provided, while the other
#'   must be missing.
#' @param L The interim adaptation look of the primary trial.
#' @param zL The z-test statistic at the interim adaptation look of
#'   the primary trial.
#' @param theta The assumed parameter value.
#' @param IMax The maximum information of the primary trial. Must be provided.
#' @param kMax The maximum number of stages of the primary trial.
#' @param informationRates The information rates of the primary trial.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage of the primary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param futilityStopping Indicators of whether futility stopping is
#'   allowed at each stage of the primary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param criticalValues The upper boundaries on the z-test statistic scale
#'   for efficacy stopping for the primary trial. If missing, boundaries
#'   will be computed based on the specified alpha spending function.
#' @param alpha The significance level of the primary trial.
#'   Defaults to 0.025.
#' @param typeAlphaSpending The type of alpha spending for the primary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function,
#'   \code{"user"} for user defined spending, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param userAlphaSpending The user-defined alpha spending for the
#'   primary trial. Represents the cumulative alpha spent up to each stage.
#' @param futilityBounds The lower boundaries on the z-test statistic scale
#'   for futility stopping for the primary trial. Defaults to
#'   \code{rep(-8, kMax-1)} if left unspecified.
#' @param futilityCP The conditional power-based futility bounds for the
#'   primary trial.
#' @param futilityTheta The parameter value-based futility bounds for the
#'   primary trial.
#' @param spendingTime The error spending time of the primary trial.
#'   Defaults to missing, in which case it is assumed to be the same as
#'   \code{informationRates}.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @param kNew The number of looks of the secondary trial.
#' @param informationRatesNew The spacing of looks of the secondary trial.
#' @param efficacyStoppingNew The indicators of whether efficacy stopping is
#'   allowed at each look of the secondary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param futilityStoppingNew The indicators of whether futility stopping is
#'   allowed at each look of the secondary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param typeAlphaSpendingNew The type of alpha spending for the secondary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param futilityBoundsInt The futility boundaries on the z statistic
#'   scale for new stages of the integrated trial.
#' @param futilityCPInt The conditional power-based futility bounds for
#'   new stages of the integrated trial.
#' @param futilityThetaInt The parameter value-based futility bounds for the
#'   new stages of the integrated trial.
#' @param typeBetaSpendingNew The type of beta spending for the secondary
#'   trial. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function,
#'   \code{"user"} for user defined spending, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @param parameterBetaSpendingNew The parameter value of beta spending
#'   for the secondary trial. Corresponds to \eqn{\rho} for \code{"sfKD"},
#'   and \eqn{\gamma} for \code{"sfHSD"}.
#' @param userBetaSpendingNew The user-defined cumulative beta spending.
#'   Represents the cumulative beta spent up to each stage of the
#'   secondary trial.
#' @param spendingTimeNew The error spending time of the secondary trial.
#'   Defaults to missing, in which case it is assumed to be the same as
#'   \code{informationRatesNew}.
#' @param varianceRatio The ratio of the variance under H0 to the
#'   variance under H1.
#'
#' @return An \code{adaptDesign} object with three list components:
#'
#' * \code{primaryTrial}: A list of selected information for the primary
#'   trial, including \code{L}, \code{zL}, \code{theta},
#'   \code{maxInformation}, \code{kMax},
#'   \code{informationRates}, \code{efficacyBounds}, \code{futilityBounds},
#'   \code{information}, \code{alpha}, \code{conditionalAlpha},
#'   \code{conditionalPower}, \code{predictivePower}, and
#'   and \code{MullerSchafer}.
#'
#' * \code{secondaryTrial}: A list of selected information for the secondary
#'   trial, including \code{overallReject}, \code{alpha}, \code{kMax},
#'   \code{maxInformation}, \code{informationRates}, \code{efficacyBounds},
#'   \code{futilityBounds}, \code{cumulativeRejection},
#'   \code{cumulativeFutility}, \code{cumulativeAlphaSpent},
#'   \code{information}, \code{typeAlphaSpending},
#'   \code{parameterAlphaSpending}, \code{typeBetaSpending},
#'   \code{parameterBetaSpending}, \code{userBetaSpending}, and
#'   \code{spendingTime}.
#'
#' * \code{integratedTrial}: A list of selected information for the integrated
#'   trial, including \code{L}, \code{zL}, \code{theta}, \code{maxInformation},
#'   \code{kMax}, \code{informationRates}, \code{efficacyBounds},
#'   \code{futilityBounds}, and \code{information}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Lu Chi, H. M. James Hung, and Sue-Jane Wang.
#' Modification of sample size in group sequential clinical trials.
#' Biometrics 1999;55:853-857.
#'
#' Hans-Helge Muller and Helmut Schafer.
#' Adaptive group sequential designs for clinical trials:
#' Combining the advantages of adaptive and of
#' classical group sequential approaches.
#' Biometrics 2001;57:886-891.
#'
#' @seealso \code{\link{getDesign}}
#'
#' @examples
#'
#' # two-arm randomized clinical trial with a normally distributed endpoint
#' # 90% power to detect mean difference of 15 with a standard deviation of 50
#' # Design the Stage I Trial with 3 looks and Lan-DeMets O'Brien-Fleming type
#' # spending function
#' delta <- 15
#' sigma <- 50
#'
#' (des1 <- getDesignMeanDiff(
#'   beta = 0.1, meanDiff = delta, stDev = sigma,
#'   kMax = 3, alpha = 0.025, typeAlphaSpending = "sfOF"
#' ))
#'
#' s1 <- des1$byStageResults$informationRates
#' b1 <- des1$byStageResults$efficacyBounds
#' n <- des1$overallResults$numberOfSubjects
#'
#' # Monitoring the Stage I Trial
#' L <- 1
#' nL <- des1$byStageResults$numberOfSubjects[L]
#' deltahat <- 8
#' sigmahat <- 55
#' sedeltahat <- sigmahat * sqrt( 4 / nL)
#' zL <- deltahat / sedeltahat
#'
#' # Making an Adaptive Change: Stage I to Stage II
#' # revised clinically meaningful difference downward to 10 power the study
#' # retain the standard deviation at the design stage
#' # Muller & Schafer (2001) method to design the secondary trial
#' # with 2 looks and Lan-DeMets Pocock type spending function
#' # re-estimate sample size to reach 90% conditional power
#' deltaNew <- 10
#'
#' (des2 <- adaptDesign(
#'   betaNew = 0.1, L = L, zL = zL, theta = deltaNew,
#'   IMax = n / (4 * sigma^2), kMax = 3, informationRates = s1,
#'   alpha = 0.025, typeAlphaSpending = "sfOF",
#'   MullerSchafer = TRUE, kNew = 2, typeAlphaSpendingNew = "sfP"
#' ))
#'
#' INew <- des2$maxInformation
#' (nNew <- ceiling(INew * 4 * sigma^2))
#' (nTotal <- nL + nNew)
#'
#' @export
adaptDesign <- function(betaNew = NA_real_, INew = NA_real_, L = NA_integer_, zL = NA_real_, theta = NA_real_, IMax = NA_real_, kMax = NA_integer_, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityTheta = NULL, spendingTime = NA_real_, MullerSchafer = FALSE, kNew = NA_integer_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, futilityStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, futilityBoundsInt = NULL, futilityCPInt = NULL, futilityThetaInt = NULL, typeBetaSpendingNew = "none", parameterBetaSpendingNew = NA_real_, userBetaSpendingNew = NA_real_, spendingTimeNew = NA_real_, varianceRatio = 1.0) {
    .Call(`_lrstat_adaptDesign`, betaNew, INew, L, zL, theta, IMax, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityTheta, spendingTime, MullerSchafer, kNew, informationRatesNew, efficacyStoppingNew, futilityStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, futilityBoundsInt, futilityCPInt, futilityThetaInt, typeBetaSpendingNew, parameterBetaSpendingNew, userBetaSpendingNew, spendingTimeNew, varianceRatio)
}

#' @title Stratified Difference in Milestone Survival Probabilities
#' @description Obtains the stratified milestone survival probabilities
#' and difference in milestone survival probabilities at given
#' calendar times.
#'
#' @param time A vector of calendar times for data cut.
#' @param milestone The milestone time at which to calculate the
#'   survival probability.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#'
#' @return A data frame containing the following variables:
#'
#' * \code{time}: The calendar time since trial start.
#'
#' * \code{subjects}: The number of enrolled subjects.
#'
#' * \code{nevents}: The total number of events.
#'
#' * \code{nevents1}: The number of events in the active treatment group.
#'
#' * \code{nevents2}: The number of events in the control group.
#'
#' * \code{ndropouts}: The total number of dropouts.
#'
#' * \code{ndropouts1}: The number of dropouts in the active treatment
#'   group.
#'
#' * \code{ndropouts2}: The number of dropouts in the control group.
#'
#' * \code{milestone}: The milestone time relative to randomization.
#'
#' * \code{nmilestone}: The total number of subjects reaching milestone.
#'
#' * \code{nmilestone1}: The number of subjects reaching milestone
#'   in the active treatment group.
#'
#' * \code{nmiletone2}: The number of subjects reaching milestone
#'   in the control group.
#'
#' * \code{surv1}: The milestone survival probability for the treatment
#'   group.
#'
#' * \code{surv2}: The milestone survival probability for the control group.
#'
#' * \code{survDiff}: The difference in milestone survival probabilities,
#'   i.e., \code{surv1 - surv2}.
#'
#' * \code{vsurv1}: The variance for \code{surv1}.
#'
#' * \code{vsurv2}: The variance for \code{surv2}.
#'
#' * \code{vsurvDiff}: The variance for \code{survDiff}.
#'
#' * \code{information}: The information for \code{survDiff}, equal to
#'   \code{1/vsurvDiff}.
#'
#' * \code{survDiffZ}: The Z-statistic value, i.e.,
#'   \code{survDiff/sqrt(vsurvDiff)}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#'
#' kmstat(time = c(22, 40),
#'        milestone = 18,
#'        allocationRatioPlanned = 1,
#'        accrualTime = seq(0, 8),
#'        accrualIntensity = 26/9*seq(1, 9),
#'        piecewiseSurvivalTime = c(0, 6),
#'        stratumFraction = c(0.2, 0.8),
#'        lambda1 = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'        lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'        gamma1 = -log(1-0.05)/12,
#'        gamma2 = -log(1-0.05)/12,
#'        accrualDuration = 22,
#'        followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
kmstat <- function(time = NA_real_, milestone = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE) {
    .Call(`_lrstat_kmstat`, time, milestone, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup)
}

#' @title Power for Difference in Milestone Survival Probabilities
#' @description Estimates the power for testing the difference in
#' milestone survival probabilities in a two-sample survival design.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilitySurvDiff A vector of length \code{kMax - 1} for the
#'   futility bounds on the milestone survival difference scale.
#' @param typeBetaSpending The type of beta spending. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @inheritParams param_parameterBetaSpending
#' @param milestone The milestone time at which to calculate the survival
#'   probability.
#' @param survDiffH0 The difference in milestone survival probabilities
#'   under the null hypothesis. Defaults to 0 for superiority test.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#'
#' @return An S3 class \code{kmpower} object with 4 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numberOfDropouts}: The total number of dropouts.
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{numberOfMilestone}: The total number of subjects reaching
#'       milestone.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfDropouts}: The expected number of dropouts.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedNumberOfMilestone}: The expected number of subjects
#'       reaching milestone.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up duration.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{milestone}: The milestone time relative to randomization.
#'
#'     - \code{survDiffH0}: The difference in milestone survival
#'       probabilities under the null hypothesis.
#'
#'     - \code{surv1}: The milestone survival probability for the
#'       treatment group.
#'
#'     - \code{surv2}: The milestone survival probability for the
#'       control group.
#'
#'     - \code{survDiff}: The difference in milestone survival
#'       probabilities, equal to \code{surv1 - surv2}.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale.
#'
#'     - \code{futilityBounds}: The futility boundaries on the Z-scale.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{futilityPerStage}: The probability for futility stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeFutility}: The cumulative probability for futility
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha spent.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{numberOfMilestone}: The number of subjects reaching
#'       milestone.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacySurvDiff}: The efficacy boundaries on the survival
#'       difference scale.
#'
#'     - \code{futilitySurvDiff}: The futility boundaries on the survival
#'       difference scale.
#'
#'     - \code{efficacyP}: The efficacy boundaries on the p-value scale.
#'
#'     - \code{futilityP}: The futility boundaries on the p-value scale.
#'
#'     - \code{information}: The cumulative information.
#'
#'     - \code{efficacyStopping}: Whether to allow efficacy stopping.
#'
#'     - \code{futilityStopping}: Whether to allow futility stopping.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{typeBetaSpending},
#'   \code{parameterBetaSpending}, \code{allocationRatioPlanned},
#'   \code{accrualTime}, \code{accuralIntensity},
#'   \code{piecewiseSurvivalTime}, \code{stratumFraction},
#'   \code{lambda1}, \code{lambda2}, \code{gamma1}, \code{gamma2},
#'   and \code{spendingTime}.
#'
#' * \code{byTreatmentCounts}: A list containing the following counts by
#'   treatment group:
#'
#'     - \code{numberOfEvents1}: The number of events by stage for
#'       the treatment group.
#'
#'     - \code{numberOfDropouts1}: The number of dropouts by stage for
#'       the treatment group.
#'
#'     - \code{numberOfSubjects1}: The number of subjects by stage for
#'       the treatment group.
#'
#'     - \code{numberOfMilestone1}: The number of subjects reaching
#'       milestone by stage for the active treatment group.
#'
#'     - \code{numberOfEvents2}: The number of events by stage for
#'       the control group.
#'
#'     - \code{numberOfDropouts2}: The number of dropouts by stage for
#'       the control group.
#'
#'     - \code{numberOfSubjects2}: The number of subjects by stage for
#'       the control group.
#'
#'     - \code{numberOfMilestone2}: The number of subjects reaching
#'       milestone by stage for the control group.
#'
#'     - \code{expectedNumberOfEvents1}: The expected number of events for
#'       the treatment group.
#'
#'     - \code{expectedNumberOfDropouts1}: The expected number of dropouts
#'       for the active treatment group.
#'
#'     - \code{expectedNumberOfSubjects1}: The expected number of subjects
#'       for the active treatment group.
#'
#'     - \code{expectedNumberOfMilestone1}: The expected number of subjects
#'       reaching milestone for the active treatment group.
#'
#'     - \code{expectedNumberOfEvents2}: The expected number of events for
#'       control group.
#'
#'     - \code{expectedNumberOfDropouts2}: The expected number of dropouts
#'       for the control group.
#'
#'     - \code{expectedNumberOfSubjects2}: The expected number of subjects
#'       for the control group.
#'
#'     - \code{expectedNumberOfMilestone2}: The expected number of subjects
#'       reaching milestone for the control group.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survival, and 5% dropout by
#' # the end of 1 year.
#'
#' kmpower(kMax = 2, informationRates = c(0.8, 1),
#'         alpha = 0.025, typeAlphaSpending = "sfOF",
#'         milestone = 18,
#'         allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'         accrualIntensity = 26/9*seq(1, 9),
#'         piecewiseSurvivalTime = c(0, 6),
#'         stratumFraction = c(0.2, 0.8),
#'         lambda1 = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'         lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'         gamma1 = -log(1-0.05)/12,
#'         gamma2 = -log(1-0.05)/12, accrualDuration = 22,
#'         followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
kmpower <- function(kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilitySurvDiff = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, milestone = NA_real_, survDiffH0 = 0, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_kmpower`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilitySurvDiff, typeBetaSpending, parameterBetaSpending, milestone, survDiffH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, studyDuration)
}

#' @title Sample Size for Difference in Milestone Survival Probabilities
#' @description Obtains the needed accrual duration given power,
#' accrual intensity, and follow-up time, the needed follow-up time
#' given power, accrual intensity, and accrual duration, or the needed
#' absolute accrual intensity given power, relative accrual intensity,
#' accrual duration, and follow-up time in a two-group survival design.
#'
#' @param beta Type II error. Defaults to 0.2.
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilitySurvDiff A vector of length \code{kMax - 1} for the
#'   futility bounds on the milestone survival difference scale.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @param milestone The milestone time at which to calculate the survival
#'   probability.
#' @param survDiffH0 The difference in milestone survival probabilities
#'   under the null hypothesis. Defaults to 0 for superiority test.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size.
#'   Defaults to 1 for sample size rounding.
#'
#' @return A list of two components:
#'
#' * \code{resultsUnderH1}: An S3 class \code{kmpower} object under the
#'   alternative hypothesis.
#'
#' * \code{resultsUnderH0}: An S3 class \code{kmpower} object under the
#'   null hypothesis.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{kmpower}}
#'
#' @examples
#' # Example 1: Obtains follow-up time given power, accrual intensity,
#' # and accrual duration for variable follow-up. Of note, the power
#' # reaches the maximum when the follow-up time equals milestone.
#'
#' kmsamplesize(beta = 0.25, kMax = 2, informationRates = c(0.8, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              milestone = 18,
#'              allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'              accrualIntensity = 26/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              stratumFraction = c(0.2, 0.8),
#'              lambda1 = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'              lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12, accrualDuration = 22,
#'              followupTime = NA, fixedFollowup = FALSE)
#'
#' # Example 2: Obtains accrual intensity given power, accrual duration, and
#' # follow-up time for variable follow-up
#'
#' kmsamplesize(beta = 0.2, kMax = 2, informationRates = c(0.8, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              milestone = 18,
#'              allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'              accrualIntensity = 26/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              stratumFraction = c(0.2, 0.8),
#'              lambda1 = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'              lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12, accrualDuration = 22,
#'              followupTime = 18, fixedFollowup = FALSE)
#'
#'
#' # Example 3: Obtains accrual duration given power, accrual intensity, and
#' # follow-up time for fixed follow-up
#'
#' kmsamplesize(beta = 0.2, kMax = 2, informationRates = c(0.8, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              milestone = 18,
#'              allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'              accrualIntensity = 26/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              stratumFraction = c(0.2, 0.8),
#'              lambda1 = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'              lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12, accrualDuration = NA,
#'              followupTime = 18, fixedFollowup = TRUE)
#'
#' @export
kmsamplesize <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilitySurvDiff = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, milestone = NA_real_, survDiffH0 = 0, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, rounding = TRUE) {
    .Call(`_lrstat_kmsamplesize`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilitySurvDiff, typeBetaSpending, parameterBetaSpending, userBetaSpending, milestone, survDiffH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, rounding)
}

#' @title Power for One-Sample Milestone Survival Probability
#' @description Estimates the power, stopping probabilities, and expected
#' sample size in a one-group survival design.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilitySurv A vector of length \code{kMax - 1} for the
#'   futility bounds on the milestone survival scale.
#' @param typeBetaSpending The type of beta spending. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no  early futility stopping.
#'   Defaults to \code{"none"}.
#' @inheritParams param_parameterBetaSpending
#' @param milestone The milestone time at which to calculate the survival
#'   probability.
#' @param survH0 The milestone survival probability under the null
#'   hypothesis.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param lambda A vector of hazard rates for the event in each analysis
#'  time interval by stratum under the alternative hypothesis.
#' @param gamma The hazard rate for exponential dropout or a vector of
#'   hazard rates for piecewise exponential dropout. Defaults to 0 for
#'   no dropout.
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#'
#' @return An S3 class \code{kmpower1s} object with 3 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{numberOfMilestone}: The total number of subjects reaching
#'       milestone.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedNumberOfMilestone}: The expected number of subjects
#'       reaching milestone.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up duration.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{milestone}: The milestone time to calculate the survival
#'       probability.
#'
#'     - \code{survH0}: The milestone survival probability under the null
#'       hypothesis.
#'
#'     - \code{surv}: The milestone survival probability under the
#'       alternative hypothesis.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale.
#'
#'     - \code{futilityBounds}: The futility boundaries on the Z-scale.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{futilityPerStage}: The probability for futility stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeFutility}: The cumulative probability for futility
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha spent.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{numberOfMilestone}: The number of subjects reaching
#'       milestone.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacySurv}: The efficacy boundaries on the milestone
#'       survival probability scale.
#'
#'     - \code{futilitySurv}: The futility boundaries on the milestone
#'       survival probability scale.
#'
#'     - \code{efficacyP}: The efficacy boundaries on the p-value scale.
#'
#'     - \code{futilityP}: The futility boundaries on the p-value scale.
#'
#'     - \code{information}: The cumulative information.
#'
#'     - \code{efficacyStopping}: Whether to allow efficacy stopping.
#'
#'     - \code{futilityStopping}: Whether to allow futility stopping.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{typeBetaSpending},
#'   \code{parameterBetaSpending}, \code{accrualTime},
#'   \code{accuralIntensity}, \code{piecewiseSurvivalTime},
#'   \code{stratumFraction}, \code{lambda}, \code{gamma},
#'   and \code{spendingTime}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{kmstat}}
#'
#' @examples
#'
#' kmpower1s(kMax = 2, informationRates = c(0.8, 1),
#'           alpha = 0.025, typeAlphaSpending = "sfOF",
#'           milestone = 18, survH0 = 0.30,
#'           accrualTime = seq(0, 8),
#'           accrualIntensity = 26/9*seq(1, 9),
#'           piecewiseSurvivalTime = c(0, 6),
#'           stratumFraction = c(0.2, 0.8),
#'           lambda = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'           gamma = -log(1-0.05)/12, accrualDuration = 22,
#'           followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
#'
kmpower1s <- function(kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilitySurv = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, milestone = NA_real_, survH0 = NA_real_, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda = NA_real_, gamma = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_kmpower1s`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilitySurv, typeBetaSpending, parameterBetaSpending, milestone, survH0, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda, gamma, accrualDuration, followupTime, fixedFollowup, spendingTime, studyDuration)
}

#' @title Sample Size for One-Sample Milestone Survival Probability
#' @description Obtains the needed accrual duration given power and
#' follow-up time, the needed follow-up time given power and
#' accrual duration, or the needed absolute accrual rates given
#' power, accrual duration, follow-up duration, and relative accrual
#' rates in a one-group survival design.
#'
#' @param beta Type II error. Defaults to 0.2.
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilitySurv A vector of length \code{kMax - 1} for the
#'   futility bounds on the milestone survival scale.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @param milestone The milestone time at which to calculate the survival
#'   probability.
#' @param survH0 The milestone survival probability under the null
#'   hypothesis.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param lambda A vector of hazard rates for the event in each analysis
#'  time interval by stratum under the alternative hypothesis.
#' @param gamma The hazard rate for exponential dropout or a vector of
#'   hazard rates for piecewise exponential dropout. Defaults to 0 for
#'   no dropout.
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size.
#'   Defaults to 1 for sample size rounding.
#'
#' @return A list of two components:
#'
#' * \code{resultsUnderH1}: An S3 class \code{kmpower1s} object under the
#'   alternative hypothesis.
#'
#' * \code{resultsUnderH0}: An S3 class \code{kmpower1s} object under the
#'   null hypothesis.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{kmpower1s}}
#'
#' @examples
#' # Example 1: Obtains follow-up duration given power, accrual intensity,
#' # and accrual duration for variable follow-up
#'
#' kmsamplesize1s(beta = 0.2, kMax = 2,
#'                informationRates = c(0.8, 1),
#'                alpha = 0.025, typeAlphaSpending = "sfOF",
#'                milestone = 18, survH0 = 0.30,
#'                accrualTime = seq(0, 8),
#'                accrualIntensity = 26/9*seq(1, 9),
#'                piecewiseSurvivalTime = c(0, 6),
#'                stratumFraction = c(0.2, 0.8),
#'                lambda = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'                gamma = -log(1-0.05)/12, accrualDuration = 22,
#'                followupTime = NA, fixedFollowup = FALSE)
#'
#' # Example 2: Obtains accrual intensity given power, accrual duration, and
#' # follow-up duration for variable follow-up
#'
#' kmsamplesize1s(beta = 0.2, kMax = 2,
#'                informationRates = c(0.8, 1),
#'                alpha = 0.025, typeAlphaSpending = "sfOF",
#'                milestone = 18, survH0 = 0.30,
#'                accrualTime = seq(0, 8),
#'                accrualIntensity = 26/9*seq(1, 9),
#'                piecewiseSurvivalTime = c(0, 6),
#'                stratumFraction = c(0.2, 0.8),
#'                lambda = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'                gamma = -log(1-0.05)/12, accrualDuration = 22,
#'                followupTime = 18, fixedFollowup = FALSE)
#'
#'
#' # Example 3: Obtains accrual duration given power, accrual intensity, and
#' # follow-up duration for fixed follow-up
#'
#' kmsamplesize1s(beta = 0.2, kMax = 2,
#'                informationRates = c(0.8, 1),
#'                alpha = 0.025, typeAlphaSpending = "sfOF",
#'                milestone = 18, survH0 = 0.30,
#'                accrualTime = seq(0, 8),
#'                accrualIntensity = 26/9*seq(1, 9),
#'                piecewiseSurvivalTime = c(0, 6),
#'                stratumFraction = c(0.2, 0.8),
#'                lambda = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'                gamma = -log(1-0.05)/12, accrualDuration = NA,
#'                followupTime = 18, fixedFollowup = TRUE)
#'
#' @export
kmsamplesize1s <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilitySurv = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, milestone = NA_real_, survH0 = NA_real_, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda = NA_real_, gamma = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, rounding = TRUE) {
    .Call(`_lrstat_kmsamplesize1s`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilitySurv, typeBetaSpending, parameterBetaSpending, userBetaSpending, milestone, survH0, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda, gamma, accrualDuration, followupTime, fixedFollowup, spendingTime, rounding)
}

#' @title Power for Equivalence in Milestone Survival Probability Difference
#' @description Obtains the power for equivalence in milestone survival
#' probability difference.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_criticalValues
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param milestone The milestone time at which to calculate the survival
#'   probability.
#' @param survDiffLower The lower equivalence limit of milestone survival
#'   probability difference.
#' @param survDiffUpper The upper equivalence limit of milestone survival
#'   probability difference.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#'
#' @return An S3 class \code{kmpowerequiv} object with 4 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numberOfSubjects}: The total number of subjects.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{milestone}: The milestone time relative to randomization.
#'
#'     - \code{survDiffLower}: The lower equivalence limit of milestone
#'       survival probability difference.
#'
#'     - \code{survDiffUpper}: The upper equivalence limit of milestone
#'       survival probability difference.
#'
#'     - \code{surv1}: The milestone survival probability for the
#'       treatment group.
#'
#'     - \code{surv2}: The milestone survival probability for the
#'       control group.
#'
#'     - \code{survDiff}: The milestone survival probability difference.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up duration.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale for
#'       each of the two one-sided tests.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha for each of
#'       the two one-sided tests.
#'
#'     - \code{cumulativeAttainedAlphaH10}: The cumulative alpha attained
#'       under \code{H10}.
#'
#'     - \code{cumulativeAttainedAlphaH20}: The cumulative alpha attained
#'       under \code{H20}.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{numberOfMilestone}: The number of subjects reaching
#'       milestone.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacySurvDiffLower}: The efficacy boundaries on the
#'       milestone survival probability difference scale for the one-sided
#'       null hypothesis at the lower equivalence limit.
#'
#'     - \code{efficacySurvDiffUpper}: The efficacy boundaries on the
#'       milestone survival probability difference scale for the one-sided
#'       null hypothesis at the upper equivalence limit.
#'
#'     - \code{efficacyP}: The efficacy bounds on the p-value scale for
#'       each of the two one-sided tests.
#'
#'     - \code{information}: The cumulative information.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{allocationRatioPlanned},
#'   \code{accrualTime}, \code{accuralIntensity},
#'   \code{piecewiseSurvivalTime}, \code{stratumFraction},
#'   \code{lambda1}, \code{lambda2}, \code{gamma1}, \code{gamma2},
#'   and \code{spendingTime}.
#'
#' * \code{byTreatmentCounts}: A list containing the following counts by
#'   treatment group:
#'
#'     - \code{numberOfEvents1}: The number of events by stage for
#'       the treatment group.
#'
#'     - \code{numberOfDropouts1}: The number of dropouts by stage for
#'       the treatment group.
#'
#'     - \code{numberOfSubjects1}: The number of subjects by stage for
#'       the treatment group.
#'
#'     - \code{numberOfMilestone1}: The number of subjects reaching
#'       milestone by stage for the active treatment group.
#'
#'     - \code{numberOfEvents2}: The number of events by stage for
#'       the control group.
#'
#'     - \code{numberOfDropouts2}: The number of dropouts by stage for
#'       the control group.
#'
#'     - \code{numberOfSubjects2}: The number of subjects by stage for
#'       the control group.
#'
#'     - \code{numberOfMilestone2}: The number of subjects reaching
#'       milestone by stage for the control group.
#'
#'     - \code{expectedNumberOfEvents1}: The expected number of events for
#'       the treatment group.
#'
#'     - \code{expectedNumberOfDropouts1}: The expected number of dropouts
#'       for the active treatment group.
#'
#'     - \code{expectedNumberOfSubjects1}: The expected number of subjects
#'       for the active treatment group.
#'
#'     - \code{expectedNumberOfMilestone1}: The expected number of subjects
#'       reaching milestone for the active treatment group.
#'
#'     - \code{expectedNumberOfEvents2}: The expected number of events for
#'       control group.
#'
#'     - \code{expectedNumberOfDropouts2}: The expected number of dropouts
#'       for the control group.
#'
#'     - \code{expectedNumberOfSubjects2}: The expected number of subjects
#'       for the control group.
#'
#'     - \code{expectedNumberOfMilestone2}: The expected number of subjects
#'       reaching milestone for the control group.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{kmstat}}
#'
#' @examples
#'
#' kmpowerequiv(kMax = 2, informationRates = c(0.5, 1),
#'              alpha = 0.05, typeAlphaSpending = "sfOF",
#'              milestone = 18,
#'              survDiffLower = -0.13, survDiffUpper = 0.13,
#'              allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'              accrualIntensity = 26/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              stratumFraction = c(0.2, 0.8),
#'              lambda1 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'              lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12, accrualDuration = 22,
#'              followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
kmpowerequiv <- function(kMax = 1L, informationRates = NA_real_, criticalValues = NA_real_, alpha = 0.05, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, milestone = NA_real_, survDiffLower = NA_real_, survDiffUpper = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_kmpowerequiv`, kMax, informationRates, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, milestone, survDiffLower, survDiffUpper, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, studyDuration)
}

#' @title Sample Size for Equivalence in Milestone Survival Probability
#' Difference
#' @description Obtains the sample size for equivalence in milestone
#' survival probability difference.
#'
#' @param beta The type II error.
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_criticalValues
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param milestone The milestone time at which to calculate the survival
#'   probability.
#' @param survDiffLower The lower equivalence limit of milestone survival
#'   probability difference.
#' @param survDiffUpper The upper equivalence limit of milestone survival
#'   probability difference.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size.
#'   Defaults to 1 for sample size rounding.
#'
#' @return An S3 class \code{kmpowerequiv} object
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{kmpowerequiv}}
#'
#' @examples
#'
#' kmsamplesizeequiv(beta = 0.1, kMax = 2, informationRates = c(0.5, 1),
#'                   alpha = 0.05, typeAlphaSpending = "sfOF",
#'                   milestone = 18,
#'                   survDiffLower = -0.13, survDiffUpper = 0.13,
#'                   allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'                   accrualIntensity = 26/9*seq(1, 9),
#'                   piecewiseSurvivalTime = c(0, 6),
#'                   stratumFraction = c(0.2, 0.8),
#'                   lambda1 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'                   lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'                   gamma1 = -log(1-0.05)/12,
#'                   gamma2 = -log(1-0.05)/12, accrualDuration = NA,
#'                   followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
kmsamplesizeequiv <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, criticalValues = NULL, alpha = 0.05, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, milestone = NA_real_, survDiffLower = NA_real_, survDiffUpper = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = 0L, spendingTime = NA_real_, rounding = 1L) {
    .Call(`_lrstat_kmsamplesizeequiv`, beta, kMax, informationRates, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, milestone, survDiffLower, survDiffUpper, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, rounding)
}

logisregRcpp <- function(data, event, covariates, freq, weight, offset, id, link, init, robust, firth, flic, plci, alpha, maxiter, eps) {
    .Call(`_lrstat_logisregRcpp`, data, event, covariates, freq, weight, offset, id, link, init, robust, firth, flic, plci, alpha, maxiter, eps)
}

lrsimRcpp <- function(kMax = 1L, informationRates = NA_real_, criticalValues = NA_real_, futilityBounds = NA_real_, hazardRatioH0 = 1, allocation1 = 1L, allocation2 = 1L, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, n = NA_integer_, followupTime = NA_real_, fixedFollowup = FALSE, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = 0L) {
    .Call(`_lrstat_lrsimRcpp`, kMax, informationRates, criticalValues, futilityBounds, hazardRatioH0, allocation1, allocation2, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, n, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

lrsim3aRcpp <- function(kMax = 1L, hazardRatioH013 = 1, hazardRatioH023 = 1, hazardRatioH012 = 1, allocation1 = 1L, allocation2 = 1L, allocation3 = 1L, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, lambda3 = NA_real_, gamma1 = 0L, gamma2 = 0L, gamma3 = 0L, n = NA_integer_, followupTime = NA_real_, fixedFollowup = FALSE, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = 0L) {
    .Call(`_lrstat_lrsim3aRcpp`, kMax, hazardRatioH013, hazardRatioH023, hazardRatioH012, allocation1, allocation2, allocation3, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, lambda3, gamma1, gamma2, gamma3, n, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

lrsim2eRcpp <- function(kMax = 1L, kMaxpfs = 1L, hazardRatioH0pfs = 1, hazardRatioH0os = 1, allocation1 = 1L, allocation2 = 1L, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, rho_pd_os = 0, lambda1pfs = NA_real_, lambda2pfs = NA_real_, lambda1os = NA_real_, lambda2os = NA_real_, gamma1pfs = 0L, gamma2pfs = 0L, gamma1os = 0L, gamma2os = 0L, n = NA_integer_, followupTime = NA_real_, fixedFollowup = FALSE, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = 0L) {
    .Call(`_lrstat_lrsim2eRcpp`, kMax, kMaxpfs, hazardRatioH0pfs, hazardRatioH0os, allocation1, allocation2, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, rho_pd_os, lambda1pfs, lambda2pfs, lambda1os, lambda2os, gamma1pfs, gamma2pfs, gamma1os, gamma2os, n, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

lrsim2e3aRcpp <- function(kMax = 1L, kMaxpfs = 1L, hazardRatioH013pfs = 1, hazardRatioH023pfs = 1, hazardRatioH012pfs = 1, hazardRatioH013os = 1, hazardRatioH023os = 1, hazardRatioH012os = 1, allocation1 = 1L, allocation2 = 1L, allocation3 = 1L, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, rho_pd_os = 0, lambda1pfs = NA_real_, lambda2pfs = NA_real_, lambda3pfs = NA_real_, lambda1os = NA_real_, lambda2os = NA_real_, lambda3os = NA_real_, gamma1pfs = 0L, gamma2pfs = 0L, gamma3pfs = 0L, gamma1os = 0L, gamma2os = 0L, gamma3os = 0L, n = NA_integer_, followupTime = NA_real_, fixedFollowup = FALSE, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = 0L) {
    .Call(`_lrstat_lrsim2e3aRcpp`, kMax, kMaxpfs, hazardRatioH013pfs, hazardRatioH023pfs, hazardRatioH012pfs, hazardRatioH013os, hazardRatioH023os, hazardRatioH012os, allocation1, allocation2, allocation3, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, rho_pd_os, lambda1pfs, lambda2pfs, lambda3pfs, lambda1os, lambda2os, lambda3os, gamma1pfs, gamma2pfs, gamma3pfs, gamma1os, gamma2os, gamma3os, n, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

lrsimsubRcpp <- function(kMax = 1L, kMaxitt = 1L, hazardRatioH0itt = 1, hazardRatioH0pos = 1, hazardRatioH0neg = 1, allocation1 = 1L, allocation2 = 1L, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, p_pos = NA_real_, lambda1itt = NA_real_, lambda2itt = NA_real_, lambda1pos = NA_real_, lambda2pos = NA_real_, gamma1itt = 0L, gamma2itt = 0L, gamma1pos = 0L, gamma2pos = 0L, n = NA_integer_, followupTime = NA_real_, fixedFollowup = FALSE, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = 0L) {
    .Call(`_lrstat_lrsimsubRcpp`, kMax, kMaxitt, hazardRatioH0itt, hazardRatioH0pos, hazardRatioH0neg, allocation1, allocation2, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, p_pos, lambda1itt, lambda2itt, lambda1pos, lambda2pos, gamma1itt, gamma2itt, gamma1pos, gamma2pos, n, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

binary_tte_simRcpp <- function(kMax1 = 1L, kMax2 = 1L, riskDiffH0 = 0, hazardRatioH0 = 1, allocation1 = 1L, allocation2 = 1L, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, globalOddsRatio = 1, pi1 = NA_real_, pi2 = NA_real_, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, delta1 = 0L, delta2 = 0L, upper1 = NA_real_, upper2 = NA_real_, n = NA_integer_, plannedTime = NA_real_, plannedEvents = NA_integer_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = 0L) {
    .Call(`_lrstat_binary_tte_simRcpp`, kMax1, kMax2, riskDiffH0, hazardRatioH0, allocation1, allocation2, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, globalOddsRatio, pi1, pi2, lambda1, lambda2, gamma1, gamma2, delta1, delta2, upper1, upper2, n, plannedTime, plannedEvents, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

lrsim_mams_Rcpp <- function(M = 2L, kMax = 1L, criticalValues = NULL, futilityBounds = NULL, hazardRatioH0s = 1L, allocations = 1L, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambdas = NULL, gammas = NULL, n = NA_integer_, followupTime = NA_real_, fixedFollowup = FALSE, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = 0L) {
    .Call(`_lrstat_lrsim_mams_Rcpp`, M, kMax, criticalValues, futilityBounds, hazardRatioH0s, allocations, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambdas, gammas, n, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

lrsim_seamless_Rcpp <- function(M = 2L, K = 1L, criticalValues = NA_real_, futilityBounds = NULL, hazardRatioH0s = 1L, allocations = 1L, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambdas = NULL, gammas = NULL, n = NA_integer_, followupTime = NA_real_, fixedFollowup = FALSE, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = 0L) {
    .Call(`_lrstat_lrsim_seamless_Rcpp`, M, K, criticalValues, futilityBounds, hazardRatioH0s, allocations, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambdas, gammas, n, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

#' @title Kaplan-Meier Survival Probability Based on Pooled Sample
#' @description Obtains the limit of Kaplan-Meier estimate of the survival
#' probabilities based on the pooled sample.
#'
#' @param time A vector of analysis times at which to calculate the
#'   Kaplan-Meier Survival Probability.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda1
#' @inheritParams param_lambda2
#' @inheritParams param_gamma1
#' @inheritParams param_gamma2
#'
#' @return A vector of Kaplan-Meier survival probabilities at the
#' specified analysis times for piecewise exponential survival and
#' dropout distributions.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise exponential survivals, and 5% dropout by the end of
#' # 1 year.
#'
#' kmsurv(t = c(2, 8), allocationRatioPlanned = 1,
#'        piecewiseSurvivalTime = c(0, 6),
#'        lambda1 = c(0.0533, 0.0309), lambda2 = c(0.0533, 0.0533),
#'        gamma1 = -log(1-0.05)/12, gamma2 = -log(1-0.05)/12)
#'
#' @export
kmsurv <- function(time = NA_real_, allocationRatioPlanned = 1, piecewiseSurvivalTime = 0L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L) {
    .Call(`_lrstat_kmsurv`, time, allocationRatioPlanned, piecewiseSurvivalTime, lambda1, lambda2, gamma1, gamma2)
}

#' @title Number of Subjects Having an Event and Log-Rank Statistics
#' @description Obtains the number of subjects accrued, number of events,
#' number of dropouts, and number of subjects reaching the maximum
#' follow-up in each group, mean and variance of weighted log-rank
#' score statistic, estimated hazard ratio from weighted Cox regression
#' and variance of log hazard ratio estimate at given calendar times.
#'
#' @param time A vector of calendar times at which to calculate the number
#'   of events and the mean and variance of log-rank test score statistic.
#' @inheritParams param_hazardRatioH0
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @inheritParams param_rho1
#' @inheritParams param_rho2
#' @param predictTarget The target of prediction.
#'   Set \code{predictTarget = 1} to predict the number of events only.
#'   Set \code{predictTarget = 2} (default) to predict the number of events
#'   and log-rank score statistic mean and variance.
#'   Set \code{predictTarget = 3} to predict the number of events,
#'   log-rank score statistic mean and variance, and
#'   hazard ratio and variance of log hazard ratio.
#'
#' @return A data frame containing the following variables if
#' \code{predictTarget = 1}:
#'
#' * \code{time}: The analysis time since trial start.
#'
#' * \code{subjects}: The number of enrolled subjects.
#'
#' * \code{nevents}: The total number of events.
#'
#' * \code{nevents1}: The number of events in the active treatment group.
#'
#' * \code{nevents2}: The number of events in the control group.
#'
#' * \code{ndropouts}: The total number of dropouts.
#'
#' * \code{ndropouts1}: The number of dropouts in the active treatment
#'   group.
#'
#' * \code{ndropouts2}: The number of dropouts in the control group.
#'
#' * \code{nfmax}: The total number of subjects reaching maximum follow-up.
#'
#' * \code{nfmax1}: The number of subjects reaching maximum follow-up in
#'   the active treatment group.
#'
#' * \code{nfmax2}: The number of subjects reaching maximum follow-up in
#'   the control group.
#'
#' If \code{predictTarget = 2}, the following variables will also
#' be included:
#'
#' * \code{uscore}: The numerator of the log-rank test statistic.
#'
#' * \code{vscore}: The variance of the log-rank score test statistic.
#'
#' * \code{logRankZ}: The log-rank test statistic on the Z-scale.
#'
#' * \code{hazardRatioH0}: The hazard ratio under the null hypothesis.
#'
#' Furthermore, if \code{predictTarget = 3}, the following additional
#' variables will also be included:
#'
#' * \code{HR}: The average hazard ratio from weighted Cox regression.
#'
#' * \code{vlogHR}: The variance of log hazard ratio.
#'
#' * \code{zlogHR}: The Z-statistic for log hazard ratio.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#'
#' lrstat(time = c(22, 40), allocationRatioPlanned = 1,
#'        accrualTime = seq(0, 8),
#'        accrualIntensity = 26/9*seq(1, 9),
#'        piecewiseSurvivalTime = c(0, 6),
#'        lambda1 = c(0.0533, 0.0309),
#'        lambda2 = c(0.0533, 0.0533),
#'        gamma1 = -log(1-0.05)/12,
#'        gamma2 = -log(1-0.05)/12,
#'        accrualDuration = 22,
#'        followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
lrstat <- function(time = NA_real_, hazardRatioH0 = 1, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, rho1 = 0, rho2 = 0, predictTarget = 2L) {
    .Call(`_lrstat_lrstat`, time, hazardRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, rho1, rho2, predictTarget)
}

#' @title Calendar Times for Target Number of Events
#' @description Obtains the calendar times needed to reach the target
#' number of subjects experiencing an event.
#'
#' @param nevents A vector of target number of events.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#'
#' @return A vector of calendar times expected to yield the target
#' number of events.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#'
#' caltime(nevents = c(24, 80), allocationRatioPlanned = 1,
#'         accrualTime = seq(0, 8),
#'         accrualIntensity = 26/9*seq(1, 9),
#'         piecewiseSurvivalTime = c(0, 6),
#'         lambda1 = c(0.0533, 0.0309),
#'         lambda2 = c(0.0533, 0.0533),
#'         gamma1 = -log(1-0.05)/12,
#'         gamma2 = -log(1-0.05)/12,
#'         accrualDuration = 22,
#'         followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
caltime <- function(nevents = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE) {
    .Call(`_lrstat_caltime`, nevents, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup)
}

#' @title Range of Accrual Duration for Target Number of Events
#' @description Obtains a range of accrual duration to reach the
#' target number of events.
#'
#' @param nevents The target number of events.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @param followupTime Follow-up time for the last enrolled subjects.
#'   Must be provided for fixed follow-up design.
#' @inheritParams param_fixedFollowup
#' @param npoints The number of accrual duration time points.
#'   Defaults to 23.
#'
#' @return A data frame of the following variables:
#'
#' * \code{nevents}: The target number of events.
#'
#' * \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#' * \code{accrualDuration}: The accrual duration.
#'
#' * \code{subjects}: The total number of subjects.
#'
#' * \code{followupTime}: The follow-up time for the last enrolled subject.
#'
#' * \code{studyDuration}: The study duration.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#'
#' getDurationFromNevents(
#'   nevents = 80, allocationRatioPlanned = 1,
#'   accrualTime = seq(0, 8),
#'   accrualIntensity = 26/9*seq(1, 9),
#'   piecewiseSurvivalTime = c(0, 6),
#'   lambda1 = c(0.0533, 0.0309),
#'   lambda2 = c(0.0533, 0.0533),
#'   gamma1 = -log(1-0.05)/12,
#'   gamma2 = -log(1-0.05)/12,
#'   fixedFollowup = FALSE)
#'
#' @export
getDurationFromNevents <- function(nevents = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, followupTime = NA_real_, fixedFollowup = FALSE, npoints = 23L) {
    .Call(`_lrstat_getDurationFromNevents`, nevents, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, followupTime, fixedFollowup, npoints)
}

#' @title Log-Rank Test Power
#' @description Estimates the power, stopping probabilities, and expected
#' sample size in a two-group survival design.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates in terms of number
#'   of events for the conventional log-rank test and in terms of
#'   the actual information for weighted log-rank tests.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityHR A vector of length \code{kMax - 1} for the
#'   futility bounds on the hazard ratio scale.
#' @param typeBetaSpending The type of beta spending. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_hazardRatioH0
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @inheritParams param_rho1
#' @inheritParams param_rho2
#' @inheritParams param_typeOfComputation
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#'
#' @return An S3 class \code{lrpower} object with 4 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numberOfDropouts}: The total number of dropouts.
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfDropouts}: The expected number of dropouts.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up time.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#'     - \code{rho1}: The first parameter of the Fleming-Harrington family
#'       of weighted log-rank test.
#'
#'     - \code{rho2}: The second parameter of the Fleming-Harrington family
#'       of weighted log-rank test.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{hazardRatioH0}: The hazard ratio under the null hypothesis.
#'
#'     - \code{typeOfComputation}: The type of computation,
#'       either "direct" for the direct approximation method,
#'       or "schoenfeld" for the Schoenfeld method.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale.
#'
#'     - \code{futilityBounds}: The futility boundaries on the Z-scale.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{futilityPerStage}: The probability for futility stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeFutility}: The cumulative probability for futility
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha spent.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacyHR}: The efficacy boundaries on the hazard ratio
#'       scale.
#'
#'     - \code{futilityHR}: The futility boundaries on the hazard ratio
#'       scale.
#'
#'     - \code{efficacyP}: The efficacy boundaries on the p-value scale.
#'
#'     - \code{futilityP}: The futility boundaries on the p-value scale.
#'
#'     - \code{information}: The cumulative information.
#'
#'     - \code{HR}: The average hazard ratio.
#'
#'     - \code{efficacyStopping}: Whether to allow efficacy stopping.
#'
#'     - \code{futilityStopping}: Whether to allow futility stopping.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{typeBetaSpending},
#'   \code{parameterBetaSpending}, \code{allocationRatioPlanned},
#'   \code{accrualTime}, \code{accuralIntensity},
#'   \code{piecewiseSurvivalTime}, \code{stratumFraction},
#'   \code{lambda1}, \code{lambda2}, \code{gamma1}, \code{gamma2},
#'   and \code{spendingTime}.
#'
#' * \code{byTreatmentCounts}: A list containing the following counts by
#'   treatment group:
#'
#'     - \code{numberOfEvents1}: The number of events by stage for
#'       the treatment group.
#'
#'     - \code{numberOfDropouts1}: The number of dropouts by stage for
#'       the treatment group.
#'
#'     - \code{numberOfSubjects1}: The number of subjects by stage for
#'       the treatment group.
#'
#'     - \code{numberOfEvents2}: The number of events by stage for
#'       the control group.
#'
#'     - \code{numberOfDropouts2}: The number of dropouts by stage for
#'       the control group.
#'
#'     - \code{numberOfSubjects2}: The number of subjects by stage for
#'       the control group.
#'
#'     - \code{expectedNumberOfEvents1}: The expected number of events for
#'       the treatment group.
#'
#'     - \code{expectedNumberOfDropouts1}: The expected number of dropouts
#'       for the treatment group.
#'
#'     - \code{expectedNumberOfSubjects1}: The expected number of subjects
#'       for the treatment group.
#'
#'     - \code{expectedNumberOfEvents2}: The expected number of events for
#'       control group.
#'
#'     - \code{expectedNumberOfDropouts2}: The expected number of dropouts
#'       for the control group.
#'
#'     - \code{expectedNumberOfSubjects2}: The expected number of subjects
#'       for the control group.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survival, and 5% dropout by
#' # the end of 1 year.
#'
#' lrpower(kMax = 2, informationRates = c(0.8, 1),
#'         alpha = 0.025, typeAlphaSpending = "sfOF",
#'         allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'         accrualIntensity = 26/9*seq(1, 9),
#'         piecewiseSurvivalTime = c(0, 6),
#'         lambda1 = c(0.0533, 0.0309),
#'         lambda2 = c(0.0533, 0.0533),
#'         gamma1 = -log(1-0.05)/12,
#'         gamma2 = -log(1-0.05)/12, accrualDuration = 22,
#'         followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
lrpower <- function(kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityHR = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, hazardRatioH0 = 1, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, rho1 = 0, rho2 = 0, typeOfComputation = "", spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_lrpower`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityHR, typeBetaSpending, parameterBetaSpending, hazardRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, rho1, rho2, typeOfComputation, spendingTime, studyDuration)
}

#' @title Required Number of Events Given Hazard Ratio
#' @description Obtains the required number of events given the hazard
#' ratios under the null and alternative hypotheses for a group
#' sequential design.
#'
#' @param beta Type II error. Defaults to 0.2.
#' @inheritParams param_kMax
#' @inheritParams param_informationRates
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityHR A vector of length \code{kMax - 1} for the futility
#'   bounds on the hazard ratio scale.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @inheritParams param_hazardRatioH0
#' @param hazardRatio Hazard ratio under the alternative hypothesis
#'   for the active treatment versus control.
#' @inheritParams param_allocationRatioPlanned
#' @param rounding Whether to round up the number of events.
#'   Defaults to 1 for rounding.
#'
#' @return The required number of events.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' getNeventsFromHazardRatio(
#'   beta = 0.2, kMax = 2,
#'   informationRates = c(0.5,1),
#'   alpha = 0.025, typeAlphaSpending = "sfOF",
#'   typeBetaSpending = "sfP",
#'   hazardRatio = 0.673)
#'
#' @export
getNeventsFromHazardRatio <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityHR = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, spendingTime = NA_real_, hazardRatioH0 = 1, hazardRatio = NA_real_, allocationRatioPlanned = 1, rounding = TRUE) {
    .Call(`_lrstat_getNeventsFromHazardRatio`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityHR, typeBetaSpending, parameterBetaSpending, userBetaSpending, spendingTime, hazardRatioH0, hazardRatio, allocationRatioPlanned, rounding)
}

#' @title Log-Rank Test Sample Size
#' @description Obtains the needed accrual duration given power and
#' follow-up time, the needed follow-up time given power and
#' accrual duration, or the needed absolute accrual rates given
#' power, accrual duration, follow-up time, and relative accrual
#' rates in a two-group survival design.
#'
#' @param beta Type II error. Defaults to 0.2.
#' @inheritParams param_kMax
#' @param informationRates The information rates in terms of number
#'   of events for the conventional log-rank test and in terms of
#'   the actual information for weighted log-rank tests.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityHR A vector of length \code{kMax - 1} for the
#'   futility bounds on the hazard ratio scale.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @inheritParams param_hazardRatioH0
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @inheritParams param_rho1
#' @inheritParams param_rho2
#' @inheritParams param_typeOfComputation
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size and events.
#'   Defaults to 1 for sample size rounding.
#'
#' @return A list of two components:
#'
#' * \code{resultsUnderH1}: An S3 class \code{lrpower} object under the
#' alternative hypothesis.
#'
#' * \code{resultsUnderH0}: An S3 class \code{lrpower} object under the
#' null hypothesis.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{lrpower}}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survival, and 5% dropout by
#' # the end of 1 year.
#'
#' # Example 1: Obtains accrual duration given power and follow-up time
#'
#' lrsamplesize(beta = 0.2, kMax = 2,
#'              informationRates = c(0.8, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              accrualTime = seq(0, 8),
#'              accrualIntensity = 26/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              lambda1 = c(0.0533, 0.0309),
#'              lambda2 = c(0.0533, 0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12,
#'              accrualDuration = NA,
#'              followupTime = 18, fixedFollowup = FALSE)
#'
#'
#' # Example 2: Obtains follow-up time given power and accrual duration
#'
#' lrsamplesize(beta = 0.2, kMax = 2,
#'              informationRates = c(0.8, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              accrualTime = seq(0, 8),
#'              accrualIntensity = 26/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              lambda1 = c(0.0533, 0.0309),
#'              lambda2 = c(0.0533, 0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12,
#'              accrualDuration = 22,
#'              followupTime = NA, fixedFollowup = FALSE)
#'
#'
#' # Example 3: Obtains absolute accrual intensity given power,
#' # accrual duration, follow-up time, and relative accrual intensity
#'
#' lrsamplesize(beta = 0.2, kMax = 2,
#'              informationRates = c(0.8, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              accrualTime = seq(0, 8),
#'              accrualIntensity = 26/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              lambda1 = c(0.0533, 0.0309),
#'              lambda2 = c(0.0533, 0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12,
#'              accrualDuration = 22,
#'              followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
lrsamplesize <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityHR = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, hazardRatioH0 = 1, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, rho1 = 0, rho2 = 0, typeOfComputation = "", spendingTime = NA_real_, rounding = TRUE) {
    .Call(`_lrstat_lrsamplesize`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityHR, typeBetaSpending, parameterBetaSpending, userBetaSpending, hazardRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, rho1, rho2, typeOfComputation, spendingTime, rounding)
}

#' @title Power for Equivalence in Hazard Ratio
#' @description Obtains the power for equivalence in hazard ratio.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_criticalValues
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param hazardRatioLower The lower equivalence limit of hazard ratio.
#' @param hazardRatioUpper The upper equivalence limit of hazard ratio.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @inheritParams param_typeOfComputation
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#'
#' @return An S3 class \code{lrpowerequiv} object with 4 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numberOfDropouts}: The total number of dropouts.
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfDropouts}: The expected number of dropouts.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{hazardRatioLower}: The lower equivalence limit of hazard
#'       ratio.
#'
#'     - \code{hazardRatioUpper}: The upper equivalence limit of hazard
#'       ratio.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up time.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale for
#'       each of the two one-sided tests.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha for each of
#'       the two one-sided tests.
#'
#'     - \code{cumulativeAttainedAlphaH10}: The cumulative alpha attained
#'       under \code{H10}.
#'
#'     - \code{cumulativeAttainedAlphaH20}: The cumulative alpha attained
#'       under \code{H20}.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacyHRLower}: The efficacy boundaries on the
#'       hazard ratio scale for the one-sided null hypothesis
#'       at the lower equivalence limit.
#'
#'     - \code{efficacyHRUpper}: The efficacy boundaries on the
#'       hazard ratio scale for the one-sided null hypothesis
#'       at the upper equivalence limit.
#'
#'     - \code{efficacyP}: The efficacy bounds on the p-value scale for
#'       each of the two one-sided tests.
#'
#'     - \code{information}: The cumulative information.
#'
#'     - \code{HR}: The average hazard ratio.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{allocationRatioPlanned},
#'   \code{accrualTime}, \code{accuralIntensity},
#'   \code{piecewiseSurvivalTime}, \code{stratumFraction},
#'   \code{lambda1}, \code{lambda2}, \code{gamma1}, \code{gamma2},
#'   \code{typeOfComputation}, and \code{spendingTime}.
#'
#' * \code{byTreatmentCounts}: A list containing the following counts by
#'   treatment group:
#'
#'     - \code{numberOfEvents1}: The number of events by stage for
#'       the treatment group.
#'
#'     - \code{numberOfDropouts1}: The number of dropouts by stage for
#'       the treatment group.
#'
#'     - \code{numberOfSubjects1}: The number of subjects by stage for
#'       the treatment group.
#'
#'     - \code{numberOfEvents2}: The number of events by stage for
#'       the control group.
#'
#'     - \code{numberOfDropouts2}: The number of dropouts by stage for
#'       the control group.
#'
#'     - \code{numberOfSubjects2}: The number of subjects by stage for
#'       the control group.
#'
#'     - \code{expectedNumberOfEvents1}: The expected number of events for
#'       the treatment group.
#'
#'     - \code{expectedNumberOfDropouts1}: The expected number of dropouts
#'       for the treatment group.
#'
#'     - \code{expectedNumberOfSubjects1}: The expected number of subjects
#'       for the treatment group.
#'
#'     - \code{expectedNumberOfEvents2}: The expected number of events for
#'       control group.
#'
#'     - \code{expectedNumberOfDropouts2}: The expected number of dropouts
#'       for the control group.
#'
#'     - \code{expectedNumberOfSubjects2}: The expected number of subjects
#'       for the control group.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{rmstat}}
#'
#' @examples
#'
#' lrpowerequiv(kMax = 2, informationRates = c(0.5, 1),
#'              alpha = 0.05, typeAlphaSpending = "sfOF",
#'              hazardRatioLower = 0.71, hazardRatioUpper = 1.4,
#'              allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'              accrualIntensity = 100/9*seq(1, 9),
#'              lambda1 = 0.0533,
#'              lambda2 = 0.0533,
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12, accrualDuration = 22,
#'              followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
lrpowerequiv <- function(kMax = 1L, informationRates = NA_real_, criticalValues = NULL, alpha = 0.05, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, hazardRatioLower = NA_real_, hazardRatioUpper = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, typeOfComputation = "direct", spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_lrpowerequiv`, kMax, informationRates, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, hazardRatioLower, hazardRatioUpper, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, typeOfComputation, spendingTime, studyDuration)
}

#' @title Sample Size for Equivalence in Hazard Ratio
#' @description Obtains the sample size for equivalence in hazard ratio.
#'
#' @param beta The type II error.
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_criticalValues
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param hazardRatioLower The lower equivalence limit of hazard ratio.
#' @param hazardRatioUpper The upper equivalence limit of hazard ratio.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @inheritParams param_typeOfComputation
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size.
#'   Defaults to 1 for sample size rounding.
#'
#' @return An S3 class \code{lrpowerequiv} object
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{lrpowerequiv}}
#'
#' @examples
#'
#' lrsamplesizeequiv(kMax = 2, informationRates = c(0.5, 1),
#'                   alpha = 0.05, typeAlphaSpending = "sfOF",
#'                   hazardRatioLower = 0.71, hazardRatioUpper = 1.4,
#'                   allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'                   accrualIntensity = 26/9*seq(1, 9),
#'                   piecewiseSurvivalTime = c(0, 6),
#'                   lambda1 = c(0.0533, 0.0533),
#'                   lambda2 = c(0.0533, 0.0533),
#'                   gamma1 = -log(1-0.05)/12,
#'                   gamma2 = -log(1-0.05)/12, accrualDuration = NA,
#'                   followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
lrsamplesizeequiv <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, criticalValues = NULL, alpha = 0.05, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, hazardRatioLower = NA_real_, hazardRatioUpper = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, typeOfComputation = "direct", spendingTime = NA_real_, rounding = TRUE) {
    .Call(`_lrstat_lrsamplesizeequiv`, beta, kMax, informationRates, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, hazardRatioLower, hazardRatioUpper, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, typeOfComputation, spendingTime, rounding)
}

#' @title Exit Probabilities for Multi-Arm Multi-Stage Design
#' @description Computes the exit (rejection) probabilities for a multi-arm
#' multi-stage design.
#'
#' @param M Number of active treatment arms.
#' @param r Randomization ratio of each active arm to the common control.
#' @param theta A vector of length \eqn{M} representing the true treatment
#'   effects for each active arm versus the common control.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is used.
#' @param kMax Number of sequential looks.
#' @param b A vector of efficacy boundaries for the max-Z statistics.
#' @param a A vector of futility boundaries for the max-Z statistics.
#' @param I A vector of information levels for any active arm versus the
#'   common control.
#'
#' @details
#' The function assumes a multivariate normal distribution for the Wald
#' statistics and all active arms share the same information level.
#'
#' @return A vector \code{exitProb} of length \code{kMax} containing the
#' probability of rejection at each look.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive multiple comparison sequential design (AMCSD) for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2024, 34(3), 424-440.
#'
#' @examples
#'
#' # Setup: 2 active arms vs control and 3 sequential looks.
#'
#' # Information levels: equal spacing over 3 looks based on a maximum of
#' # 95 patients per arm, SD = 1.0
#' I <- 95 / (2 * 1.0^2) * seq(1, 3)/3
#'
#' # O'Brien-Fleming critical values
#' b <- c(3.886562, 2.748214, 2.243907)
#'
#' # Type I error under the global null hypothesis
#' p0 <- exitprob_mams(M = 2, theta = c(0, 0), kMax = 3, b = b, I = I)
#' cumsum(p0$exitProbUpper)
#'
#' # Power under alternative: Treatment effects of 0.3 and 0.5
#' p1 <- exitprob_mams(M = 2, theta = c(0.3, 0.5), kMax = 3, b = b, I = I)
#' cumsum(p1$exitProbUpper)
#'
#' @export
exitprob_mams <- function(M = NA_integer_, r = 1, theta = NA_real_, corr_known = TRUE, kMax = NA_integer_, b = NULL, a = NULL, I = NULL) {
    .Call(`_lrstat_exitprob_mams`, M, r, theta, corr_known, kMax, b, a, I)
}

#' @title Efficacy Boundaries for Multi-Arm Multi-Stage Design
#' @description Calculates the efficacy stopping boundaries for a multi-arm
#' multi-stage design.
#'
#' @param M Number of active treatment arms.
#' @param r Randomization ratio of each active arm to the common control.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is assumed.
#' @param k The index of the current look.
#' @param informationRates A numeric vector of information rates up to the
#'   current look. Values must be strictly increasing and \eqn{\le 1}.
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param spendingTime A numeric vector of length \eqn{k} specifying the
#'   error spending time at each analysis. Values must be strictly increasing
#'   and \eqn{\le 1}. If omitted, defaults to \code{informationRates}.
#' @inheritParams param_efficacyStopping
#'
#' @details
#' The function determines critical values by solving for the boundary that
#' satisfies the alpha-spending requirement.
#'
#' If \code{typeAlphaSpending} is \code{"OF"}, \code{"P"}, \code{"WT"}, or
#' \code{"none"}, then \code{informationRates}, \code{efficacyStopping},
#' and \code{spendingTime} must be of full length \code{kMax}, and
#' \code{informationRates} and \code{spendingTime} must end with 1.
#'
#' @return A numeric vector of length \eqn{k} containing the critical
#' values (on the standard normal Z-scale) for each analysis up to the
#' current look.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive multiple comparison sequential design (AMCSD) for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2024, 34(3), 424-440.
#'
#' @examples
#'
#' # Determine O'Brien-Fleming boundaries for a TSSSD with
#' # 2 active arms and 3 looks.
#' getBound_mams(M = 2, k = 3, informationRates = seq(1, 3)/3,
#'               alpha = 0.025, typeAlphaSpending = "OF")
#'
#' @export
getBound_mams <- function(M = NA_integer_, r = 1, corr_known = TRUE, k = NA_integer_, informationRates = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, spendingTime = NA_real_, efficacyStopping = NA_integer_) {
    .Call(`_lrstat_getBound_mams`, M, r, corr_known, k, informationRates, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, spendingTime, efficacyStopping)
}

#' @title Power and Sample Size for Multi-Arm Multi-Stage Design
#' @description Computes either the maximum information and stopping
#' boundaries for a multi-arm multi-stage design, or
#' the achieved power when the maximum information and stopping boundaries
#' are provided.
#'
#' @param beta Type II error rate. Provide either \code{beta} or \code{IMax};
#'   the other should be missing.
#' @param IMax Maximum information for any active arm versus the common
#'   control. Provide either \code{IMax} or \code{beta}; the other should
#'   be missing.
#' @param theta A vector of length \eqn{M} representing the true treatment
#'   effects for each active arm versus the common control. The global null
#'   is \eqn{\theta_i = 0} for all \eqn{i}, and alternatives are one-sided:
#'   \eqn{\theta_i > 0} for at least one \eqn{i = 1, \ldots, M}.
#' @param M Number of active treatment arms.
#' @param r Randomization ratio of each active arm to the common control.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is used.
#' @param kMax Number of sequential looks.
#' @param informationRates A numeric vector of information rates fixed
#'   before the trial. If unspecified, defaults to \eqn{(1:kMax) / kMax}.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @param criticalValues The matrix of by-level upper boundaries on the
#'   max z-test statistic scale for efficacy stopping.
#'   The first column is for level \code{M}, the second column is for
#'   level \code{M - 1}, and so on, with the last column for level 1.
#'   If left unspecified, the critical values will be computed based
#'   on the specified alpha spending function.
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param futilityBounds A numeric vector of length \code{kMax - 1}
#'   specifying the futility boundaries on the max z-test statistic scale
#'   for futility stopping.
#' @param futilityCP A numeric vector of length \code{kMax - 1} specifying
#'   the futility boundaries on the conditional power scale for futility
#'   stopping.
#' @param futilityTheta A numeric vector of length \code{kMax - 1} specifying
#'   the futility boundaries on the parameter scale for futility stopping.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @param spendingTime A numeric vector of length \code{kMax} specifying the
#'   error spending time at each analysis. Values must be strictly increasing
#'   and ends at 1. If omitted, defaults to \code{informationRates}.
#'
#' @return An S3 object of class \code{mams} with the following components:
#'
#' * \code{overallResults}: A data frame containing:
#'     - \code{overallReject}: Overall probability of rejecting the global
#'       null hypothesis.
#'     - \code{alpha}: Overall significance level.
#'     - \code{attainedAlpha}: The attained significance level, which is
#'       different from the overall significance level in the presence of
#'       futility stopping.
#'     - \code{M}: Number of active arms.
#'     - \code{r}: Randomization ratio per active arm versus control.
#'     - \code{corr_known}: Whether the correlation among Wald statistics
#'       was assumed known.
#'     - \code{kMax}: Number of stages.
#'     - \code{information}: Maximum information for any active arm versus
#'       control.
#'     - \code{expectedInformationH1}: The expected information under H1.
#'     - \code{expectedInformationH0}: The expected information under H0.
#'
#' * \code{byStageResults}: A data frame containing:
#'     - \code{informationRates}: Information rates at each analysis.
#'     - \code{efficacyBounds}: Efficacy boundaries on the max Z-scale.
#'     - \code{futilityBounds}: Futility boundaries on the max Z-scale.
#'     - \code{rejectPerStage}: Probability of efficacy stopping at each stage.
#'     - \code{futilityPerStage}: Probability of futility stopping at each stage.
#'     - \code{cumulativeRejection}: Cumulative probability of efficacy stopping.
#'     - \code{cumulativeFutility}: Cumulative probability of futility stopping.
#'     - \code{cumulativeAlphaSpent}: Cumulative alpha spent.
#'     - \code{efficacyTheta}: Efficacy boundaries on the parameter scale.
#'     - \code{futilityTheta}: Futility boundaries on the parameter scale.
#'     - \code{efficacyP}: Efficacy boundaries on the p-value scale.
#'     - \code{futilityP}: Futility boundaries on the p-value scale.
#'     - \code{information}: Cumulative information for any active arm versus
#'       control at each analysis.
#'     - \code{efficacyStopping}: Indicator of whether efficacy stopping
#'       is permitted at each stage.
#'     - \code{futilityStopping}: Indicator of whether futility stopping
#'       is permitted at each stage.
#'     - \code{rejectPerStageH0}: The probability for efficacy stopping
#'       under H0.
#'     - \code{futilityPerStageH0}: The probability for futility stopping
#'       under H0.
#'     - \code{cumulativeRejectionH0}: The cumulative probability for
#'       efficacy stopping under H0.
#'     - \code{cumulativeFutilityH0}: The cumulative probability for
#'       futility stopping under H0.
#'
#' * \code{settings}: A list of input settings:
#'     - \code{typeAlphaSpending}: The type of alpha spending.
#'     - \code{parameterAlphaSpending}: The parameter value for the chosen
#'       alpha spending function.
#'     - \code{userAlphaSpending}: The user-specified alpha spending values.
#'     - \code{typeBetaSpending}: The type of beta spending.
#'     - \code{parameterBetaSpending}: The parameter value for the chosen
#'       beta spending function.
#'     - \code{userBetaSpending}: The user-specified beta spending values.
#'     - \code{spendingTime}: The error-spending time at each analysis.
#'
#' * \code{byLevelBounds}: A data frame containing the efficacy boundaries
#'   for each level of testing (i.e., number of active arms remaining) and
#'   each stage. Columns include:
#'     - \code{level}: Number of active arms remaining (1 to \eqn{M}).
#'     - \code{stage}: Stage index (1 to \code{kMax}).
#'     - \code{efficacyBounds}: Efficacy boundaries on the max Z-scale
#'       for the given level and stage.
#'
#' @details If \code{corr_known} is \code{FALSE}, critical boundaries are
#' computed assuming independence among the Wald statistics in each stage
#' (a conservative assumption). Power calculations, however, use the
#' correlation implied by the randomization ratio \eqn{r}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive multiple comparison sequential design (AMCSD) for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2024, 34(3), 424-440.
#'
#' @examples
#'
#' # Example 1: obtain the maximum information given power
#' (design1 <- getDesign_mams(
#'   beta = 0.1, theta = c(0.3, 0.5), M = 2, r = 1.0,
#'   kMax = 3, informationRates = seq(1, 3)/3,
#'   alpha = 0.025, typeAlphaSpending = "OF"))
#'
#' # Example 2: obtain power given the maximum information
#' (design2 <- getDesign_mams(
#'   IMax = 110/(2*1^2), theta = c(0.3, 0.5), M = 2, r = 1.0,
#'   kMax = 3, informationRates = seq(1, 3)/3,
#'   alpha = 0.025, typeAlphaSpending = "OF"))
#'
#' # Example 3: derive futility boundaries using beta spending
#' (design3 <- getDesign_mams(
#'   beta = 0.1, theta = c(-log(0.5), -log(0.75)),
#'   M = 2, r = 1.0, corr_known = FALSE,
#'   kMax = 3, informationRates = seq(1, 3)/3,
#'   alpha = 0.025, typeAlphaSpending = "sfOF",
#'   typeBetaSpending = "sfHSD", parameterBetaSpending = -2))
#'
#' @export
getDesign_mams <- function(beta = NA_real_, IMax = NA_real_, theta = NA_real_, M = NA_integer_, r = 1, corr_known = TRUE, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityTheta = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, spendingTime = NA_real_) {
    .Call(`_lrstat_getDesign_mams`, beta, IMax, theta, M, r, corr_known, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityTheta, typeBetaSpending, parameterBetaSpending, userBetaSpending, spendingTime)
}

#' @title Adaptive Multi-Arm Multi-Stage Design
#' @description
#' Calculates the conditional power for specified incremental
#' information, given the interim results, parameter value,
#' data-dependent changes in treatment selection,
#' the error spending function, and
#' the number and spacing of interim looks. Conversely,
#' calculates the incremental information required to attain
#' a specified conditional power, given the interim results,
#' parameter value, data-dependent changes in treatment selection,
#' the error spending function, and the number and spacing of interim looks.
#'
#' @param betaNew The type II error for the secondary trial.
#' @param INew The maximum information for any active arm versus the common
#'   control in the secondary trial. Either
#'   \code{betaNew} or \code{INew} should be provided, while the other
#'   must be missing.
#' @param M Number of active treatment arms in the primary trial.
#' @param r Randomization ratio of each active arm to the common control
#'   in the primary trial.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is assumed.
#' @param L The interim adaptation look of the primary trial.
#' @param zL The z-test statistics at the interim adaptation look of
#'   the primary trial.
#' @param theta A vector of length \eqn{M} representing the assumed treatment
#'   effects for each active arm versus the common control. The global null
#'   is \eqn{\theta_i = 0} for all \eqn{i}, and alternatives are one-sided:
#'   \eqn{\theta_i > 0} for at least one \eqn{i = 1, \ldots, M}.
#' @param IMax Maximum information for any active arm versus the common
#'   control for the primary trial. Must be provided.
#' @param kMax The maximum number of stages of the primary trial.
#' @param informationRates The information rates of the primary trial.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage of the primary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param futilityStopping Indicators of whether futility stopping is
#'   allowed at each stage of the primary trial.
#' @param criticalValues The matrix of by-level upper boundaries on the
#'   max z-test statistic scale for efficacy stopping for the primary trial.
#'   The first column is for level \code{M}, the second column is for
#'   level \code{M - 1}, and so on, with the last column for level 1.
#'   If left unspecified, the critical values will be computed based
#'   on the specified alpha spending function.
#' @param alpha The significance level of the primary trial.
#'   Defaults to 0.025.
#' @param typeAlphaSpending The type of alpha spending for the primary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function,
#'   \code{"user"} for user defined spending, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param userAlphaSpending The user-defined alpha spending for the
#'   primary trial. Represents the cumulative alpha spent up to each stage.
#' @param futilityBounds The futility boundaries on the max-z statistic
#'   scale for the primary trial. Defaults to \code{rep(-8, kMax-1)}
#'   if left unspecified.
#' @param futilityCP The conditional power-based futility bounds for the
#'   primary trial.
#' @param futilityTheta The parameter value-based futility bounds for the
#'   primary trial.
#' @param spendingTime The error spending time of the primary trial.
#'   Defaults to missing, in which case it is assumed to be the same as
#'   \code{informationRates}.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @param MNew Number of active treatment arms in the secondary trial.
#' @param selected The indices of the selected active treatment arms for
#'   the secondary trial.
#' @param rNew Randomization ratio of each active arm to the common control
#'   in the secondary trial.
#' @param kNew The number of looks of the secondary trial.
#' @param informationRatesNew The spacing of looks of the secondary trial.
#' @param efficacyStoppingNew The indicators of whether efficacy stopping is
#'   allowed at each look of the secondary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param futilityStoppingNew The indicators of whether futility stopping is
#'   allowed at each look of the secondary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param typeAlphaSpendingNew The type of alpha spending for the secondary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param futilityBoundsInt The futility boundaries on the max-z statistic
#'   scale for new stages of the integrated trial.
#' @param futilityCPInt The conditional power-based futility bounds for
#'   new stages of the integrated trial.
#' @param futilityThetaInt The parameter value-based futility bounds for the
#'   new stages of the integrated trial.
#' @param typeBetaSpendingNew The type of beta spending for the secondary
#'   trial. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function,
#'   \code{"user"} for user defined spending, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @param parameterBetaSpendingNew The parameter value of beta spending
#'   for the secondary trial. Corresponds to \eqn{\rho} for \code{"sfKD"},
#'   and \eqn{\gamma} for \code{"sfHSD"}.
#' @param userBetaSpendingNew The user-defined cumulative beta spending.
#'   Represents the cumulative beta spent up to each stage of the
#'   secondary trial.
#' @param spendingTimeNew The error spending time of the secondary trial.
#'   Defaults to missing, in which case it is assumed to be the same as
#'   \code{informationRatesNew}.
#'
#' @return An \code{adaptDesign_mams} object with three list components:
#'
#' * \code{primaryTrial}: A list of selected information for the primary
#'   trial, including \code{M}, \code{r}, \code{corr_known}, \code{L},
#'   \code{zL}, \code{theta}, \code{maxInformation}, \code{kMax},
#'   \code{informationRates}, \code{efficacyBounds}, \code{futilityBounds},
#'   \code{information}, \code{alpha}, \code{conditionalAlpha},
#'   \code{conditionalPower}, \code{MullerSchafer}, and \code{byLevelBounds},
#'   where \code{byLevelBounds} is a data frame with columns \code{level},
#'   \code{stage}, and \code{efficacyBounds}, representing the efficacy
#'   bounds for each combination of the number of active arms and
#'   the stage of analysis in the primary trial.
#'
#' * \code{secondaryTrial}: A list of selected information for the secondary
#'   trial, including \code{overallReject}, \code{alpha}, \code{M}, \code{r},
#'   \code{selected}, \code{corr_known}, \code{kMax}, \code{maxInformation},
#'   \code{informationRates}, \code{cumulativeRejection},
#'   \code{cumulativeAlphaSpent}, \code{information},
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{typeBetaSpending}, \code{parameterBetaSpending},
#'   \code{userBetaSpending}, \code{spendingTime}, and
#'   \code{byHypothesisBounds}, where \code{byHypothesisBounds} is a
#'   data frame with columns \code{hypothesis}, \code{stage},
#'   \code{efficacyBounds}, and \code{futilityBounds}, representing
#'   the efficacy and futility bounds for each hypothesis and each
#'   stage of analysis in the secondary trial.
#'
#' * \code{integratedTrial}: A list of selected information for the integrated
#'   trial, including \code{M}, \code{r}, \code{corr_known}, \code{MNew},
#'   \code{rNew}, \code{selected}, \code{L}, \code{zL}, \code{theta},
#'   \code{maxInformation}, \code{kMax}, \code{informationRates},
#'   \code{efficacyBounds}, \code{futilityBounds}, \code{information},
#'   and \code{byIntersectionBounds}, where \code{byIntersectionBounds} is
#'   a data frame with columns \code{intersectionHypothesis}, \code{stage},
#'   and \code{efficacyBounds}, representing the efficacy bounds for
#'   each intersection hypothesis and each stage of analysis in the
#'   integrated trial.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive multiple comparison sequential design (AMCSD) for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2024, 34(3), 424-440.
#'
#' @seealso \code{\link{getDesign_mams}}
#'
#' @examples
#'
#' # Two active treatment arms are compared with a common control in a
#' # two-look time-to-event design using O'Brien–Fleming–type alpha spending.
#' # Suppose each active arm has a true hazard ratio of 0.75 versus control,
#' # and the total number of events across all three arms at the final analysis
#' # is 486. This corresponds to approximately 324 events for each active arm
#' # versus the common control. Under these assumptions, the trial has about
#' # 80% power to detect the treatment effect in at least one active arm.
#'
#' (des1 <- getDesign_mams(
#'   IMax = 324 / 4, theta = c(-log(0.75), -log(0.75)),
#'   M = 2, r = 1, kMax = 2, informationRates = c(1/2, 1),
#'   alpha = 0.025, typeAlphaSpending = "OF"))
#'
#' # Now assume that, at the interim analysis, the observed hazard ratios for
#' # the two active arms versus control are 0.91 and 0.78, respectively. Using
#' # the rule “drop any arm with an observed hazard ratio > 0.9”, arm 1 is
#' # dropped. We then aim to achieve 80% conditional power to detect a hazard
#' # ratio of 0.78 for the remaining arm at the final look. The analysis below
#' # indicates that the required total number of events for arm 2 versus control
#' # at the final analysis should be increased from 324 to 535.
#'
#' (des2 <- adaptDesign_mams(
#'   betaNew = 0.2, M = 2, r = 1, corr_known = FALSE,
#'   L = 1, zL = c(-log(0.91), -log(0.78)) * sqrt(324 / 4 / 2),
#'   theta = c(-log(0.91), -log(0.78)),
#'   IMax = 324 / 4, kMax = 2, informationRates = c(1/2, 1),
#'   alpha = 0.025, typeAlphaSpending = "OF",
#'   MNew = 1, selected = 2, rNew = 1))
#'
#' @export
adaptDesign_mams <- function(betaNew = NA_real_, INew = NA_real_, M = NA_integer_, r = 1, corr_known = TRUE, L = NA_integer_, zL = NA_real_, theta = NA_real_, IMax = NA_real_, kMax = NA_integer_, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityTheta = NULL, spendingTime = NA_real_, MullerSchafer = FALSE, MNew = NA_integer_, selected = NA_integer_, rNew = 1, kNew = NA_integer_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, futilityStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, futilityBoundsInt = NULL, futilityCPInt = NULL, futilityThetaInt = NULL, typeBetaSpendingNew = "none", parameterBetaSpendingNew = NA_real_, userBetaSpendingNew = NA_real_, spendingTimeNew = NA_real_) {
    .Call(`_lrstat_adaptDesign_mams`, betaNew, INew, M, r, corr_known, L, zL, theta, IMax, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityTheta, spendingTime, MullerSchafer, MNew, selected, rNew, kNew, informationRatesNew, efficacyStoppingNew, futilityStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, futilityBoundsInt, futilityCPInt, futilityThetaInt, typeBetaSpendingNew, parameterBetaSpendingNew, userBetaSpendingNew, spendingTimeNew)
}

#' @title REML Estimates of Individual Proportions With Specified Risk
#' difference
#' @description Obtains the restricted maximum likelihood estimates of
#' individual proportions with specified risk difference.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param riskDiffH0 The specified risk difference.
#'
#' @return A vector of the restricted maximum likelihood estimates
#' of the response probabilities for the two treatment groups.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' remlRiskDiff(n1 = 10, y1 = 4, n2 = 20, y2 = 0, riskDiffH0 = 0.1)
#'
#' @export
remlRiskDiff <- function(n1, y1, n2, y2, riskDiffH0 = 0.0) {
    .Call(`_lrstat_remlRiskDiff`, n1, y1, n2, y2, riskDiffH0)
}

#' @title Miettinen-Nurminen Score Test Statistic for Two-Sample Risk
#' difference
#' @description Obtains the Miettinen-Nurminen score test statistic
#' for two-sample risk difference possibly with stratification.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param riskDiffH0 The risk difference under the null hypothesis.
#'   Defaults to 0.
#'
#' @details
#' The Mantel-Haenszel sample size weights are used for stratified
#' samples.
#'
#' @return The value of the score test statistic.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' zstatRiskDiff(n1 = c(10, 10), y1 = c(4, 3),
#'               n2 = c(20, 10), y2 = c(2, 0), riskDiffH0 = 0)
#'
#' @export
zstatRiskDiff <- function(n1, y1, n2, y2, riskDiffH0 = 0.0) {
    .Call(`_lrstat_zstatRiskDiff`, n1, y1, n2, y2, riskDiffH0)
}

#' @title Miettinen-Nurminen Score Confidence Interval for
#' Two-Sample Risk Difference
#' @description Obtains the Miettinen-Nurminen score confidence
#' interval for two-sample risk difference possibly with
#' stratification.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param cilevel The confidence interval level.
#'
#' @details
#' The Mantel-Haenszel sample size weights are used for stratified
#' samples.
#'
#' @return A list with two components:
#'
#' * \code{data} A data frame containing the input sample size
#'   and number of responses for each treatment group.
#'   It has the following variables:
#'
#'     - \code{n1}: The sample size for the active treatment group.
#'
#'     - \code{y1}: The number of responses for the active treatment group.
#'
#'     - \code{n2}: The sample size for the control group.
#'
#'     - \code{y2}: The number of responses for the control group.
#'
#' * \code{estimates}: A data frame containing the point estimate
#'   and confidence interval for risk difference. It has the following
#'   variables:
#'
#'     - \code{scale}: The scale of treatment effect.
#'
#'     - \code{estimate}: The point estimate.
#'
#'     - \code{lower}: The lower limit of the confidence interval.
#'
#'     - \code{upper}: The upper limit of the confidence interval.
#'
#'     - \code{cilevel}: The confidence interval level.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' mnRiskDiffCI(n1 = c(10, 10), y1 = c(4, 3),
#'              n2 = c(20, 10), y2 = c(2, 0))
#'
#' @export
mnRiskDiffCI <- function(n1, y1, n2, y2, cilevel = 0.95) {
    .Call(`_lrstat_mnRiskDiffCI`, n1, y1, n2, y2, cilevel)
}

#' @title REML Estimates of Individual Proportions With Specified Risk
#' Ratio
#' @description Obtains the restricted maximum likelihood estimates of
#' individual proportions with specified risk ratio.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param riskRatioH0 The specified risk ratio.
#'
#' @return A vector of the restricted maximum likelihood estimates
#' of the response probabilities for the two treatment groups.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' remlRiskRatio(n1 = 10, y1 = 4, n2 = 20, y2 = 2, riskRatioH0 = 1.2)
#'
#' @export
remlRiskRatio <- function(n1, y1, n2, y2, riskRatioH0 = 1.0) {
    .Call(`_lrstat_remlRiskRatio`, n1, y1, n2, y2, riskRatioH0)
}

#' @title Miettinen-Nurminen Score Test Statistic for Two-Sample Risk Ratio
#' @description Obtains the Miettinen-Nurminen score test statistic for
#' two-sample risk ratio possibly with stratification.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param riskRatioH0 The risk ratio under the null hypothesis.
#'   Defaults to 1.
#'
#' @details
#' The Mantel-Haenszel sample size weights are used for stratified
#' samples.
#'
#' @return The value of the score test statistic.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' zstatRiskRatio(n1 = c(10, 10), y1 = c(4, 3),
#'                n2 = c(20, 10), y2 = c(2, 0), riskRatioH0 = 1)
#'
#' @export
zstatRiskRatio <- function(n1, y1, n2, y2, riskRatioH0 = 1.0) {
    .Call(`_lrstat_zstatRiskRatio`, n1, y1, n2, y2, riskRatioH0)
}

#' @title Miettinen-Nurminen Score Confidence Interval for
#' Two-Sample Risk Ratio
#' @description Obtains the Miettinen-Nurminen score confidence
#' interval for two-sample risk ratio possibly with
#' stratification.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param cilevel The confidence interval level.
#'
#' @details
#' The Mantel-Haenszel sample size weights are used for stratified
#' samples.
#'
#' @return A list with two components:
#'
#' * \code{data} A data frame containing the input sample size
#'   and number of responses for each treatment group.
#'   It has the following variables:
#'
#'     - \code{n1}: The sample size for the active treatment group.
#'
#'     - \code{y1}: The number of responses for the active treatment group.
#'
#'     - \code{n2}: The sample size for the control group.
#'
#'     - \code{y2}: The number of responses for the control group.
#'
#' * \code{estimates}: A data frame containing the point estimate
#'   and confidence interval for risk ratio. It has the following
#'   variables:
#'
#'     - \code{scale}: The scale of treatment effect.
#'
#'     - \code{estimate}: The point estimate.
#'
#'     - \code{lower}: The lower limit of the confidence interval.
#'
#'     - \code{upper}: The upper limit of the confidence interval.
#'
#'     - \code{cilevel}: The confidence interval level.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' mnRiskRatioCI(n1 = c(10, 10), y1 = c(4, 3),
#'               n2 = c(20, 10), y2 = c(2, 0))
#'
#' @export
mnRiskRatioCI <- function(n1, y1, n2, y2, cilevel = 0.95) {
    .Call(`_lrstat_mnRiskRatioCI`, n1, y1, n2, y2, cilevel)
}

#' @title REML Estimates of Individual Proportions With Specified Odds
#' Ratio
#' @description Obtains the restricted maximum likelihood estimates of
#' individual proportions with specified odds ratio.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param oddsRatioH0 The specified odds ratio.
#'
#' @return A vector of the restricted maximum likelihood estimates
#' of the response probabilities for the two treatment groups.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' remlOddsRatio(n1 = 10, y1 = 4, n2 = 20, y2 = 2, oddsRatioH0 = 1.25)
#'
#' @export
remlOddsRatio <- function(n1, y1, n2, y2, oddsRatioH0 = 1.0) {
    .Call(`_lrstat_remlOddsRatio`, n1, y1, n2, y2, oddsRatioH0)
}

#' @title Miettinen-Nurminen Score Test Statistic for Two-Sample Odds Ratio
#' @description Obtains the Miettinen-Nurminen score test statistic for
#' two-sample odds ratio possibly with stratification.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param oddsRatioH0 The odds ratio under the null hypothesis.
#'   Defaults to 1.
#'
#' @details
#' The Mantel-Haenszel sample size weights are used for stratified
#' samples.
#'
#' @return The value of the score test statistic.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' zstatOddsRatio(n1 = c(10, 10), y1 = c(4, 3),
#'                n2 = c(20, 10), y2 = c(2, 0), oddsRatioH0 = 1)
#'
#' @export
zstatOddsRatio <- function(n1, y1, n2, y2, oddsRatioH0 = 1.0) {
    .Call(`_lrstat_zstatOddsRatio`, n1, y1, n2, y2, oddsRatioH0)
}

#' @title Miettinen-Nurminen Score Confidence Interval for
#' Two-Sample Odds Ratio
#' @description Obtains the Miettinen-Nurminen score confidence
#' interval for two-sample odds ratio possibly with
#' stratification.
#'
#' @param n1 The sample size for the active treatment group.
#' @param y1 The number of responses for the active treatment group.
#' @param n2 The sample size for the control group.
#' @param y2 The number of responses for the control group.
#' @param cilevel The confidence interval level.
#'
#' @details
#' The Mantel-Haenszel sample size weights are used for stratified
#' samples.
#'
#' @return A list with two components:
#'
#' * \code{data} A data frame containing the input sample size
#'   and number of responses for each treatment group.
#'   It has the following variables:
#'
#'     - \code{n1}: The sample size for the active treatment group.
#'
#'     - \code{y1}: The number of responses for the active treatment group.
#'
#'     - \code{n2}: The sample size for the control group.
#'
#'     - \code{y2}: The number of responses for the control group.
#'
#' * \code{estimates}: A data frame containing the point estimate
#'   and confidence interval for odds ratio. It has the following
#'   variables:
#'
#'     - \code{scale}: The scale of treatment effect.
#'
#'     - \code{estimate}: The point estimate.
#'
#'     - \code{lower}: The lower limit of the confidence interval.
#'
#'     - \code{upper}: The upper limit of the confidence interval.
#'
#'     - \code{cilevel}: The confidence interval level.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' mnOddsRatioCI(n1 = c(10,10), y1 = c(4,3), n2 = c(20,10), y2 = c(2,0))
#'
#' @export
mnOddsRatioCI <- function(n1, y1, n2, y2, cilevel = 0.95) {
    .Call(`_lrstat_mnOddsRatioCI`, n1, y1, n2, y2, cilevel)
}

#' @title REML Estimates of Individual Rates With Specified Rate
#' Difference
#' @description Obtains the restricted maximum likelihood estimates of
#' individual proportions with specified rate difference.
#'
#' @param t1 The exposure for the active treatment group.
#' @param y1 The number of events for the active treatment group.
#' @param t2 The exposure for the control group.
#' @param y2 The number of events for the control group.
#' @param rateDiffH0 The specified rate difference.
#'
#' @return A vector of the restricted maximum likelihood estimates
#' of the incidence rates for the two treatment groups.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' remlRateDiff(t1 = 10, y1 = 4, t2 = 20, y2 = 2, rateDiffH0 = 0.1)
#'
#' @export
remlRateDiff <- function(t1, y1, t2, y2, rateDiffH0 = 0.0) {
    .Call(`_lrstat_remlRateDiff`, t1, y1, t2, y2, rateDiffH0)
}

#' @title Miettinen-Nurminen Score Test Statistic for Two-Sample Rate
#' Difference
#' @description Obtains the Miettinen-Nurminen score test statistic for
#' two-sample rate difference possibly with stratification.
#'
#' @param t1 The exposure for the active treatment group.
#' @param y1 The number of events for the active treatment group.
#' @param t2 The exposure for the control group.
#' @param y2 The number of events for the control group.
#' @param rateDiffH0 The rate difference under the null hypothesis.
#'   Defaults to 0.
#'
#' @details
#' The Mantel-Haenszel weights are used for stratified samples.
#'
#' @return The value of the score test statistic.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' zstatRateDiff(t1 = c(10, 10), y1 = c(4, 3),
#'               t2 = c(20, 10), y2 = c(2, 0), rateDiffH0 = 0)
#'
#' @export
zstatRateDiff <- function(t1, y1, t2, y2, rateDiffH0 = 0.0) {
    .Call(`_lrstat_zstatRateDiff`, t1, y1, t2, y2, rateDiffH0)
}

#' @title Miettinen-Nurminen Score Confidence Interval for
#' Two-Sample Rate Difference
#' @description Obtains the Miettinen-Nurminen score confidence
#' interval for two-sample rate difference possibly with
#' stratification.
#'
#' @param t1 The exposure for the active treatment group.
#' @param y1 The number of events for the active treatment group.
#' @param t2 The exposure for the control group.
#' @param y2 The number of events for the control group.
#' @param cilevel The confidence interval level.
#'
#' @details
#' The Mantel-Haenszel weights are used for stratified samples.
#'
#' @return A list with two components:
#'
#' * \code{data} A data frame containing the input exposure
#'   and number of events for each treatment group.
#'   It has the following variables:
#'
#'     - \code{t1}: The exposure for the active treatment group.
#'
#'     - \code{y1}: The number of events for the active treatment group.
#'
#'     - \code{t2}: The exposure for the control group.
#'
#'     - \code{y2}: The number of events for the control group.
#'
#' * \code{estimates}: A data frame containing the point estimate
#'   and confidence interval for rate difference. It has the following
#'   variables:
#'
#'     - \code{scale}: The scale of treatment effect.
#'
#'     - \code{estimate}: The point estimate.
#'
#'     - \code{lower}: The lower limit of the confidence interval.
#'
#'     - \code{upper}: The upper limit of the confidence interval.
#'
#'     - \code{cilevel}: The confidence interval level.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' mnRateDiffCI(t1 = c(10,10), y1 = c(4,3), t2 = c(20,10), y2 = c(2,0))
#'
#' @export
mnRateDiffCI <- function(t1, y1, t2, y2, cilevel = 0.95) {
    .Call(`_lrstat_mnRateDiffCI`, t1, y1, t2, y2, cilevel)
}

#' @title REML Estimates of Individual Rates With Specified Rate Ratio
#' @description Obtains the restricted maximum likelihood estimates of
#' individual proportions with specified rate ratio.
#'
#' @param t1 The exposure for the active treatment group.
#' @param y1 The number of events for the active treatment group.
#' @param t2 The exposure for the control group.
#' @param y2 The number of events for the control group.
#' @param rateRatioH0 The specified rate ratio.
#'
#' @return A vector of the restricted maximum likelihood estimates
#' of the incidence rates for the two treatment groups.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' remlRateRatio(t1 = 10, y1 = 4, t2 = 20, y2 = 2, rateRatioH0 = 1.1)
#'
#' @export
remlRateRatio <- function(t1, y1, t2, y2, rateRatioH0 = 1.0) {
    .Call(`_lrstat_remlRateRatio`, t1, y1, t2, y2, rateRatioH0)
}

#' @title Miettinen-Nurminen Score Test Statistic for Two-Sample Rate Ratio
#' @description Obtains the Miettinen-Nurminen score test statistic for
#' two-sample rate ratio possibly with stratification.
#'
#' @param t1 The exposure for the active treatment group.
#' @param y1 The number of events for the active treatment group.
#' @param t2 The exposure for the control group.
#' @param y2 The number of events for the control group.
#' @param rateRatioH0 The rate ratio under the null hypothesis.
#'   Defaults to 1.
#'
#' @details
#' The Mantel-Haenszel weights are used for stratified samples.
#'
#' @return The value of the score test statistic.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' zstatRateRatio(t1 = c(10, 10), y1 = c(4, 3),
#'                t2 = c(20, 10), y2 = c(2, 0), rateRatioH0 = 1)
#'
#' @export
zstatRateRatio <- function(t1, y1, t2, y2, rateRatioH0 = 1.0) {
    .Call(`_lrstat_zstatRateRatio`, t1, y1, t2, y2, rateRatioH0)
}

#' @title Miettinen-Nurminen Score Confidence Interval for
#' Two-Sample Rate Ratio
#' @description Obtains the Miettinen-Nurminen score confidence
#' interval for two-sample rate ratio possibly with
#' stratification.
#'
#' @param t1 The exposure for the active treatment group.
#' @param y1 The number of events for the active treatment group.
#' @param t2 The exposure for the control group.
#' @param y2 The number of events for the control group.
#' @param cilevel The confidence interval level.
#'
#' @details
#' The Mantel-Haenszel weights are used for stratified samples.
#'
#' @return A list with two components:
#'
#' * \code{data} A data frame containing the input exposure
#'   and number of events for each treatment group.
#'   It has the following variables:
#'
#'     - \code{t1}: The exposure for the active treatment group.
#'
#'     - \code{y1}: The number of events for the active treatment group.
#'
#'     - \code{t2}: The exposure for the control group.
#'
#'     - \code{y2}: The number of events for the control group.
#'
#' * \code{estimates}: A data frame containing the point estimate
#'   and confidence interval for rate ratio. It has the following
#'   variables:
#'
#'     - \code{scale}: The scale of treatment effect.
#'
#'     - \code{estimate}: The point estimate.
#'
#'     - \code{lower}: The lower limit of the confidence interval.
#'
#'     - \code{upper}: The upper limit of the confidence interval.
#'
#'     - \code{cilevel}: The confidence interval level.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' mnRateRatioCI(t1 = c(10,10), y1 = c(4,3), t2 = c(20,10), y2 = c(2,0))
#'
#' @export
mnRateRatioCI <- function(t1, y1, t2, y2, cilevel = 0.95) {
    .Call(`_lrstat_mnRateRatioCI`, t1, y1, t2, y2, cilevel)
}

#' @title Update Graph for Graphical Approaches
#' @description Updates the weights and transition matrix for graphical
#' approaches.
#'
#' @param w The current vector of weights for elementary hypotheses.
#' @param G The current transition matrix.
#' @param I The set of indices for yet to be rejected hypotheses.
#' @param j The hypothesis to remove from index set \code{I}.
#'
#' @return A list containing the new vector of weights, the new
#' transition matrix for the graph, and the new set of indices of yet
#' to be rejected hypotheses.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' updateGraph(w = c(0.5, 0.5, 0, 0),
#'             G = matrix(c(0, 0.5, 0.5, 0,  0.5, 0, 0, 0.5,
#'                          0, 1, 0, 0,  1, 0, 0, 0),
#'                        nrow=4, ncol=4, byrow=TRUE),
#'             I = c(1, 2, 3, 4),
#'             j = 1)
#'
#' @export
updateGraph <- function(w, G, I, j) {
    .Call(`_lrstat_updateGraph`, w, G, I, j)
}

fadjpboncpp <- function(w, G, p) {
    .Call(`_lrstat_fadjpboncpp`, w, G, p)
}

#' @title Weight Matrix for All Intersection Hypotheses
#' @description Obtains the weight matrix for all intersection hypotheses.
#'
#' @param w The vector of weights for elementary hypotheses.
#' @param G The transition matrix.
#'
#' @return The weight matrix starting with the global null hypothesis.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' w <- c(0.5,0.5,0,0)
#' g <- matrix(c(0,0,1,0, 0,0,0,1, 0,1,0,0, 1,0,0,0),
#'             nrow=4, ncol=4, byrow=TRUE)
#' (wgtmat <- fwgtmat(w,g))
#'
#' @export
fwgtmat <- function(w, G) {
    .Call(`_lrstat_fwgtmat`, w, G)
}

fadjpsimcpp <- function(wgtmat, p, family) {
    .Call(`_lrstat_fadjpsimcpp`, wgtmat, p, family)
}

repeatedPValuecpp <- function(kMax, typeAlphaSpending, parameterAlphaSpending, maxInformation, p, information, spendingTime) {
    .Call(`_lrstat_repeatedPValuecpp`, kMax, typeAlphaSpending, parameterAlphaSpending, maxInformation, p, information, spendingTime)
}

fseqboncpp <- function(w, G, alpha, kMax, typeAlphaSpending, parameterAlphaSpending, maxInformation, incidenceMatrix, k1, p, information, spendingTime) {
    .Call(`_lrstat_fseqboncpp`, w, G, alpha, kMax, typeAlphaSpending, parameterAlphaSpending, maxInformation, incidenceMatrix, k1, p, information, spendingTime)
}

fstp2seqcpp <- function(p, gamma, test = "hochberg", retest = TRUE) {
    .Call(`_lrstat_fstp2seqcpp`, p, gamma, test, retest)
}

fstdmixcpp <- function(p, family, serial, parallel, gamma, test = "hommel", exhaust = TRUE) {
    .Call(`_lrstat_fstdmixcpp`, p, family, serial, parallel, gamma, test, exhaust)
}

fmodmixcpp <- function(p, family, serial, parallel, gamma, test = "hommel", exhaust = TRUE) {
    .Call(`_lrstat_fmodmixcpp`, p, family, serial, parallel, gamma, test, exhaust)
}

ftrunccpp <- function(p, test, gamma) {
    .Call(`_lrstat_ftrunccpp`, p, test, gamma)
}

pmvnormRcpp <- function(lower, upper, mean, sigma, n0 = 1024L, n_max = 16384L, R = 8L, abseps = 1e-4, releps = 0.0, seed = 0L, parallel = TRUE) {
    .Call(`_lrstat_pmvnormRcpp`, lower, upper, mean, sigma, n0, n_max, R, abseps, releps, seed, parallel)
}

qmvnormRcpp <- function(p, mean, sigma, n0 = 1024L, n_max = 16384L, R = 8L, abseps = 1e-4, releps = 0.0, seed = 0L, parallel = TRUE) {
    .Call(`_lrstat_qmvnormRcpp`, p, mean, sigma, n0, n_max, R, abseps, releps, seed, parallel)
}

#' @title Negative Binomial Rate Ratio
#' @description Obtains the number of subjects accrued, number of events,
#' number of dropouts, number of subjects reaching the maximum
#' follow-up, total exposure, and variance for log rate in each group,
#' rate ratio, variance, and Wald test statistic of
#' log rate ratio at given calendar times.
#'
#' @param time A vector of calendar times for data cut.
#' @param rateRatioH0 Rate ratio under the null hypothesis.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param kappa1 The dispersion parameter (reciprocal of the shape
#'   parameter of the gamma mixing distribution) for the active treatment
#'   group by stratum.
#' @param kappa2 The dispersion parameter (reciprocal of the shape
#'   parameter of the gamma mixing distribution) for the control group by
#'   stratum.
#' @param lambda1 The rate parameter of the negative binomial distribution
#'   for the active treatment group by stratum.
#' @param lambda2 The rate parameter of the negative binomial distribution
#'   for the control group by stratum.
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param nullVariance Whether to calculate the variance for log rate ratio
#'   under the null hypothesis.
#'
#' @details
#' The probability mass function for a negative binomial distribution with
#' dispersion parameter \eqn{\kappa_i} and rate parameter \eqn{\lambda_i}
#' is given by
#' \deqn{P(Y_{ij} = y) = \frac{\Gamma(y+1/\kappa_i)}{\Gamma(1/\kappa_i) y!}
#' \left(\frac{1}{1 + \kappa_i \lambda_i t_{ij}}\right)^{1/\kappa_i}
#' \left(\frac{\kappa_i \lambda_i t_{ij}}
#' {1 + \kappa_i \lambda_i t_{ij}}\right)^{y},}
#' where \eqn{Y_{ij}} is the event count for subject \eqn{j} in
#' treatment group \eqn{i}, and \eqn{t_{ij}} is the exposure time for
#' the subject. If \eqn{\kappa_i=0}, the negative binomial distribution
#' reduces to the Poisson distribution.
#'
#' For treatment group \eqn{i}, let \eqn{\beta_i = \log(\lambda_i)}.
#' The log-likelihood for \eqn{\{(\kappa_i, \beta_i):i=1,2\}}
#' can be written as
#' \deqn{l = \sum_{i=1}^{2}\sum_{j=1}^{n_{i}}
#' \{\log \Gamma(y_{ij} + 1/\kappa_i) - \log \Gamma(1/\kappa_i) + y_{ij}
#' (\log(\kappa_i) + \beta_i) - (y_{ij} + 1/\kappa_i)
#' \log(1+ \kappa_i \exp(\beta_i) t_{ij})\}.}
#' It follows that
#' \deqn{\frac{\partial l}{\partial \beta_i} = \sum_{j=1}^{n_i}
#' \left\{y_{ij} - (y_{ij} + 1/\kappa_i)
#' \frac{\kappa_i \exp(\beta_i) t_{ij}}
#' {1 + \kappa_i \exp(\beta_i)t_{ij}}\right\},}
#' and
#' \deqn{-\frac{\partial^2 l}{\partial \beta_i^2} =
#' \sum_{j=1}^{n_i} (y_{ij} + 1/\kappa_i) \frac{\kappa_i \lambda_i t_{ij}}
#' {(1 + \kappa_i \lambda_i t_{ij})^2}.}
#' The Fisher information for \eqn{\beta_i} is
#' \deqn{E\left(-\frac{\partial^2 l}{\partial \beta_i^2}\right)
#' = n_i E\left(\frac{\lambda_i t_{ij}}
#' {1 + \kappa_i \lambda_i t_{ij}}\right).}
#' In addition, we can show that
#' \deqn{E\left(-\frac{\partial^2 l}
#' {\partial \beta_i \partial \kappa_i}\right) = 0.}
#' Therefore, the variance of \eqn{\hat{\beta}_i} is
#' \deqn{Var(\hat{\beta}_i) = \frac{1}{n_i} \left\{
#' E\left(\frac{\lambda_i t_{ij}}{1 + \kappa_i \lambda_i t_{ij}}\right)
#' \right\}^{-1}.}
#'
#' To evaluate the integral, we need to obtain the distribution of the
#' exposure time,
#' \deqn{t_{ij} = \min(\tau - W_{ij}, C_{ij}, T_{fmax}),}
#' where \eqn{\tau} denotes the calendar time since trial start,
#' \eqn{W_{ij}} denotes the enrollment time for subject \eqn{j}
#' in treatment group \eqn{i}, \eqn{C_{ij}} denotes the time to dropout
#' after enrollment for subject \eqn{j} in treatment group \eqn{i}, and
#' \eqn{T_{fmax}} denotes the maximum follow-up time for
#' all subjects. Therefore,
#' \deqn{P(t_{ij} \geq t) = P(W_{ij} \leq \tau - t)P(C_{ij} \geq t)
#' I(t\leq T_{fmax}).}
#' Let \eqn{H} denote the distribution function of the enrollment time,
#' and \eqn{G_i} denote the survival function of the dropout time for
#' treatment group \eqn{i}. By the change of variables, we have
#' \deqn{E\left(\frac{\lambda_i t_{ij}}{1 + \kappa_i \lambda_i t_{ij}}
#' \right) = \int_{0}^{\tau \wedge T_{fmax}}
#' \frac{\lambda_i}{(1 + \kappa_i \lambda_i t)^2} H(\tau - t) G_i(t) dt.}
#' A numerical integration algorithm for a univariate function can be
#' used to evaluate the above integral.
#'
#' For the restricted maximum likelihood (reml) estimate of
#' \eqn{(\beta_1,\beta_2)} subject to the
#' constraint that \eqn{\beta_1 - \beta_2 = \Delta}, we express the
#' log-likelihood in terms of \eqn{(\beta_2,\Delta,\kappa_1,\kappa_2)},
#' and takes the derivative of the log-likelihood function with respect
#' to \eqn{\beta_2}. The resulting score equation has asymptotic limit
#' \deqn{E\left(\frac{\partial l}{\partial \beta_2}\right) = s_1 + s_2,}
#' where
#' \deqn{s_1 = n r E\left\{\lambda_1 t_{1j} - \left(\lambda_1t_{1j}
#' + \frac{1}{\kappa_1}\right) \frac{\kappa_1 e^{\tilde{\beta}_2 +
#' \Delta}t_{1j}}{1 + \kappa_1 e^{\tilde{\beta}_2 +\Delta}t_{1j}}\right\},}
#' and
#' \deqn{s_2 = n (1-r) E\left\{\lambda_2 t_{2j} -
#' \left(\lambda_2 t_{2j} + \frac{1}{\kappa_2}\right)
#' \frac{\kappa_2 e^{\tilde{\beta}_2} t_{2j}}
#' {1 + \kappa_2 e^{\tilde{\beta}_2}t_{2j}}\right\}.}
#' Here \eqn{r} is the randomization probability for the active
#' treatment group. The asymptotic limit of the reml of \eqn{\beta_2}
#' is the solution \eqn{\tilde{\beta}_2} to
#' \eqn{E\left(\frac{\partial l}{\partial \beta_2}\right) = 0.}
#'
#' @return A list with two components:
#'
#' * \code{resultsUnderH1}: A data frame containing the following variables:
#'
#'     - \code{time}: The analysis time since trial start.
#'
#'     - \code{subjects}: The number of enrolled subjects.
#'
#'     - \code{nevents}: The total number of events.
#'
#'     - \code{nevents1}: The number of events in the active treatment
#'       group.
#'
#'     - \code{nevents2}: The number of events in the control group.
#'
#'     - \code{ndropouts}: The total number of dropouts.
#'
#'     - \code{ndropouts1}: The number of dropouts in the active treatment
#'       group.
#'
#'     - \code{ndropouts2}: The number of dropouts in the control group.
#'
#'     - \code{nfmax}: The total number of subjects reaching maximum
#'       follow-up.
#'
#'     - \code{nfmax1}: The number of subjects reaching maximum follow-up
#'       in the active treatment group.
#'
#'     - \code{nfmax2}: The number of subjects reaching maximum follow-up
#'       in the control group.
#'
#'     - \code{exposure}: The total exposure time.
#'
#'     - \code{exposure1}: The exposure time for the active treatment group.
#'
#'     - \code{exposure2}: The exposure time for the control group.
#'
#'     - \code{rateRatio}: The rate ratio of the active treatment group
#'       versus the control group.
#'
#'     - \code{vlogRate1}: The variance for the log rate
#'       parameter for the active treatment group.
#'
#'     - \code{vlogRate2}: The variance for the log rate
#'       parameter for the control group.
#'
#'     - \code{vlogRR}: The variance of log rate ratio.
#'
#'     - \code{information}: The information of log rate ratio.
#'
#'     - \code{zlogRR}: The Z-statistic for log rate ratio.
#'
#' * \code{resultsUnderH0} when \code{nullVariance = TRUE}: A data frame
#'   with the following variables:
#'
#'     - \code{time}: The analysis time since trial start.
#'
#'     - \code{lambda1H0}: The restricted maximum likelihood estimate
#'       of the event rate for the active treatment group.
#'
#'     - \code{lambda2H0}: The restricted maximum likelihood estimate
#'       of the event rate for the control group.
#'
#'     - \code{rateRatioH0}: The rate ratio under H0.
#'
#'     - \code{vlogRate1H0}: The variance for the log rate
#'       parameter for the active treatment group under H0.
#'
#'     - \code{vlogRate2H0}: The variance for the log rate
#'       parameter for the control group under H0.
#'
#'     - \code{vlogRRH0}: The variance of log rate ratio under H0.
#'
#'     - \code{informationH0}: The information of log rate ratio under H0.
#'
#'     - \code{zlogRRH0}: The Z-statistic for log rate ratio with variance
#'       evaluated under H0.
#'
#'     - \code{varianceRatio}: The ratio of the variance under H0 versus
#'       the variance under H1.
#'
#'     - \code{lambda1}: The true event rate for the active treatment group.
#'
#'     - \code{lambda2}: The true event rate for the control group.
#'
#'     - \code{rateRatio}: The true rate ratio.
#'
#' * \code{resultsUnderH0} when \code{nullVariance = FALSE}: A data frame
#'   with the following variables:
#'
#'     - \code{time}: The analysis time since trial start.
#'
#'     - \code{rateRatioH0}: The rate ratio under H0.
#'
#'     - \code{varianceRatio}: Equal to 1.
#'
#'     - \code{lambda1}: The true event rate for the active treatment group.
#'
#'     - \code{lambda2}: The true event rate for the control group.
#'
#'     - \code{rateRatio}: The true rate ratio.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Example 1: Variable follow-up design
#'
#' nbstat(time = c(1, 1.25, 2, 3, 4),
#'        accrualIntensity = 1956/1.25,
#'        kappa1 = 5,
#'        kappa2 = 5,
#'        lambda1 = 0.7*0.125,
#'        lambda2 = 0.125,
#'        gamma1 = 0,
#'        gamma2 = 0,
#'        accrualDuration = 1.25,
#'        followupTime = 2.75)
#'
#' # Example 2: Fixed follow-up design
#'
#' nbstat(time = c(0.5, 1, 1.5, 2),
#'        accrualIntensity = 220/1.5,
#'        stratumFraction = c(0.2, 0.8),
#'        kappa1 = 3,
#'        kappa2 = 3,
#'        lambda1 = c(0.5*8.4, 0.6*10.5),
#'        lambda2 = c(8.4, 10.5),
#'        gamma1 = 0,
#'        gamma2 = 0,
#'        accrualDuration = 1.5,
#'        followupTime = 0.5,
#'        fixedFollowup = 1,
#'        nullVariance = 1)
#'
#' @export
nbstat <- function(time = NA_real_, rateRatioH0 = 1, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, kappa1 = NA_real_, kappa2 = NA_real_, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, nullVariance = FALSE) {
    .Call(`_lrstat_nbstat`, time, rateRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, kappa1, kappa2, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, nullVariance)
}

#' @title Power for Negative Binomial Rate Ratio
#' @description Estimates the power for negative binomial rate ratio test.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityRateRatio A vector of length \code{kMax - 1} for the
#'   futility bounds on the rate ratio scale.
#' @param typeBetaSpending The type of beta spending. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @inheritParams param_parameterBetaSpending
#' @param rateRatioH0 Rate ratio under the null hypothesis.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param kappa1 The dispersion parameter (reciprocal of the shape
#'   parameter of the gamma mixing distribution) for the active treatment
#'   group by stratum.
#' @param kappa2 The dispersion parameter (reciprocal of the shape
#'   parameter of the gamma mixing distribution) for the control group by
#'   stratum.
#' @param lambda1 The rate parameter of the negative binomial distribution
#'   for the active treatment group by stratum.
#' @param lambda2 The rate parameter of the negative binomial distribution
#'   for the control group by stratum.
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#' @param nullVariance Whether to calculate the variance for log rate ratio
#'   under the null hypothesis.
#'
#' @return An S3 class \code{nbpower} object with 4 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numberOfDropouts}: The total number of dropouts.
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{exposure}: The total exposure.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfDropouts}: The expected number of dropouts.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedExposure}: The expected exposure.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up duration.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{rateRatioH0}: The rate ratio under the null hypothesis.
#'
#'     - \code{rateRatio}: The rate ratio.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale.
#'
#'     - \code{futilityBounds}: The futility boundaries on the Z-scale.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{futilityPerStage}: The probability for futility stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeFutility}: The cumulative probability for futility
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha spent.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{exposure}: The exposure.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacyRateRatio}: The efficacy boundaries on the rate
#'       ratio scale.
#'
#'     - \code{futilityRateRatio}: The futility boundaries on the rate
#'       ratio scale.
#'
#'     - \code{efficacyP}: The efficacy boundaries on the p-value scale.
#'
#'     - \code{futilityP}: The futility boundaries on the p-value scale.
#'
#'     - \code{information}: The cumulative information.
#'
#'     - \code{efficacyStopping}: Whether to allow efficacy stopping.
#'
#'     - \code{futilityStopping}: Whether to allow futility stopping.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{typeBetaSpending},
#'   \code{parameterBetaSpending}, \code{allocationRatioPlanned},
#'   \code{accrualTime}, \code{accuralIntensity},
#'   \code{piecewiseSurvivalTime}, \code{kappa1}, \code{kappa2},
#'   \code{lambda1}, \code{lambda2}, \code{gamma1}, \code{gamma2},
#'   \code{spendingTime}, and \code{nullVariance}.
#'
#' * \code{byTreatmentCounts}: A list containing the following counts by
#'   treatment group:
#'
#'     - \code{numberOfEvents1}: The number of events by stage for
#'       the treatment group.
#'
#'     - \code{numberOfDropouts1}: The number of dropouts by stage for
#'       the treatment group.
#'
#'     - \code{numberOfSubjects1}: The number of subjects by stage for
#'       the treatment group.
#'
#'     - \code{exposure1}: The exposure by stage for the treatment group.
#'
#'     - \code{numberOfEvents2}: The number of events by stage for
#'       the control group.
#'
#'     - \code{numberOfDropouts2}: The number of dropouts by stage for
#'       the control group.
#'
#'     - \code{numberOfSubjects2}: The number of subjects by stage for
#'       the control group.
#'
#'     - \code{exposure2}: The exposure by stage for the control group.
#'
#'     - \code{expectedNumberOfEvents1}: The expected number of events for
#'       the treatment group.
#'
#'     - \code{expectedNumberOfDropouts1}: The expected number of dropouts
#'       for the treatment group.
#'
#'     - \code{expectedNumberOfSubjects1}: The expected number of subjects
#'       for the treatment group.
#'
#'     - \code{expectedExposure1}: The expected exposure for the treatment
#'       group.
#'
#'     - \code{expectedNumberOfEvents2}: The expected number of events for
#'       control group.
#'
#'     - \code{expectedNumberOfDropouts2}: The expected number of dropouts
#'       for the control group.
#'
#'     - \code{expectedNumberOfSubjects2}: The expected number of subjects
#'       for the control group.
#'
#'     - \code{expectedExposure2}: The expected exposure for the control
#'       group.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{nbstat}}
#'
#' @examples
#' # Example 1: Variable follow-up design
#'
#' nbpower(kMax = 2, informationRates = c(0.5, 1),
#'         alpha = 0.025, typeAlphaSpending = "sfOF",
#'         accrualIntensity = 1956/1.25,
#'         stratumFraction = c(0.2, 0.8),
#'         kappa1 = 5, kappa2 = 5,
#'         lambda1 = c(0.7*0.125, 0.75*0.25),
#'         lambda2 = c(0.125, 0.25),
#'         gamma1 = 0, gamma2 = 0,
#'         accrualDuration = 1.25,
#'         followupTime = 2.75, fixedFollowup = FALSE,
#'         nullVariance = 1)
#'
#' # Example 2: Fixed follow-up design
#'
#' nbpower(kMax = 2, informationRates = c(0.5, 1),
#'         alpha = 0.025, typeAlphaSpending = "sfOF",
#'         accrualIntensity = 220/1.5,
#'         kappa1 = 3, kappa2 = 3,
#'         lambda1 = 0.5*8.4, lambda2 = 8.4,
#'         gamma1 = 0, gamma2 = 0,
#'         accrualDuration = 1.5,
#'         followupTime = 0.5, fixedFollowup = TRUE)
#'
#' @export
nbpower <- function(kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityRateRatio = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, rateRatioH0 = 1, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, kappa1 = NA_real_, kappa2 = NA_real_, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, studyDuration = NA_real_, nullVariance = FALSE) {
    .Call(`_lrstat_nbpower`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityRateRatio, typeBetaSpending, parameterBetaSpending, rateRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, kappa1, kappa2, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, studyDuration, nullVariance)
}

#' @title Sample Size for Negative Binomial Rate Ratio
#' @description Obtains the needed accrual duration given power and
#' follow-up time, the needed follow-up time given power and
#' accrual duration, or the needed absolute accrual rates given
#' power, accrual duration, follow-up duration, and relative accrual
#' rates in a two-group negative binomial design.
#'
#' @param beta Type II error. Defaults to 0.2.
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityRateRatio A vector of length \code{kMax - 1} for the
#'   futility bounds on the rate ratio scale.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @param rateRatioH0 Rate ratio under the null hypothesis.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param kappa1 The dispersion parameter (reciprocal of the shape
#'   parameter of the gamma mixing distribution) for the active treatment
#'   group by stratum.
#' @param kappa2 The dispersion parameter (reciprocal of the shape
#'   parameter of the gamma mixing distribution) for the control group by
#'   stratum.
#' @param lambda1 The rate parameter of the negative binomial distribution
#'   for the active treatment group by stratum.
#' @param lambda2 The rate parameter of the negative binomial distribution
#'   for the control group by stratum.
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size.
#'   Defaults to 1 for sample size rounding.
#' @param nullVariance Whether to calculate the variance for log rate ratio
#'   under the null hypothesis.
#'
#' @return A list of two components:
#'
#' * \code{resultsUnderH1}: An S3 class \code{nbpower} object under the
#'   alternative hypothesis.
#'
#' * \code{resultsUnderH0}: An S3 class \code{nbpower} object under the
#'   null hypothesis.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{nbpower}}
#'
#' @examples
#' # Example 1: Obtains follow-up duration given power, accrual intensity,
#' # and accrual duration for variable follow-up
#'
#' nbsamplesize(beta = 0.2, kMax = 2,
#'              informationRates = c(0.5, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              accrualIntensity = 1956/1.25,
#'              kappa1 = 5, kappa2 = 5,
#'              lambda1 = 0.0875, lambda2 = 0.125,
#'              gamma1 = 0, gamma2 = 0,
#'              accrualDuration = 1.25,
#'              followupTime = NA, fixedFollowup = FALSE)
#'
#' # Example 2: Obtains accrual intensity given power, accrual duration, and
#' # follow-up duration for variable follow-up
#'
#' nbsamplesize(beta = 0.2, kMax = 2,
#'              informationRates = c(0.5, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              accrualIntensity = 100,
#'              kappa1 = 5, kappa2 = 5,
#'              lambda1 = 0.0875, lambda2 = 0.125,
#'              gamma1 = 0, gamma2 = 0,
#'              accrualDuration = 1.25,
#'              followupTime = 2.25, fixedFollowup = FALSE)
#'
#'
#' # Example 3: Obtains accrual duration given power, accrual intensity, and
#' # follow-up duration for fixed follow-up
#'
#' nbsamplesize(beta = 0.2, kMax = 2,
#'              informationRates = c(0.5, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              accrualIntensity = 1667,
#'              stratumFraction = c(0.2, 0.8),
#'              kappa1 = 5, kappa2 = 5,
#'              lambda1 = c(0.7*0.125, 0.75*0.25),
#'              lambda2 = c(0.125, 0.25),
#'              gamma1 = 0, gamma2 = 0,
#'              accrualDuration = NA,
#'              followupTime = 0.5, fixedFollowup = TRUE)
#'
#' @export
nbsamplesize <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityRateRatio = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, rateRatioH0 = 1, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, kappa1 = NA_real_, kappa2 = NA_real_, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, rounding = TRUE, nullVariance = FALSE) {
    .Call(`_lrstat_nbsamplesize`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityRateRatio, typeBetaSpending, parameterBetaSpending, userBetaSpending, rateRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, kappa1, kappa2, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, rounding, nullVariance)
}

#' @title Power for One-Sample Negative Binomial Rate
#' @description Estimates the power, stopping probabilities, and expected
#' sample size in a one-group negative binomial design.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityRate A vector of length \code{kMax - 1} for the
#'   futility bounds on the rate scale.
#' @param typeBetaSpending The type of beta spending. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @param lambdaH0 The rate parameter of the negative binomial distribution
#'   under the null hypothesis.
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param kappa The dispersion parameter (reciprocal of the shape parameter
#'   of the gamma mixing distribution) of the negative binomial
#'   distribution by stratum.
#' @param lambda The rate parameter of the negative binomial distribution
#'   under the alternative hypothesis by stratum.
#' @param gamma The hazard rate for exponential dropout or a vector of
#'   hazard rates for piecewise exponential dropout by stratum.
#'   Defaults to 0 for no dropout.
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#'
#' @return An S3 class \code{nbpower1s} object with 3 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numberOfDropouts}: The total number of dropouts.
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{exposure}: The total exposure.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfDropouts}: The expected number of dropouts.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedExposure}: The expected exposure.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up duration.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{lambdaH0}: The rate parameter of the negative binomial
#'       distribution under the null hypothesis.
#'
#'     - \code{lambda}: The overall rate parameter of the negative binomial
#'       distribution under the alternative hypothesis.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale.
#'
#'     - \code{futilityBounds}: The futility boundaries on the Z-scale.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{futilityPerStage}: The probability for futility stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeFutility}: The cumulative probability for futility
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha spent.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{exposure}: The exposure.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacyRate}: The efficacy boundaries on the rate scale.
#'
#'     - \code{futilityRate}: The futility boundaries on the rate scale.
#'
#'     - \code{efficacyP}: The efficacy boundaries on the p-value scale.
#'
#'     - \code{futilityP}: The futility boundaries on the p-value scale.
#'
#'     - \code{information}: The cumulative information.
#'
#'     - \code{efficacyStopping}: Whether to allow efficacy stopping.
#'
#'     - \code{futilityStopping}: Whether to allow futility stopping.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{typeBetaSpending},
#'   \code{parameterBetaSpending}, \code{accrualTime},
#'   \code{accuralIntensity}, \code{piecewiseSurvivalTime},
#'   \code{stratumFraction}, \code{kappa}, \code{lambda}, \code{gamma},
#'   and \code{spendingTime}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{nbstat}}
#'
#' @examples
#' # Example 1: Variable follow-up design
#'
#' nbpower1s(kMax = 2, informationRates = c(0.5, 1),
#'           alpha = 0.025, typeAlphaSpending = "sfOF",
#'           lambdaH0 = 0.125, accrualIntensity = 500,
#'           stratumFraction = c(0.2, 0.8),
#'           kappa = c(3, 5), lambda = c(0.0875, 0.085),
#'           gamma = 0, accrualDuration = 1.25,
#'           followupTime = 2.75, fixedFollowup = FALSE)
#'
#' # Example 2: Fixed follow-up design
#'
#' nbpower1s(kMax = 2, informationRates = c(0.5, 1),
#'           alpha = 0.025, typeAlphaSpending = "sfOF",
#'           lambdaH0 = 8.4, accrualIntensity = 40,
#'           kappa = 3, lambda = 0.5*8.4,
#'           gamma = 0, accrualDuration = 1.5,
#'           followupTime = 0.5, fixedFollowup = TRUE)
#'
#' @export
nbpower1s <- function(kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityRate = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, lambdaH0 = NA_real_, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, kappa = NA_real_, lambda = NA_real_, gamma = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_nbpower1s`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityRate, typeBetaSpending, parameterBetaSpending, lambdaH0, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, kappa, lambda, gamma, accrualDuration, followupTime, fixedFollowup, spendingTime, studyDuration)
}

#' @title Sample Size for One-Sample Negative Binomial Rate
#' @description Obtains the needed accrual duration given power and
#' follow-up time, the needed follow-up time given power and
#' accrual duration, or the needed absolute accrual rates given
#' power, accrual duration, follow-up duration, and relative accrual
#' rates in a one-group negative binomial design.
#'
#' @param beta Type II error. Defaults to 0.2.
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityRate A vector of length \code{kMax - 1} for the
#'   futility bounds on the rate scale.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @param lambdaH0 The rate parameter of the negative binomial distribution
#'   under the null hypothesis.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param kappa The dispersion parameter (reciprocal of the shape parameter
#'   of the gamma mixing distribution) of the negative binomial
#'   distribution by stratum.
#' @param lambda The rate parameter of the negative binomial distribution
#'   under the alternative hypothesis by stratum.
#' @param gamma The hazard rate for exponential dropout or a vector of
#'   hazard rates for piecewise exponential dropout by stratum.
#'   Defaults to 0 for no dropout.
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size.
#'   Defaults to 1 for sample size rounding.
#'
#' @return A list of two components:
#'
#' * \code{resultsUnderH1}: An S3 class \code{nbpower1s} object under the
#'   alternative hypothesis.
#'
#' * \code{resultsUnderH0}: An S3 class \code{nbpower1s} object under the
#'   null hypothesis.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{nbpower1s}}
#'
#' @examples
#' # Example 1: Obtains follow-up duration given power, accrual intensity,
#' # and accrual duration for variable follow-up
#'
#' nbsamplesize1s(beta = 0.2, kMax = 2,
#'                informationRates = c(0.5, 1),
#'                alpha = 0.025, typeAlphaSpending = "sfOF",
#'                lambdaH0 = 0.125, accrualIntensity = 500,
#'                stratumFraction = c(0.2, 0.8),
#'                kappa = c(3, 5), lambda = c(0.0875, 0.085),
#'                gamma = 0, accrualDuration = 1.25,
#'                followupTime = NA, fixedFollowup = FALSE)
#'
#' # Example 2: Obtains accrual intensity given power, accrual duration, and
#' # follow-up duration for variable follow-up
#'
#' nbsamplesize1s(beta = 0.2, kMax = 2,
#'                informationRates = c(0.5, 1),
#'                alpha = 0.025, typeAlphaSpending = "sfOF",
#'                lambdaH0 = 0.125, accrualIntensity = 100,
#'                kappa = 5, lambda = 0.0875,
#'                gamma = 0, accrualDuration = 1.25,
#'                followupTime = 2.25, fixedFollowup = FALSE)
#'
#'
#' # Example 3: Obtains accrual duration given power, accrual intensity, and
#' # follow-up duration for fixed follow-up
#'
#' nbsamplesize1s(beta = 0.2, kMax = 2,
#'                informationRates = c(0.5, 1),
#'                alpha = 0.025, typeAlphaSpending = "sfOF",
#'                lambdaH0 = 8.4, accrualIntensity = 40,
#'                kappa = 3, lambda = 4.2,
#'                gamma = 0, accrualDuration = NA,
#'                followupTime = 0.5, fixedFollowup = TRUE)
#'
#' @export
nbsamplesize1s <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityRate = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, lambdaH0 = NA_real_, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, kappa = NA_real_, lambda = NA_real_, gamma = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, rounding = TRUE) {
    .Call(`_lrstat_nbsamplesize1s`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityRate, typeBetaSpending, parameterBetaSpending, userBetaSpending, lambdaH0, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, kappa, lambda, gamma, accrualDuration, followupTime, fixedFollowup, spendingTime, rounding)
}

#' @title Power for Equivalence in Negative Binomial Rate Ratio
#' @description Obtains the power for equivalence in negative binomial
#' rate ratio.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_criticalValues
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param rateRatioLower The lower equivalence limit of rate ratio.
#' @param rateRatioUpper The upper equivalence limit of rate ratio.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param kappa1 The dispersion parameter (reciprocal of the shape parameter
#'   of the gamma mixing distribution) for the active treatment group
#'   by stratum.
#' @param kappa2 The dispersion parameter (reciprocal of the shape parameter
#'   of the gamma mixing distribution) for the control group by stratum.
#' @param lambda1 The rate parameter of the negative binomial distribution
#'   for the active treatment group by stratum.
#' @param lambda2 The rate parameter of the negative binomial distribution
#'   for the control group by stratum.
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#'
#' @return An S3 class \code{nbpowerequiv} object with 4 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{exposure}: The total exposure.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedExposure}: The expected exposure.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{rateRatioLower}: The lower equivalence limit of rate ratio.
#'
#'     - \code{rateRatioUpper}: The upper equivalence limit of rate ratio.
#'
#'     - \code{rateRatio}: The rate ratio.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up duration.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale for
#'       each of the two one-sided tests.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha for each of
#'       the two one-sided tests.
#'
#'     - \code{cumulativeAttainedAlphaH10}: The cumulative alpha attained
#'       under \code{H10}.
#'
#'     - \code{cumulativeAttainedAlphaH20}: The cumulative alpha attained
#'       under \code{H20}.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{exposure}: The exposure.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacyRateRatioLower}: The efficacy boundaries on the
#'       rate ratio scale for the one-sided null hypothesis at the
#'       lower equivalence limit.
#'
#'     - \code{efficacyRateRatioUpper}: The efficacy boundaries on the
#'       rate ratio scale for the one-sided null hypothesis at the
#'       upper equivalence limit.
#'
#'     - \code{efficacyP}: The efficacy bounds on the p-value scale for
#'       each of the two one-sided tests.
#'
#'     - \code{information}: The cumulative information.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{allocationRatioPlanned},
#'   \code{accrualTime}, \code{accuralIntensity},
#'   \code{piecewiseSurvivalTime}, \code{stratumFraction},
#'   \code{kappa1}, \code{kappa2},
#'   \code{lambda1}, \code{lambda2}, \code{gamma1}, \code{gamma2},
#'   \code{spendingTime}.
#'
#' * \code{byTreatmentCounts}: A list containing the following counts by
#'   treatment group:
#'
#'     - \code{numberOfEvents1}: The number of events by stage for
#'       the treatment group.
#'
#'     - \code{numberOfDropouts1}: The number of dropouts by stage for
#'       the treatment group.
#'
#'     - \code{numberOfSubjects1}: The number of subjects by stage for
#'       the treatment group.
#'
#'     - \code{exposure1}: The exposure by stage for the treatment group.
#'
#'     - \code{numberOfEvents2}: The number of events by stage for
#'       the control group.
#'
#'     - \code{numberOfDropouts2}: The number of dropouts by stage for
#'       the control group.
#'
#'     - \code{numberOfSubjects2}: The number of subjects by stage for
#'       the control group.
#'
#'     - \code{exposure2}: The exposure by stage for the control group.
#'
#'     - \code{expectedNumberOfEvents1}: The expected number of events for
#'       the treatment group.
#'
#'     - \code{expectedNumberOfDropouts1}: The expected number of dropouts
#'       for the treatment group.
#'
#'     - \code{expectedNumberOfSubjects1}: The expected number of subjects
#'       for the treatment group.
#'
#'     - \code{expectedExposure1}: The expected exposure for the treatment
#'       group.
#'
#'     - \code{expectedNumberOfEvents2}: The expected number of events for
#'       control group.
#'
#'     - \code{expectedNumberOfDropouts2}: The expected number of dropouts
#'       for the control group.
#'
#'     - \code{expectedNumberOfSubjects2}: The expected number of subjects
#'       for the control group.
#'
#'     - \code{expectedExposure2}: The expected exposure for the control
#'       group.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{nbstat}}
#'
#' @examples
#'
#' # Example 1: Variable follow-up design
#' nbpowerequiv(kMax = 2, informationRates = c(0.5, 1),
#'              alpha = 0.05, typeAlphaSpending = "sfOF",
#'              rateRatioLower = 2/3, rateRatioUpper = 3/2,
#'              accrualIntensity = 1956/1.25,
#'              kappa1 = 5, kappa2 = 5,
#'              lambda1 = 0.125, lambda2 = 0.125,
#'              gamma1 = 0, gamma2 = 0,
#'              accrualDuration = 1.25,
#'              followupTime = 2.75, fixedFollowup = FALSE)
#'
#' # Example 2: Fixed follow-up design
#' nbpowerequiv(kMax = 2, informationRates = c(0.5, 1),
#'              alpha = 0.05, typeAlphaSpending = "sfOF",
#'              rateRatioLower = 0.5, rateRatioUpper = 2,
#'              accrualIntensity = 220/1.5,
#'              stratumFraction = c(0.2, 0.8),
#'              kappa1 = 3, kappa2 = 3,
#'              lambda1 = c(8.4, 10.2),
#'              lambda2 = c(8.0, 11.5),
#'              gamma1 = 0, gamma2 = 0,
#'              accrualDuration = 1.5,
#'              followupTime = 0.5, fixedFollowup = TRUE)
#'
#' @export
nbpowerequiv <- function(kMax = 1L, informationRates = NA_real_, criticalValues = NULL, alpha = 0.05, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, rateRatioLower = NA_real_, rateRatioUpper = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, kappa1 = NA_real_, kappa2 = NA_real_, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_nbpowerequiv`, kMax, informationRates, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, rateRatioLower, rateRatioUpper, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, kappa1, kappa2, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, studyDuration)
}

#' @title Sample Size for Equivalence in Negative Binomial Rate Ratio
#' @description Obtains the sample size for equivalence in negative binomial
#' rate ratio.
#'
#' @param beta The type II error.
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_criticalValues
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param rateRatioLower The lower equivalence limit of rate ratio.
#' @param rateRatioUpper The upper equivalence limit of rate ratio.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param kappa1 The dispersion parameter (reciprocal of the shape parameter
#'   of the gamma mixing distribution) for the active treatment group by
#'   stratum.
#' @param kappa2 The dispersion parameter (reciprocal of the shape parameter
#'   of the gamma mixing distribution) for the control group by stratum.
#' @param lambda1 The rate parameter of the negative binomial distribution
#'   for the active treatment group by stratum.
#' @param lambda2 The rate parameter of the negative binomial distribution
#'   for the control group by stratum.
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size.
#'   Defaults to 1 for sample size rounding.
#'
#' @return An S3 class \code{nbpowerequiv} object
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{nbpowerequiv}}
#'
#' @examples
#'
#' # Example 1: Variable follow-up design and solve for follow-up time
#' nbsamplesizeequiv(beta = 0.1, kMax = 2, informationRates = c(0.5, 1),
#'                   alpha = 0.05, typeAlphaSpending = "sfOF",
#'                   rateRatioLower = 2/3, rateRatioUpper = 3/2,
#'                   accrualIntensity = 1956/1.25,
#'                   stratumFraction = c(0.2, 0.8),
#'                   kappa1 = c(3, 5),
#'                   kappa2 = c(2, 3),
#'                   lambda1 = c(0.125, 0.165),
#'                   lambda2 = c(0.135, 0.175),
#'                   gamma1 = -log(1-0.05),
#'                   gamma2 = -log(1-0.10),
#'                   accrualDuration = 1.25,
#'                   followupTime = NA, fixedFollowup = FALSE)
#'
#' # Example 2: Fixed follow-up design and solve for accrual duration
#' nbsamplesizeequiv(beta = 0.2, kMax = 2, informationRates = c(0.5, 1),
#'                   alpha = 0.05, typeAlphaSpending = "sfOF",
#'                   rateRatioLower = 0.5, rateRatioUpper = 2,
#'                   accrualIntensity = 220/1.5,
#'                   kappa1 = 3, kappa2 = 3,
#'                   lambda1 = 8.4, lambda2 = 8.4,
#'                   gamma1 = 0, gamma2 = 0,
#'                   accrualDuration = NA,
#'                   followupTime = 0.5, fixedFollowup = TRUE)
#'
#' @export
nbsamplesizeequiv <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, criticalValues = NULL, alpha = 0.05, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, rateRatioLower = NA_real_, rateRatioUpper = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, kappa1 = NA_real_, kappa2 = NA_real_, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, rounding = TRUE) {
    .Call(`_lrstat_nbsamplesizeequiv`, beta, kMax, informationRates, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, rateRatioLower, rateRatioUpper, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, kappa1, kappa2, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, rounding)
}

#' @title Restricted Mean Survival Time
#' @description Obtains the restricted mean survival time over an interval.
#'
#' @param t1 Lower bound of the analysis time interval.
#' @param t2 Upper bound of the analysis time interval.
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda
#'
#' @return The integral of the survival function from \code{t1} to \code{t2}
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' rmst(t1 = 0, t2 = 7, piecewiseSurvivalTime = c(0, 6),
#'      lambda = c(0.0533, 0.0309))
#'
#' @export
rmst <- function(t1 = 0, t2 = NA_real_, piecewiseSurvivalTime = 0L, lambda = NA_real_) {
    .Call(`_lrstat_rmst`, t1, t2, piecewiseSurvivalTime, lambda)
}

#' @title Covariance Between Restricted Mean Survival Times
#' @description Obtains the covariance between restricted mean survival
#' times at two different time points.
#'
#' @param t2 The calendar time for analysis 2.
#' @param tau1 The milestone time for analysis 1.
#' @param tau2 The milestone time for analysis 2.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda1
#' @inheritParams param_lambda2
#' @inheritParams param_gamma1
#' @inheritParams param_gamma2
#' @inheritParams param_accrualDuration
#' @inheritParams param_maxFollowupTime
#'
#' @return The covariance between the restricted mean survival times
#' for each treatment group.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' covrmst(t2 = 25, tau1 = 16, tau2 = 18, allocationRatioPlanned = 1,
#'         accrualTime = c(0, 3), accrualIntensity = c(10, 20),
#'         piecewiseSurvivalTime = c(0, 6),
#'         lambda1 = c(0.0533, 0.0309), lambda2 = c(0.0533, 0.0533),
#'         gamma1 = -log(1-0.05)/12, gamma2 = -log(1-0.05)/12,
#'         accrualDuration = 12, maxFollowupTime = 30)
#'
#' @export
covrmst <- function(t2 = NA_real_, tau1 = NA_real_, tau2 = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, maxFollowupTime = NA_real_) {
    .Call(`_lrstat_covrmst`, t2, tau1, tau2, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, lambda1, lambda2, gamma1, gamma2, accrualDuration, maxFollowupTime)
}

#' @title Stratified Difference in Restricted Mean Survival Times
#' @description Obtains the stratified restricted mean survival times
#' and difference in restricted mean survival times at given calendar
#' times.
#'
#' @param time A vector of calendar times for data cut.
#' @param milestone The milestone time at which to calculate the
#'   restricted mean survival time.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#'
#' @return A data frame containing the following variables:
#'
#' * \code{time}: The calendar time since trial start.
#'
#' * \code{subjects}: The number of enrolled subjects.
#'
#' * \code{nevents}: The total number of events.
#'
#' * \code{nevents1}: The number of events in the active treatment group.
#'
#' * \code{nevents2}: The number of events in the control group.
#'
#' * \code{ndropouts}: The total number of dropouts.
#'
#' * \code{ndropouts1}: The number of dropouts in the active treatment
#'   group.
#'
#' * \code{ndropouts2}: The number of dropouts in the control group.
#'
#' * \code{milestone}: The milestone time relative to randomization.
#'
#' * \code{nmilestone}: The total number of subjects reaching milestone.
#'
#' * \code{nmilestone1}: The number of subjects reaching milestone
#'   in the active treatment group.
#'
#' * \code{nmiletone2}: The number of subjects reaching milestone
#'   in the control group.
#'
#' * \code{rmst1}: The restricted mean survival time for the treatment
#'   group.
#'
#' * \code{rmst2}: The restricted mean survival time for the control group.
#'
#' * \code{rmstDiff}: The difference in restricted mean survival times,
#'   i.e., \code{rmst1 - rmst2}.
#'
#' * \code{vrmst1}: The variance for \code{rmst1}.
#'
#' * \code{vrmst2}: The variance for \code{rmst2}.
#'
#' * \code{vrmstDiff}: The variance for \code{rmstDiff}.
#'
#' * \code{information}: The information for \code{rmstDiff}, equal to
#'   \code{1/vrmstDiff}.
#'
#' * \code{rmstDiffZ}: The Z-statistic value, i.e.,
#'   \code{rmstDiff/sqrt(vrmstDiff)}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#'
#' rmstat(time = c(22, 40),
#'        milestone = 18,
#'        allocationRatioPlanned = 1,
#'        accrualTime = seq(0, 8),
#'        accrualIntensity = 26/9*seq(1, 9),
#'        piecewiseSurvivalTime = c(0, 6),
#'        stratumFraction = c(0.2, 0.8),
#'        lambda1 = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'        lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'        gamma1 = -log(1-0.05)/12,
#'        gamma2 = -log(1-0.05)/12,
#'        accrualDuration = 22,
#'        followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
rmstat <- function(time = NA_real_, milestone = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE) {
    .Call(`_lrstat_rmstat`, time, milestone, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup)
}

#' @title Power for Difference in Restricted Mean Survival Times
#' @description Estimates the power for testing the difference in
#' restricted mean survival times in a two-sample survival design.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityRmstDiff A vector of length \code{kMax - 1} for the
#'   futility bounds on the restricted mean survival time difference scale.
#' @param typeBetaSpending The type of beta spending. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @inheritParams param_parameterBetaSpending
#' @param milestone The milestone time at which to calculate the
#'   restricted mean survival time.
#' @param rmstDiffH0 The difference in restricted mean survival times
#'   under the null hypothesis. Defaults to 0 for superiority test.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#'
#' @return An S3 class \code{rmpower} object with 4 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numberOfDropouts}: The total number of dropouts.
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{numberOfMilestone}: The total number of subjects reaching
#'       milestone.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfDropouts}: The expected number of dropouts.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedNumberOfMilestone}: The expected number of subjects
#'       reaching milestone.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up duration.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{milestone}: The milestone time relative to randomization.
#'
#'     - \code{rmstDiffH0}: The difference in restricted mean survival
#'       times under the null hypothesis.
#'
#'     - \code{rmst1}: The restricted mean survival time for the
#'       treatment group.
#'
#'     - \code{rmst2}: The restricted mean survival time for the
#'       control group.
#'
#'     - \code{rmstDiff}: The difference in restricted mean survival times,
#'       equal to \code{rmst1 - rmst2}.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale.
#'
#'     - \code{futilityBounds}: The futility boundaries on the Z-scale.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{futilityPerStage}: The probability for futility stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeFutility}: The cumulative probability for futility
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha spent.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{numberOfMilestone}: The number of subjects reaching
#'       milestone.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacyRmstDiff}: The efficacy boundaries on the restricted
#'       mean survival time difference scale.
#'
#'     - \code{futilityRmstDiff}: The futility boundaries on the restricted
#'       mean survival time difference scale.
#'
#'     - \code{efficacyP}: The efficacy boundaries on the p-value scale.
#'
#'     - \code{futilityP}: The futility boundaries on the p-value scale.
#'
#'     - \code{information}: The cumulative information.
#'
#'     - \code{efficacyStopping}: Whether to allow efficacy stopping.
#'
#'     - \code{futilityStopping}: Whether to allow futility stopping.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{typeBetaSpending},
#'   \code{parameterBetaSpending}, \code{allocationRatioPlanned},
#'   \code{accrualTime}, \code{accuralIntensity},
#'   \code{piecewiseSurvivalTime}, \code{stratumFraction},
#'   \code{lambda1}, \code{lambda2}, \code{gamma1}, \code{gamma2},
#'   and \code{spendingTime}.
#'
#' * \code{byTreatmentCounts}: A list containing the following counts by
#'   treatment group:
#'
#'     - \code{numberOfEvents1}: The number of events by stage for
#'       the treatment group.
#'
#'     - \code{numberOfDropouts1}: The number of dropouts by stage for
#'       the treatment group.
#'
#'     - \code{numberOfSubjects1}: The number of subjects by stage for
#'       the treatment group.
#'
#'     - \code{numberOfMilestone1}: The number of subjects reaching
#'       milestone by stage for the active treatment group.
#'
#'     - \code{numberOfEvents2}: The number of events by stage for
#'       the control group.
#'
#'     - \code{numberOfDropouts2}: The number of dropouts by stage for
#'       the control group.
#'
#'     - \code{numberOfSubjects2}: The number of subjects by stage for
#'       the control group.
#'
#'     - \code{numberOfMilestone2}: The number of subjects reaching
#'       milestone by stage for the control group.
#'
#'     - \code{expectedNumberOfEvents1}: The expected number of events for
#'       the treatment group.
#'
#'     - \code{expectedNumberOfDropouts1}: The expected number of dropouts
#'       for the active treatment group.
#'
#'     - \code{expectedNumberOfSubjects1}: The expected number of subjects
#'       for the active treatment group.
#'
#'     - \code{expectedNumberOfMilestone1}: The expected number of subjects
#'       reaching milestone for the active treatment group.
#'
#'     - \code{expectedNumberOfEvents2}: The expected number of events for
#'       control group.
#'
#'     - \code{expectedNumberOfDropouts2}: The expected number of dropouts
#'       for the control group.
#'
#'     - \code{expectedNumberOfSubjects2}: The expected number of subjects
#'       for the control group.
#'
#'     - \code{expectedNumberOfMilestone2}: The expected number of subjects
#'       reaching milestone for the control group.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survival, and 5% dropout by
#' # the end of 1 year.
#'
#' rmpower(kMax = 2, informationRates = c(0.8, 1),
#'         alpha = 0.025, typeAlphaSpending = "sfOF",
#'         milestone = 18,
#'         allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'         accrualIntensity = 26/9*seq(1, 9),
#'         piecewiseSurvivalTime = c(0, 6),
#'         stratumFraction = c(0.2, 0.8),
#'         lambda1 = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'         lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'         gamma1 = -log(1-0.05)/12,
#'         gamma2 = -log(1-0.05)/12, accrualDuration = 22,
#'         followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
rmpower <- function(kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityRmstDiff = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, milestone = NA_real_, rmstDiffH0 = 0, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_rmpower`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityRmstDiff, typeBetaSpending, parameterBetaSpending, milestone, rmstDiffH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, studyDuration)
}

#' @title Sample Size for Difference in Restricted Mean Survival Times
#' @description Obtains the needed accrual duration given power,
#' accrual intensity, and follow-up time, the needed follow-up time
#' given power, accrual intensity, and accrual duration, or the needed
#' absolute accrual intensity given power, relative accrual intensity,
#' accrual duration, and follow-up time in a two-group survival design.
#'
#' @param beta Type II error. Defaults to 0.2.
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityRmstDiff A vector of length \code{kMax - 1} for the
#'   futility bounds on the restricted mean survival time difference scale.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @param milestone The milestone time at which to calculate the
#'   restricted mean survival time.
#' @param rmstDiffH0 The difference in restricted mean survival times
#'   under the null hypothesis. Defaults to 0 for superiority test.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size.
#'   Defaults to 1 for sample size rounding.
#'
#' @return A list of two components:
#'
#' * \code{resultsUnderH1}: An S3 class \code{rmpower} object under the
#'   alternative hypothesis.
#'
#' * \code{resultsUnderH0}: An S3 class \code{rmpower} object under the
#'   null hypothesis.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{rmpower}}
#'
#' @examples
#' # Example 1: Obtains follow-up time given power, accrual intensity,
#' # and accrual duration for variable follow-up. Of note, the power
#' # reaches the maximum when the follow-up time equals milestone.
#'
#' rmsamplesize(beta = 0.2, kMax = 2, informationRates = c(0.8, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              milestone = 18,
#'              allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'              accrualIntensity = 100/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              stratumFraction = c(0.2, 0.8),
#'              lambda1 = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'              lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12, accrualDuration = 22,
#'              followupTime = NA, fixedFollowup = FALSE)
#'
#' # Example 2: Obtains accrual intensity given power, accrual duration, and
#' # follow-up time for variable follow-up
#'
#' rmsamplesize(beta = 0.2, kMax = 2, informationRates = c(0.8, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              milestone = 18,
#'              allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'              accrualIntensity = 100/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              stratumFraction = c(0.2, 0.8),
#'              lambda1 = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'              lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12, accrualDuration = 22,
#'              followupTime = 18, fixedFollowup = FALSE)
#'
#'
#' # Example 3: Obtains accrual duration given power, accrual intensity, and
#' # follow-up time for fixed follow-up
#'
#' rmsamplesize(beta = 0.2, kMax = 2, informationRates = c(0.8, 1),
#'              alpha = 0.025, typeAlphaSpending = "sfOF",
#'              milestone = 18,
#'              allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'              accrualIntensity = 100/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              stratumFraction = c(0.2, 0.8),
#'              lambda1 = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'              lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12, accrualDuration = NA,
#'              followupTime = 18, fixedFollowup = TRUE)
#'
#' @export
rmsamplesize <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityRmstDiff = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, milestone = NA_real_, rmstDiffH0 = 0, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, rounding = TRUE) {
    .Call(`_lrstat_rmsamplesize`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityRmstDiff, typeBetaSpending, parameterBetaSpending, userBetaSpending, milestone, rmstDiffH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, rounding)
}

#' @title Power for One-Sample Restricted Mean Survival Time
#' @description Estimates the power, stopping probabilities, and expected
#' sample size in a one-group survival design.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityRmst A vector of length \code{kMax - 1} for the
#'   futility bounds on the restricted mean survival time scale.
#' @param typeBetaSpending The type of beta spending. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @inheritParams param_parameterBetaSpending
#' @param milestone The milestone time at which to calculate the
#'   restricted mean survival time.
#' @param rmstH0 The restricted mean survival time under the null
#'   hypothesis.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param lambda A vector of hazard rates for the event in each analysis
#'  time interval by stratum under the alternative hypothesis.
#' @param gamma The hazard rate for exponential dropout or a vector of
#'   hazard rates for piecewise exponential dropout. Defaults to 0 for
#'   no dropout.
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#'
#' @return An S3 class \code{rmpower1s} object with 3 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{numberOfMilestone}: The total number of subjects reaching
#'       milestone.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedNumberOfMilestone}: The expected number of subjects
#'       reaching milestone.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up duration.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{milestone}: The milestone time to calculate the restricted
#'       mean survival time.
#'
#'     - \code{rmstH0}: The restricted mean survival time under the null
#'       hypothesis.
#'
#'     - \code{rmst}: The restricted mean survival time under the
#'       alternative hypothesis.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale.
#'
#'     - \code{futilityBounds}: The futility boundaries on the Z-scale.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{futilityPerStage}: The probability for futility stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeFutility}: The cumulative probability for futility
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha spent.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{numberOfMilestone}: The number of subjects reaching
#'       milestone.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacyRmst}: The efficacy boundaries on the restricted
#'       mean survival time.
#'
#'     - \code{futilityRmst}: The futility boundaries on the restricted
#'       mean survival time.
#'
#'     - \code{efficacyP}: The efficacy boundaries on the p-value scale.
#'
#'     - \code{futilityP}: The futility boundaries on the p-value scale.
#'
#'     - \code{information}: The cumulative information.
#'
#'     - \code{efficacyStopping}: Whether to allow efficacy stopping.
#'
#'     - \code{futilityStopping}: Whether to allow futility stopping.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{typeBetaSpending},
#'   \code{parameterBetaSpending}, \code{accrualTime},
#'   \code{accuralIntensity}, \code{piecewiseSurvivalTime},
#'   \code{stratumFraction}, \code{lambda}, \code{gamma},
#'   and \code{spendingTime}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{rmstat}}
#'
#' @examples
#'
#' rmpower1s(kMax = 2, informationRates = c(0.8, 1),
#'           alpha = 0.025, typeAlphaSpending = "sfOF",
#'           milestone = 18, rmstH0 = 10,
#'           accrualTime = seq(0, 8),
#'           accrualIntensity = 26/9*seq(1, 9),
#'           piecewiseSurvivalTime = c(0, 6),
#'           stratumFraction = c(0.2, 0.8),
#'           lambda = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'           gamma = -log(1-0.05)/12, accrualDuration = 22,
#'           followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
rmpower1s <- function(kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityRmst = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, milestone = NA_real_, rmstH0 = NA_real_, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda = NA_real_, gamma = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_rmpower1s`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityRmst, typeBetaSpending, parameterBetaSpending, milestone, rmstH0, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda, gamma, accrualDuration, followupTime, fixedFollowup, spendingTime, studyDuration)
}

#' @title Sample Size for One-Sample Restricted Mean Survival Time
#' @description Obtains the needed accrual duration given power and
#' follow-up time, the needed follow-up time given power and
#' accrual duration, or the needed absolute accrual rates given
#' power, accrual duration, follow-up duration, and relative accrual
#' rates in a one-group survival design.
#'
#' @param beta Type II error. Defaults to 0.2.
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @inheritParams param_criticalValues
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @inheritParams param_futilityBounds
#' @param futilityCP A vector of length \code{kMax - 1} for the futility
#'   bounds on the conditional power scale.
#' @param futilityRmst A vector of length \code{kMax - 1} for the
#'   futility bounds on the restricted mean survival time scale.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @param milestone The milestone time at which to calculate the
#'   restricted survival time.
#' @param rmstH0 The restricted mean survival time under the null
#'   hypothesis.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param lambda A vector of hazard rates for the event in each analysis
#'  time interval by stratum under the alternative hypothesis.
#' @param gamma The hazard rate for exponential dropout or a vector of
#'   hazard rates for piecewise exponential dropout. Defaults to 0 for
#'   no dropout.
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size.
#'   Defaults to 1 for sample size rounding.
#'
#' @return A list of two components:
#'
#' * \code{resultsUnderH1}: An S3 class \code{rmpower1s} object under the
#'   alternative hypothesis.
#'
#' * \code{resultsUnderH0}: An S3 class \code{rmpower1s} object under the
#'   null hypothesis.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{rmpower1s}}
#'
#' @examples
#' # Example 1: Obtains follow-up duration given power, accrual intensity,
#' # and accrual duration for variable follow-up
#'
#' rmsamplesize1s(beta = 0.2, kMax = 2,
#'                informationRates = c(0.8, 1),
#'                alpha = 0.025, typeAlphaSpending = "sfOF",
#'                milestone = 18, rmstH0 = 10,
#'                accrualTime = seq(0, 8),
#'                accrualIntensity = 26/9*seq(1, 9),
#'                piecewiseSurvivalTime = c(0, 6),
#'                stratumFraction = c(0.2, 0.8),
#'                lambda = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'                gamma = -log(1-0.05)/12, accrualDuration = 22,
#'                followupTime = NA, fixedFollowup = FALSE)
#'
#' # Example 2: Obtains accrual intensity given power, accrual duration, and
#' # follow-up duration for variable follow-up
#'
#' rmsamplesize1s(beta = 0.2, kMax = 2,
#'                informationRates = c(0.8, 1),
#'                alpha = 0.025, typeAlphaSpending = "sfOF",
#'                milestone = 18, rmstH0 = 10,
#'                accrualTime = seq(0, 8),
#'                accrualIntensity = 26/9*seq(1, 9),
#'                piecewiseSurvivalTime = c(0, 6),
#'                stratumFraction = c(0.2, 0.8),
#'                lambda = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'                gamma = -log(1-0.05)/12, accrualDuration = 22,
#'                followupTime = 18, fixedFollowup = FALSE)
#'
#'
#' # Example 3: Obtains accrual duration given power, accrual intensity, and
#' # follow-up duration for fixed follow-up
#'
#' rmsamplesize1s(beta = 0.2, kMax = 2,
#'                informationRates = c(0.8, 1),
#'                alpha = 0.025, typeAlphaSpending = "sfOF",
#'                milestone = 18, rmstH0 = 10,
#'                accrualTime = seq(0, 8),
#'                accrualIntensity = 26/9*seq(1, 9),
#'                piecewiseSurvivalTime = c(0, 6),
#'                stratumFraction = c(0.2, 0.8),
#'                lambda = c(0.0533, 0.0309, 1.5*0.0533, 1.5*0.0309),
#'                gamma = -log(1-0.05)/12, accrualDuration = NA,
#'                followupTime = 18, fixedFollowup = TRUE)
#'
#' @export
rmsamplesize1s <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityRmst = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, milestone = NA_real_, rmstH0 = NA_real_, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda = NA_real_, gamma = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, rounding = TRUE) {
    .Call(`_lrstat_rmsamplesize1s`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityRmst, typeBetaSpending, parameterBetaSpending, userBetaSpending, milestone, rmstH0, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda, gamma, accrualDuration, followupTime, fixedFollowup, spendingTime, rounding)
}

#' @title Power for Equivalence in Restricted Mean Survival Time Difference
#' @description Obtains the power for equivalence in restricted mean
#' survival time difference.
#'
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_criticalValues
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param milestone The milestone time at which to calculate the
#'   restricted mean survival time.
#' @param rmstDiffLower The lower equivalence limit of restricted mean
#'   survival time difference.
#' @param rmstDiffUpper The upper equivalence limit of restricted mean
#'   survival time difference.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param studyDuration Study duration for fixed follow-up design.
#'   Defaults to missing, which is to be replaced with the sum of
#'   \code{accrualDuration} and \code{followupTime}. If provided,
#'   the value is allowed to be less than the sum of \code{accrualDuration}
#'   and \code{followupTime}.
#'
#' @return An S3 class \code{rmpowerequiv} object with 4 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{numberOfEvents}: The total number of events.
#'
#'     - \code{numberOfSubjects}: The total number of subjects.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{expectedInformation}: The expected information.
#'
#'     - \code{kMax}: The number of stages.
#'
#'     - \code{milestone}: The milestone time relative to randomization.
#'
#'     - \code{rmstDiffLower}: The lower equivalence limit of restricted
#'       mean survival time difference.
#'
#'     - \code{rmstDiffUpper}: The upper equivalence limit of restricted
#'       mean survival time difference.
#'
#'     - \code{rmst1}: The restricted mean survival time for the
#'       treatment group.
#'
#'     - \code{rmst2}: The restricted mean survival time for the
#'       control group.
#'
#'     - \code{rmstDiff}: The restricted mean survival time difference.
#'
#'     - \code{accrualDuration}: The accrual duration.
#'
#'     - \code{followupTime}: The follow-up duration.
#'
#'     - \code{fixedFollowup}: Whether a fixed follow-up design is used.
#'
#' * \code{byStageResults}: A data frame containing the following variables:
#'
#'     - \code{informationRates}: The information rates.
#'
#'     - \code{efficacyBounds}: The efficacy boundaries on the Z-scale for
#'       each of the two one-sided tests.
#'
#'     - \code{rejectPerStage}: The probability for efficacy stopping.
#'
#'     - \code{cumulativeRejection}: The cumulative probability for efficacy
#'       stopping.
#'
#'     - \code{cumulativeAlphaSpent}: The cumulative alpha for each of
#'       the two one-sided tests.
#'
#'     - \code{cumulativeAttainedAlphaH10}: The cumulative alpha attained
#'       under \code{H10}.
#'
#'     - \code{cumulativeAttainedAlphaH20}: The cumulative alpha attained
#'       under \code{H20}.
#'
#'     - \code{numberOfEvents}: The number of events.
#'
#'     - \code{numberOfDropouts}: The number of dropouts.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#'     - \code{numberOfMilestone}: The number of subjects reaching
#'       milestone.
#'
#'     - \code{analysisTime}: The average time since trial start.
#'
#'     - \code{efficacyRmstDiffLower}: The efficacy boundaries on the
#'       restricted mean survival time difference scale for the one-sided
#'       null hypothesis at the lower equivalence limit.
#'
#'     - \code{efficacyRmstDiffUpper}: The efficacy boundaries on the
#'       restricted mean survival time difference scale for the one-sided
#'       null hypothesis at the upper equivalence limit.
#'
#'     - \code{efficacyP}: The efficacy bounds on the p-value scale for
#'       each of the two one-sided tests.
#'
#'     - \code{information}: The cumulative information.
#'
#' * \code{settings}: A list containing the following input parameters:
#'   \code{typeAlphaSpending}, \code{parameterAlphaSpending},
#'   \code{userAlphaSpending}, \code{allocationRatioPlanned},
#'   \code{accrualTime}, \code{accuralIntensity},
#'   \code{piecewiseSurvivalTime}, \code{stratumFraction},
#'   \code{lambda1}, \code{lambda2}, \code{gamma1}, \code{gamma2},
#'   and \code{spendingTime}.
#'
#' * \code{byTreatmentCounts}: A list containing the following counts by
#'   treatment group:
#'
#'     - \code{numberOfEvents1}: The number of events by stage for
#'       the treatment group.
#'
#'     - \code{numberOfDropouts1}: The number of dropouts by stage for
#'       the treatment group.
#'
#'     - \code{numberOfSubjects1}: The number of subjects by stage for
#'       the treatment group.
#'
#'     - \code{numberOfMilestone1}: The number of subjects reaching
#'       milestone by stage for the active treatment group.
#'
#'     - \code{numberOfEvents2}: The number of events by stage for
#'       the control group.
#'
#'     - \code{numberOfDropouts2}: The number of dropouts by stage for
#'       the control group.
#'
#'     - \code{numberOfSubjects2}: The number of subjects by stage for
#'       the control group.
#'
#'     - \code{numberOfMilestone2}: The number of subjects reaching
#'       milestone by stage for the control group.
#'
#'     - \code{expectedNumberOfEvents1}: The expected number of events for
#'       the treatment group.
#'
#'     - \code{expectedNumberOfDropouts1}: The expected number of dropouts
#'       for the active treatment group.
#'
#'     - \code{expectedNumberOfSubjects1}: The expected number of subjects
#'       for the active treatment group.
#'
#'     - \code{expectedNumberOfMilestone1}: The expected number of subjects
#'       reaching milestone for the active treatment group.
#'
#'     - \code{expectedNumberOfEvents2}: The expected number of events for
#'       control group.
#'
#'     - \code{expectedNumberOfDropouts2}: The expected number of dropouts
#'       for the control group.
#'
#'     - \code{expectedNumberOfSubjects2}: The expected number of subjects
#'       for the control group.
#'
#'     - \code{expectedNumberOfMilestone2}: The expected number of subjects
#'       reaching milestone for the control group.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{rmstat}}
#'
#' @examples
#'
#' rmpowerequiv(kMax = 2, informationRates = c(0.5, 1),
#'              alpha = 0.05, typeAlphaSpending = "sfOF",
#'              milestone = 18,
#'              rmstDiffLower = -2, rmstDiffUpper = 2,
#'              allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'              accrualIntensity = 29/9*seq(1, 9),
#'              piecewiseSurvivalTime = c(0, 6),
#'              stratumFraction = c(0.2, 0.8),
#'              lambda1 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'              lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'              gamma1 = -log(1-0.05)/12,
#'              gamma2 = -log(1-0.05)/12, accrualDuration = 22,
#'              followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
rmpowerequiv <- function(kMax = 1L, informationRates = NA_real_, criticalValues = NULL, alpha = 0.05, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, milestone = NA_real_, rmstDiffLower = NA_real_, rmstDiffUpper = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = FALSE, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_rmpowerequiv`, kMax, informationRates, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, milestone, rmstDiffLower, rmstDiffUpper, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, studyDuration)
}

#' @title Sample Size for Equivalence in Restricted Mean Survival Time
#' Difference
#' @description Obtains the sample size for equivalence in restricted
#' mean survival time difference.
#'
#' @param beta The type II error.
#' @inheritParams param_kMax
#' @param informationRates The information rates.
#'   Defaults to \code{(1:kMax) / kMax} if left unspecified.
#' @inheritParams param_criticalValues
#' @param alpha The significance level for each of the two one-sided
#'   tests. Defaults to 0.05.
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param milestone The milestone time at which to calculate the
#'   restricted mean survival time.
#' @param rmstDiffLower The lower equivalence limit of restricted mean
#'   survival time difference.
#' @param rmstDiffUpper The upper equivalence limit of restricted mean
#'   survival time difference.
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @inheritParams param_lambda1_stratified
#' @inheritParams param_lambda2_stratified
#' @inheritParams param_gamma1_stratified
#' @inheritParams param_gamma2_stratified
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @param spendingTime A vector of length \code{kMax} for the error spending
#'   time at each analysis. Defaults to missing, in which case, it is the
#'   same as \code{informationRates}.
#' @param rounding Whether to round up sample size.
#'   Defaults to 1 for sample size rounding.
#'
#' @return An S3 class \code{rmpowerequiv} object
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @seealso \code{\link{rmpowerequiv}}
#'
#' @examples
#'
#' rmsamplesizeequiv(beta = 0.1, kMax = 2, informationRates = c(0.5, 1),
#'                   alpha = 0.05, typeAlphaSpending = "sfOF",
#'                   milestone = 18,
#'                   rmstDiffLower = -2, rmstDiffUpper = 2,
#'                   allocationRatioPlanned = 1, accrualTime = seq(0, 8),
#'                   accrualIntensity = 26/9*seq(1, 9),
#'                   piecewiseSurvivalTime = c(0, 6),
#'                   stratumFraction = c(0.2, 0.8),
#'                   lambda1 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'                   lambda2 = c(0.0533, 0.0533, 1.5*0.0533, 1.5*0.0533),
#'                   gamma1 = -log(1-0.05)/12,
#'                   gamma2 = -log(1-0.05)/12, accrualDuration = NA,
#'                   followupTime = 18, fixedFollowup = FALSE)
#'
#' @export
rmsamplesizeequiv <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, criticalValues = NULL, alpha = 0.05, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, milestone = NA_real_, rmstDiffLower = NA_real_, rmstDiffUpper = NA_real_, allocationRatioPlanned = 1, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, lambda1 = NA_real_, lambda2 = NA_real_, gamma1 = 0L, gamma2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = 0L, spendingTime = NA_real_, rounding = 1L) {
    .Call(`_lrstat_rmsamplesizeequiv`, beta, kMax, informationRates, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, milestone, rmstDiffLower, rmstDiffUpper, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, spendingTime, rounding)
}

#' @title Exit Probabilities for Phase 2/3 Seamless Design
#' @description Computes the upper and lower exit probabilities for a phase
#' 2/3 seamless design. In Phase 2, multiple active arms are compared
#' against a common control arm. If the phase-2 max-Z statistic crosses the
#' efficacy boundary, the trial stops early for efficacy; if it falls below
#' the futility boundary, the trial stops early for futility. Otherwise, the
#' best-performing arm is selected to proceed to Phase 3, where it is tested
#' against the common control over multiple looks with upper and optional
#' lower stopping boundaries.
#'
#' @param M Number of active treatment arms in Phase 2.
#' @param r Randomization ratio of each active arm to the common control
#'   in Phase 2.
#' @param theta A vector of length \eqn{M} representing the true treatment
#'   effects for each active arm versus the common control.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics in Phase 2 is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is used.
#' @param K Number of sequential looks in Phase 3.
#' @param b A vector of efficacy boundaries (length \eqn{K+1}). The first
#'   element is the efficacy boundary for the phase-2 max-Z statistic;
#'   the remaining \eqn{K} elements are efficacy boundaries for the selected
#'   arm in Phase 3.
#' @param a An optional vector of futility boundaries (length \eqn{K+1}).
#'   The first element is the futility boundary for the phase-2 max-Z
#'   statistic; the remaining \eqn{K} elements are futility boundaries for
#'   the selected arm in Phase 3. If omitted, no futility stopping is
#'   applied.
#' @param I A vector of information levels (length \eqn{K+1}) for any active
#'   arm versus the common control. The first element is for Phase 2;
#'   the remaining \eqn{K} elements are for the looks in Phase 3.
#'
#' @details
#' The function assumes a multivariate normal distribution for the Wald
#' statistics. The "best" arm is defined as the active arm with the largest
#' Z-statistic at the end of Phase 2 among designs that continue beyond the
#' phase-2 analysis.
#'
#' \strong{Decision Rules:}
#'
#' * \strong{Phase 2 efficacy stop}: reject if the phase-2 max-Z statistic
#'   satisfies \eqn{\max_m Z_m(I_0) \ge b_0}.
#'
#' * \strong{Phase 2 futility stop}: stop for futility if the phase-2 max-Z
#'   statistic satisfies \eqn{\max_m Z_m(I_0) \le a_0}.
#'
#' * \strong{Continue to Phase 3}: if \eqn{a_0 < \max_m Z_m(I_0) < b_0},
#'   select the arm with the largest phase-2 Z-statistic and continue with
#'   that arm only.
#'
#' * \strong{Phase 3 efficacy stop}: at look \eqn{k}, reject if the selected
#'   arm's Z-statistic exceeds the efficacy boundary and no earlier stop has
#'   occurred.
#'
#' * \strong{Phase 3 futility stop}: at look \eqn{k}, stop for futility if
#'   the selected arm's Z-statistic is below the futility boundary and no
#'   earlier stop has occurred.
#'
#' \strong{Design Assumptions:}
#'
#' * All active arms share the same information level in Phase 2.
#'
#' * Exactly one active arm is selected at the end of Phase 2 based on the
#'   largest observed Z-statistic when the trial continues to Phase 3.
#'
#' @return A list containing the following components:
#'
#' * \code{exitProbUpper}: A vector of length \eqn{K + 1}. The first element
#'   is the probability of stopping for efficacy in Phase 2; the remaining
#'   elements are the probabilities of stopping for efficacy at each look in
#'   Phase 3.
#'
#' * \code{exitProbLower}: A vector of length \eqn{K + 1}. The first element
#'   is the probability of stopping for futility in Phase 2; the remaining
#'   elements are the probabilities of stopping for futility at each look in
#'   Phase 3.
#'
#' * \code{exitProbByArmUpper}: A \eqn{(K+1) \times M} matrix. The
#'   \eqn{(k, m)}-th entry gives the probability of stopping for efficacy at
#'   look \eqn{k} given that arm \eqn{m} is selected as best.
#'
#' * \code{exitProbByArmLower}: A \eqn{(K+1) \times M} matrix. The
#'   \eqn{(k, m)}-th entry gives the probability of stopping for futility at
#'   look \eqn{k} given that arm \eqn{m} is selected as best.
#'
#' * \code{selectAsBest}: A vector of length \eqn{M} containing the
#'   probability that each active arm is selected to move on to Phase 3.
#'
#' For backward compatibility, the list also contains:
#'
#' * \code{exitProb}: identical to \code{exitProbUpper}.
#'
#' * \code{exitProbByArm}: identical to \code{exitProbByArmUpper}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive two-stage seamless sequential design for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2025, 35(4), 565-587.
#'
#' @examples
#'
#' # Setup: 2 active arms vs control in Phase 2; 1 selected arm vs control
#' # in Phase 3. Phase 3 has 2 sequential looks.
#'
#' # Information levels: equal spacing over 3 looks based on a maximum of
#' # 110 patients per arm, SD = 1.0
#' I <- c(110 / (2 * 1.0^2) * seq(1, 3)/3)
#'
#' # O'Brien-Fleming efficacy boundaries
#' b <- c(3.776605, 2.670463, 2.180424)
#'
#' # No futility stopping
#' p0 <- exitprob_seamless(M = 2, theta = c(0, 0), K = 2, b = b, I = I)
#' cumsum(p0$exitProbUpper)
#'
#' # Add futility stopping
#' a <- c(0, 0.5, b[3])
#' p1 <- exitprob_seamless(M = 2, theta = c(0.3, 0.5), K = 2, b = b, a = a, I = I)
#' cbind(
#'   cumulativeEfficacy = cumsum(p1$exitProbUpper),
#'   cumulativeFutility = cumsum(p1$exitProbLower)
#' )
#'
#' @export
exitprob_seamless <- function(M = NA_integer_, r = 1, theta = NA_real_, corr_known = TRUE, K = NA_integer_, b = NULL, a = NULL, I = NULL) {
    .Call(`_lrstat_exitprob_seamless`, M, r, theta, corr_known, K, b, a, I)
}

#' @title Efficacy Boundaries for Phase 2/3 Seamless Design
#' @description Calculates the efficacy stopping boundaries for a phase 2/3
#' seamless design, accounting for the selection of the best arm
#' at the end of Phase 2 and sequential testing in Phase 3.
#'
#' @param M Number of active treatment arms in Phase 2.
#' @param r Randomization ratio of each active arm to the common control
#'   in Phase 2.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics in Phase 2 is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is assumed.
#' @param k The index of the current look in Phase 3.
#' @param informationRates A numeric vector of information rates up to the
#'   current look. Values must be strictly increasing and \eqn{\le 1}.
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param spendingTime A numeric vector of length \eqn{k+1} specifying the
#'   error spending time at each analysis. Values must be strictly increasing
#'   and \eqn{\le 1}. If omitted, defaults to \code{informationRates}.
#' @inheritParams param_efficacyStopping
#'
#' @details
#' The function determines critical values by solving for the boundary that
#' satisfies the alpha-spending requirement, given the selection of the
#' "best" arm at the end of Phase 2.
#'
#' If \code{typeAlphaSpending} is \code{"OF"}, \code{"P"}, \code{"WT"}, or
#' \code{"none"}, then \code{informationRates}, \code{efficacyStopping},
#' and \code{spendingTime} must be of full length \code{kMax}, and
#' \code{informationRates} and \code{spendingTime} must end with 1.
#'
#' @return A numeric vector of length \eqn{k + 1} containing the critical
#' values (on the standard normal Z-scale) for each analysis up to the
#' current look.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive two-stage seamless sequential design for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2025, 35(4), 565-587.
#'
#' @examples
#'
#' # Determine O'Brien-Fleming boundaries for a seamless design with
#' # 2 active arms in Phase 2 and 2 looks in Phase 3 (3 looks total).
#' getBound_seamless(M = 2, k = 2, informationRates = seq(1, 3)/3,
#'                   alpha = 0.025, typeAlphaSpending = "OF")
#'
#' @export
getBound_seamless <- function(M = NA_integer_, r = 1, corr_known = TRUE, k = NA_integer_, informationRates = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, spendingTime = NA_real_, efficacyStopping = NA_integer_) {
    .Call(`_lrstat_getBound_seamless`, M, r, corr_known, k, informationRates, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, spendingTime, efficacyStopping)
}

#' @title Power and Sample Size for Phase 2/3 Seamless Design
#' @description Computes either the maximum information and stopping
#' boundaries for a phase 2/3 seamless design, or the achieved power when
#' the maximum information and stopping boundaries are provided. Both
#' efficacy and futility stopping can be incorporated.
#'
#' @param beta Type II error rate. Provide either \code{beta} or \code{IMax};
#'   the other should be missing.
#' @param IMax Maximum information for any active arm versus the common
#'   control. Provide either \code{IMax} or \code{beta}; the other should
#'   be missing.
#' @param theta A vector of length \eqn{M} representing the true treatment
#'   effects for each active arm versus the common control. The global null
#'   is \eqn{\theta_i = 0} for all \eqn{i}, and alternatives are one-sided:
#'   \eqn{\theta_i > 0} for at least one \eqn{i = 1, \ldots, M}.
#' @param M Number of active treatment arms in Phase 2.
#' @param r Randomization ratio of each active arm to the common control
#'   in Phase 2.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics in Phase 2 is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is used.
#' @param K Number of sequential looks in Phase 3.
#' @param informationRates A numeric vector of information rates fixed
#'   before the trial. If unspecified, defaults to \eqn{(1:(K+1)) / (K+1)}.
#' @inheritParams param_efficacyStopping
#' @inheritParams param_futilityStopping
#' @param criticalValues The upper boundaries on the max-Z statistic scale
#'   for Phase 2 and the Z statistics for the selected arm in Phase 3.
#'   If missing, boundaries will be computed based on the specified alpha
#'   spending function.
#' @inheritParams param_alpha
#' @inheritParams param_typeAlphaSpending
#' @inheritParams param_parameterAlphaSpending
#' @inheritParams param_userAlphaSpending
#' @param futilityBounds A numeric vector of length \eqn{K} specifying
#'   futility boundaries on the max-Z scale at the end of Phase 2 and
#'   on the Z scale for the \eqn{K - 1} analyses in Phase 3. The final analysis
#'   uses the efficacy boundary as the futility boundary.
#' @param futilityCP A numeric vector of length \eqn{K} specifying futility
#'   boundaries on the conditional power scale.
#' @param futilityTheta A numeric vector of length \eqn{K} specifying futility
#'   boundaries on the parameter scale.
#' @inheritParams param_typeBetaSpending
#' @inheritParams param_parameterBetaSpending
#' @inheritParams param_userBetaSpending
#' @param spendingTime A numeric vector of length \eqn{K+1} specifying the
#'   error spending time at each analysis. Values must be strictly increasing
#'   and end at 1. If omitted, defaults to \code{informationRates}.
#'
#' @return An S3 object of class \code{seamless} with the following components:
#'
#' * \code{overallResults}: A data frame containing:
#'     - \code{overallReject}: Overall probability of rejecting the null
#'       hypothesis.
#'     - \code{alpha}: Overall significance level.
#'     - \code{attainedAlpha}: The attained significance level, which may
#'       differ from \code{alpha} in the presence of futility stopping.
#'     - \code{M}: Number of active arms in Phase 2.
#'     - \code{r}: Randomization ratio per active arm versus control in
#'       Phase 2.
#'     - \code{corr_known}: Whether the phase-2 correlation was assumed known.
#'     - \code{K}: Number of looks in Phase 3.
#'     - \code{information}: Maximum information for any active arm versus
#'       control.
#'     - \code{expectedInformationH1}: Expected information under the
#'       alternative.
#'     - \code{expectedInformationH0}: Expected information under the null.
#'     - \code{informationOverall}: Maximum information for the overall study.
#'     - \code{expectedInformationH1}: Expected information under the
#'       alternative for the overall study.
#'     - \code{expectedInformationH0}: Expected information under the null
#'       for the overall study.
#'
#' * \code{byStageResults}: A data frame containing:
#'     - \code{informationRates}: Information rates at each analysis.
#'     - \code{efficacyBounds}: Efficacy boundaries on the Z scale.
#'     - \code{futilityBounds}: Futility boundaries on the Z scale.
#'     - \code{rejectPerStage}: Probability of efficacy stopping at each stage.
#'     - \code{futilityPerStage}: Probability of futility stopping at each
#'       stage.
#'     - \code{cumulativeRejection}: Cumulative probability of efficacy
#'       stopping.
#'     - \code{cumulativeFutility}: Cumulative probability of futility
#'       stopping.
#'     - \code{cumulativeAlphaSpent}: Cumulative alpha spent.
#'     - \code{efficacyTheta}: Efficacy boundaries on the parameter scale.
#'     - \code{futilityTheta}: Futility boundaries on the parameter scale.
#'     - \code{efficacyP}: Efficacy boundaries on the p-value scale.
#'     - \code{futilityP}: Futility boundaries on the p-value scale.
#'     - \code{information}: Cumulative information at each analysis.
#'     - \code{informationOverall}: Cumulative information for the overall
#'       study at each analysis.
#'     - \code{efficacyStopping}: Indicator of whether efficacy stopping is
#'       permitted.
#'     - \code{futilityStopping}: Indicator of whether futility stopping is
#'       permitted.
#'     - \code{rejectPerStageH0}: Probability of efficacy stopping under the
#'       global null.
#'     - \code{futilityPerStageH0}: Probability of futility stopping under the
#'       global null.
#'     - \code{cumulativeRejectionH0}: Cumulative probability of efficacy
#'       stopping under the global null.
#'     - \code{cumulativeFutilityH0}: Cumulative probability of futility
#'       stopping under the global null.
#'
#' * \code{byArmResults}: A data frame containing:
#'     - \code{theta}: Parameter values for the active arms.
#'     - \code{selectAsBest}: Probability an arm is selected as best at the
#'       end of Phase 2.
#'     - \code{powerByArm}: Probability of rejecting the null for each arm by
#'       trial end.
#'     - \code{condPowerByArm}: Conditional power for each arm given it was
#'       selected as the best at the end of Phase 2.
#'
#' * \code{settings}: A list of input settings:
#'     - \code{typeAlphaSpending}: Type of alpha spending function.
#'     - \code{parameterAlphaSpending}: Parameter value for the chosen alpha
#'       spending function.
#'     - \code{userAlphaSpending}: User-specified alpha spending values.
#'     - \code{typeBetaSpending}: Type of beta spending function.
#'     - \code{parameterBetaSpending}: Parameter value for the chosen beta
#'       spending function.
#'     - \code{userBetaSpending}: User-specified beta spending values.
#'     - \code{spendingTime}: Error-spending times at each analysis.
#'
#' @details If \code{corr_known} is \code{FALSE}, critical boundaries are
#' computed assuming independence among the Phase-2 Wald statistics
#' (a conservative assumption). Power calculations, however, use the
#' correlation implied by the randomization ratio \eqn{r}.
#'
#' Futility boundaries may be supplied directly on the Z scale, derived from
#' conditional power, derived from parameter values, or computed from a beta
#' spending function.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive two-stage seamless sequential design for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2025, 35(4), 565-587.
#'
#' @examples
#'
#' # Example 1: obtain the maximum information given power with no futility
#' (design1 <- getDesign_seamless(
#'   beta = 0.1, theta = c(0.3, 0.5), M = 2, r = 1.0,
#'   K = 2, informationRates = seq(1, 3)/3,
#'   alpha = 0.025, typeAlphaSpending = "OF"))
#'
#' # Example 2: obtain power given the maximum information and a futility rule
#' (design2 <- getDesign_seamless(
#'   IMax = 110/(2*1^2), theta = c(0.3, 0.5), M = 2, r = 1.0,
#'   K = 2, informationRates = seq(1, 3)/3,
#'   alpha = 0.025, typeAlphaSpending = "OF",
#'   futilityBounds = c(0.0, 0.5)))
#'
#' # Example 3: derive futility boundaries using beta spending
#' (design3 <- getDesign_seamless(
#'   beta = 0.1, theta = c(-log(0.5), -log(0.7)),
#'   M = 2, r = 1.0, corr_known = FALSE,
#'   K = 2, informationRates = seq(1, 3)/3,
#'   alpha = 0.025, typeAlphaSpending = "sfOF",
#'   typeBetaSpending = "sfHSD", parameterBetaSpending = -2))
#'
#' @export
getDesign_seamless <- function(beta = NA_real_, IMax = NA_real_, theta = NA_real_, M = NA_integer_, r = 1, corr_known = TRUE, K = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityTheta = NULL, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, spendingTime = NA_real_) {
    .Call(`_lrstat_getDesign_seamless`, beta, IMax, theta, M, r, corr_known, K, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityTheta, typeBetaSpending, parameterBetaSpending, userBetaSpending, spendingTime)
}

#' @title Adaptive Phase 2/3 Seamless Design
#' @description
#' Calculates the conditional power for specified incremental
#' information, given the interim results, parameter value,
#' data-dependent changes in the error spending function, and
#' the number and spacing of interim looks. Conversely,
#' calculates the incremental information required to attain
#' a specified conditional power, given the interim results,
#' parameter value, data-dependent changes in
#' the error spending function, and the number and spacing of interim looks.
#'
#' @param betaNew The type II error for the secondary trial.
#' @param INew The maximum information for the active arm versus the common
#'   control in the secondary trial. Either
#'   \code{betaNew} or \code{INew} should be provided, while the other
#'   must be missing.
#' @param M Number of active treatment arms in Phase 2.
#' @param r Randomization ratio of each active arm to the common control
#'   in Phase 2.
#' @param corr_known Logical. If \code{TRUE}, the correlation between Wald
#'   statistics in Phase 2 is derived from the randomization ratio \eqn{r}
#'   as \eqn{r / (r + 1)}. If \code{FALSE}, a conservative correlation of
#'   0 is used.
#' @param L The interim adaptation look in Phase 3.
#' @param zL The z-test statistic at the interim adaptation look of
#'   Phase 3.
#' @param theta The assumed treatment effect for the selected arm versus the
#'   common control.
#' @param IMax Maximum information for the active arm versus the common
#'   control for the original trial. Must be provided.
#' @param K Number of sequential looks in Phase 3.
#' @param informationRates A numeric vector of information rates fixed
#'   before the trial. If unspecified, defaults to \eqn{(1:(K+1)) / (K+1)}.
#' @param efficacyStopping Indicators of whether efficacy stopping is
#'   allowed at each stage of the primary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param futilityStopping Indicators of whether futility stopping is
#'   allowed at each stage of the primary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param criticalValues The upper boundaries on the max z-test statistic
#'   scale for Phase 2 and the z-test statistics for the selected arm
#'   in Phase 3 for the primary trial. If missing, boundaries
#'   will be computed based on the specified alpha spending function.
#' @param alpha The significance level of the primary trial.
#'   Defaults to 0.025.
#' @param typeAlphaSpending The type of alpha spending for the primary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function,
#'   \code{"user"} for user defined spending, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param userAlphaSpending The user-defined alpha spending for the
#'   primary trial. Represents the cumulative alpha spent up to each stage.
#' @param futilityBounds The lower boundaries on the max-z statistic scale
#'   at end of phase 2 and the z-test statistic scale in phase 3
#'   for futility stopping for the primary trial. Defaults to
#'   \code{rep(-8, kMax-1)} if left unspecified.
#' @param futilityCP The conditional power-based futility bounds for the
#'   primary trial.
#' @param futilityTheta The parameter value-based futility bounds for the
#'   primary trial.
#' @param spendingTime The error spending time of the primary trial.
#'   Defaults to missing, in which case it is assumed to be the same as
#'   \code{informationRates}.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @param kNew The number of looks of the secondary trial.
#' @param informationRatesNew The spacing of looks of the secondary trial.
#' @param efficacyStoppingNew The indicators of whether efficacy stopping is
#'   allowed at each look of the secondary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param futilityStoppingNew The indicators of whether futility stopping is
#'   allowed at each look of the secondary trial. Defaults to \code{TRUE}
#'   if left unspecified.
#' @param typeAlphaSpendingNew The type of alpha spending for the secondary
#'   trial. One of the following:
#'   \code{"OF"} for O'Brien-Fleming boundaries,
#'   \code{"P"} for Pocock boundaries,
#'   \code{"WT"} for Wang & Tsiatis boundaries,
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function, and
#'   \code{"none"} for no early efficacy stopping.
#'   Defaults to \code{"sfOF"}.
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to \eqn{\Delta} for \code{"WT"},
#'   \eqn{\rho} for \code{"sfKD"}, and \eqn{\gamma} for \code{"sfHSD"}.
#' @param futilityBoundsInt The futility boundaries on the z statistic
#'   scale for new stages of the integrated trial.
#' @param futilityCPInt The conditional power-based futility bounds for
#'   new stages of the integrated trial.
#' @param futilityThetaInt The parameter value-based futility bounds for the
#'   new stages of the integrated trial.
#' @param typeBetaSpendingNew The type of beta spending for the secondary
#'   trial. One of the following:
#'   \code{"sfOF"} for O'Brien-Fleming type spending function,
#'   \code{"sfP"} for Pocock type spending function,
#'   \code{"sfKD"} for Kim & DeMets spending function,
#'   \code{"sfHSD"} for Hwang, Shi & DeCani spending function,
#'   \code{"user"} for user defined spending, and
#'   \code{"none"} for no early futility stopping.
#'   Defaults to \code{"none"}.
#' @param parameterBetaSpendingNew The parameter value of beta spending
#'   for the secondary trial. Corresponds to \eqn{\rho} for \code{"sfKD"},
#'   and \eqn{\gamma} for \code{"sfHSD"}.
#' @param userBetaSpendingNew The user-defined cumulative beta spending.
#'   Represents the cumulative beta spent up to each stage of the
#'   secondary trial.
#' @param spendingTimeNew The error spending time of the secondary trial.
#'   Defaults to missing, in which case it is assumed to be the same as
#'   \code{informationRatesNew}.
#'
#' @return An \code{adaptDesign_seamless} object with three list components:
#'
#' * \code{primaryTrial}: A list of selected information for the primary
#'   trial, including \code{M}, \code{r}, \code{corr_known}, \code{K},
#'   \code{L}, \code{zL}, \code{theta}, \code{maxInformation}, \code{kMax},
#'   \code{informationRates}, \code{efficacyBounds}, \code{futilityBounds},
#'   \code{information}, \code{alpha}, \code{conditionalAlpha},
#'   \code{conditionalPower}, and \code{MullerSchafer}.
#'
#' * \code{secondaryTrial}: A list of selected information for the seconary
#'   trial, including \code{overallReject}, \code{alpha}, \code{kMax},
#'   \code{maxInformation}, \code{informationRates}, \code{efficacyBounds},
#'   \code{futilityBounds}, \code{cumulativeRejection},
#'   \code{cumulativeFutility}, \code{cumulativeAlphaSpent},
#'   \code{information}, \code{typeAlphaSpending},
#'   \code{parameterAlphaSpending}, \code{typeBetaSpending},
#'   \code{parameterBetaSpending}, \code{userBetaSpending}, and
#'   \code{spendingTime}.
#'
#' * \code{integratedTrial}: A list of selected information for the integrated
#'   trial, including \code{M}, \code{r}, \code{corr_known}, \code{K},
#'   \code{L}, \code{zL}, \code{theta}, \code{maxInformation}, \code{kMax},
#'   \code{informationRates}, \code{efficacyBounds}, \code{futilityBounds},
#'   and \code{information}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Ping Gao, Yingqiu Li.
#' Adaptive two-stage seamless sequential design for clinical trials.
#' Journal of Biopharmaceutical Statistics, 2025, 35(4), 565-587.
#'
#' @seealso \code{\link{getDesign_seamless}}
#'
#' @examples
#'
#' (des1 <- adaptDesign_seamless(
#'   betaNew = 0.1, M = 2, r = 1, corr_known = FALSE,
#'   L = 1, zL = -log(0.67) * sqrt(80 / 4), theta = -log(0.691),
#'   IMax = 120 / 4, K = 2, informationRates = c(1/3, 2/3, 1),
#'   alpha = 0.025, typeAlphaSpending = "OF", kNew = 1))
#'
#' @export
adaptDesign_seamless <- function(betaNew = NA_real_, INew = NA_real_, M = NA_integer_, r = 1, corr_known = TRUE, L = NA_integer_, zL = NA_real_, theta = NA_real_, IMax = NA_real_, K = NA_integer_, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NULL, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NULL, futilityCP = NULL, futilityTheta = NULL, spendingTime = NA_real_, MullerSchafer = FALSE, kNew = NA_integer_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, futilityStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, futilityBoundsInt = NULL, futilityCPInt = NULL, futilityThetaInt = NULL, typeBetaSpendingNew = "none", parameterBetaSpendingNew = NA_real_, userBetaSpendingNew = NA_real_, spendingTimeNew = NA_real_) {
    .Call(`_lrstat_adaptDesign_seamless`, betaNew, INew, M, r, corr_known, L, zL, theta, IMax, K, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, futilityCP, futilityTheta, spendingTime, MullerSchafer, kNew, informationRatesNew, efficacyStoppingNew, futilityStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, futilityBoundsInt, futilityCPInt, futilityThetaInt, typeBetaSpendingNew, parameterBetaSpendingNew, userBetaSpendingNew, spendingTimeNew)
}

#' @title Simon's Two-Stage Design
#' @description Obtains Simon's two-stage minimax, admissible, and
#' optimal designs.
#'
#' @param alpha Type I error rate (one-sided).
#' @param beta Type II error rate (1-power).
#' @param piH0 Response probability under the null hypothesis.
#' @param pi Response probability under the alternative hypothesis.
#' @param n_max Upper limit for sample size, defaults to 110.
#'
#' @return A data frame containing the following variables:
#'
#' * \code{piH0}: Response probability under the null hypothesis.
#'
#' * \code{pi}: Response probability under the alternative hypothesis.
#'
#' * \code{alpha}: The specified one-sided significance level.
#'
#' * \code{beta}: The specified type II error.
#'
#' * \code{n}: Total sample size.
#'
#' * \code{n1}: Stage 1 sample size.
#'
#' * \code{r1}: Futility boundary for stage 1.
#'
#' * \code{r}: Futility boundary for stage 2.
#'
#' * \code{EN0}: Expected sample size under the null hypothesis.
#'
#' * \code{attainedAlpha}: Attained type 1 error.
#'
#' * \code{power}: Attained power.
#'
#' * \code{PET0}: Probability of early stopping under the null hypothesis.
#'
#' * \code{w_lower}: Lower bound of the interval for \code{w}.
#'
#' * \code{w_upper}: Upper bound of the interval for \code{w}.
#'
#' * \code{design}: Description of the design, e.g., minimax, admissible,
#'   or optimal.
#'
#' Here \code{w} is the weight in the objective function:
#' \code{w*n + (1-w)*EN0}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' simon2stage(0.05, 0.2, 0.1, 0.3)
#'
#' @export
simon2stage <- function(alpha = NA_real_, beta = NA_real_, piH0 = NA_real_, pi = NA_real_, n_max = 110L) {
    .Call(`_lrstat_simon2stage`, alpha, beta, piH0, pi, n_max)
}

#' @title Analysis of Simon's Bayesian Basket Trials
#' @description Obtains the prior and posterior probabilities for
#' Simon's Bayesian basket discovery trials.
#'
#' @param nstrata The number of strata.
#' @param r The vector of number of responders across strata.
#' @param n The vector of number of subjects across strata.
#' @param lambda The prior probability that the drug activity is
#'   homogeneous across strata.
#' @param gamma The prior probability that the drug is active in a
#'   stratum.
#' @param phi The response probability for an active drug.
#' @param plo The response probability for an inactive drug.
#'
#' @return A list containing the following five components:
#'
#' * \code{case}: The matrix with each row corresponding to a combination
#'   of drug activity over strata represented by the columns.
#'
#' * \code{prior_case}: The vector of joint prior probabilities
#'   for the stratum-specific response rates.
#'
#' * \code{prior_stratum}: The vector of marginal prior probabilities
#'   for the stratum-specific response rates.
#'
#' * \code{post_case}: The vector of joint posterior probabilities
#'   for the stratum-specific response rates.
#'
#' * \code{post_stratum}: The vector of marginal posterior probabilities
#'   for the stratum-specific response rates.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' a <- simonBayesAnalysis(
#'   nstrata = 10,
#'   r = c(8,0,1,1,6,2,0,0,3,3),
#'   n = c(19,10,26,8,14,7,8,5,4,14),
#'   lambda = 0.5, gamma = 0.33,
#'   phi = 0.35, plo = 0.15)
#'
#' a$post_stratum
#'
#' @export
simonBayesAnalysis <- function(nstrata = NA_integer_, r = NA_real_, n = NA_real_, lambda = NA_real_, gamma = NA_real_, phi = NA_real_, plo = NA_real_) {
    .Call(`_lrstat_simonBayesAnalysis`, nstrata, r, n, lambda, gamma, phi, plo)
}

#' @title Simulation of Simon's Bayesian Basket Trials
#' @description Obtains the simulated raw and summary data for Simon's
#' Bayesian basket discovery trials.
#'
#' @param p The vector of true response probabilities across strata.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_stratumFraction
#' @param lambda The prior probability that the drug activity is
#'   homogeneous across strata.
#' @param gamma The prior probability that the drug is active in a
#'   stratum.
#' @param phi The response probability for an active drug.
#' @param plo The response probability for an inactive drug.
#' @param T The threshold for a conclusive posterior probability to
#'   stop enrollment.
#' @param maxSubjects The maximum total sample size.
#' @param plannedSubjects The planned cumulative number of subjects
#'   at each stage.
#' @param maxNumberOfIterations The number of simulation iterations.
#'   Defaults to 1000.
#' @param maxNumberOfRawDatasets The number of raw datasets to extract.
#' @param seed The seed to reproduce the simulation results.
#'   The seed from the environment will be used if left unspecified,
#'
#' @return A list containing the following four components:
#'
#' * \code{rawdata}: A data frame for subject-level data, containing
#'   the following variables:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{stageNumber}: The stage number.
#'
#'     - \code{subjectId}: The subject ID.
#'
#'     - \code{arrivalTime}: The enrollment time for the subject.
#'
#'     - \code{stratum}: The stratum for the subject.
#'
#'     - \code{y}: Whether the subject was a responder (1) or
#'       nonresponder (0).
#'
#' * \code{sumdata1}: A data frame for simulation and stratum-level
#'   summary data, containing the following variables:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{stageNumber}: The stage number.
#'
#'     - \code{stratum}: The stratum number.
#'
#'     - \code{active}: Whether the drug is active in the stratum.
#'
#'     - \code{n}: The number of subjects in the stratum.
#'
#'     - \code{r}: The number of responders in the stratum.
#'
#'     - \code{posterior}: The posterior probability that the drug is
#'       active in the stratum.
#'
#'     - \code{open}: Whether the stratum is still open for enrollment.
#'
#'     - \code{positive}: Whether the stratum has been determined to be
#'       a positive stratum.
#'
#'     - \code{negative}: Whether the stratum has been determined to be
#'       a negative stratum.
#'
#' * \code{sumdata2}: A data frame for the simulation level summary data,
#'   containing the following variables:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{numberOfStrata}: The total number of strata.
#'
#'     - \code{n_active_strata}: The number of active strata.
#'
#'     - \code{true_positive}: The number of true positive strata.
#'
#'     - \code{false_negative}: The number of false negative strata.
#'
#'     - \code{false_positive}: The number of false positive strata.
#'
#'     - \code{true_negative}: The number of true negative strata.
#'
#'     - \code{n_indet_strata}: The number of indeterminate strata.
#'
#'     - \code{numberOfSubjects}: The number of subjects.
#'
#' * \code{overview}: A data frame for the summary across simulations,
#'   containing the following variables:
#'
#'     - \code{numberOfStrata}: The total number of strata.
#'
#'     - \code{n_active_strata}: The average number of active strata.
#'
#'     - \code{true_positive}: The average number of true positive strata.
#'
#'     - \code{false_negative}: The average number of false negative strata.
#'
#'     - \code{false_positive}: The average number of false positive strata.
#'
#'     - \code{true_negative}: The average number of true negative strata.
#'
#'     - \code{n_indet_strata}: The average number of indeterminate strata.
#'
#'     - \code{numberOfSubjects}: The average number of subjects.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' sim1 <- simonBayesSim(
#'   p = c(0.25, 0.25, 0.05),
#'   accrualIntensity = 5,
#'   stratumFraction = c(1/3, 1/3, 1/3),
#'   lambda = 0.33, gamma = 0.5,
#'   phi = 0.25, plo = 0.05,
#'   T = 0.8, maxSubjects = 50,
#'   plannedSubjects = seq(5, 50, 5),
#'   maxNumberOfIterations = 1000,
#'   maxNumberOfRawDatasets = 1,
#'   seed = 314159)
#'
#' sim1$overview
#'
#' @export
simonBayesSim <- function(p = NA_real_, accrualTime = 0L, accrualIntensity = NA_real_, stratumFraction = 1L, lambda = NA_real_, gamma = NA_real_, phi = NA_real_, plo = NA_real_, T = NA_real_, maxSubjects = NA_integer_, plannedSubjects = NA_integer_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasets = 1L, seed = 0L) {
    .Call(`_lrstat_simonBayesSim`, p, accrualTime, accrualIntensity, stratumFraction, lambda, gamma, phi, plo, T, maxSubjects, plannedSubjects, maxNumberOfIterations, maxNumberOfRawDatasets, seed)
}

#' @title Brookmeyer-Crowley Confidence Interval for Quantiles of
#' Right-Censored Time-to-Event Data
#' @description Obtains the Brookmeyer-Crowley confidence
#' interval for quantiles of right-censored time-to-event data.
#'
#' @param time The vector of possibly right-censored survival times.
#' @param event The vector of event indicators.
#' @param cilevel The confidence interval level. Defaults to 0.95.
#' @param transform The transformation of the survival function to use
#'   to construct the confidence interval. Options include
#'   "linear" (alternatively "plain"), "log",
#'   "loglog" (alternatively "log-log" or "cloglog"),
#'   "asinsqrt" (alternatively "asin" or "arcsin"), and "logit".
#'   Defaults to "loglog".
#'
#' @param probs The vector of probabilities to calculate the quantiles.
#'   Defaults to c(0.25, 0.5, 0.75).
#'
#' @return A data frame containing the estimated quantile and
#' confidence interval corresponding to each specified probability.
#' It includes the following variables:
#'
#' * \code{prob}: The probability to calculate the quantile.
#'
#' * \code{quantile}: The estimated quantile.
#'
#' * \code{lower}: The lower limit of the confidence interval.
#'
#' * \code{upper}: The upper limit of the confidence interval.
#'
#' * \code{cilevel}: The confidence interval level.
#'
#' * \code{transform}: The transformation of the survival function to use
#'   to construct the confidence interval.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' survQuantile(
#'   time = c(33.7, 3.9, 10.5, 5.4, 19.5, 23.8, 7.9, 16.9, 16.6,
#'            33.7, 17.1, 7.9, 10.5, 38),
#'   event = c(0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1),
#'   probs = c(0.25, 0.5, 0.75))
#'
#' @export
survQuantile <- function(time, event, cilevel = 0.95, transform = "loglog", probs = as.numeric( c(0.25, 0.5, 0.75))) {
    .Call(`_lrstat_survQuantile`, time, event, cilevel, transform, probs)
}

#' @title Kaplan-Meier Estimates of Survival Curve
#' @description Obtains the Kaplan-Meier estimates of the survival curve.
#'
#' @param data The input data frame that contains the following variables:
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{time}: The follow-up time for right censored data, or
#'     the left end of each interval for counting process data.
#'
#'   * \code{time2}: The right end of each interval for counting process
#'     data. Intervals are assumed to be open on the left
#'     and closed on the right, and event indicates whether an event
#'     occurred at the right end of each interval.
#'
#'   * \code{event}: The event indicator, 1=event, 0=no event.
#'
#'   * \code{weight}: The weight for each observation.
#'
#' @param stratum The name(s) of the stratum variable(s) in the input data.
#' @param time The name of the time variable or the left end of each
#'   interval for counting process data in the input data.
#' @param time2 The name of the right end of each interval for counting
#'   process data in the input data.
#' @param event The name of the event variable in the input data.
#' @param weight The name of the weight variable in the input data.
#' @param conftype The type of the confidence interval. One of "none",
#'   "plain", "log", "log-log" (the default), or "arcsin".
#'   The arcsin option bases the intervals on asin(sqrt(survival)).
#' @param conflev The level of the two-sided confidence interval for
#'   the survival probabilities. Defaults to 0.95.
#' @param keep_censor Whether to retain the censoring time in the output
#'   data frame.
#'
#' @return A data frame with the following variables:
#'
#' * \code{size}: The number of subjects in the stratum.
#'
#' * \code{time}: The event time.
#'
#' * \code{nrisk}: The number of subjects at risk.
#'
#' * \code{nevent}: The number of subjects having the event.
#'
#' * \code{ncensor}: The number of censored subjects.
#'
#' * \code{surv}: The Kaplan-Meier estimate of the survival probability.
#'
#' * \code{sesurv}: The standard error of the estimated survival
#'   probability based on the Greendwood formula.
#'
#' * \code{lower}: The lower bound of confidence interval if requested.
#'
#' * \code{upper}: The upper bound of confidence interval if requested.
#'
#' * \code{conflev}: The level of confidence interval if requested.
#'
#' * \code{conftype}: The type of confidence interval if requested.
#'
#' * \code{stratum}: The stratum.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' kmest(data = aml, stratum = "x", time = "time", event = "status")
#'
#' @export
kmest <- function(data, stratum = "", time = "time", time2 = "", event = "event", weight = "", conftype = "log-log", conflev = 0.95, keep_censor = FALSE) {
    .Call(`_lrstat_kmest`, data, stratum, time, time2, event, weight, conftype, conflev, keep_censor)
}

#' @title Estimate of Milestone Survival Difference
#' @description Obtains the estimate of milestone survival difference
#' between two treatment groups.
#'
#' @param data The input data frame that contains the following variables:
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{treat}: The treatment.
#'
#'   * \code{time}: The follow-up time for right censored data, or
#'     the left end of each interval for counting process data.
#'
#'   * \code{time2}: The right end of each interval for counting process
#'     data. Intervals are assumed to be open on the left
#'     and closed on the right, and event indicates whether an event
#'     occurred at the right end of each interval.
#'
#'   * \code{event}: The event indicator, 1=event, 0=no event.
#'
#'   * \code{weight}: The weight for each observation.
#'
#' @param stratum The name of the stratum variable in the input data.
#' @param treat The name of the treatment variable in the input data.
#' @param time The name of the time variable or the left end of each
#'   interval for counting process data in the input data.
#' @param time2 The name of the right end of each interval for counting
#'   process data in the input data.
#' @param event The name of the event variable in the input data.
#' @param weight The name of the weight variable in the input data.
#' @param milestone The milestone time at which to calculate the
#'   survival probability.
#' @param survDiffH0 The difference in milestone survival probabilities
#'   under the null hypothesis. Defaults to 0 for superiority test.
#' @param conflev The level of the two-sided confidence interval for
#'   the difference in milestone survival probabilities. Defaults to 0.95.
#'
#' @return A data frame with the following variables:
#'
#' * \code{milestone}: The milestone time relative to randomization.
#'
#' * \code{survDiffH0}: The difference in milestone survival probabilities
#'   under the null hypothesis.
#'
#' * \code{surv1}: The estimated milestone survival probability for
#'   the treatment group.
#'
#' * \code{surv2}: The estimated milestone survival probability for
#'   the control group.
#'
#' * \code{survDiff}: The estimated difference in milestone survival
#'   probabilities.
#'
#' * \code{vsurv1}: The variance for surv1.
#'
#' * \code{vsurv2}: The variance for surv2.
#'
#' * \code{sesurvDiff}: The standard error for survDiff.
#'
#' * \code{survDiffZ}: The Z-statistic value.
#'
#' * \code{survDiffPValue}: The two-sided p-value.
#'
#' * \code{lower}: The lower bound of confidence interval.
#'
#' * \code{upper}: The upper bound of confidence interval.
#'
#' * \code{conflev}: The level of confidence interval.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' kmdiff(data = rawdata[rawdata$iterationNumber == 1, ],
#'        stratum = "stratum", treat = "treatmentGroup",
#'        time = "timeUnderObservation", event = "event",
#'        milestone = 12)
#'
#' @export
kmdiff <- function(data, stratum = "", treat = "treat", time = "time", time2 = "", event = "event", weight = "", milestone = 0, survDiffH0 = 0, conflev = 0.95) {
    .Call(`_lrstat_kmdiff`, data, stratum, treat, time, time2, event, weight, milestone, survDiffH0, conflev)
}

#' @title Log-Rank Test of Survival Curve Difference
#' @description Obtains the log-rank test using the Fleming-Harrington
#' family of weights.
#'
#' @param data The input data frame or list of data frames that contains
#' the following variables:
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{treat}: The treatment.
#'
#'   * \code{time}: The follow-up time for right censored data, or
#'     the left end of each interval for counting process data.
#'
#'   * \code{time2}: The right end of each interval for counting process
#'     data. Intervals are assumed to be open on the left
#'     and closed on the right, and event indicates whether an event
#'     occurred at the right end of each interval.
#'
#'   * \code{event}: The event indicator, 1=event, 0=no event.
#'
#'   * \code{weight}: The weight for each observation.
#'
#' @param stratum The name(s) of the stratum variable(s) in the input data.
#' @param treat The name of the treatment variable in the input data.
#' @param time The name of the time variable or the left end of each
#'   interval for counting process data in the input data.
#' @param time2 The name of the right end of each interval for counting
#'   process data in the input data.
#' @param event The name of the event variable in the input data.
#' @param weight The name of the weight variable in the input data.
#' @param weight_readj Whether the weight variable at each event time
#'   will be readjusted to be proportional to the number at risk by
#'   treatment group. Defaults to `FALSE`.
#' @param rho1 The first parameter of the Fleming-Harrington family of
#'   weighted log-rank test. Defaults to 0 for conventional log-rank test.
#' @param rho2 The second parameter of the Fleming-Harrington family of
#'   weighted log-rank test. Defaults to 0 for conventional log-rank test.
#'
#' @return A data frame with the following variables:
#'
#' * \code{uscore}: The numerator of the log-rank test statistic.
#'
#' * \code{vscore}: The variance of the log-rank score test statistic.
#'
#' * \code{logRankZ}: The Z-statistic value.
#'
#' * \code{logRankPValue}: The two-sided p-value.
#'
#' * \code{weight_readj}: Whether the weight variable will be readjusted.
#'
#' * \code{rho1}: The first parameter of the Fleming-Harrington weights.
#'
#' * \code{rho2}: The second parameter of the Fleming-Harrington weights.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' lrtest(rawdata[rawdata$iterationNumber == 1, ],
#'        stratum = "stratum", treat = "treatmentGroup",
#'        time = "timeUnderObservation", event = "event",
#'        rho1 = 0.5, rho2 = 0)
#'
#' @export
lrtest <- function(data, stratum = "", treat = "treat", time = "time", time2 = "", event = "event", weight = "", weight_readj = FALSE, rho1 = 0, rho2 = 0) {
    .Call(`_lrstat_lrtest`, data, stratum, treat, time, time2, event, weight, weight_readj, rho1, rho2)
}

#' @title Estimate of Restricted Mean Survival Time
#' @description Obtains the estimate of restricted means survival time
#' for each stratum.
#'
#' @param data The input data frame that contains the following variables:
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{time}: The possibly right-censored survival time.
#'
#'   * \code{event}: The event indicator.
#'
#' @param stratum The name of the stratum variable in the input data.
#' @param time The name of the time variable in the input data.
#' @param event The name of the event variable in the input data.
#' @param milestone The milestone time at which to calculate the
#'   restricted mean survival time.
#' @param conflev The level of the two-sided confidence interval for
#'   the survival probabilities. Defaults to 0.95.
#' @param biascorrection Whether to apply bias correction for the
#'   variance estimate. Defaults to no bias correction.
#'
#' @return A data frame with the following variables:
#'
#' * \code{stratum}: The stratum variable.
#'
#' * \code{size}: The number of subjects in the stratum.
#'
#' * \code{milestone}: The milestone time relative to randomization.
#'
#' * \code{rmst}: The estimate of restricted mean survival time.
#'
#' * \code{stderr}: The standard error of the estimated rmst.
#'
#' * \code{lower}: The lower bound of confidence interval if requested.
#'
#' * \code{upper}: The upper bound of confidence interval if requested.
#'
#' * \code{conflev}: The level of confidence interval if requested.
#'
#' * \code{biascorrection}: Whether to apply bias correction for the
#'   variance estimate.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' rmest(data = aml, stratum = "x",
#'       time = "time", event = "status", milestone = 24)
#'
#' @export
rmest <- function(data, stratum = "", time = "time", event = "event", milestone = 0, conflev = 0.95, biascorrection = FALSE) {
    .Call(`_lrstat_rmest`, data, stratum, time, event, milestone, conflev, biascorrection)
}

#' @title Estimate of Restricted Mean Survival Time Difference
#' @description Obtains the estimate of restricted mean survival time
#' difference between two treatment groups.
#'
#' @param data The input data frame that contains the following variables:
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{treat}: The treatment.
#'
#'   * \code{time}: The possibly right-censored survival time.
#'
#'   * \code{event}: The event indicator.
#'
#' @param stratum The name of the stratum variable in the input data.
#' @param treat The name of the treatment variable in the input data.
#' @param time The name of the time variable in the input data.
#' @param event The name of the event variable in the input data.
#' @param milestone The milestone time at which to calculate the
#'   restricted mean survival time.
#' @param rmstDiffH0 The difference in restricted mean survival times
#'   under the null hypothesis. Defaults to 0 for superiority test.
#' @param conflev The level of the two-sided confidence interval for
#'   the difference in restricted mean survival times. Defaults to 0.95.
#' @param biascorrection Whether to apply bias correction for the
#'   variance estimate of individual restricted mean survival times.
#'   Defaults to no bias correction.
#'
#' @return A data frame with the following variables:
#'
#' * \code{milestone}: The milestone time relative to randomization.
#'
#' * \code{rmstDiffH0}: The difference in restricted mean survival times
#'   under the null hypothesis.
#'
#' * \code{rmst1}: The estimated restricted mean survival time for
#'   the treatment group.
#'
#' * \code{rmst2}: The estimated restricted mean survival time for
#'   the control group.
#'
#' * \code{rmstDiff}: The estimated difference in restricted mean
#'   survival times.
#'
#' * \code{vrmst1}: The variance for rmst1.
#'
#' * \code{vrmst2}: The variance for rmst2.
#'
#' * \code{sermstDiff}: The standard error for rmstDiff.
#'
#' * \code{rmstDiffZ}: The Z-statistic value.
#'
#' * \code{rmstDiffPValue}: The two-sided p-value.
#'
#' * \code{lower}: The lower bound of confidence interval.
#'
#' * \code{upper}: The upper bound of confidence interval.
#'
#' * \code{conflev}: The level of confidence interval.
#'
#' * \code{biascorrection}: Whether to apply bias correction for the
#'   variance estimate of individual restricted mean survival times.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' rmdiff(data = rawdata[rawdata$iterationNumber == 1, ],
#'        stratum = "stratum", treat = "treatmentGroup",
#'        time = "timeUnderObservation", event = "event",
#'        milestone = 12)
#'
#' @export
rmdiff <- function(data, stratum = "", treat = "treat", time = "time", event = "event", milestone = 0, rmstDiffH0 = 0, conflev = 0.95, biascorrection = FALSE) {
    .Call(`_lrstat_rmdiff`, data, stratum, treat, time, event, milestone, rmstDiffH0, conflev, biascorrection)
}

liferegRcpp <- function(data, stratum, time, time2, event, covariates, weight, offset, id, dist, init, robust, plci, alpha, maxiter, eps) {
    .Call(`_lrstat_liferegRcpp`, data, stratum, time, time2, event, covariates, weight, offset, id, dist, init, robust, plci, alpha, maxiter, eps)
}

residuals_liferegRcpp <- function(beta, vbeta, data, stratum, time, time2, event, covariates, weight, offset, id, dist, type, collapse, weighted) {
    .Call(`_lrstat_residuals_liferegRcpp`, beta, vbeta, data, stratum, time, time2, event, covariates, weight, offset, id, dist, type, collapse, weighted)
}

phregRcpp <- function(data, stratum, time, time2, event, covariates, weight, offset, id, ties, init, robust, est_basehaz, est_resid, firth, plci, alpha, maxiter, eps) {
    .Call(`_lrstat_phregRcpp`, data, stratum, time, time2, event, covariates, weight, offset, id, ties, init, robust, est_basehaz, est_resid, firth, plci, alpha, maxiter, eps)
}

survfit_phregRcpp <- function(p, beta, vbeta, basehaz, newdata, covariates, stratum, offset, id, tstart, tstop, sefit, conftype, conflev) {
    .Call(`_lrstat_survfit_phregRcpp`, p, beta, vbeta, basehaz, newdata, covariates, stratum, offset, id, tstart, tstop, sefit, conftype, conflev)
}

residuals_phregRcpp <- function(p, beta, vbeta, resmart, data, stratum, time, time2, event, covariates, weight, offset, id, ties, type, collapse, weighted) {
    .Call(`_lrstat_residuals_phregRcpp`, p, beta, vbeta, resmart, data, stratum, time, time2, event, covariates, weight, offset, id, ties, type, collapse, weighted)
}

assess_phregRcpp <- function(p, beta, vbeta, data, stratum, time, time2, event, covariates, weight, offset, ties, resample, seed) {
    .Call(`_lrstat_assess_phregRcpp`, p, beta, vbeta, data, stratum, time, time2, event, covariates, weight, offset, ties, resample, seed)
}

zph_phregRcpp <- function(p, beta, vbeta, resmart, data, stratum, time, time2, event, covariates, weight, offset, ties, transform) {
    .Call(`_lrstat_zph_phregRcpp`, p, beta, vbeta, resmart, data, stratum, time, time2, event, covariates, weight, offset, ties, transform)
}

pnorm_fast <- function(x) {
    .Call(`_lrstat_pnorm_fast`, x)
}

qnorm_acklam <- function(p) {
    .Call(`_lrstat_qnorm_acklam`, p)
}

dtpwexpcpp <- function(q, piecewiseSurvivalTime, lambda, lowerBound, logd) {
    .Call(`_lrstat_dtpwexpcpp`, q, piecewiseSurvivalTime, lambda, lowerBound, logd)
}

ptpwexpcpp <- function(q, piecewiseSurvivalTime, lambda, lowerBound, lowertail, logp) {
    .Call(`_lrstat_ptpwexpcpp`, q, piecewiseSurvivalTime, lambda, lowerBound, lowertail, logp)
}

qtpwexpcpp <- function(p, piecewiseSurvivalTime, lambda, lowerBound, lowertail, logp) {
    .Call(`_lrstat_qtpwexpcpp`, p, piecewiseSurvivalTime, lambda, lowerBound, lowertail, logp)
}

#' @title Mean and Variance of Truncated Piecewise Exponential Distribution
#' @description Obtains the mean and variance from a truncated piecewise
#' exponential distribution.
#'
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda
#' @param lowerBound The left truncation time point for the survival time.
#'   Defaults to 0 for no truncation.
#'
#' @return A list with two components, one for the mean, and the other for
#' the variance of the truncated piecewise exponential distribution.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' mtpwexp(piecewiseSurvivalTime = c(0, 6, 9, 15),
#'         lambda = c(0.025, 0.04, 0.015, 0.007))
#'
#' @export
mtpwexp <- function(piecewiseSurvivalTime = 0L, lambda = NA_real_, lowerBound = 0) {
    .Call(`_lrstat_mtpwexp`, piecewiseSurvivalTime, lambda, lowerBound)
}

#' @title Distribution Function of the Standard Bivariate Normal
#' @description Computes the cumulative distribution function (CDF) of
#' the standard bivariate normal distribution with specified lower and
#' upper integration limits and correlation coefficient.
#'
#' @param lower A numeric vector of length 2 specifying the lower limits
#'   of integration.
#' @param upper A numeric vector of length 2 specifying the upper limits
#'   of integration.
#' @param rho A numeric value specifying the correlation coefficient of
#'   the standard bivariate normal distribution.
#'
#' @details This function evaluates the probability
#' \eqn{P(\code{lower[1]} < X < \code{upper[1]},
#' \code{lower[2]} < Y < \code{upper[2]})} where
#' \eqn{(X, Y)} follows a standard bivariate normal
#' distribution with correlation \code{corr}.
#'
#' @return A numeric value representing the probability that a standard
#' bivariate normal vector falls within the specified rectangular region.
#'
#' @examples
#' pbvnorm(c(-1, -1), c(1, 1), 0.5)
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @export
pbvnorm <- function(lower = NA_real_, upper = NA_real_, rho = 0) {
    .Call(`_lrstat_pbvnorm`, lower, upper, rho)
}

#' @title Hazard Function for Progressive Disease (PD) Given Correlation
#' Between PD and OS
#'
#' @description
#' Computes the hazard function of a piecewise exponential
#' distribution for progressive disease (PD), such that the
#' resulting hazard function for progression-free survival (PFS)
#' closely matches a given piecewise hazard for PFS.
#'
#' @inheritParams param_piecewiseSurvivalTime
#' @param hazard_pfs A scalar or numeric vector specifying the
#'   hazard(s) for PFS based on a piecewise exponential distribution.
#' @param hazard_os A scalar or numeric vector specifying the
#'   hazard(s) for overall survival (OS) based on a piecewise
#'   exponential distribution.
#' @param rho_pd_os A numeric value specifying the correlation
#'   between PD and OS times.
#'
#' @details
#' This function determines the hazard vector \eqn{\lambda_{\text{pd}}}
#' for the piecewise exponential distribution of PD, so that the
#' implied survival function for PFS time,
#' \eqn{T_{\text{pfs}} = \min(T_{\text{pd}}, T_{\text{os}})}, closely
#' matches the specified piecewise exponential distribution for PFS
#' with hazard vector \eqn{\lambda_{\text{pfs}}}.
#'
#' To achieve this, we simulate
#' \eqn{(Z_{\text{pd}}, Z_{\text{os}})} from
#' a standard bivariate normal distribution with correlation
#' \eqn{\rho}. Then, \eqn{U_{\text{pd}} = \Phi(Z_{\text{pd}})}
#' and \eqn{U_{\text{os}} = \Phi(Z_{\text{os}})} are generated, where
#' \eqn{\Phi} denotes the standard normal CDF.
#'
#' The times to PD and OS are obtained via the inverse transform
#' method using quantile functions of the piecewise exponential distribution:
#' \deqn{T_{\text{pd}} = \text{qpwexp}(U_{\text{pd}},u,\lambda_{\text{pd}})}
#' \deqn{T_{\text{os}} = \text{qpwexp}(U_{\text{os}},u,\lambda_{\text{os}})}
#' where \code{u = piecewiseSurvivalTime}.
#'
#' The function solves for \eqn{\lambda_{\text{pd}}} such that
#' the survival function of \eqn{T_{\text{pfs}}} closely matches that
#' of a piecewise exponential distribution with hazard
#' \eqn{\lambda_{\text{pfs}}}:
#' \deqn{P(\min(T_{\text{pd}}, T_{\text{os}}) > t) = S_{\text{pfs}}(t)}
#' Since \deqn{Z_{\text{pd}} =
#'   \Phi^{-1}(\text{ppwexp}(T_\text{pd}, u, \lambda_{\text{pd}}))} and
#' \deqn{Z_{\text{os}} =
#'   \Phi^{-1}(\text{ppwexp}(T_\text{os}, u, \lambda_{\text{os}}))}
#' we have
#' \deqn{P(\min(T_{\text{pd}}, T_{\text{os}}) > t) =
#' P(Z_{\text{pd}} >
#'     \Phi^{-1}(\text{ppwexp}(t,u,\lambda_{\text{pd}})),
#'   Z_{\text{os}} >
#'     \Phi^{-1}(\text{ppwexp}(t,u,\lambda_{\text{os}})))}
#' while
#' \deqn{S_{\text{pfs}}(t) = 1 - \text{ppwexp}(t,u,\lambda_{\text{pfs}})}
#'
#' Matching is performed sequentially at the internal cut points
#' \eqn{u_2, ..., u_J} and at the point
#' \eqn{u_J + \log(2)/\lambda_{\text{pfs},J}} for the final interval,
#' as well as the percentile points at 10%, 20%, ..., 90%, and 95%
#' to solve for \eqn{\lambda_{\text{pd},1}, \ldots,
#' \lambda_{\text{pd},K}}, where \eqn{K} is the total number of
#' unique cut points.
#'
#' @return A list with the following components:
#'
#' * \code{piecewiseSurvivalTime}: A vector that specifies the starting time
#'   points of the intervals for the piecewise exponential distribution
#'   for PD.
#'
#' * \code{hazard_pd}: A numeric vector representing the calculated hazard
#'   rates for the piecewise exponential distribution of PD.
#'
#' * \code{hazard_os}: A numeric vector representing the hazard rates for
#'   the piecewise exponential distribution of OS at the same time points
#'   as PD.
#'
#' * \code{rho_pd_os}: The correlation between PD and OS times (as input).
#'
#' @author
#' Kaifeng Lu (\email{kaifenglu@gmail.com})
#'
#' @examples
#' u <- c(0, 1, 3, 4)
#' lambda1 <- c(0.0151, 0.0403, 0.0501, 0.0558)
#' lambda2 <- 0.0145
#' rho_pd_os <- 0.5
#' hazard_pd(u, lambda1, lambda2, rho_pd_os)
#'
#' @export
hazard_pd <- function(piecewiseSurvivalTime = 0L, hazard_pfs = NA_real_, hazard_os = NA_real_, rho_pd_os = 0.5) {
    .Call(`_lrstat_hazard_pd`, piecewiseSurvivalTime, hazard_pfs, hazard_os, rho_pd_os)
}

#' @title Correlation Between PFS and OS Given Correlation Between PD and OS
#'
#' @description
#' Computes the correlation between PFS and OS given the correlation
#' between PD and OS.
#'
#' @inheritParams param_piecewiseSurvivalTime
#' @param hazard_pfs A scalar or numeric vector specifying the
#'   hazard(s) for PFS based on a piecewise exponential distribution.
#' @param hazard_os A scalar or numeric vector specifying the
#'   hazard(s) for overall survival (OS) based on a piecewise
#'   exponential distribution.
#' @param rho_pd_os A numeric value specifying the correlation
#'   between PD and OS times.
#'
#' @details
#' This function first determines the piecewise exponential distribution
#' for PD such that the implied survival function for PFS time,
#' \eqn{T_{\text{pfs}} = \min(T_{\text{pd}}, T_{\text{os}})}, closely
#' matches the specified piecewise exponential distribution for PFS
#' with hazard vector \eqn{\lambda_{\text{pfs}}}. Then, it calculates
#' the correlation between PFS and OS times based on the derived
#' piecewise exponential distribution for PD and the given piecewise
#' exponential distribution for OS.
#'
#' @return The estimated correlation between PFS and OS.
#'
#' @author
#' Kaifeng Lu (\email{kaifenglu@gmail.com})
#'
#' @examples
#' u <- c(0, 1, 3, 4)
#' lambda1 <- c(0.0151, 0.0403, 0.0501, 0.0558)
#' lambda2 <- 0.0145
#' rho_pd_os <- 0.5
#' corr_pfs_os(u, lambda1, lambda2, rho_pd_os)
#'
#' @export
corr_pfs_os <- function(piecewiseSurvivalTime = 0L, hazard_pfs = NA_real_, hazard_os = NA_real_, rho_pd_os = NA_real_) {
    .Call(`_lrstat_corr_pfs_os`, piecewiseSurvivalTime, hazard_pfs, hazard_os, rho_pd_os)
}

#' @title Hazard Function for Sub Population
#'
#' @description
#' Computes the hazard function of a piecewise exponential
#' distribution for the biomarker negative sub population, such that the
#' resulting survival function for the ITT population
#' closely matches a given piecewise survival function.
#'
#' @inheritParams param_piecewiseSurvivalTime
#' @param hazard_itt A scalar or numeric vector specifying the
#'   hazard(s) for the ITT population based on a piecewise exponential
#'   distribution.
#' @param hazard_pos A scalar or numeric vector specifying the
#'   hazard(s) for the biomarker positive sub population
#'   based on a piecewise exponential distribution.
#' @param p_pos A numeric value specifying the prevalence of the
#'   biomarker positive sub population.
#'
#' @details
#' This function determines the hazard vector \eqn{\lambda_{\text{neg}}}
#' for the piecewise exponential distribution of the biomarker negative
#' sub population, so that the implied survival function for the ITT
#' population closely matches the specified piecewise exponential
#' distribution with hazard vector \eqn{\lambda_{\text{itt}}}.
#'
#' Let \eqn{p_{\text{pos}}} be the
#' prevalence of the biomarker positive sub population,
#' then the survival function for the ITT population is given by
#' \deqn{S_{\text{itt}}(t) = p_{\text{pos}} S_{\text{pos}}(t) +
#' (1 - p_{\text{pos}}) S_{\text{neg}}(t)}
#' where \eqn{S_{\text{pos}}(t)} and \eqn{S_{\text{neg}}(t)} are
#' the survival functions for the biomarker positive and
#' biomarker negative sub populations, respectively.
#'
#' Matching is performed sequentially at the internal cutpoints
#' \eqn{u_2, ..., u_J} and at the point
#' \eqn{u_J + \log(2)/\lambda_{\text{itt},J}} for the final interval,
#' as well as the percentile points at 10%, 20%, ..., 90%, and 95%,
#' to solve for \eqn{\lambda_{\text{neg},1}, \ldots,
#' \lambda_{\text{neg},K}}, where \eqn{K} is the total number of
#' unique cut points.
#'
#' @return A list with the following components:
#'
#' * \code{piecewiseSurvivalTime}: A vector that specifies the starting time
#'   points of the intervals for the piecewise exponential distribution
#'   for the biomarker negative sub population.
#'
#' * \code{hazard_pos}: A numeric vector representing the hazard rates for
#'   the piecewise exponential distribution of the biomarker positive
#'   sub population at the same time points as the biomarker negative
#'   sub population.
#'
#' * \code{hazard_neg}: A numeric vector representing the estimated hazard
#'   rates for the piecewise exponential distribution of the biomarker
#'   negative sub population.
#'
#' * \code{p_pos}: The prevalence of the biomarker positive sub population
#'  (as input).
#'
#' @author
#' Kaifeng Lu (\email{kaifenglu@gmail.com})
#'
#' @examples
#' u <- c(0, 1, 3, 4)
#' lambda_itt <- c(0.0151, 0.0403, 0.0501, 0.0558)
#' lambda_pos <- c(0.0115, 0.0302, 0.0351, 0.0404)
#' p_pos <- 0.3
#' hazard_sub(u, lambda_itt, lambda_pos, p_pos)
#'
#' @export
hazard_sub <- function(piecewiseSurvivalTime = 0L, hazard_itt = NA_real_, hazard_pos = NA_real_, p_pos = NA_real_) {
    .Call(`_lrstat_hazard_sub`, piecewiseSurvivalTime, hazard_itt, hazard_pos, p_pos)
}

#' @title Singular Value Decomposition of a Matrix
#' @description Computes the singular-value decomposition of a
#' rectangular matrix.
#'
#' @param X A numeric matrix whose SVD decomposition is to be computed.
#' @param outtransform Whether the orthogonal matrices composing of the
#'   left and right singular vectors are to be computed.
#' @param decreasing Whether the singular values should be sorted in
#'   decreasing order and the corresponding singular vectors rearranged
#'   accordingly.
#'
#' @details
#' Given \eqn{A \in R^{m\times n} (m \geq n)}, the following algorithm
#' overwrites \eqn{A} with \eqn{U^T A V = D}, where
#' \eqn{U\in R^{m\times m}} is orthogonal, \eqn{V \in R^{n\times n}} is
#' orthogonal, and \eqn{D \in R^{m\times n}} is diagonal.
#'
#' @return A list with the following components:
#'
#' * \code{d}: A vector containing the singular values of \eqn{X}.
#'
#' * \code{U}: A matrix whose columns contain the left singular vectors
#'   of \eqn{X}.
#'
#' * \code{V}: A matrix whose columns contain the right singular vectors
#'   of \eqn{X}.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @references
#' Gene N. Golub and Charles F. Van Loan.
#' Matrix Computations, second edition. Baltimore, Maryland:
#' The John Hopkins University Press, 1989, p.434.
#'
#' @examples
#'
#' A <- matrix(c(1,0,0,0, 1,2,0,0, 0,1,3,0, 0,0,1,4), 4, 4)
#' svdcpp(A)
#'
#' @export
svdcpp <- function(X, outtransform = TRUE, decreasing = TRUE) {
    .Call(`_lrstat_svdcpp`, X, outtransform, decreasing)
}

#' @title Converting a decimal to a fraction
#' @description Converts a decimal to a fraction based on the algorithm
#' from http://stackoverflow.com/a/5128558/221955.
#'
#' @param x The fraction in decimal form.
#' @param tol The tolerance level for the conversion error.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' float_to_fraction(5/3)
#'
#' @export
float_to_fraction <- function(x, tol = 0.000001) {
    .Call(`_lrstat_float_to_fraction`, x, tol)
}

