R/RcppExports.R

Defines functions quantilecpp invsympd hasVariable adaptDesign getDesignEquiv getDesign nevent2 nevent natrisk ad pd hd pevent patrisk getAccrualDurationFromN accrual getPower getBoundcpp rtpwexpcpp qtpwexpcpp qtpwexpcpp1 ptpwexpcpp exitprobcpp errorSpentcpp findInterval3 stl_sort set_seed phregr liferegr lrtest kmest rpsft rmdiff rmest rmsamplesizeequiv rmpowerequiv rmsamplesize1s rmpower1s rmsamplesize rmpower rmstat rmstat1 covrmst rmst nbsamplesizeequiv nbpowerequiv nbsamplesize1s nbpower1s nbsamplesize nbpower nbstat nbstat1 riskRatioExactCI riskRatioExactPValue riskDiffExactCI riskDiffExactPValue samplesizeRiskRatioExactEquiv powerRiskRatioExactEquiv samplesizeRiskDiffExactEquiv powerRiskDiffExactEquiv samplesizeRiskRatioExact powerRiskRatioExact samplesizeRiskDiffExact powerRiskDiffExact mnRateRatioCI zstatRateRatio remlRateRatio2 remlRateRatio mnRateDiffCI zstatRateDiff remlRateDiff2 remlRateDiff mnOddsRatioCI zstatOddsRatio remlOddsRatio2 remlOddsRatio mnRiskRatioCI zstatRiskRatio remlRiskRatio2 remlRiskRatio mnRiskDiffCI zstatRiskDiff remlRiskDiff2 remlRiskDiff samplesizeFisherExact powerFisherExact samplesizeOneRateExact powerOneRateExact samplesizeOnePropExact powerOnePropExact simon2stage ftrunccpp getCP getADRCI getADCI getRCI getCI fmodmixcpp fstdmixcpp fstp2seqcpp fseqboncpp repeatedPValuecpp fadjpsimcpp fwgtmat fadjpboncpp updateGraph lrsamplesizeequiv lrpowerequiv lrsamplesize getNeventsFromHazardRatio lrpower getDurationFromNevents caltime lrstat lrstat1 lrsim2e3a lrsim2e lrsim3a lrsim kmdiff kmsamplesizeequiv kmpowerequiv kmsamplesize1s kmpower1s kmsamplesize kmpower kmstat kmstat1 binary_tte_sim simonBayesSim simonBayesAnalysis

Documented in accrual ad adaptDesign binary_tte_sim caltime covrmst findInterval3 fwgtmat getAccrualDurationFromN getADCI getADRCI getCI getCP getDesign getDesignEquiv getDurationFromNevents getNeventsFromHazardRatio getRCI hd kmdiff kmest kmpower kmpower1s kmpowerequiv kmsamplesize kmsamplesize1s kmsamplesizeequiv kmstat kmstat1 liferegr lrpower lrpowerequiv lrsamplesize lrsamplesizeequiv lrsim lrsim2e lrsim2e3a lrsim3a lrstat lrstat1 lrtest mnOddsRatioCI mnRateDiffCI mnRateRatioCI mnRiskDiffCI mnRiskRatioCI natrisk nbpower nbpower1s nbpowerequiv nbsamplesize nbsamplesize1s nbsamplesizeequiv nbstat nbstat1 nevent nevent2 patrisk pd pevent phregr powerFisherExact powerOnePropExact powerOneRateExact powerRiskDiffExact powerRiskDiffExactEquiv powerRiskRatioExact powerRiskRatioExactEquiv remlOddsRatio remlRateDiff remlRateRatio remlRiskDiff remlRiskRatio riskDiffExactCI riskDiffExactPValue riskRatioExactCI riskRatioExactPValue rmdiff rmest rmpower rmpower1s rmpowerequiv rmsamplesize rmsamplesize1s rmsamplesizeequiv rmst rmstat rmstat1 rpsft samplesizeFisherExact samplesizeOnePropExact samplesizeOneRateExact samplesizeRiskDiffExact samplesizeRiskDiffExactEquiv samplesizeRiskRatioExact samplesizeRiskRatioExactEquiv simon2stage simonBayesAnalysis simonBayesSim updateGraph zstatOddsRatio zstatRateDiff zstatRateRatio zstatRiskDiff zstatRiskRatio

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

#' @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_integer_, n = NA_integer_, 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 = NA_integer_) {
    .Call(`_lrstat_simonBayesSim`, p, accrualTime, accrualIntensity, stratumFraction, lambda, gamma, phi, plo, T, maxSubjects, plannedSubjects, maxNumberOfIterations, maxNumberOfRawDatasets, seed)
}

#' @title Simulation for a binary endpoint and a time-to-event endpoint
#' @description Performs simulation for two-endpoint two-arm group
#' sequential trials. The first endpoint is a binary endpoint and
#' the Mantel-Haenszel test is used to test risk difference.
#' The second endpoint is a time-to-event endpoint and the log-rank
#' test is used to test the treatment difference. The analysis times
#' of the first endpoint are determined by the specified calendar times,
#' while the analysis times for the second endpoint is based on the
#' planned number of events at each look. The binary endpoint is
#' assessed at the first post-treatment follow-up visit.
#'
#' @param kMax1 Number of stages for the binary endpoint.
#' @param kMax2 Number of stages for the time-to-event endpoint.
#' @param riskDiffH0 Risk difference under the null hypothesis for the
#'   binary endpoint.
#' @param hazardRatioH0 Hazard ratio under the null hypothesis for the
#'   time-to-event endpoint.
#' @param allocation1 Number of subjects in the treatment group in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @param allocation2 Number of subjects in the control group in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param globalOddsRatio The global odds ratio of the Plackett copula.
#' @param pi1 Response probabilities by stratum for the treatment group
#'   for the binary endpoint.
#' @param pi2 Response probabilities by stratum for the control group
#'   for the binary endpoint.
#' @param lambda1 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for the treatment group for the time-to-event
#'   endpoint.
#' @param lambda2 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for the control group for the time-to-event
#'   endpoint.
#' @param gamma1 The hazard rate for exponential dropout, a vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for the treatment group.
#' @param gamma2 The hazard rate for exponential dropout, a vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for the control group.
#' @param delta1 The hazard rate for exponential treatment discontinuation,
#'   a vector of hazard rates for piecewise exponential treatment
#'   discontinuation applicable for all strata, or a vector of hazard rates
#'   for treatment discontinuation in each analysis time interval by
#'   stratum for the treatment group for the binary endpoint.
#' @param delta2 The hazard rate for exponential treatment discontinuation,
#'   a vector of hazard rates for piecewise exponential treatment
#'   discontinuation applicable for all strata, or a vector of hazard rates
#'   for treatment discontinuation in each analysis time interval by
#'   stratum for the control group for the binary endpoint.
#' @param upper1 The protocol-specified treatment duration for the treatment
#'   group.
#' @param upper2 The protocol-specified treatment duration for the control
#'   group.
#' @inheritParams param_accrualDuration
#' @param plannedTime The calendar times for the analyses of the binary
#'   endpoint.
#' @param plannedEvents The planned cumulative total number of events for
#'   the time-to-event endpoint.
#' @param maxNumberOfIterations The number of simulation iterations.
#' @param maxNumberOfRawDatasetsPerStage The number of raw datasets per
#'   stage to extract.
#' @param seed The seed to reproduce the simulation results.
#'   The seed from the environment will be used if left unspecified,
#'
#' @details We consider dual primary endpoints with endpoint 1 being a
#'   binary endpoint and endpoint 2 being a time-to-event endpoint.
#'   The analyses of endpoint 1 will be based on calendar times, while
#'   the analyses of endpoint 2 will be based on the number of events.
#'   Therefor the analyses of the two endpoints are not at the same
#'   time points. The correlation between the two endpoints is
#'   characterized by the global odds ratio of the Plackett copula.
#'   In addition, the time-to-event endpoint will render the binary
#'   endpoint as a non-responder, and so does the dropout. In addition,
#'   the treatment discontinuation will impact the number of available
#'   subjects for analysis. The administrative censoring will exclude
#'   subjects from the analysis of the binary endpoint.
#'
#'
#' @return A list with 4 components:
#'
#' * \code{sumdataBIN}: A data frame of summary data by iteration and stage
#'   for the binary endpoint:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{stageNumber}: The stage number, covering all stages even if
#'       the trial stops at an interim look.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{accruals1}: The number of subjects enrolled at the stage for
#'       the treatment group.
#'
#'     - \code{accruals2}: The number of subjects enrolled at the stage for
#'       the control group.
#'
#'     - \code{totalAccruals}: The total number of subjects enrolled at
#'       the stage.
#'
#'     - \code{source1}: The total number of subjects with response status
#'       determined by the underlying latent response variable.
#'
#'     - \code{source2}: The total number of subjects with response status
#'       (non-responder) determined by experiencing the event for the
#'       time-to-event endpoint.
#'
#'     - \code{source3}: The total number of subjects with response status
#'       (non-responder) determined by dropping out prior to the PTFU1
#'       visit.
#'
#'     - \code{n1}: The number of subjects included in the analysis of
#'       the binary endpoint for the treatment group.
#'
#'     - \code{n2}: The number of subjects included in the analysis of
#'       the binary endpoint for the control group.
#'
#'     - \code{n}: The total number of subjects included in the analysis of
#'       the binary endpoint at the stage.
#'
#'     - \code{y1}: The number of responders for the binary endpoint in
#'       the treatment group.
#'
#'     - \code{y2}: The number of responders for the binary endpoint in
#'       the control group.
#'
#'     - \code{y}: The total number of responders for the binary endpoint
#'       at the stage.
#'
#'     - \code{riskDiff}: The estimated risk difference for the binary
#'       endpoint.
#'
#'     - \code{seRiskDiff}: The standard error for risk difference based on
#'       the Sato approximation.
#'
#'     - \code{mnStatistic}: The Mantel-Haenszel test Z-statistic for
#'       the binary endpoint.
#'
#' * \code{sumdataTTE}: A data frame of summary data by iteration and stage
#'   for the time-to-event endpoint:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{eventsNotAchieved}: Whether the target number of events
#'       is not achieved for the iteration.
#'
#'     - \code{stageNumber}: The stage number, covering all stages even if
#'       the trial stops at an interim look.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{accruals1}: The number of subjects enrolled at the stage for
#'       the treatment group.
#'
#'     - \code{accruals2}: The number of subjects enrolled at the stage for
#'       the control group.
#'
#'     - \code{totalAccruals}: The total number of subjects enrolled at
#'       the stage.
#'
#'     - \code{events1}: The number of events at the stage for
#'       the treatment group.
#'
#'     - \code{events2}: The number of events at the stage for
#'       the control group.
#'
#'     - \code{totalEvents}: The total number of events at the stage.
#'
#'     - \code{dropouts1}: The number of dropouts at the stage for
#'       the treatment group.
#'
#'     - \code{dropouts2}: The number of dropouts at the stage for
#'       the control group.
#'
#'     - \code{totalDropouts}: The total number of dropouts at the stage.
#'
#'     - \code{logRankStatistic}: The log-rank test Z-statistic for
#'       the time-to-event endpoint.
#'
#' * \code{rawdataBIN} (exists if \code{maxNumberOfRawDatasetsPerStage} is a
#'   positive integer): A data frame for subject-level data for the binary
#'   endpoint for selected replications, containing the following variables:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{stageNumber}: The stage under consideration.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{subjectId}: The subject ID.
#'
#'     - \code{arrivalTime}: The enrollment time for the subject.
#'
#'     - \code{stratum}: The stratum for the subject.
#'
#'     - \code{treatmentGroup}: The treatment group (1 or 2) for the
#'       subject.
#'
#'     - \code{survivalTime}: The underlying survival time for the
#'       time-to-event endpoint for the subject.
#'
#'     - \code{dropoutTime}: The underlying dropout time for the
#'       time-to-event endpoint for the subject.
#'
#'     - \code{ptfu1Time}:The underlying assessment time for the
#'       binary endpoint for the subject.
#'
#'     - \code{timeUnderObservation}: The time under observation
#'       since randomization for the binary endpoint for the subject.
#'
#'     - \code{responder}: Whether the subject is a responder for the
#'       binary endpoint.
#'
#'     - \code{source}: The source of the determination of responder
#'       status for the binary endpoint: = 1 based on the underlying
#'       latent response variable, = 2 based on the occurrence of
#'       the time-to-event endpoint before the assessment time of the
#'       binary endpoint (imputed as a non-responder), = 3 based on
#'       the dropout before the assessment time of the binary endpoint
#'       (imputed as a non-responder), = 4 excluded from analysis
#'       due to administrative censoring.
#'
#' * \code{rawdataTTE} (exists if \code{maxNumberOfRawDatasetsPerStage} is a
#'   positive integer): A data frame for subject-level data for the
#'   time-to-event endpoint for selected replications, containing the
#'   following variables:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{stageNumber}: The stage under consideration.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{subjectId}: The subject ID.
#'
#'     - \code{arrivalTime}: The enrollment time for the subject.
#'
#'     - \code{stratum}: The stratum for the subject.
#'
#'     - \code{treatmentGroup}: The treatment group (1 or 2) for the
#'       subject.
#'
#'     - \code{survivalTime}: The underlying survival time for the
#'       time-to-event endpoint for the subject.
#'
#'     - \code{dropoutTime}: The underlying dropout time for the
#'       time-to-event endpoint for the subject.
#'
#'     - \code{timeUnderObservation}: The time under observation
#'       since randomization for the time-to-event endpoint for the subject.
#'
#'     - \code{event}: Whether the subject experienced the event for the
#'       time-to-event endpoint.
#'
#'     - \code{dropoutEvent}: Whether the subject dropped out for the
#'       time-to-event endpoint.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' tcut = c(0, 12, 36, 48)
#' surv = c(1, 0.95, 0.82, 0.74)
#' lambda2 = (log(surv[1:3]) - log(surv[2:4]))/(tcut[2:4] - tcut[1:3])
#'
#' sim1 = binary_tte_sim(
#'   kMax1 = 1,
#'   kMax2 = 2,
#'   accrualTime = 0:8,
#'   accrualIntensity = c(((1:8) - 0.5)/8, 1)*40,
#'   piecewiseSurvivalTime = c(0,12,36),
#'   globalOddsRatio = 1,
#'   pi1 = 0.80,
#'   pi2 = 0.65,
#'   lambda1 = 0.65*lambda2,
#'   lambda2 = lambda2,
#'   gamma1 = -log(1-0.04)/12,
#'   gamma2 = -log(1-0.04)/12,
#'   delta1 = -log(1-0.02)/12,
#'   delta2 = -log(1-0.02)/12,
#'   upper1 = 15*28/30.4,
#'   upper2 = 12*28/30.4,
#'   accrualDuration = 20,
#'   plannedTime = 20 + 15*28/30.4,
#'   plannedEvents = c(130, 173),
#'   maxNumberOfIterations = 1000,
#'   maxNumberOfRawDatasetsPerStage = 1,
#'   seed = 314159)
#'
#'
#' @export
binary_tte_sim <- 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_, accrualDuration = NA_real_, plannedTime = NA_real_, plannedEvents = NA_integer_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = NA_integer_) {
    .Call(`_lrstat_binary_tte_sim`, kMax1, kMax2, riskDiffH0, hazardRatioH0, allocation1, allocation2, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, globalOddsRatio, pi1, pi2, lambda1, lambda2, gamma1, gamma2, delta1, delta2, upper1, upper2, accrualDuration, plannedTime, plannedEvents, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

#' @title Milestone survival probability by stratum
#'
#' @description Obtains the milestone survival probability and associated
#' variance by treatment group and by stratum at a given calendar time.
#'
#' @param time The calendar time 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{stratum}: The stratum.
#'
#' * \code{time}: The calendar time since trial start.
#'
#' * \code{subjects}: The number of enrolled subjects.
#'
#' * \code{milestone}: The milestone time relative to randomization.
#'
#' * \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}.
#'
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#'
#' kmstat1(time = 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
kmstat1 <- 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 = 0L) {
    .Call(`_lrstat_kmstat1`, time, milestone, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup)
}

#' @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{milestone}: The milestone time relative to randomization.
#'
#' * \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 = 0L) {
    .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 typeBetaSpending The type of beta spending. One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function, "sfP" for Pocock
#'   type spending function, "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and "none" for no
#'   early futility stopping. Defaults to "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 3 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{drift}: The drift parameter, equal to
#'       \code{(survDiff - survDiffH0)*sqrt(information)}.
#'
#'     - \code{inflationFactor}: The inflation factor (relative to the
#'       fixed design).
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \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 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{numberOfSubjects}: The number of subjects.
#'
#'     - \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}.
#'
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_kmpower`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, 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
#' @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 interval The interval to search for the solution of
#'   accrualDuration, followupTime, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}.
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, interval = as.numeric( c(0.001, 240)), spendingTime = NA_real_, rounding = 1L) {
    .Call(`_lrstat_kmsamplesize`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, typeBetaSpending, parameterBetaSpending, userBetaSpending, milestone, survDiffH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, interval, 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 typeBetaSpending The type of beta spending. One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function, "sfP" for Pocock
#'   type spending function, "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and "none" for no
#'   early futility stopping. Defaults to "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{drift}: The drift parameter, equal to
#'       \code{(surv - survH0)*sqrt(information)}.
#'
#'     - \code{inflationFactor}: The inflation factor (relative to the
#'       fixed design).
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \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 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{numberOfSubjects}: The number of subjects.
#'
#'     - \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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_kmpower1s`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, 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
#' @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 interval The interval to search for the solution of
#'   accrualDuration, followupDuration, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}.
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, interval = as.numeric( c(0.001, 240)), spendingTime = NA_real_, rounding = 1L) {
    .Call(`_lrstat_kmsamplesize1s`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, typeBetaSpending, parameterBetaSpending, userBetaSpending, milestone, survH0, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda, gamma, accrualDuration, followupTime, fixedFollowup, interval, 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 3 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{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \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{numberOfSubjects}: The number of subjects.
#'
#'     - \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}.
#'
#' @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 = 0L, 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 interval The interval to search for the solution of
#'   accrualDuration, followupDuration, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}.
#' @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 = 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 = 0L, interval = as.numeric( c(0.001, 240)), 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, interval, spendingTime, rounding)
}

#' @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{rep}: The replication for by-group processing.
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{treat}: The treatment.
#'
#'   * \code{time}: The possibly right-censored survival time.
#'
#'   * \code{event}: The event indicator.
#'
#' @param rep The name of the replication variable in the input data.
#' @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
#'   survival probability.
#' @param survDiffH0 The difference in milestone survival probabilities
#'   under the null hypothesis. Defaults to 0 for superiority test.
#' @param confint 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{rep}: The replication.
#'
#' * \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{vsurvDiff}: The variance for survDiff.
#'
#' * \code{survDiffZ}: The Z-statistic value.
#'
#' * \code{survDiffPValue}: The one-sided p-value.
#'
#' * \code{lower}: The lower bound of confidence interval.
#'
#' * \code{upper}: The upper bound of confidence interval.
#'
#' * \code{confint}: The level of confidence interval.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' df <- kmdiff(data = rawdata, rep = "iterationNumber",
#'              stratum = "stratum", treat = "treatmentGroup",
#'              time = "timeUnderObservation", event = "event",
#'              milestone = 12)
#' head(df)
#'
#' @export
kmdiff <- function(data, rep = "rep", stratum = "stratum", treat = "treat", time = "time", event = "event", milestone = NA_real_, survDiffH0 = 0, confint = 0.95) {
    .Call(`_lrstat_kmdiff`, data, rep, stratum, treat, time, event, milestone, survDiffH0, confint)
}

#' @title Log-rank test simulation
#' @description Performs simulation for two-arm group sequential
#' trials based on weighted log-rank test.
#'
#' @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.
#'   Fixed prior to the trial. If left unspecified, it defaults to
#'   \code{plannedEvents / plannedEvents[kMax]} when \code{plannedEvents}
#'   is provided and to \code{plannedTime / plannedTime[kMax]} otherwise.
#' @inheritParams param_criticalValues
#' @inheritParams param_futilityBounds
#' @inheritParams param_hazardRatioH0
#' @param allocation1 Number of subjects in the active treatment group in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @param allocation2 Number of subjects in the control group in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @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 plannedEvents The planned cumulative total number of events at
#'   each stage.
#' @param plannedTime The calendar times for the analyses. To use calendar
#'   time to plan the analyses, \code{plannedEvents} should be missing.
#' @param maxNumberOfIterations The number of simulation iterations.
#'   Defaults to 1000.
#' @param maxNumberOfRawDatasetsPerStage The number of raw datasets per
#'   stage to extract.
#' @param seed The seed to reproduce the simulation results.
#'   The seed from the environment will be used if left unspecified,
#'
#' @return An S3 class \code{lrsim} object with 3 components:
#'
#' * \code{overview}: A list containing the following information:
#'
#'     - \code{rejectPerStage}: The efficacy stopping probability by stage.
#'
#'     - \code{futilityPerStage}: The futility stopping probability by
#'       stage.
#'
#'     - \code{cumulativeRejection}: Cumulative efficacy stopping
#'       probability by stage.
#'
#'     - \code{cumulativeFutility}: The cumulative futility stopping
#'       probability by stage.
#'
#'     - \code{numberOfEvents}: The average number of events by stage.
#'
#'     - \code{numberOfDropouts}: The average number of dropouts by stage.
#'
#'     - \code{numberOfSubjects}: The average number of subjects by stage.
#'
#'     - \code{analysisTime}: The average analysis time by stage.
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{expectedNumberOfEvents}: The expected number of events for
#'       the overall study.
#'
#'     - \code{expectedNumberOfDropouts}: The expected number of dropouts
#'       for the overall study.
#'
#'     - \code{expectedNumberOfSubjects}: The expected number of subjects
#'       for the overall study.
#'
#'     - \code{expectedStudyDuration}: The expected study duration.
#'
#'     - \code{hazardRatioH0}: Hazard ratio under the null hypothesis for
#'       the active treatment versus control.
#'
#'     - \code{useEvents}: whether the analyses are planned
#'       based on the number of events or calendar time.
#'
#'     - \code{accrualDuration}: Duration of the enrollment period.
#'
#'     - \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. Defaults to 0 for conventional log-rank
#'       test.
#'
#'     - \code{rho2}: The second parameter of the Fleming-Harrington family
#'       of weighted log-rank test. Defaults to 0 for conventional log-rank
#'       test.
#'
#'     - \code{kMax}: The maximum number of stages.
#'
#' * \code{sumdata}: A data frame of summary data by iteration and stage:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{stopStage}: The stage at which the trial stops.
#'
#'     - \code{eventsNotAchieved}: Whether the target number of events
#'       is not achieved for the iteration.
#'
#'     - \code{stageNumber}: The stage number, covering all stages even if
#'       the trial stops at an interim look.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{accruals1}: The number of subjects enrolled at the stage for
#'       the treatment group.
#'
#'     - \code{accruals2}: The number of subjects enrolled at the stage for
#'       the control group.
#'
#'     - \code{totalAccruals}: The total number of subjects enrolled at
#'       the stage.
#'
#'     - \code{events1}: The number of events at the stage for
#'       the treatment group.
#'
#'     - \code{events2}: The number of events at the stage for
#'       the control group.
#'
#'     - \code{totalEvents}: The total number of events at the stage.
#'
#'     - \code{dropouts1}: The number of dropouts at the stage for
#'       the treatment group.
#'
#'     - \code{dropouts2}: The number of dropouts at the stage for
#'       the control group.
#'
#'     - \code{totalDropouts}: The total number of dropouts at the stage.
#'
#'     - \code{uscore}: The numerator of the log-rank test statistic.
#'
#'     - \code{vscore}: The variance of the log-rank test statistic.
#'
#'     - \code{logRankStatistic}: The log-rank test Z-statistic.
#'
#'     - \code{rejectPerStage}: Whether to reject the null hypothesis
#'       at the stage.
#'
#'     - \code{futilityPerStage}: Whether to stop the trial for futility
#'       at the stage.
#'
#' * \code{rawdata} (exists if \code{maxNumberOfRawDatasetsPerStage} is a
#'   positive integer): A data frame for subject-level data for selected
#'   replications, containing the following variables:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{stopStage}: The stage at which the trial stops.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{subjectId}: The subject ID.
#'
#'     - \code{arrivalTime}: The enrollment time for the subject.
#'
#'     - \code{stratum}: The stratum for the subject.
#'
#'     - \code{treatmentGroup}: The treatment group (1 or 2) for the
#'       subject.
#'
#'     - \code{survivalTime}: The underlying survival time for the subject.
#'
#'     - \code{dropoutTime}: The underlying dropout time for the subject.
#'
#'     - \code{timeUnderObservation}: The time under observation
#'       since randomization.
#'
#'     - \code{event}: Whether the subject experienced the event.
#'
#'     - \code{dropoutEvent}: Whether the subject dropped out.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Example 1: analyses based on number of events
#'
#' sim1 = lrsim(kMax = 2, informationRates = c(0.5, 1),
#'              criticalValues = c(2.797, 1.977),
#'              accrualIntensity = 11,
#'              lambda1 = 0.018, lambda2 = 0.030,
#'              accrualDuration = 12,
#'              plannedEvents = c(60, 120),
#'              maxNumberOfIterations = 1000,
#'              maxNumberOfRawDatasetsPerStage = 1,
#'              seed = 314159)
#'
#' # summary statistics
#' sim1
#'
#' # summary for each simulated data set
#' head(sim1$sumdata)
#'
#' # raw data for selected replication
#' head(sim1$rawdata)
#'
#'
#' # Example 2: analyses based on calendar time have similar power
#'
#' sim2 = lrsim(kMax = 2, informationRates = c(0.5, 1),
#'              criticalValues = c(2.797, 1.977),
#'              accrualIntensity = 11,
#'              lambda1 = 0.018, lambda2 = 0.030,
#'              accrualDuration = 12,
#'              plannedTime = c(31.9, 113.2),
#'              maxNumberOfIterations = 1000,
#'              maxNumberOfRawDatasetsPerStage = 1,
#'              seed = 314159)
#'
#' # summary statistics
#' sim2
#'
#' # summary for each simulated data set
#' head(sim2$sumdata)
#'
#' @export
lrsim <- 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, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = 0L, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = NA_integer_) {
    .Call(`_lrstat_lrsim`, kMax, informationRates, criticalValues, futilityBounds, hazardRatioH0, allocation1, allocation2, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

#' @title Log-rank test simulation for three arms
#' @description Performs simulation for three-arm group sequential trials
#' based on weighted log-rank test. The looks are driven by the total
#' number of events in Arm A and Arm C combined. Alternatively,
#' the analyses can be planned to occur at specified calendar times.
#'
#' @inheritParams param_kMax
#' @param hazardRatioH013 Hazard ratio under the null hypothesis for arm 1
#'   versus arm 3. Defaults to 1 for superiority test.
#' @param hazardRatioH023 Hazard ratio under the null hypothesis for arm 2
#'   versus arm 3. Defaults to 1 for superiority test.
#' @param hazardRatioH012 Hazard ratio under the null hypothesis for arm 1
#'   versus arm 2. Defaults to 1 for superiority test.
#' @param allocation1 Number of subjects in Arm A in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @param allocation2 Number of subjects in Arm B in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @param allocation3 Number of subjects in Arm C in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param lambda1 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for arm 1.
#' @param lambda2 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for arm 2.
#' @param lambda3 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for arm 3.
#' @param gamma1 The hazard rate for exponential dropout. A vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for arm 1.
#' @param gamma2 The hazard rate for exponential dropout. A vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for arm 2.
#' @param gamma3 The hazard rate for exponential dropout. A vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for arm 3.
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @inheritParams param_rho1
#' @inheritParams param_rho2
#' @param plannedEvents The planned cumulative total number of events at
#'   Look 1 to Look \code{kMax} for Arms A and C combined.
#' @param plannedTime The calendar times for the analyses. To use calendar
#'   time to plan the analyses, \code{plannedEvents} should be missing.
#' @param maxNumberOfIterations The number of simulation iterations.
#'   Defaults to 1000.
#' @param maxNumberOfRawDatasetsPerStage The number of raw datasets per
#'   stage 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 with 2 components:
#'
#' * \code{sumdata}: A data frame of summary data by iteration and stage:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{eventsNotAchieved}: Whether the target number of events
#'       is not achieved for the iteration.
#'
#'     - \code{stageNumber}: The stage number, covering all stages even if
#'       the trial stops at an interim look.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{accruals1}: The number of subjects enrolled at the stage for
#'       the active treatment 1 group.
#'
#'     - \code{accruals2}: The number of subjects enrolled at the stage for
#'       the active treatment 2 group.
#'
#'     - \code{accruals3}: The number of subjects enrolled at the stage for
#'       the control group.
#'
#'     - \code{totalAccruals}: The total number of subjects enrolled at
#'       the stage.
#'
#'     - \code{events1}: The number of events at the stage for
#'       the active treatment 1 group.
#'
#'     - \code{events2}: The number of events at the stage for
#'       the active treatment 2 group.
#'
#'     - \code{events3}: The number of events at the stage for
#'       the control group.
#'
#'     - \code{totalEvents}: The total number of events at the stage.
#'
#'     - \code{dropouts1}: The number of dropouts at the stage for
#'       the active treatment 1 group.
#'
#'     - \code{dropouts2}: The number of dropouts at the stage for
#'       the active treatment 2 group.
#'
#'     - \code{dropouts3}: The number of dropouts at the stage for
#'       the control group.
#'
#'     - \code{totalDropouts}: The total number of dropouts at the stage.
#'
#'     - \code{logRankStatistic13}: The log-rank test Z-statistic
#'       comparing the active treatment 1 to the control.
#'
#'     - \code{logRankStatistic23}: The log-rank test Z-statistic
#'       comparing the active treatment 2 to the control.
#'
#'     - \code{logRankStatistic12}: The log-rank test Z-statistic
#'       comparing the active treatment 1 to the active treatment 2.
#'
#' * \code{rawdata} (exists if \code{maxNumberOfRawDatasetsPerStage} is a
#'   positive integer): A data frame for subject-level data for selected
#'   replications, containing the following variables:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{stageNumber}: The stage under consideration.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{subjectId}: The subject ID.
#'
#'     - \code{arrivalTime}: The enrollment time for the subject.
#'
#'     - \code{stratum}: The stratum for the subject.
#'
#'     - \code{treatmentGroup}: The treatment group (1, 2, or 3) for
#'       the subject.
#'
#'     - \code{survivalTime}: The underlying survival time for the subject.
#'
#'     - \code{dropoutTime}: The underlying dropout time for the subject.
#'
#'     - \code{timeUnderObservation}: The time under observation
#'       since randomization for the subject.
#'
#'     - \code{event}: Whether the subject experienced the event.
#'
#'     - \code{dropoutEvent}: Whether the subject dropped out.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' sim1 = lrsim3a(
#'   kMax = 3,
#'   allocation1 = 2,
#'   allocation2 = 2,
#'   allocation3 = 1,
#'   accrualTime = c(0, 8),
#'   accrualIntensity = c(10, 28),
#'   piecewiseSurvivalTime = 0,
#'   lambda1 = log(2)/12*0.60,
#'   lambda2 = log(2)/12*0.70,
#'   lambda3 = log(2)/12,
#'   accrualDuration = 30.143,
#'   plannedEvents = c(186, 259, 295),
#'   maxNumberOfIterations = 1000,
#'   maxNumberOfRawDatasetsPerStage = 1,
#'   seed = 314159)
#'
#' head(sim1$sumdata)
#' head(sim1$rawdata)
#'
#' @export
lrsim3a <- function(kMax = NA_integer_, 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, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = 0L, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = NA_integer_) {
    .Call(`_lrstat_lrsim3a`, kMax, hazardRatioH013, hazardRatioH023, hazardRatioH012, allocation1, allocation2, allocation3, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, lambda3, gamma1, gamma2, gamma3, accrualDuration, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

#' @title Log-rank test simulation for two endpoints
#' @description Performs simulation for two-endpoint two-arm group
#' sequential trials based on weighted log-rank test. The first
#' \code{kMaxe1} looks are driven by the total number of PFS events in
#' two arms combined, and the subsequent looks are driven by the total
#' number of OS events in two arms combined. Alternatively,
#' the analyses can be planned to occur at specified calendar times.
#'
#' @inheritParams param_kMax
#' @param kMaxe1 Number of stages with timing determined by PFS events.
#'   Ranges from 0 (none) to \code{kMax}.
#' @param hazardRatioH0e1 Hazard ratio under the null hypothesis for the
#'   active treatment vs control for endpoint 1 (PFS). Defaults to 1 for
#'   superiority test.
#' @param hazardRatioH0e2 Hazard ratio under the null hypothesis for the
#'   active treatment vs control for endpoint 2 (OS). Defaults to 1 for
#'   superiority test.
#' @param allocation1 Number of subjects in the treatment group in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @param allocation2 Number of subjects in the control group in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param rho The correlation coefficient for the standard bivariate normal
#'   random variables used to generate time to disease progression and time
#'   to death using the inverse CDF method.
#' @param lambda1e1 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for the treatment group and endpoint 1 (PFS).
#' @param lambda2e1 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for the control group and endpoint 1 (PFS).
#' @param lambda1e2 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for the treatment group and endpoint 2 (OS).
#' @param lambda2e2 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for the control group and endpoint 2 (OS).
#' @param gamma1e1 The hazard rate for exponential dropout, a vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for the treatment group and endpoint 1 (PFS).
#' @param gamma2e1 The hazard rate for exponential dropout, a vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for the control group and endpoint 1 (PFS).
#' @param gamma1e2 The hazard rate for exponential dropout, a vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for the treatment group and endpoint 2 (OS).
#' @param gamma2e2 The hazard rate for exponential dropout, a vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for the control group and endpoint 2 (OS).
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @inheritParams param_rho1
#' @inheritParams param_rho2
#' @param plannedEvents The planned cumulative total number of PFS events at
#'   Look 1 to Look \code{kMaxe1} and the planned cumulative total number
#'   of OS events at Look \code{kMaxe1+1} to Look \code{kMax}.
#' @param plannedTime The calendar times for the analyses. To use calendar
#'   time to plan the analyses, \code{plannedEvents} should be missing.
#' @param maxNumberOfIterations The number of simulation iterations.
#'   Defaults to 1000.
#' @param maxNumberOfRawDatasetsPerStage The number of raw datasets per
#'   stage 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 with 2 components:
#'
#' * \code{sumdata}: A data frame of summary data by iteration and stage:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{eventsNotAchieved}: Whether the target number of events
#'       is not achieved for the iteration.
#'
#'     - \code{stageNumber}: The stage number, covering all stages even if
#'       the trial stops at an interim look.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{accruals1}: The number of subjects enrolled at the stage for
#'       the treatment group.
#'
#'     - \code{accruals2}: The number of subjects enrolled at the stage for
#'       the control group.
#'
#'     - \code{totalAccruals}: The total number of subjects enrolled at
#'       the stage.
#'
#'     - \code{endpoint}: The endpoint (1 or 2) under consideration.
#'
#'     - \code{events1}: The number of events at the stage for
#'       the treatment group.
#'
#'     - \code{events2}: The number of events at the stage for
#'       the control group.
#'
#'     - \code{totalEvents}: The total number of events at the stage.
#'
#'     - \code{dropouts1}: The number of dropouts at the stage for
#'       the treatment group.
#'
#'     - \code{dropouts2}: The number of dropouts at the stage for
#'       the control group.
#'
#'     - \code{totalDropouts}: The total number of dropouts at the stage.
#'
#'     - \code{logRankStatistic}: The log-rank test Z-statistic for
#'       the endpoint.
#'
#' * \code{rawdata} (exists if \code{maxNumberOfRawDatasetsPerStage} is a
#'   positive integer): A data frame for subject-level data for selected
#'   replications, containing the following variables:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{stageNumber}: The stage under consideration.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{subjectId}: The subject ID.
#'
#'     - \code{arrivalTime}: The enrollment time for the subject.
#'
#'     - \code{stratum}: The stratum for the subject.
#'
#'     - \code{treatmentGroup}: The treatment group (1 or 2) for the
#'       subject.
#'
#'     - \code{survivalTime1}: The underlying survival time for
#'       event endpoint 1 for the subject.
#'
#'     - \code{dropoutTime1}: The underlying dropout time for
#'       event endpoint 1 for the subject.
#'
#'     - \code{timeUnderObservation1}: The time under observation
#'       since randomization for event endpoint 1 for the subject.
#'
#'     - \code{event1}: Whether the subject experienced event endpoint 1.
#'
#'     - \code{dropoutEvent1}: Whether the subject dropped out for
#'       endpoint 1.
#'
#'     - \code{survivalTime2}: The underlying survival time for
#'       event endpoint 2 for the subject.
#'
#'     - \code{dropoutTime2}: The underlying dropout time for
#'       event endpoint 2 for the subject.
#'
#'     - \code{timeUnderObservation2}: The time under observation
#'       since randomization for event endpoint 2 for the subject.
#'
#'     - \code{event2}: Whether the subject experienced event endpoint 2.
#'
#'     - \code{dropoutEvent2}: Whether the subject dropped out for
#'       endpoint 2.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' sim1 = lrsim2e(
#'   kMax = 3,
#'   kMaxe1 = 2,
#'   allocation1 = 2,
#'   allocation2 = 1,
#'   accrualTime = c(0, 8),
#'   accrualIntensity = c(10, 28),
#'   piecewiseSurvivalTime = 0,
#'   rho = 0,
#'   lambda1e1 = log(2)/12*0.60,
#'   lambda2e1 = log(2)/12,
#'   lambda1e2 = log(2)/30*0.65,
#'   lambda2e2 = log(2)/30,
#'   accrualDuration = 20.143,
#'   plannedEvents = c(186, 259, 183),
#'   maxNumberOfIterations = 1000,
#'   maxNumberOfRawDatasetsPerStage = 1,
#'   seed = 314159)
#'
#' head(sim1$sumdata)
#' head(sim1$rawdata)
#'
#' @export
lrsim2e <- function(kMax = NA_integer_, kMaxe1 = NA_integer_, hazardRatioH0e1 = 1, hazardRatioH0e2 = 1, allocation1 = 1L, allocation2 = 1L, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, rho = 0, lambda1e1 = NA_real_, lambda2e1 = NA_real_, lambda1e2 = NA_real_, lambda2e2 = NA_real_, gamma1e1 = 0L, gamma2e1 = 0L, gamma1e2 = 0L, gamma2e2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = 0L, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = NA_integer_) {
    .Call(`_lrstat_lrsim2e`, kMax, kMaxe1, hazardRatioH0e1, hazardRatioH0e2, allocation1, allocation2, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, rho, lambda1e1, lambda2e1, lambda1e2, lambda2e2, gamma1e1, gamma2e1, gamma1e2, gamma2e2, accrualDuration, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

#' @title Log-rank test simulation for two endpoints and three arms
#' @description Performs simulation for two-endpoint three-arm group
#' sequential trials based on weighted log-rank test. The first
#' \code{kMaxe1} looks are driven by the total number of PFS events in Arm A
#' and Arm C combined, and the subsequent looks are driven by the total
#' number of OS events in Arm A and Arm C combined. Alternatively,
#' the analyses can be planned to occur at specified calendar times.
#'
#' @inheritParams param_kMax
#' @param kMaxe1 Number of stages with timing determined by PFS events.
#'   Ranges from 0 (none) to \code{kMax}.
#' @param hazardRatioH013e1 Hazard ratio under the null hypothesis for arm 1
#'   vs arm 3 for endpoint 1 (PFS). Defaults to 1 for superiority test.
#' @param hazardRatioH023e1 Hazard ratio under the null hypothesis for arm 2
#'   vs arm 3 for endpoint 1 (PFS). Defaults to 1 for superiority test.
#' @param hazardRatioH012e1 Hazard ratio under the null hypothesis for arm 1
#'   vs arm 2 for endpoint 1 (PFS). Defaults to 1 for superiority test.
#' @param hazardRatioH013e2 Hazard ratio under the null hypothesis for arm 1
#'   vs arm 3 for endpoint 2 (OS). Defaults to 1 for superiority test.
#' @param hazardRatioH023e2 Hazard ratio under the null hypothesis for arm 2
#'   vs arm 3 for endpoint 2 (OS). Defaults to 1 for superiority test.
#' @param hazardRatioH012e2 Hazard ratio under the null hypothesis for arm 1
#'   vs arm 2 for endpoint 2 (OS). Defaults to 1 for superiority test.
#' @param allocation1 Number of subjects in Arm A in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @param allocation2 Number of subjects in Arm B in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @param allocation3 Number of subjects in Arm C in
#'   a randomization block. Defaults to 1 for equal randomization.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_stratumFraction
#' @param rho The correlation coefficient for the standard bivariate normal
#'   random variables used to generate time to disease progression and time
#'   to death using the inverse CDF method.
#' @param lambda1e1 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for arm 1 and endpoint 1 (PFS).
#' @param lambda2e1 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for arm 2 and endpoint 1 (PFS).
#' @param lambda3e1 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for arm 3 and endpoint 1 (PFS).
#' @param lambda1e2 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for arm 1 and endpoint 2 (OS).
#' @param lambda2e2 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for arm 2 and endpoint 2 (OS).
#' @param lambda3e2 A vector of hazard rates for the event in each analysis
#'   time interval by stratum for arm 3 and endpoint 2 (OS).
#' @param gamma1e1 The hazard rate for exponential dropout. A vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for arm 1 and endpoint 1 (PFS).
#' @param gamma2e1 The hazard rate for exponential dropout. A vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for arm 2 and endpoint 1 (PFS).
#' @param gamma3e1 The hazard rate for exponential dropout. A vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for arm 3 and endpoint 1 (PFS).
#' @param gamma1e2 The hazard rate for exponential dropout. A vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for arm 1 and endpoint 2 (OS).
#' @param gamma2e2 The hazard rate for exponential dropout. A vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for arm 2 and endpoint 2 (OS).
#' @param gamma3e2 The hazard rate for exponential dropout. A vector of
#'   hazard rates for piecewise exponential dropout applicable for all
#'   strata, or a vector of hazard rates for dropout in each analysis time
#'   interval by stratum for arm 3 and endpoint 2 (OS).
#' @inheritParams param_accrualDuration
#' @inheritParams param_followupTime
#' @inheritParams param_fixedFollowup
#' @inheritParams param_rho1
#' @inheritParams param_rho2
#' @param plannedEvents The planned cumulative total number of PFS events at
#'   Look 1 to Look \code{kMaxe1} for Arms A and C combined and the planned
#'   cumulative total number of OS events at Look \code{kMaxe1+1} to Look
#'   \code{kMax} for Arms A and C combined.
#' @param plannedTime The calendar times for the analyses. To use calendar
#'   time to plan the analyses, \code{plannedEvents} should be missing.
#' @param maxNumberOfIterations The number of simulation iterations.
#'   Defaults to 1000.
#' @param maxNumberOfRawDatasetsPerStage The number of raw datasets per
#'   stage 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 with 2 components:
#'
#' * \code{sumdata}: A data frame of summary data by iteration and stage:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{eventsNotAchieved}: Whether the target number of events
#'       is not achieved for the iteration.
#'
#'     - \code{stageNumber}: The stage number, covering all stages even if
#'       the trial stops at an interim look.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{accruals1}: The number of subjects enrolled at the stage for
#'       the active treatment 1 group.
#'
#'     - \code{accruals2}: The number of subjects enrolled at the stage for
#'       the active treatment 2 group.
#'
#'     - \code{accruals3}: The number of subjects enrolled at the stage for
#'       the control group.
#'
#'     - \code{totalAccruals}: The total number of subjects enrolled at
#'       the stage.
#'
#'     - \code{endpoint}: The endpoint (1 or 2) under consideration.
#'
#'     - \code{events1}: The number of events at the stage for
#'       the active treatment 1 group.
#'
#'     - \code{events2}: The number of events at the stage for
#'       the active treatment 2 group.
#'
#'     - \code{events3}: The number of events at the stage for
#'       the control group.
#'
#'     - \code{totalEvents}: The total number of events at the stage.
#'
#'     - \code{dropouts1}: The number of dropouts at the stage for
#'       the active treatment 1 group.
#'
#'     - \code{dropouts2}: The number of dropouts at the stage for
#'       the active treatment 2 group.
#'
#'     - \code{dropouts3}: The number of dropouts at the stage for
#'       the control group.
#'
#'     - \code{totalDropouts}: The total number of dropouts at the stage.
#'
#'     - \code{logRankStatistic13}: The log-rank test Z-statistic
#'       comparing the active treatment 1 to the control for the endpoint.
#'
#'     - \code{logRankStatistic23}: The log-rank test Z-statistic
#'       comparing the active treatment 2 to the control for the endpoint.
#'
#'     - \code{logRankStatistic12}: The log-rank test Z-statistic
#'       comparing the active treatment 1 to the active treatment 2
#'       for the endpoint.
#'
#' * \code{rawdata} (exists if \code{maxNumberOfRawDatasetsPerStage} is a
#'   positive integer): A data frame for subject-level data for selected
#'   replications, containing the following variables:
#'
#'     - \code{iterationNumber}: The iteration number.
#'
#'     - \code{stageNumber}: The stage under consideration.
#'
#'     - \code{analysisTime}: The time for the stage since trial start.
#'
#'     - \code{subjectId}: The subject ID.
#'
#'     - \code{arrivalTime}: The enrollment time for the subject.
#'
#'     - \code{stratum}: The stratum for the subject.
#'
#'     - \code{treatmentGroup}: The treatment group (1, 2, or 3) for
#'       the subject.
#'
#'     - \code{survivalTime1}: The underlying survival time for
#'       event endpoint 1 for the subject.
#'
#'     - \code{dropoutTime1}: The underlying dropout time for
#'       event endpoint 1 for the subject.
#'
#'     - \code{timeUnderObservation1}: The time under observation
#'       since randomization for event endpoint 1 for the subject.
#'
#'     - \code{event1}: Whether the subject experienced event endpoint 1.
#'
#'     - \code{dropoutEvent1}: Whether the subject dropped out for
#'       endpoint 1.
#'
#'     - \code{survivalTime2}: The underlying survival time for
#'       event endpoint 2 for the subject.
#'
#'     - \code{dropoutTime2}: The underlying dropout time for
#'       event endpoint 2 for the subject.
#'
#'     - \code{timeUnderObservation2}: The time under observation
#'       since randomization for event endpoint 2 for the subject.
#'
#'     - \code{event2}: Whether the subject experienced event endpoint 2.
#'
#'     - \code{dropoutEvent2}: Whether the subject dropped out for
#'       endpoint 2.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' sim1 = lrsim2e3a(
#'   kMax = 3,
#'   kMaxe1 = 2,
#'   allocation1 = 2,
#'   allocation2 = 2,
#'   allocation3 = 1,
#'   accrualTime = c(0, 8),
#'   accrualIntensity = c(10, 28),
#'   piecewiseSurvivalTime = 0,
#'   rho = 0,
#'   lambda1e1 = log(2)/12*0.60,
#'   lambda2e1 = log(2)/12*0.70,
#'   lambda3e1 = log(2)/12,
#'   lambda1e2 = log(2)/30*0.65,
#'   lambda2e2 = log(2)/30*0.75,
#'   lambda3e2 = log(2)/30,
#'   accrualDuration = 30.143,
#'   plannedEvents = c(186, 259, 183),
#'   maxNumberOfIterations = 1000,
#'   maxNumberOfRawDatasetsPerStage = 1,
#'   seed = 314159)
#'
#' head(sim1$sumdata)
#' head(sim1$rawdata)
#'
#' @export
lrsim2e3a <- function(kMax = NA_integer_, kMaxe1 = NA_integer_, hazardRatioH013e1 = 1, hazardRatioH023e1 = 1, hazardRatioH012e1 = 1, hazardRatioH013e2 = 1, hazardRatioH023e2 = 1, hazardRatioH012e2 = 1, allocation1 = 1L, allocation2 = 1L, allocation3 = 1L, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, stratumFraction = 1L, rho = 0, lambda1e1 = NA_real_, lambda2e1 = NA_real_, lambda3e1 = NA_real_, lambda1e2 = NA_real_, lambda2e2 = NA_real_, lambda3e2 = NA_real_, gamma1e1 = 0L, gamma2e1 = 0L, gamma3e1 = 0L, gamma1e2 = 0L, gamma2e2 = 0L, gamma3e2 = 0L, accrualDuration = NA_real_, followupTime = NA_real_, fixedFollowup = 0L, rho1 = 0, rho2 = 0, plannedEvents = NA_integer_, plannedTime = NA_real_, maxNumberOfIterations = 1000L, maxNumberOfRawDatasetsPerStage = 0L, seed = NA_integer_) {
    .Call(`_lrstat_lrsim2e3a`, kMax, kMaxe1, hazardRatioH013e1, hazardRatioH023e1, hazardRatioH012e1, hazardRatioH013e2, hazardRatioH023e2, hazardRatioH012e2, allocation1, allocation2, allocation3, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, rho, lambda1e1, lambda2e1, lambda3e1, lambda1e2, lambda2e2, lambda3e2, gamma1e1, gamma2e1, gamma3e1, gamma1e2, gamma2e2, gamma3e2, accrualDuration, followupTime, fixedFollowup, rho1, rho2, plannedEvents, plannedTime, maxNumberOfIterations, maxNumberOfRawDatasetsPerStage, seed)
}

#' @title Number of subjects having an event and log-rank statistic
#' for a hypothesized hazard ratio at a given calendar time
#'
#' @description Obtains the number of subjects having an event in each
#' treatment group by stratum, the mean and variance of weighted log-rank
#' score statistic for a hypothesized hazard ratio at a given calendar time.
#'
#' @param time The calendar time 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
#' @inheritParams param_numSubintervals
#' @param predictEventOnly Whether to predict the number of events only.
#'   Defaults to 0 for obtaining log-rank test score statistic mean
#'   and variance.
#'
#' @return A data frame of the following variables if
#' \code{predictEventOnly = 1}:
#'
#' * \code{stratum}: The stratum number.
#'
#' * \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{predictEventOnly = 0}, the following variables will also
#' be included:
#'
#' * \code{uscore}: The numerator of the weighted log-rank test statistic.
#'
#' * \code{vscore}: The variance of the weighted log-rank score statistic
#'   with weight squared.
#'
#' * \code{iscore}: The Fisher information of the weighted log-rank score
#'   statistic.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#'
#' lrstat1(time = 22, hazardRatioH0 = 1,
#'         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
lrstat1 <- 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 = 0L, rho1 = 0, rho2 = 0, numSubintervals = 300L, predictEventOnly = 0L) {
    .Call(`_lrstat_lrstat1`, time, hazardRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, rho1, rho2, numSubintervals, predictEventOnly)
}

#' @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
#' @inheritParams param_numSubintervals
#' @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),
#'        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
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 = 0L, rho1 = 0, rho2 = 0, numSubintervals = 300L, predictTarget = 2L) {
    .Call(`_lrstat_lrstat`, time, hazardRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, rho1, rho2, numSubintervals, 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),
#'         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
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 = 0L) {
    .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.
#' @param interval The interval to search for the solution of
#'   accrualDuration. Defaults to \code{c(0.001, 240)}.
#'
#' @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),
#'   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,
#'   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 = 0L, npoints = 23L, interval = as.numeric( c(0.001, 240))) {
    .Call(`_lrstat_getDurationFromNevents`, nevents, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, followupTime, fixedFollowup, npoints, interval)
}

#' @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 typeBetaSpending The type of beta spending. One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function, "sfP" for Pocock
#'   type spending function, "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and "none" for no
#'   early futility stopping. Defaults to "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_numSubintervals
#' @inheritParams param_estimateHazardRatio
#' @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 if \code{estimateHazardRatio}.
#'
#'     - \code{futilityHR}: The futility boundaries on the hazard ratio
#'       scale if \code{estimateHazardRatio}.
#'
#'     - \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},
#'   \code{estimateHazardRatio}, 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),
#'         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
lrpower <- function(kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, rho1 = 0, rho2 = 0, numSubintervals = 300L, estimateHazardRatio = 1L, typeOfComputation = "direct", spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_lrpower`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, typeBetaSpending, parameterBetaSpending, hazardRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, rho1, rho2, numSubintervals, estimateHazardRatio, typeOfComputation, spendingTime, studyDuration)
}

#' @title Get the 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
#' @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. Defaults to 0.5.
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, typeBetaSpending = "none", parameterBetaSpending = NA_real_, userBetaSpending = NA_real_, spendingTime = NA_real_, hazardRatioH0 = 1, hazardRatio = NA_real_, allocationRatioPlanned = 1, rounding = 1L) {
    .Call(`_lrstat_getNeventsFromHazardRatio`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, 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
#' @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_numSubintervals
#' @inheritParams param_estimateHazardRatio
#' @inheritParams param_typeOfComputation
#' @param interval The interval to search for the solution of
#'   accrualDuration, followupTime, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}. Adjustment
#'   may be needed for non-monotone relationship with study power.
#' @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),
#'              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 = 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),
#'              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 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),
#'              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
lrsamplesize <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, rho1 = 0, rho2 = 0, numSubintervals = 300L, estimateHazardRatio = 1L, typeOfComputation = "direct", interval = as.numeric( c(0.001, 240)), spendingTime = NA_real_, rounding = 1L) {
    .Call(`_lrstat_lrsamplesize`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, typeBetaSpending, parameterBetaSpending, userBetaSpending, hazardRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, rho1, rho2, numSubintervals, estimateHazardRatio, typeOfComputation, interval, 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{attainedAlphaH10}: The attained significance level under H10.
#'
#'     - \code{attainedAlphaH20}: The attained significance level under H20.
#'
#'     - \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),
#'              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
lrpowerequiv <- function(kMax = 1L, informationRates = NA_real_, criticalValues = NA_real_, 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 = 0L, 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 interval The interval to search for the solution of
#'   accrualDuration, followupDuration, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}.
#' @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),
#'                   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
lrsamplesizeequiv <- function(beta = 0.2, kMax = 1L, informationRates = NA_real_, criticalValues = NA_real_, 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 = 0L, typeOfComputation = "direct", interval = as.numeric( c(0.001, 240)), spendingTime = NA_real_, rounding = 1L) {
    .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, interval, spendingTime, rounding)
}

#' @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, incidenceMatrix, maxInformation, p, information, spendingTime) {
    .Call(`_lrstat_fseqboncpp`, w, G, alpha, kMax, typeAlphaSpending, parameterAlphaSpending, incidenceMatrix, maxInformation, p, information, spendingTime)
}

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

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

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

#' @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.
#'   One of the following:
#'   "OF" for O'Brien-Fleming boundaries,
#'   "P" for Pocock boundaries,
#'   "WT" for Wang & Tsiatis boundaries,
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early efficacy stopping.
#'   Defaults to "sfOF".
#' @param parameterAlphaSpending The parameter value of alpha spending.
#'   Corresponds to Delta for "WT", rho for "sfKD", and gamma for "sfHSD".
#' @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.
#'
#' @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.
#'   One of the following:
#'   "OF" for O'Brien-Fleming boundaries,
#'   "P" for Pocock boundaries,
#'   "WT" for Wang & Tsiatis boundaries,
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early efficacy stopping.
#'   Defaults to "sfOF".
#' @param parameterAlphaSpending The parameter value of alpha spending.
#'   Corresponds to Delta for "WT", rho for "sfKD", and gamma for "sfHSD".
#' @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.
#'
#' @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:
#'   "OF" for O'Brien-Fleming boundaries,
#'   "P" for Pocock boundaries,
#'   "WT" for Wang & Tsiatis boundaries,
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early efficacy stopping.
#'   Defaults to "sfOF".
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to Delta for "WT", rho for "sfKD",
#'   and gamma for "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 L2 The termination look of the secondary trial.
#' @param zL2 The z-test statistic at the termination look of the
#'   secondary trial.
#' @param INew The maximum information of the secondary trial.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @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:
#'   "OF" for O'Brien-Fleming boundaries,
#'   "P" for Pocock boundaries,
#'   "WT" for Wang & Tsiatis boundaries,
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early efficacy stopping.
#'   Defaults to "sfOF".
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to Delta for "WT",
#'   rho for "sfKD", and gamma for "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.
#'
#' @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
#'
#' # original 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))
#'
#' # interim look results
#' L = 1
#' n1 = n/3
#' delta1 = 4.5
#' sigma1 = 20
#' zL = delta1/sqrt(4/n1*sigma1^2)
#'
#' t = des1$byStageResults$informationRates
#'
#' # Muller & Schafer (2001) method to design the secondary trial:
#' des2 = adaptDesign(
#'   betaNew = 0.2, L = L, zL = zL, theta = 5,
#'   kMax = 3, informationRates = t,
#'   alpha = 0.05, typeAlphaSpending = "sfHSD",
#'   parameterAlphaSpending = -4,
#'   MullerSchafer = TRUE,
#'   kNew = 3, typeAlphaSpendingNew = "sfHSD",
#'   parameterAlphaSpendingNew = -2)
#'
#' n2 = ceiling(des2$secondaryTrial$overallResults$information*4*20^2)
#' ns = round(n2*(1:3)/3)
#'  (des2 = adaptDesign(
#'    INew = n2/(4*20^2), L = L, zL = zL, theta = 5,
#'    kMax = 3, informationRates = t,
#'    alpha = 0.05, typeAlphaSpending = "sfHSD",
#'    parameterAlphaSpending = -4,
#'    MullerSchafer = TRUE,
#'    kNew = 3, informationRatesNew = ns/n2,
#'    typeAlphaSpendingNew = "sfHSD",
#'    parameterAlphaSpendingNew = -2))
#'
#' # termination at the second look of the secondary trial
#' L2 = 2
#' delta2 = 6.86
#' sigma2 = 21.77
#' zL2 = delta2/sqrt(4/197*sigma2^2)
#'
#' t2 = des2$secondaryTrial$byStageResults$informationRates[1:L2]
#'
#' # confidence interval
#' getADCI(L = L, zL = zL,
#'         IMax = n/(4*sigma1^2), kMax = 3,
#'         informationRates = t,
#'         alpha = 0.05, typeAlphaSpending = "sfHSD",
#'         parameterAlphaSpending = -4,
#'         L2 = L2, zL2 = zL2,
#'         INew = n2/(4*sigma2^2),
#'         MullerSchafer = TRUE,
#'         informationRatesNew = t2,
#'         typeAlphaSpendingNew = "sfHSD",
#'         parameterAlphaSpendingNew = -2)
#'
#' @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_, L2 = NA_integer_, zL2 = NA_real_, INew = NA_real_, MullerSchafer = 0L, 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, L2, zL2, INew, MullerSchafer, 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:
#'   "OF" for O'Brien-Fleming boundaries,
#'   "P" for Pocock boundaries,
#'   "WT" for Wang & Tsiatis boundaries,
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early efficacy stopping.
#'   Defaults to "sfOF".
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to Delta for "WT", rho for "sfKD",
#'   and gamma for "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 L2 The look of interest in the secondary trial.
#' @param zL2 The z-test statistic at the look of the secondary trial.
#' @param INew The maximum information of the secondary trial.
#' @param MullerSchafer Whether to use the Muller and Schafer (2001) method
#'   for trial adaptation.
#' @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:
#'   "OF" for O'Brien-Fleming boundaries,
#'   "P" for Pocock boundaries,
#'   "WT" for Wang & Tsiatis boundaries,
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early efficacy stopping.
#'   Defaults to "sfOF".
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to Delta for "WT",
#'   rho for "sfKD", and gamma for "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.
#'
#' @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
#'
#' # original 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))
#'
#' # interim look results
#' L = 1
#' n1 = n/3
#' delta1 = 4.5
#' sigma1 = 20
#' zL = delta1/sqrt(4/n1*sigma1^2)
#'
#' t = des1$byStageResults$informationRates
#'
#' # Muller & Schafer (2001) method to design the secondary trial:
#' des2 = adaptDesign(
#'   betaNew = 0.2, L = L, zL = zL, theta = 5,
#'   kMax = 3, informationRates = t,
#'   alpha = 0.05, typeAlphaSpending = "sfHSD",
#'   parameterAlphaSpending = -4,
#'   MullerSchafer = TRUE,
#'   kNew = 3, typeAlphaSpendingNew = "sfHSD",
#'   parameterAlphaSpendingNew = -2)
#'
#' n2 = ceiling(des2$secondaryTrial$overallResults$information*4*20^2)
#' ns = round(n2*(1:3)/3)
#' (des2 = adaptDesign(
#'   INew = n2/(4*20^2), L = L, zL = zL, theta = 5,
#'   kMax = 3, informationRates = t,
#'   alpha = 0.05, typeAlphaSpending = "sfHSD",
#'   parameterAlphaSpending = -4,
#'   MullerSchafer = TRUE,
#'   kNew = 3, informationRatesNew = ns/n2,
#'   typeAlphaSpendingNew = "sfHSD",
#'   parameterAlphaSpendingNew = -2))
#'
#' # termination at the second look of the secondary trial
#' L2 = 2
#' delta2 = 6.86
#' sigma2 = 21.77
#' zL2 = delta2/sqrt(4/197*sigma2^2)
#'
#' t2 = des2$secondaryTrial$byStageResults$informationRates[1:L2]
#'
#' # repeated confidence interval
#' getADRCI(L = L, zL = zL,
#'          IMax = n/(4*sigma1^2), kMax = 3,
#'          informationRates = t,
#'          alpha = 0.05, typeAlphaSpending = "sfHSD",
#'          parameterAlphaSpending = -4,
#'          L2 = L2, zL2 = zL2,
#'          INew = n2/(4*sigma2^2),
#'          MullerSchafer = TRUE,
#'          informationRatesNew = t2,
#'          typeAlphaSpendingNew = "sfHSD",
#'          parameterAlphaSpendingNew = -2)
#'
#' @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_, L2 = NA_integer_, zL2 = NA_real_, INew = NA_real_, MullerSchafer = 0L, 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, L2, zL2, INew, MullerSchafer, informationRatesNew, efficacyStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, spendingTimeNew)
}

#' @title Conditional power allowing for varying parameter values
#' @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:
#'   "OF" for O'Brien-Fleming boundaries,
#'   "P" for Pocock boundaries,
#'   "WT" for Wang & Tsiatis boundaries,
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function,
#'   "user" for user defined spending, and
#'   "none" for no early efficacy stopping.
#'   Defaults to "sfOF".
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to Delta for "WT", rho for "sfKD",
#'   and gamma for "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(-6, kMax-1)} if left unspecified.
#' @param typeBetaSpending The type of beta spending for the primary trial.
#'   One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early futility stopping.
#'   Defaults to "none".
#' @param parameterBetaSpending The parameter value of beta spending
#'   for the primary trial. Corresponds to rho for "sfKD",
#'   and gamma for "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 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:
#'   "OF" for O'Brien-Fleming boundaries,
#'   "P" for Pocock boundaries,
#'   "WT" for Wang & Tsiatis boundaries,
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early efficacy stopping.
#'   Defaults to "sfOF".
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to Delta for "WT", rho for "sfKD",
#'   and gamma for "sfHSD".
#' @param typeBetaSpendingNew The type of beta spending for the secondary
#'   trial. One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early futility stopping.
#'   Defaults to "none".
#' @param parameterBetaSpendingNew The parameter value of beta spending
#'   for the secondary trial. Corresponds to rho for "sfKD",
#'   and gamma for "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 The conditional power given the interim results, parameter
#' values, and 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{getDesign}}
#'
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, typeBetaSpending = "none", parameterBetaSpending = NA_real_, spendingTime = NA_real_, MullerSchafer = 0L, kNew = NA_integer_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, futilityStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, 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, typeBetaSpending, parameterBetaSpending, spendingTime, MullerSchafer, kNew, informationRatesNew, efficacyStoppingNew, futilityStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, typeBetaSpendingNew, parameterBetaSpendingNew, spendingTimeNew, varianceRatio)
}

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

#' @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.15, 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 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.
#'
#' @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) {
    .Call(`_lrstat_samplesizeOnePropExact`, beta, piH0, pi, alpha)
}

#' @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.
#'
#' @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) {
    .Call(`_lrstat_samplesizeOneRateExact`, beta, lambdaH0, lambda, D, alpha)
}

#' @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.
#'
#' @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) {
    .Call(`_lrstat_samplesizeFisherExact`, beta, pi1, pi2, allocationRatioPlanned, alpha)
}

#' @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 riskDiffH0 The 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.
#'
#' @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(riskDiffH0 = 0.1, n1 = 10, y1 = 4, n2 = 20, y2 = 0)
#'
#' @export
#'
remlRiskDiff <- function(riskDiffH0 = 0.0, n1 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_remlRiskDiff`, riskDiffH0, n1, y1, n2, y2)
}

remlRiskDiff2 <- function(riskDiffH0 = 0.0, n1 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_remlRiskDiff2`, riskDiffH0, n1, y1, n2, y2)
}

#' @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 riskDiffH0 The risk difference under the null hypothesis.
#'   Defaults to 0.
#' @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.
#'
#' @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(riskDiffH0 = 0, n1 = c(10,10), y1 = c(4,3),
#'               n2 = c(20,10), y2 = c(2,0))
#'
#' @export
#'
zstatRiskDiff <- function(riskDiffH0 = 0.0, n1 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_zstatRiskDiff`, riskDiffH0, n1, y1, n2, y2)
}

#' @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 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_, 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 riskRatioH0 The 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.
#'
#' @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(riskRatioH0 = 1.2, n1 = 10, y1 = 4, n2 = 20, y2 = 2)
#'
#' @export
#'
remlRiskRatio <- function(riskRatioH0 = 1.0, n1 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_remlRiskRatio`, riskRatioH0, n1, y1, n2, y2)
}

remlRiskRatio2 <- function(riskRatioH0 = 1.0, n1 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_remlRiskRatio2`, riskRatioH0, n1, y1, n2, y2)
}

#' @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 riskRatioH0 The risk ratio under the null hypothesis.
#'   Defaults to 1.
#' @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.
#'
#' @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(riskRatioH0 = 1, n1 = c(10,10), y1 = c(4,3),
#'                n2 = c(20,10), y2 = c(2,0))
#'
#' @export
#'
zstatRiskRatio <- function(riskRatioH0 = 1.0, n1 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_zstatRiskRatio`, riskRatioH0, n1, y1, n2, y2)
}

#' @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 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_, 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 oddsRatioH0 The 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.
#'
#' @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(oddsRatioH0 = 1.25, n1 = 10, y1 = 4, n2 = 20, y2 = 2)
#'
#' @export
#'
remlOddsRatio <- function(oddsRatioH0 = 1.0, n1 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_remlOddsRatio`, oddsRatioH0, n1, y1, n2, y2)
}

remlOddsRatio2 <- function(oddsRatioH0 = 1.0, n1 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_remlOddsRatio2`, oddsRatioH0, n1, y1, n2, y2)
}

#' @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 oddsRatioH0 The odds ratio under the null hypothesis.
#'   Defaults to 1.
#' @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.
#'
#' @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(oddsRatioH0 = 1, n1 = c(10,10), y1 = c(4,3),
#'                n2 = c(20,10), y2 = c(2,0))
#'
#' @export
#'
zstatOddsRatio <- function(oddsRatioH0 = 1.0, n1 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_zstatOddsRatio`, oddsRatioH0, n1, y1, n2, y2)
}

#' @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 = NA_real_, y1 = NA_real_, n2 = NA_real_, y2 = NA_real_, 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 rateDiffH0 The 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.
#'
#' @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(rateDiffH0 = 0.1, t1 = 10, y1 = 4, t2 = 20, y2 = 2)
#'
#' @export
#'
remlRateDiff <- function(rateDiffH0 = 0.0, t1 = NA_real_, y1 = NA_real_, t2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_remlRateDiff`, rateDiffH0, t1, y1, t2, y2)
}

remlRateDiff2 <- function(rateDiffH0 = 0.0, t1 = NA_real_, y1 = NA_real_, t2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_remlRateDiff2`, rateDiffH0, t1, y1, t2, y2)
}

#' @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 rateDiffH0 The rate difference under the null hypothesis.
#'   Defaults to 0.
#' @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.
#'
#' @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(rateDiffH0 = 0, t1 = c(10,10), y1 = c(4,3),
#'               t2 = c(20,10), y2 = c(2,0))
#'
#' @export
#'
zstatRateDiff <- function(rateDiffH0 = 0.0, t1 = NA_real_, y1 = NA_real_, t2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_zstatRateDiff`, rateDiffH0, t1, y1, t2, y2)
}

#' @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 = NA_real_, y1 = NA_real_, t2 = NA_real_, y2 = NA_real_, 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 rateRatioH0 The 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.
#'
#' @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(rateRatioH0 = 1.1, t1 = 10, y1 = 4, t2 = 20, y2 = 2)
#'
#' @export
#'
remlRateRatio <- function(rateRatioH0 = 1.0, t1 = NA_real_, y1 = NA_real_, t2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_remlRateRatio`, rateRatioH0, t1, y1, t2, y2)
}

remlRateRatio2 <- function(rateRatioH0 = 1.0, t1 = NA_real_, y1 = NA_real_, t2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_remlRateRatio2`, rateRatioH0, t1, y1, t2, y2)
}

#' @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 rateRatioH0 The rate ratio under the null hypothesis.
#'   Defaults to 1.
#' @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.
#'
#' @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(rateRatioH0 = 1, t1 = c(10,10), y1 = c(4,3),
#'                t2 = c(20,10), y2 = c(2,0))
#'
#' @export
#'
zstatRateRatio <- function(rateRatioH0 = 1.0, t1 = NA_real_, y1 = NA_real_, t2 = NA_real_, y2 = NA_real_) {
    .Call(`_lrstat_zstatRateRatio`, rateRatioH0, t1, y1, t2, y2)
}

#' @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 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 = 1L) {
    .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.
#'
#' @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.2,
#'                         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) {
    .Call(`_lrstat_samplesizeRiskDiffExact`, beta, riskDiffH0, pi1, pi2, allocationRatioPlanned, alpha)
}

#' @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 = 1L) {
    .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.
#'
#' @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.833,
#'                          pi1 = 0.9, pi2 = 0.9, alpha = 0.05)
#'
#' @export
samplesizeRiskRatioExact <- function(beta = NA_real_, riskRatioH0 = 1, pi1 = NA_real_, pi2 = NA_real_, allocationRatioPlanned = 1, alpha = 0.025) {
    .Call(`_lrstat_samplesizeRiskRatioExact`, beta, riskRatioH0, pi1, pi2, allocationRatioPlanned, alpha)
}

#' @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 = 1L) {
    .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.
#' @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.85, pi2 = 0.85, 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) {
    .Call(`_lrstat_samplesizeRiskDiffExactEquiv`, beta, riskDiffLower, riskDiffUpper, pi1, pi2, allocationRatioPlanned, alpha)
}

#' @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 = 1L) {
    .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.
#' @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.85, pi2 = 0.85, 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) {
    .Call(`_lrstat_samplesizeRiskRatioExactEquiv`, beta, riskRatioLower, riskRatioUpper, pi1, pi2, allocationRatioPlanned, alpha)
}

#' @title P-value for exact unconditional test of risk difference
#' @description Obtains the p-value for exact unconditional
#' test of risk difference.
#'
#' @param riskDiffH0 The risk difference under the null hypothesis.
#'   Defaults to 0.
#' @param directionUpper Whether larger values represent better
#'   responses.
#' @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.
#'
#' @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(riskDiffH0 = 0, directionUpper = 1L, n1 = NA_integer_, y1 = NA_integer_, n2 = NA_integer_, y2 = NA_integer_) {
    .Call(`_lrstat_riskDiffExactPValue`, riskDiffH0, directionUpper, n1, y1, n2, y2)
}

#' @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 = 68, y1 = 2, n2 = 65, 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 riskRatioH0 The risk ratio under the null hypothesis.
#'   Defaults to 1.
#' @param directionUpper Whether larger values represent better
#'   responses.
#' @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.
#'
#' @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(riskRatioH0 = 1, directionUpper = 1L, n1 = NA_integer_, y1 = NA_integer_, n2 = NA_integer_, y2 = NA_integer_) {
    .Call(`_lrstat_riskRatioExactPValue`, riskRatioH0, directionUpper, n1, y1, n2, y2)
}

#' @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 = 68, y1 = 2, n2 = 65, 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 Negative binomial rate ratio by stratum
#'
#' @description Obtains the number of subjects accrued, number of events,
#' number of dropouts, number of subjects reaching the maximum
#' follow-up, total exposure, rate and variance for log rate in each group,
#' rate ratio and variance for log rate ratio by stratum at a given
#' calendar time.
#'
#' @param time The calendar time 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.
#'
#' @return A list with two components:
#'
#' * \code{resultsUnderH1}: A data frame containing the following variables:
#'
#'     - \code{stratum}: The stratum.
#'
#'     - \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{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{resultsUnderH0} when \code{nullVariance = TRUE}: A data frame
#'   with the following variables:
#'
#'     - \code{stratum}: The stratum.
#'
#'     - \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{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{stratum}: The stratum.
#'
#'     - \code{time}: The analysis time since trial start.
#'
#'     - \code{rateRatioH0}: The rate ratio under H0.
#'
#'     - \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.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Example 1: Variable follow-up design
#'
#' nbstat1(time = 2,
#'        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
#'
#' nbstat1(time = 1.8,
#'        accrualIntensity = 220/1.5,
#'        stratumFraction = c(0.2, 0.8),
#'        kappa1 = 3,
#'        kappa2 = 3,
#'        lambda1 = c(0.5*8.4, 0.7*10.2),
#'        lambda2 = c(8.4, 10.2),
#'        gamma1 = 0.05,
#'        gamma2 = 0.05,
#'        accrualDuration = 1.5,
#'        followupTime = 0.5,
#'        fixedFollowup = 1,
#'        nullVariance = 1)
#'
#' @export
nbstat1 <- 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 = 0L, nullVariance = 0L) {
    .Call(`_lrstat_nbstat1`, time, rateRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, kappa1, kappa2, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, nullVariance)
}

#' @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 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\{\lambda1_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 = 0L, nullVariance = 0L) {
    .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 typeBetaSpending The type of beta spending. One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function, "sfP" for Pocock
#'   type spending function, "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and "none" for no
#'   early futility stopping. Defaults to "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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, spendingTime = NA_real_, studyDuration = NA_real_, nullVariance = 0L) {
    .Call(`_lrstat_nbpower`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, 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
#' @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 interval The interval to search for the solution of
#'   accrualDuration, followupDuration, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}.
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, interval = as.numeric( c(0.001, 240)), spendingTime = NA_real_, rounding = 1L, nullVariance = 0L) {
    .Call(`_lrstat_nbsamplesize`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, typeBetaSpending, parameterBetaSpending, userBetaSpending, rateRatioH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, kappa1, kappa2, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, interval, 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 typeBetaSpending The type of beta spending. One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function, "sfP" for Pocock
#'   type spending function, "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and "none" for no
#'   early futility stopping. Defaults to "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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_nbpower1s`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, 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
#' @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 interval The interval to search for the solution of
#'   accrualDuration, followupDuration, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}.
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, interval = as.numeric( c(0.001, 240)), spendingTime = NA_real_, rounding = 1L) {
    .Call(`_lrstat_nbsamplesize1s`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, typeBetaSpending, parameterBetaSpending, userBetaSpending, lambdaH0, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, kappa, lambda, gamma, accrualDuration, followupTime, fixedFollowup, interval, 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}.
#' @param nullVariance Whether to calculate the variance for log rate ratio
#'   under the null hypothesis.
#'
#' @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{attainedAlphaH10}: The attained significance level under H10.
#'
#'     - \code{attainedAlphaH20}: The attained significance level under H20.
#'
#'     - \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{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{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{accrualDuration}, \code{followupTime}, \code{fixedFollowup},
#'   \code{spendingTime}, \code{nullVariance}, and \code{varianceRatios}.
#'   The \code{varianceRatios} is a data frame with the following
#'   variables:
#'
#'     - \code{varianceRatioH10}: The ratio of the variance under
#'       \code{H10} to the variance under \code{H1}.
#'
#'     - \code{varianceRatioH20}: The ratio of the variance under
#'       \code{H20} to the variance under \code{H1}.
#'
#'     - \code{varianceRatioH12}: The ratio of the variance under
#'       \code{H10} to the variance under \code{H20}.
#'
#'     - \code{varianceRatioH21}: The ratio of the variance under
#'       \code{H20} to the variance under \code{H10}.
#'
#' * \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,
#'              nullVariance = 1)
#'
#' # 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 = NA_real_, 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 = 0L, spendingTime = NA_real_, studyDuration = NA_real_, nullVariance = 0L) {
    .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, nullVariance)
}

#' @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 interval The interval to search for the solution of
#'   accrualDuration, followupDuration, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}.
#' @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 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,
#'                   nullVariance = 1)
#'
#' # 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 = NA_real_, 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 = 0L, interval = as.numeric( c(0.001, 240)), spendingTime = NA_real_, rounding = 1L, nullVariance = 0L) {
    .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, interval, spendingTime, rounding, nullVariance)
}

#' @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 Restricted mean survival time by stratum
#'
#' @description Obtains the restricted mean survival time and associated
#' variance by treatment group and by stratum at a given calendar time.
#'
#' @param time The calendar time 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{stratum}: The stratum.
#'
#' * \code{time}: The calendar time since trial start.
#'
#' * \code{subjects}: The number of enrolled subjects.
#'
#' * \code{milestone}: The milestone time relative to randomization.
#'
#' * \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}.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#'
#' rmstat1(time = 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
rmstat1 <- 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 = 0L) {
    .Call(`_lrstat_rmstat1`, time, milestone, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup)
}

#' @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 at which to calculate the
#'   restricted mean survival time.
#' @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 at which to calculate the restricted
#'   mean survival time.
#'
#' * \code{subjects}: The number of enrolled subjects.
#'
#' * \code{milestone}: The milestone time relative to randomization.
#'
#' * \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 = 0L) {
    .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 typeBetaSpending The type of beta spending. One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function, "sfP" for Pocock
#'   type spending function, "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and "none" for no
#'   early futility stopping. Defaults to "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 3 components:
#'
#' * \code{overallResults}: A data frame containing the following variables:
#'
#'     - \code{overallReject}: The overall rejection probability.
#'
#'     - \code{alpha}: The overall significance level.
#'
#'     - \code{drift}: The drift parameter, equal to
#'       \code{(rmstDiff - rmstDiffH0)*sqrt(information)}.
#'
#'     - \code{inflationFactor}: The inflation factor (relative to the
#'       fixed design).
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \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 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{numberOfSubjects}: The number of subjects.
#'
#'     - \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}.
#'
#' @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 = 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)
#'
#' @export
rmpower <- function(kMax = 1L, informationRates = NA_real_, efficacyStopping = NA_integer_, futilityStopping = NA_integer_, criticalValues = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_rmpower`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, 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
#' @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 interval The interval to search for the solution of
#'   accrualDuration, followupTime, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}.
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, interval = as.numeric( c(0.001, 240)), spendingTime = NA_real_, rounding = 1L) {
    .Call(`_lrstat_rmsamplesize`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, typeBetaSpending, parameterBetaSpending, userBetaSpending, milestone, rmstDiffH0, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda1, lambda2, gamma1, gamma2, accrualDuration, followupTime, fixedFollowup, interval, 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 typeBetaSpending The type of beta spending. One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function, "sfP" for Pocock
#'   type spending function, "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and "none" for no
#'   early futility stopping. Defaults to "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{drift}: The drift parameter, equal to
#'       \code{(rmst - rmstH0)*sqrt(information)}.
#'
#'     - \code{inflationFactor}: The inflation factor (relative to the
#'       fixed design).
#'
#'     - \code{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \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 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{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{numberOfSubjects}: The number of subjects.
#'
#'     - \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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, spendingTime = NA_real_, studyDuration = NA_real_) {
    .Call(`_lrstat_rmpower1s`, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, 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
#' @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 interval The interval to search for the solution of
#'   accrualDuration, followupDuration, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}.
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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 = 0L, interval = as.numeric( c(0.001, 240)), spendingTime = NA_real_, rounding = 1L) {
    .Call(`_lrstat_rmsamplesize1s`, beta, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, typeBetaSpending, parameterBetaSpending, userBetaSpending, milestone, rmstH0, accrualTime, accrualIntensity, piecewiseSurvivalTime, stratumFraction, lambda, gamma, accrualDuration, followupTime, fixedFollowup, interval, 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 3 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{numbeOfSubjects}: The total number of subjects.
#'
#'     - \code{studyDuration}: The total study duration.
#'
#'     - \code{information}: The maximum information.
#'
#'     - \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{numberOfSubjects}: The number of subjects.
#'
#'     - \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}.
#'
#' @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 = 100/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 = NA_real_, 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_, 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 interval The interval to search for the solution of
#'   accrualDuration, followupDuration, or the proportionality constant
#'   of accrualIntensity. Defaults to \code{c(0.001, 240)}.
#' @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 = NA_real_, 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, interval = as.numeric( c(0.001, 240)), 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, interval, spendingTime, rounding)
}

#' @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{rep}: The replication for by-group processing.
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{time}: The possibly right-censored survival time.
#'
#'   * \code{event}: The event indicator.
#'
#' @param rep The name of the replication variable in the input data.
#' @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 confint 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{rep}: The replication.
#'
#' * \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{confint}: 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, rep = "rep", stratum = "stratum", time = "time", event = "event", milestone = NA_real_, confint = 0.95, biascorrection = 0L) {
    .Call(`_lrstat_rmest`, data, rep, stratum, time, event, milestone, confint, 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{rep}: The replication for by-group processing.
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{treat}: The treatment.
#'
#'   * \code{time}: The possibly right-censored survival time.
#'
#'   * \code{event}: The event indicator.
#'
#' @param rep The name of the replication variable in the input data.
#' @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 confint 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{rep}: The replication number.
#'
#' * \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{vrmstDiff}: The variance for rmstDiff.
#'
#' * \code{rmstDiffZ}: The Z-statistic value.
#'
#' * \code{rmstDiffPValue}: The one-sided p-value.
#'
#' * \code{lower}: The lower bound of confidence interval.
#'
#' * \code{upper}: The upper bound of confidence interval.
#'
#' * \code{confint}: 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
#'
#' df <- rmdiff(data = rawdata, rep = "iterationNumber",
#'              stratum = "stratum", treat = "treatmentGroup",
#'              time = "timeUnderObservation", event = "event",
#'              milestone = 12)
#' head(df)
#'
#' @export
rmdiff <- function(data, rep = "rep", stratum = "stratum", treat = "treat", time = "time", event = "event", milestone = NA_real_, rmstDiffH0 = 0, confint = 0.95, biascorrection = 0L) {
    .Call(`_lrstat_rmdiff`, data, rep, stratum, treat, time, event, milestone, rmstDiffH0, confint, biascorrection)
}

#' @title Rank preserving structured failure time model (RPSFTM) for
#' treatment switching
#' @description Obtains the causal parameter estimate of the RPSFTM from
#' the log-rank test and the hazard ratio estimate from the Cox model.
#'
#' @param data The input data frame that contains the following variables:
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{time}: The survival time for right censored data.
#'
#'   * \code{event}: The event indicator, 1=event, 0=no event.
#'
#'   * \code{treat}: The randomized treatment indicator, 1=treatment,
#'     0=control.
#'
#'   * \code{rx}: The proportion of time on active treatment.
#'
#'   * \code{censor_time}: The administrative censoring time. It should
#'     be provided for all subjects including those who had events.
#'
#'   * \code{base_cov}: The values of baseline covariates.
#'     This is the full-rank design matrix (excluding treat)
#'     for the Cox model, assuming that factor variables
#'     have already been expanded into dummy variables.
#'
#' @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 treat The name of the treatment variable in the input data.
#' @param rx The name of the rx variable in the input data.
#' @param censor_time The name of the censor_time variable in the input data.
#' @param base_cov The vector of names of baseline covariates (excluding
#'   treat) in the input data.
#' @param low_psi The lower limit of the causal parameter of RPSFTM.
#' @param hi_psi The upper limit of the causal parameter of RPSFTM.
#' @param n_eval_z The number of points between low_psi and hi_psi at which
#'   to evaluate the log-rank Z-statistics.
#' @param alpha The significance level to calculate confidence intervals.
#' @param treat_modifier The optional sensitivity parameter for the
#'   constant treatment effect assumption.
#' @param recensor Whether to apply recensoring to counter-factual
#'   survival times. Defaults to \code{TRUE}.
#' @param autoswitch Whether to exclude recensoring for treatment arms
#'   with no switching. Defaults to \code{TRUE}.
#' @param gridsearch Whether to use grid search to estimate the causal
#'   parameter psi. Defaults to \code{FALSE}, in which case, a root
#'   finding algorithm will be used.
#' @param boot Whether to use bootstrap to obtain the confidence
#'   interval for hazard ratio. Defaults to \code{FALSE}, in which case,
#'   the confidence interval will be constructed to match the log-rank
#'   test p-value.
#' @param n_boot The number of bootstrap samples.
#'
#' @details We use the following steps to obtain the hazard ratio estimate
#' and confidence interval had there been no treatment switching:
#'
#' * use RPSFTM to estimate the causal parameter psi based on the log-rank
#'   test for counter-factual untreated survival times for both arms:
#'   \eqn{U = T_{off} + T_{on} e^{\psi}}.
#'
#' * Fit the Cox proportional hazards model to the observed survival times
#'   on the treatment arm and the counter-factual untreated survival times
#'   on the control arm to obtain the hazard ratio estimate.
#'
#' * Use either the log-rank test p-value for the treatment policy strategy
#'   or bootstrap to construct the confidence interval for hazard ratio.
#'
#' @return A list with the following components:
#'
#' * \code{psi}: The estimated causal parameter for RPSFTM.
#'
#' * \code{psi_CI}: The confidence interval for psi.
#'
#' * \code{psi_type}: The type of psi estimate, either "grid search" or
#'   "root finding".
#'
#' * \code{Sstar}: A data frame containing the counter-factual untreated
#'   survival times and the event indicators.
#'
#' * \code{kmstar}: A data frame containing the Kaplan-Meier estimates
#'   based on the counter-factual untreated survival times by treatment arm.
#'
#' * \code{eval_z}: A data frame containing the log-rank test Z-statistics
#'   evaluated at a sequence of psi values. Used to plot and to check
#'   if the range of psi values to search for the solution and
#'   limits of confidence interval of psi need be modified.
#'
#' * \code{pvalue}: The p-value of the log-rank test based on
#'   the treatment policy strategy.
#'
#' * \code{hr}: The estimated hazard ratio from the Cox model.
#'
#' * \code{hr_CI}: The confidence interval for hazard ratio.
#'
#' * \code{hr_CI_type}: The type of confidence interval for hazard ratio,
#'   either "log-rank p-value" or "bootstrap quantile".
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' library(dplyr)
#'
#' data <- immdef %>% mutate(rx = 1-xoyrs/progyrs)
#'
#' fit <- rpsft(data, time = "progyrs", event = "prog", treat = "imm",
#'              rx = "rx", censor_time = "censyrs", boot = 0)
#'
#' c(fit$hr, fit$hr_CI)
#'
#' @export
rpsft <- function(data, stratum = "stratum", time = "time", event = "event", treat = "treat", rx = "rx", censor_time = "censor_time", base_cov = "none", low_psi = -1, hi_psi = 1, n_eval_z = 100L, alpha = 0.05, treat_modifier = 1, recensor = 1L, autoswitch = 1L, gridsearch = 0L, boot = 0L, n_boot = 1000L) {
    .Call(`_lrstat_rpsft`, data, stratum, time, event, treat, rx, censor_time, base_cov, low_psi, hi_psi, n_eval_z, alpha, treat_modifier, recensor, autoswitch, gridsearch, boot, n_boot)
}

#' @title Kaplan-Meier estimates of the survival curve
#' @description Obtains the Kaplan-Meier estimates of the survival curve.
#'
#' @param data The input data frame that contains the following variables:
#'
#'   * \code{rep}: The replication for by-group processing.
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{time}: The possibly right-censored survival time.
#'
#'   * \code{event}: The event indicator.
#'
#' @param rep The name of the replication variable in the input data.
#' @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 conftype The type of confidence interval. One of "none",
#'   "plain", "log", "log-log" (the default), or "arcsin".
#'   The arcsin option bases the intervals on asin(sqrt(survival)).
#' @param confint The level of the two-sided confidence interval for
#'   the survival probabilities. Defaults to 0.95.
#'
#' @return A data frame with the following variables:
#'
#' * \code{rep}: The replication.
#'
#' * \code{stratum}: The stratum.
#'
#' * \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{survival}: The Kaplan-Meier estimate of the survival probability.
#'
#' * \code{stderr}: 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{confint}: The level of confidence interval if requested.
#'
#' * \code{conftype}: The type of confidence interval if requested.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' kmest(data = aml, stratum = "x",
#'       time = "time", event = "status")
#'
#' @export
kmest <- function(data, rep = "rep", stratum = "stratum", time = "time", event = "event", conftype = "log-log", confint = 0.95) {
    .Call(`_lrstat_kmest`, data, rep, stratum, time, event, conftype, confint)
}

#' @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 that contains the following variables:
#'
#'   * \code{rep}: The replication for by-group processing.
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{treat}: The treatment.
#'
#'   * \code{time}: The possibly right-censored survival time.
#'
#'   * \code{event}: The event indicator.
#'
#' @param rep The name of the replication variable in the input data.
#' @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.
#' @inheritParams param_rho1
#' @inheritParams param_rho2
#'
#' @return A data frame with the following variables:
#'
#' * \code{rep}: The replication.
#'
#' * \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 one-sided p-value.
#'
#' * \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
#'
#' df <- lrtest(data = rawdata, rep = "iterationNumber",
#'              stratum = "stratum", treat = "treatmentGroup",
#'              time = "timeUnderObservation", event = "event",
#'              rho1 = 0.5, rho2 = 0)
#' head(df)
#'
#' @export
lrtest <- function(data, rep = "rep", stratum = "stratum", treat = "treat", time = "time", event = "event", rho1 = 0, rho2 = 0) {
    .Call(`_lrstat_lrtest`, data, rep, stratum, treat, time, event, rho1, rho2)
}

#' @title Parametric regression models for failure time data
#' @description Obtains the parameter estimates from parametric
#' regression models with uncensored, right censored, left censored, or
#' interval censored data.
#'
#' @param data The input data frame that contains the following variables:
#'
#'   * \code{rep}: The replication for by-group processing.
#'
#'   * \code{stratum}: The stratum.
#'
#'   * \code{time}: The follow-up time for right censored data, or
#'     the left end of each interval for interval censored data.
#'
#'   * \code{time2}: The right end of each interval for interval
#'     censored data.
#'
#'   * \code{event}: The event indicator, normally 1=event, 0=no event.
#'
#'   * \code{covariates}: The values of baseline covariates.
#'     This is the full-rank design matrix (excluding the intercept)
#'     for the regression model, assuming that factor variables
#'     have already been expanded into dummy variables.
#'     The intercept will be added automatically.
#'
#'   * \code{weight}: The weight for each observation.
#'
#'   * \code{id}: The optional subject ID to group the score residuals
#'     in computing the robust sandwich variance.
#'
#' @param rep The name of the replication variable in the input data.
#' @param stratum The name of the stratum variable in the input data.
#' @param time The name of the time variable or the left end of each
#'   interval for interval censored data in the input data.
#' @param time2 The name of the right end of each interval for
#'   interval censored data in the input data.
#' @param event The name of the event variable in the input data
#'   for right censored data.
#' @param covariates The vector of names of baseline covariates
#'   in the input data.
#' @param weight The name of the weighting variable in the input data.
#' @param id The name of the id variable in the input data.
#' @param dist The assumed distribution for time to event. Options include
#'   "exponential", "weibull", "lognormal", and "loglogistic" to be
#'   modeled on the log-scale, and "normal" and "logistic" to be modeled
#'   on the original scale.
#' @param robust Whether a robust sandwich variance estimate should be
#'   computed. The default is TRUE if there are fractional weights or
#'   there is at least 1 id with >1 event. In the presence of the id
#'   variable, the score residual will be aggregated for each id when
#'   computing the robust sandwich variance estimate.
#'
#' @details There are two ways to specify the model, one for right censored
#' data through the time and event variables, and the other for interval
#' censored data through the time and time2 variables. For the second form,
#' we follow the convention used in SAS PROC LIFEREG:
#'
#' * If lower is not missing, upper is not missing, and lower is equal
#'   to upper, then there is no censoring and the event occurred at
#'   time lower.
#'
#' * If lower is not missing, upper is not missing, and lower < upper,
#'   then the event time is censored within the interval (lower, upper).
#'
#' * If lower is missing, but upper is not missing, then upper will be
#'   used as the left censoring value.
#'
#' * If lower is not missing, but upper is missing, then lower will be
#'   used as the right censoring value.
#'
#' * If lower is not missing, upper is not missing, but lower > upper,
#'   or if both lower and upper are missing, then the observation will
#'   not be used.
#'
#' @return A list with the following components:
#'
#' * \code{sumstat}: The data frame of summary statistics of model fit
#'   with the following variables:
#'
#'     - \code{rep}: The replication.
#'
#'     - \code{n}: The number of observations.
#'
#'     - \code{nevents}: The number of events.
#'
#'     - \code{loglik0}: The log-likelihood under null.
#'
#'     - \code{loglik1}: The maximum log-likelihood.
#'
#'     - \code{scoretest}: The score test statistic.
#'
#' * \code{parest}: The data frame of parameter estimates with the
#'   following variables:
#'
#'     - \code{rep}: The replication.
#'
#'     - \code{param}: The name of the covariate for the parameter estimate.
#'
#'     - \code{beta}: The parameter estimate.
#'
#'     - \code{sebeta}: The standard error of parameter estimate.
#'
#'     - \code{z}: The Wald test statistic.
#'
#'     - \code{expbeta}: The exponentiated parameter.
#'
#'     - \code{vbeta}: The covariance matrix for parameter estimates.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' library(dplyr)
#'
#' # right censored data
#' liferegr(data = rawdata %>% mutate(treat = 1*(treatmentGroup == 1)),
#'          rep = "iterationNumber", stratum = "stratum",
#'          time = "timeUnderObservation", event = "event",
#'          covariates = "treat", dist = "weibull")
#'
#' # tobit regression for left censored data
#' liferegr(data = tobin %>% mutate(time = ifelse(durable>0, durable, NA)),
#'          time = "time", time2 = "durable",
#'          covariates = c("age", "quant"), dist = "normal")
#'
#' @export
liferegr <- function(data, rep = "rep", stratum = "stratum", time = "time", time2 = "time2", event = "event", covariates = "treat", weight = "weight", id = "id", dist = "weibull", robust = 0L) {
    .Call(`_lrstat_liferegr`, data, rep, stratum, time, time2, event, covariates, weight, id, dist, robust)
}

#' @title Proportional hazards regression model
#' @description Obtains the hazard ratio estimates from the proportional
#' hazards regression model with right censored or counting process data.
#'
#' @param data The input data frame that contains the following variables:
#'
#'   * \code{rep}: The replication for by-group processing.
#'
#'   * \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 only. 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, normally 1=event, 0=no event.
#'
#'   * \code{covariates}: The values of baseline covariates (and
#'     time-dependent covariates in each interval for counting
#'     process data). This is the full-rank design matrix for the Cox
#'     model, assuming that factor variables have already been
#'     expanded into dummy variables.
#'
#'   * \code{weight}: The weight for each observation.
#'
#'   * \code{id}: The optional subject ID for counting process data
#'     with time-dependent covariates.
#'
#' @param rep The name of the replication variable in the input data.
#' @param stratum The name of the stratum 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 covariates The vector of names of baseline and time-dependent
#'   covariates in the input data.
#' @param weight The name of the weighting variable in the input data.
#' @param id The name of the id variable in the input data.
#' @param ties The method for handling ties with options including
#'   "breslow" and "efron" (default).
#' @param robust Whether a robust sandwich variance estimate should be
#'   computed. The default is TRUE if there are fractional weights or
#'   there is at least 1 id with >1 event. In the presence of the id
#'   variable, the score residual will be aggregated for each id when
#'   computing the robust sandwich variance estimate.
#'
#' @return A list with the following components:
#'
#' * \code{sumstat}: The data frame of summary statistics of model fit
#'   with the following variables:
#'
#'     - \code{rep}: The replication.
#'
#'     - \code{n}: The number of observations.
#'
#'     - \code{nevents}: The number of events.
#'
#'     - \code{loglik0}: The log-likelihood under null.
#'
#'     - \code{loglik1}: The maximum log-likelihood.
#'
#'     - \code{scoretest}: The score test statistic.
#'
#' * \code{parest}: The data frame of parameter estimates with the
#'   following variables:
#'
#'     - \code{rep}: The replication.
#'
#'     - \code{param}: The name of the covariate for the parameter estimate.
#'
#'     - \code{beta}: The log hazard ratio estimate.
#'
#'     - \code{sebeta}: The standard error of log hazard ratio estimate.
#'
#'     - \code{rsebeta}: The robust standard error of log hazard ratio
#'       estimate if robust variance is requested.
#'
#'     - \code{z}: The Wald test statistic for log hazard ratio. The
#'       \code{rsebeta} will be used if robust variance is requested.
#'
#'     - \code{hazardRatio}: The hazard ratio estimate.
#'
#'     - \code{vbeta}: The covariance matrix for parameter estimates.
#'
#'     - \code{rvbeta}: The robust covariance matrix for parameter
#'       estimates if robust variance is requested.
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#'
#' library(dplyr)
#'
#' # Example 1 with right-censored data
#' phregr(data = rawdata %>% mutate(treat = 1*(treatmentGroup == 1)),
#'        rep = "iterationNumber", stratum = "stratum",
#'        time = "timeUnderObservation", event = "event",
#'        covariates = "treat")
#'
#' # Example 2 with counting process data and robust variance estimate
#' phregr(data = heart %>% mutate(rx = as.numeric(transplant) - 1),
#'        time = "start", time2 = "stop", event = "event",
#'        covariates = c("rx", "age"), id = "id", robust = 1)
#'
#' @export
phregr <- function(data, rep = "rep", stratum = "stratum", time = "time", time2 = "time2", event = "event", covariates = "treat", weight = "weight", id = "id", ties = "efron", robust = 0L) {
    .Call(`_lrstat_phregr`, data, rep, stratum, time, time2, event, covariates, weight, id, ties, robust)
}

set_seed <- function(seed) {
    invisible(.Call(`_lrstat_set_seed`, seed))
}

stl_sort <- function(x) {
    .Call(`_lrstat_stl_sort`, x)
}

#' @title Find interval numbers of indices
#' @description The implementation of \code{findInterval()} in R from
#' Advanced R by Hadley Wickham. Given a vector of non-decreasing
#' breakpoints in v, find the interval containing each element of x; i.e.,
#' if \code{i <- findInterval3(x,v)}, for each index \code{j} in \code{x},
#' \code{v[i[j]] <= x[j] < v[i[j] + 1]}, where \code{v[0] := -Inf},
#' \code{v[N+1] := +Inf}, and \code{N = length(v)}.
#'
#' @param x The numeric vector of interest.
#' @param v The vector of break points.
#' @return A vector of \code{length(x)} with values in \code{0:N} where
#'   \code{N = length(v)}.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' x <- 2:18
#' v <- c(5, 10, 15) # create two bins [5,10) and [10,15)
#' cbind(x, findInterval3(x, v))
#'
#' @export
findInterval3 <- function(x, v) {
    .Call(`_lrstat_findInterval3`, x, v)
}

errorSpentcpp <- function(t = NA_real_, error = NA_real_, sf = NA_character_, sfpar = NA_real_) {
    .Call(`_lrstat_errorSpentcpp`, t, error, sf, sfpar)
}

exitprobcpp <- function(b, a, theta, I) {
    .Call(`_lrstat_exitprobcpp`, b, a, theta, I)
}

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

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

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

rtpwexpcpp <- function(n = NA_integer_, piecewiseSurvivalTime = NA_real_, lambda = NA_real_, lowerBound = NA_real_) {
    .Call(`_lrstat_rtpwexpcpp`, n, piecewiseSurvivalTime, lambda, lowerBound)
}

getBoundcpp <- function(k = NA_integer_, informationRates = NA_real_, alpha = NA_real_, typeAlphaSpending = NA_character_, parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, spendingTime = NA_real_, efficacyStopping = NA_integer_) {
    .Call(`_lrstat_getBoundcpp`, k, informationRates, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, spendingTime, efficacyStopping)
}

getPower <- function(alpha, kMax, b, theta, I, bsf, bsfpar, st, futilityStopping, w) {
    .Call(`_lrstat_getPower`, alpha, kMax, b, theta, I, bsf, bsfpar, st, futilityStopping, w)
}

#' @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 = NA_real_, accrualTime = 0L, accrualIntensity = NA_real_, accrualDuration = NA_real_) {
    .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 = NA_real_, accrualTime = 0L, accrualIntensity = NA_real_) {
    .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.
#'
#' @keywords internal
#'
#' @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 = NA_real_, piecewiseSurvivalTime = 0L, lambda = NA_real_, gamma = 0L) {
    .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.
#'
#' @keywords internal
#'
#' @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 = NA_real_, piecewiseSurvivalTime = 0L, lambda = NA_real_, gamma = 0L) {
    .Call(`_lrstat_pevent`, time, piecewiseSurvivalTime, lambda, gamma)
}

#' @title Integrated event probability over an interval with constant hazard
#' @description Obtains the integration probability of having an event
#' during an interval with constant hazard.
#'
#' @param j The analysis time interval with constant hazard.
#' @param t1 Lower bound of the analysis time interval.
#' @param t2 Upper bound of the analysis time interval.
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda
#' @inheritParams param_gamma
#'
#' @return A value for the integrated probability of having an event
#' during an interval with constant hazard for a treatment
#' group with specified piecewise exponential survival and dropout
#' distributions.
#'
#' @keywords internal
#'
#' @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.
#'
#' hd(j = 1, t1 = 1, t2 = 3, piecewiseSurvivalTime = c(0, 6),
#'    lambda = c(0.0533, 0.0309), gamma = -log(1-0.05)/12)
#'
#' @export
hd <- function(j = NA_integer_, t1 = NA_real_, t2 = NA_real_, piecewiseSurvivalTime = 0L, lambda = NA_real_, gamma = 0L) {
    .Call(`_lrstat_hd`, j, t1, t2, piecewiseSurvivalTime, lambda, gamma)
}

#' @title Integrated event probability over an interval
#' @description Obtains the integration of the probability of having an
#' event during an interval. The specified analysis time interval can span
#' more than one analysis time interval with constant hazard.
#'
#' @param t1 Lower bound of the analysis time interval.
#' @param t2 Upper bound of the analysis time interval.
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda
#' @inheritParams param_gamma
#'
#' @return A value for the integrated probability of having an event
#' during an interval for a treatment group with specified
#' piecewise exponential survival and dropout distributions.
#'
#' @keywords internal
#'
#' @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.
#'
#' pd(t1 = 1, t2 = 8, piecewiseSurvivalTime = c(0, 6),
#'    lambda = c(0.0533, 0.0309), gamma = -log(1-0.05)/12)
#'
#' @export
pd <- function(t1 = NA_real_, t2 = NA_real_, piecewiseSurvivalTime = 0L, lambda = NA_real_, gamma = 0L) {
    .Call(`_lrstat_pd`, t1, t2, piecewiseSurvivalTime, lambda, gamma)
}

#' @title Number of patients enrolled during an interval and having an event
#' by specified calendar times
#' @description Obtains the number of patients who are enrolled during a
#' specified enrollment time interval and have an event by the specified
#' calendar times.
#'
#' @param time A vector of calendar times at which to calculate the number
#'   of patients having an event.
#' @param u1 Lower bound of the accrual time interval.
#' @param u2 Upper bound of the accrual time interval.
#' @inheritParams param_accrualTime
#' @inheritParams param_accrualIntensity
#' @inheritParams param_piecewiseSurvivalTime
#' @inheritParams param_lambda
#' @inheritParams param_gamma
#'
#' @return A vector of number of patients who are enrolled during a
#' specified enrollment time interval and have an event by the specified
#' calendar times for a given treatment group had the enrollment being
#' restricted to the treatment group. By definition, we must have
#' \code{time >= u2}.
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, 10 patients per month for the first 3 months, and
#' # 20 patients per month thereafter. 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.
#'
#' ad(time = c(9, 15), u1 = 1, u2 = 8, accrualTime = c(0, 3),
#'    accrualIntensity = c(10, 20), piecewiseSurvivalTime=c(0, 6),
#'    lambda = c(0.0533, 0.0309), gamma = -log(1-0.05)/12)
#'
#' @export
ad <- function(time = NA_real_, u1 = NA_real_, u2 = NA_real_, accrualTime = 0L, accrualIntensity = NA_real_, piecewiseSurvivalTime = 0L, lambda = NA_real_, gamma = 0L) {
    .Call(`_lrstat_ad`, time, u1, u2, accrualTime, accrualIntensity, 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 time 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_minFollowupTime
#' @inheritParams param_maxFollowupTime
#'
#' @return A matrix of the number of patients at risk at the specified
#' analysis times (row) for each treatment group (column).
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#'
#' natrisk(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, minFollowupTime = 18,
#'         maxFollowupTime = 30)
#'
#' @export
natrisk <- 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_, minFollowupTime = NA_real_, maxFollowupTime = NA_real_) {
    .Call(`_lrstat_natrisk`, time, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, lambda1, lambda2, gamma1, gamma2, accrualDuration, minFollowupTime, maxFollowupTime)
}

#' @title Number of subjects having an event
#' @description Obtains the number of subjects having an event by given
#' analysis times for each treatment group.
#'
#' @param time A vector of analysis 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_minFollowupTime
#' @inheritParams param_maxFollowupTime
#'
#' @return A matrix of the number of patients having an event at the
#' specified analysis times (row) for each treatment group (column).
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @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, minFollowupTime = 18,
#'        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_, minFollowupTime = NA_real_, maxFollowupTime = NA_real_) {
    .Call(`_lrstat_nevent`, time, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, lambda1, lambda2, gamma1, gamma2, accrualDuration, minFollowupTime, maxFollowupTime)
}

#' @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_minFollowupTime
#' @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).
#'
#' @keywords internal
#'
#' @author Kaifeng Lu, \email{kaifenglu@@gmail.com}
#'
#' @examples
#' # Piecewise accrual, piecewise exponential survivals, and 5% dropout by
#' # the end of 1 year.
#' nevent2(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, minFollowupTime = 18,
#'         maxFollowupTime = 30)
#'
#' @export
nevent2 <- 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_, minFollowupTime = NA_real_, maxFollowupTime = NA_real_) {
    .Call(`_lrstat_nevent2`, time, allocationRatioPlanned, accrualTime, accrualIntensity, piecewiseSurvivalTime, lambda1, lambda2, gamma1, gamma2, accrualDuration, minFollowupTime, maxFollowupTime)
}

#' @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.
#' @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
#' @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.
#'
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, 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, 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}.
#' @param varianceRatioH10 The ratio of the variance under H10 to
#'   the variance under H1.
#' @param varianceRatioH20 The ratio of the variance under H20 to
#'   the variance under H1.
#' @param varianceRatioH12 The ratio of the variance under H10 to
#'   the variance under H20.
#' @param varianceRatioH21 The ratio of the variance under H20 to
#'   the variance under H10.
#'
#' @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{\frac{n_j}{v_{10}}}
#' \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{v_{10}} is the null variance of
#' \eqn{\hat{\theta}} based on the restricted maximum likelihood (reml)
#' estimate of model parameters subject to the constraint imposed by
#' \eqn{H_{10}} for one sampling unit drawn from \eqn{H_1}. For example,
#' for estimating the risk difference \eqn{\theta = \pi_1 - \pi_2},
#' the asymptotic limits of the
#' reml estimates of \eqn{\pi_1} and \eqn{\pi_2} subject to the constraint
#' imposed by \eqn{H_{10}} are given by
#' \deqn{(\tilde{\pi}_1, \tilde{\pi}_2) = f(\theta_{10}, r, r\pi_1,
#' 1-r, (1-r)\pi_2),}
#' where \eqn{f(\theta_0, n_1, y_1, n_2, y_2)} is the function to obtain
#' the reml of \eqn{\pi_1} and \eqn{\pi_2} subject to the constraint that
#' \eqn{\pi_1-\pi_2 = \theta_0} with observed data
#' \eqn{(n_1, y_1, n_2, y_2)} for the number of subjects and number of
#' responses in the active treatment and control groups,
#' \eqn{r} is the randomization probability for the active treatment
#' group, and \deqn{v_{10} = \frac{\tilde{\pi}_1 (1-\tilde{\pi}_1)}{r} +
#' \frac{\tilde{\pi}_2 (1-\tilde{\pi}_2)}{1-r}.}
#'
#' Let \eqn{I_j = n_j/v_1} denote the information for \eqn{\theta} at the
#' \eqn{j}th look, where
#' \deqn{v_{1} = \frac{\pi_1 (1-\pi_1)}{r} + \frac{\pi_2 (1-\pi_2)}{1-r}}
#' denotes the variance of \eqn{\hat{\theta}} under \eqn{H_1} for one
#' sampling unit. It follows that
#' \deqn{(Z_{1j} \geq b_j) = (Z_j \geq w_{10} b_j +
#' (\theta_{10}-\theta)\sqrt{I_j}),}
#' where \eqn{Z_j = (\hat{\theta}_j - \theta)\sqrt{I_j}}, and
#' \eqn{w_{10} = \sqrt{v_{10}/v_1}}.
#'
#' Similarly, we reject \eqn{H_{20}} at or before look \eqn{k} if
#' \deqn{Z_{2j} = (\hat{\theta}_j - \theta_{20})\sqrt{\frac{n_j}{v_{20}}}
#' \leq -b_j} for some \eqn{j=1,\ldots,k}, where \eqn{v_{20}} is the null
#' variance of \eqn{\hat{\theta}} based on the reml estimate of model
#' parameters subject to the constraint imposed by \eqn{H_{20}} for
#' one sampling unit drawn from \eqn{H_1}. We have
#' \deqn{(Z_{2j} \leq -b_j) = (Z_j \leq -w_{20} b_j +
#' (\theta_{20}-\theta)\sqrt{I_j}),}
#' where \eqn{w_{20} = \sqrt{v_{20}/v_1}}.
#'
#' Let \eqn{l_j = w_{10}b_j + (\theta_{10}-\theta)\sqrt{I_j}},
#' and \eqn{u_j = -w_{20}b_j + (\theta_{20}-\theta)\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.
#'
#' To evaluate the type I error of the equivalence trial under
#' \eqn{H_{10}}, we first match the information under \eqn{H_{10}}
#' with the information under \eqn{H_1}. For example, for estimating
#' the risk difference for two independent samples, the sample size
#' \eqn{n_{10}} under \eqn{H_{10}} must satisfy
#' \deqn{\frac{1}{n_{10}}\left(\frac{(\pi_2 + \theta_{10})
#' (1 - \pi_2 - \theta_{10})}{r} + \frac{\pi_2 (1-\pi_2)}{1-r}\right)
#' = \frac{1}{n}\left(\frac{\pi_1(1-\pi_1)}{r} +
#' \frac{\pi_2 (1-\pi_2)}{1-r}\right).}
#' Then we obtain the reml estimates of \eqn{\pi_1} and \eqn{\pi_2}
#' subject to the constraint imposed by \eqn{H_{20}} for one sampling
#' unit drawn from \eqn{H_{10}},
#' \deqn{(\tilde{\pi}_{10}, \tilde{\pi}_{20}) = f(\theta_{20}, r,
#' r(\pi_2 + \theta_{10}), 1-r, (1-r)\pi_2).}
#' Let \eqn{t_j} denote the information fraction at look \eqn{j}.
#' Define \deqn{\tilde{v}_1 = \frac{(\pi_2 + \theta_{10})
#' (1-\pi_2 -\theta_{10})}{r} + \frac{\pi_2 (1-\pi_2)}{1-r},} and
#' \deqn{\tilde{v}_{20} = \frac{\tilde{\pi}_{10}(1-\tilde{\pi}_{10})}{r} +
#' \frac{\tilde{\pi}_{20} (1-\tilde{\pi}_{20})}{1-r}.}
#'
#' The cumulative rejection probability under \eqn{H_{10}} at or before
#' look \eqn{k} is given by
#' \deqn{P_{\theta_{10}}\left(\cup_{j=1}^{k} \{(\hat{\theta}_j - \theta_{10})
#' \sqrt{n_{10} t_j/\tilde{v}_1} \geq b_j\} \cap
#' \cup_{j=1}^{k} \{(\hat{\theta}_j - \theta_{20})
#' \sqrt{n_{10} t_j/\tilde{v}_{20}} \leq -b_j\}\right) =
#' q_1 + q_2 + q_{12},}
#' where
#' \deqn{q_1 = P_{\theta_{10}}\left(\cup_{j=1}^{k}
#' \{(\hat{\theta}_j - \theta_{10})
#' \sqrt{n_{10} t_j/\tilde{v}_1} \geq b_j\}\right) =
#' P_{\theta_{10}}\left(\cup_{j=1}^{k} (Z_j \geq b_j)\right),}
#' \deqn{q_2 = P_{\theta_{10}}\left(\cup_{j=1}^{k}
#' \{(\hat{\theta}_j - \theta_{20})
#' \sqrt{n_{10} t_j/\tilde{v}_{20}} \leq -b_j\}\right) =
#' P_{\theta_{10}}\left(\cup_{j=1}^{k} (Z_j \leq -b_j w_{21} +
#' (\theta_{20} - \theta_{10})\sqrt{I_j})\right),}
#' and
#' \deqn{q_{12} = P_{\theta_{10}}\left(\cup_{j=1}^{k}
#' \{(Z_j \geq b_j) \cup (Z_j \leq -w_{21} b_j +
#' (\theta_{20} - \theta_{10})\sqrt{I_j})\}\right).}
#' Here \eqn{Z_j = (\hat{\theta}_j - \theta_{10}) \sqrt{I_j}}, and
#' \eqn{w_{21} = \sqrt{\tilde{v}_{20}/\tilde{v}_1}}.
#' Of note, \eqn{q_1}, \eqn{q_2}, and \eqn{q_{12}}
#' can be evaluated using group sequential exit probabilities.
#' Similarly, we can define \eqn{\tilde{v}_2}, \eqn{\tilde{v}_{10}},
#' and \eqn{w_{12} = \sqrt{\tilde{v}_{10}/\tilde{v}_2}}, and
#' evaluate the type I error under \eqn{H_{20}}.
#'
#' The variance ratios correspond to
#' \deqn{\text{varianceRatioH10} = v_{10}/v_1,}
#' \deqn{\text{varianceRatioH20} = v_{20}/v_1,}
#' \deqn{\text{varianceRatioH12} = \tilde{v}_{10}/\tilde{v}_2,}
#' \deqn{\text{varianceRatioH21} = \tilde{v}_{20}/\tilde{v}_1.}
#' If the alternative variance is used, then the variance ratios
#' are all equal to 1.
#'
#' @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.
#'
#'     - \code{varianceRatioH10}: The ratio of the variance under H10 to
#'       the variance under H1.
#'
#'     - \code{varianceRatioH20}: The ratio of the variance under H20 to
#'       the variance under H1.
#'
#'     - \code{varianceRatioH12}: The ratio of the variance under H10 to
#'       the variance under H20.
#'
#'     - \code{varianceRatioH21}: The ratio of the variance under H20 to
#'       the variance under H10.
#'
#' @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 = NA_real_, alpha = 0.05, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, spendingTime = NA_real_, varianceRatioH10 = 1, varianceRatioH20 = 1, varianceRatioH12 = 1, varianceRatioH21 = 1) {
    .Call(`_lrstat_getDesignEquiv`, beta, IMax, thetaLower, thetaUpper, theta, kMax, informationRates, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, spendingTime, varianceRatioH10, varianceRatioH20, varianceRatioH12, varianceRatioH21)
}

#' @title Adaptive design at an interim look
#' @description Obtains the conditional power for specified incremental
#' information given the interim results, parameter value, and
#' data-dependent changes in the error spending function, and the number
#' and spacing of interim looks. Conversely, obtains the incremental
#' information needed to attain a specified conditional power given
#' the interim results, parameter value, and 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 one
#'   should 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 parameter value.
#' @param IMax The maximum information of the primary trial. Must be
#'   provided if \code{futilityBounds} is missing and
#'   \code{typeBetaSpending} is not equal to "none", or
#'   if conditional power calculation is desired.
#' @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:
#'   "OF" for O'Brien-Fleming boundaries,
#'   "P" for Pocock boundaries,
#'   "WT" for Wang & Tsiatis boundaries,
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function,
#'   "user" for user defined spending, and
#'   "none" for no early efficacy stopping.
#'   Defaults to "sfOF".
#' @param parameterAlphaSpending The parameter value of alpha spending
#'   for the primary trial. Corresponds to Delta for "WT", rho for "sfKD",
#'   and gamma for "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(-6, kMax-1)} if left unspecified.
#' @param typeBetaSpending The type of beta spending for the primary trial.
#'   One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early futility stopping.
#'   Defaults to "none".
#' @param parameterBetaSpending The parameter value of beta spending
#'   for the primary trial. Corresponds to rho for "sfKD",
#'   and gamma for "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 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:
#'   "OF" for O'Brien-Fleming boundaries,
#'   "P" for Pocock boundaries,
#'   "WT" for Wang & Tsiatis boundaries,
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function, and
#'   "none" for no early efficacy stopping.
#'   Defaults to "sfOF".
#' @param parameterAlphaSpendingNew The parameter value of alpha spending
#'   for the secondary trial. Corresponds to Delta for "WT", rho for "sfKD",
#'   and gamma for "sfHSD".
#' @param typeBetaSpendingNew The type of beta spending for the secondary
#'   trial. One of the following:
#'   "sfOF" for O'Brien-Fleming type spending function,
#'   "sfP" for Pocock type spending function,
#'   "sfKD" for Kim & DeMets spending function,
#'   "sfHSD" for Hwang, Shi & DeCani spending function,
#'   "user" for user defined spending, and
#'   "none" for no early futility stopping.
#'   Defaults to "none".
#' @param parameterBetaSpendingNew The parameter value of beta spending
#'   for the secondary trial. Corresponds to rho for "sfKD",
#'   and gamma for "sfHSD".
#' @param userBetaSpendingNew The user defined cumulative beta spending.
#'   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 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 two list components:
#'
#' * \code{primaryTrial}: A list of selected information for the primary
#'   trial, including \code{L}, \code{zL}, \code{theta}, \code{kMax},
#'   \code{informationRates}, \code{efficacyBounds}, \code{futilityBounds},
#'   and \code{MullerSchafer}.
#'
#' * \code{secondaryTrial}: A \code{design} object for the secondary trial.
#'
#' @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
#'
#' # original 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))
#'
#' # interim look results
#' L = 1
#' n1 = n/3
#' delta1 = 4.5
#' sigma1 = 20
#' zL = delta1/sqrt(4/n1*sigma1^2)
#'
#' t = des1$byStageResults$informationRates
#'
#' # conditional power with sample size increase
#' (des2 = adaptDesign(
#'   betaNew = NA, INew = 420/(4*sigma1^2),
#'   L, zL, theta = delta1,
#'   IMax = n/(4*sigma1^2), kMax = 3, informationRates = t,
#'   alpha = 0.05, typeAlphaSpending = "sfHSD",
#'   parameterAlphaSpending = -4))
#'
#' # Muller & Schafer (2001) method to design the secondary trial:
#' # 3-look gamma(-2) spending with 84% power at delta = 4.5 and sigma = 20
#' (des2 = adaptDesign(
#'   betaNew = 0.16, INew = NA,
#'   L, zL, theta = delta1,
#'   IMax = n/(4*sigma1^2), kMax = 3, informationRates = t,
#'   alpha = 0.05, typeAlphaSpending = "sfHSD",
#'   parameterAlphaSpending = -4,
#'   MullerSchafer = TRUE,
#'   kNew = 3, typeAlphaSpendingNew = "sfHSD",
#'   parameterAlphaSpendingNew = -2))
#'
#' # incremental sample size for sigma = 20
#' (nNew = 4*sigma1^2*des2$secondaryTrial$overallResults$information)
#'
#' @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 = NA_real_, alpha = 0.025, typeAlphaSpending = "sfOF", parameterAlphaSpending = NA_real_, userAlphaSpending = NA_real_, futilityBounds = NA_real_, typeBetaSpending = "none", parameterBetaSpending = NA_real_, spendingTime = NA_real_, MullerSchafer = 0L, kNew = NA_integer_, informationRatesNew = NA_real_, efficacyStoppingNew = NA_integer_, futilityStoppingNew = NA_integer_, typeAlphaSpendingNew = "sfOF", parameterAlphaSpendingNew = NA_real_, typeBetaSpendingNew = "none", parameterBetaSpendingNew = NA_real_, userBetaSpendingNew = NA_real_, spendingTimeNew = NA_real_, varianceRatio = 1) {
    .Call(`_lrstat_adaptDesign`, betaNew, INew, L, zL, theta, IMax, kMax, informationRates, efficacyStopping, futilityStopping, criticalValues, alpha, typeAlphaSpending, parameterAlphaSpending, userAlphaSpending, futilityBounds, typeBetaSpending, parameterBetaSpending, spendingTime, MullerSchafer, kNew, informationRatesNew, efficacyStoppingNew, futilityStoppingNew, typeAlphaSpendingNew, parameterAlphaSpendingNew, typeBetaSpendingNew, parameterBetaSpendingNew, userBetaSpendingNew, spendingTimeNew, varianceRatio)
}

hasVariable <- function(df, varName) {
    .Call(`_lrstat_hasVariable`, df, varName)
}

invsympd <- function(a) {
    .Call(`_lrstat_invsympd`, a)
}

quantilecpp <- function(x, p) {
    .Call(`_lrstat_quantilecpp`, x, p)
}

Try the lrstat package in your browser

Any scripts or data that you put into this service are public.

lrstat documentation built on June 23, 2024, 5:06 p.m.