WorksMathematics
coherent4cast: Coherent Survival Modelling and Forecasting for History-Dependent Recurrent and Terminal Events in R
Abstract
Researchers studying recurrent events and terminal outcomes need software that connects incomplete event histories to interpretable forecasts and uncertainty estimates. We present coherent4cast, an R package for fitting history-dependent recurrent and terminal event models, predicting future event burden and terminal-event risk, and assessing sensitivity to incomplete observation. Users supply event histories, covariates and observation information; the package returns fitted models, dynamic forecasts, uncertainty summaries and diagnostic measures under explicitly stated assumptions. The package integrates over event histories compatible with tied dates or observation windows and supports several frailty distributions for between-subject heterogeneity. A shared probability model generates recurrent-event counts, terminal-event probabilities and restricted mean time alive. Cross-fitted targeting provides influence-function diagnostics and asymptotic inference in supported missing-at-random and right-censoring settings. Separate sensitivity analyses provide bounds under specified recording restrictions. A baseline binary-treatment interface estimates standardized treatment contrasts under consistency, conditional exchangeability, positivity and independent censoring. A C++17 computational core supports the R interface. Independent numerical checks, computational benchmarks, simulation experiments and reproducible examples document accuracy, performance and inferential limitations. Outputs retain observation assumptions, convergence information and numerical diagnostics. The package, tutorials and replication materials are publicly available, supporting transparent analysis across clinical and other event-history applications.
Introduction
A recurrent-event forecast can mean an expected event count, a probability of an event, or a probability of remaining alive. These quantities are related, but their units and eligibility rules differ. A patient may be readmitted repeatedly before death; an equipment unit may undergo several repairs before irrecoverable failure. A useful implementation must carry these distinctions from data preparation through estimation, prediction and validation. It must also distinguish events that did not occur from intervals in which events were not recorded.
The methodological framework of Adetunji and Adetunji [1] constructs prognostic targets from a common complete-history law and separates the assumptions needed for likelihood inference, missing-history sensitivity analysis and prediction-set calibration. The present paper describes its software implementation. The primary contribution is an auditable computational path: declared event eligibility and observation restrictions enter a shared likelihood; one retained law generates multiple forecast targets; independent numerical routines report their own assumptions and diagnostics. The software paper complements the methodological manuscript rather than claiming that all of its theoretical extensions are already available as general-purpose routines.
The package addresses three practical sources of implementation error. First, an observed terminal event changes every subsequent risk set. Second, a coarsened history is a set of compatible paths; choosing a convenient representative path can change the likelihood and forecast. Third, finite-sample prediction coverage, parameter confidence coverage and numerical precision are different properties. A common function name or a successful optimizer does not make their guarantees interchangeable. The interfaces expose these distinctions so that analysts can decide which calculation answers their question.
The core architecture introduced in version 0.10.0 integrates five extensions: automatic observation fibres, sparse propagation and large-support bounds, targeting through the primary modeling API, evolving forecast covariates, and alternative frailty distributions with diagnostics. All data-processing and high-level methods are available in R; the likelihood, coarsened mixture, propagation and core finite-support operations are implemented through a separate C++17 library. We report deterministic numerical agreement, measured computational performance and five case studies. Version 0.10.1 adds explicit data-regime tags, survival and competing-risk wrappers, and audit export. Its causal revision adds a separate treatment-weighted targeting engine implementing Supplement S12 of the methodological manuscript; existing prognostic numerical kernels are retained.
Related software
Several established packages provide essential recurrent-event and multistate tools. frailtypack fits shared, joint and nested frailty models and includes dynamic prediction for longitudinal, recurrent and terminal outcomes ([23, 17]). mstate organizes competing-risk and multistate data and supports transition-specific estimation and prediction ([7]). reReg implements a general scale-change regression framework for recurrent events, including informative terminal events and frailty treatment without a required parametric frailty distribution ([4]). JMbayes2 fits Bayesian joint models linking several longitudinal outcomes and event processes, with prediction and validation utilities ([22]). These packages have different scientific scopes; a single ranking would conceal the differences.
Table 1 records the relevant documented capabilities and the corresponding role of coherent4cast. The comparison does not claim that the other packages necessarily mishandle missing data or produce incoherent forecasts. In particular, a correctly specified joint model already supplies a common probability law. The additional interfaces here make legal-path integration, finite-path targeting, recording-sensitivity optimization and explicit numerical checks available in one package, within their stated observation and state models. Version 0.10.0 additionally provides continuous-time targeting for a declared finite-state right-censoring experiment and automatic construction of observed-event timing fibres.
| Software | Documented emphasis | Relationship to this implementation |
| frailtypack | Shared, joint and nested frailty estimation; dynamic prediction [23, 17]. | Established frailty workflow; the present interfaces additionally expose legal-path integration and finite-support sensitivity constraints. |
| mstate | Competing-risk and multistate data preparation, estimation and prediction [7]. | Transition-oriented workflow; retained count states here encode selected history dependence conditional on frailty. |
| reReg | Recurrent-event scale-change regression with possibly informative terminal events [4]. | Different regression and frailty assumptions; no universal accuracy or runtime ranking is implied. |
| JMbayes2 | Bayesian longitudinal and event-time joint models, prediction and validation [22]. | Richer longitudinal submodels; the present finite-path and sensitivity calculations have distinct input contracts. |
| coherent4cast | Automatic fibres, alternative frailty, finite-path and continuous targeting, evolving covariates and sparse forecasts/bounds. | Explicitly separates working-model forecasts, confidence regions and prediction sets. |
Table 1. Complementary software scopes. Statements describe documented capabilities; only the companion examples identified in the text were executed here. Absence from this table is not an assertion that another package cannot implement an extension.
For a basic execution comparison, the replication script also fits a joint Weibull gamma model to the public readmission data using frailtypack, and a terminal-event Cox model to the colon trial using survival [26]. The commands and installed versions are recorded with the outputs. Their likelihoods, baseline specifications and targets differ from the coherent4cast examples; we therefore do not compare their likelihood values as model scores or report an unmatched speed ratio.
Model and target quantities
Let index independent subjects and recurrent event types. Write for a counting process, for terminal time, for predictable measured covariates and for a retained history summary. The working intensity, conditional on a mean-one frailty, is
Here is a frailty distribution with parameter , is eligibility immediately before , is mean-one frailty with variance , is a piecewise-constant baseline, and is the complete past. A terminal intensity has its own coefficients. Eligibility is zero after the terminal event; a non-repeatable mark also becomes ineligible after its first occurrence. The package’s standard history state consists of capped prior counts. The cap changes the intensity feature, not the number of future events included in a burden reward.
At a surviving landmark and horizon , the target classes are
Here denotes the available record, is terminal risk, is expected additional type- burden, and is restricted mean time alive. Counts stop at the terminal event. These are prognostic expectations. Interpreting a coefficient as the effect of preventing a recurrence would require additional causal assumptions and a different estimand.
For an exact path, let count all eligible jumps, be the sum of log intensities excluding frailty at those jumps, and be integrated total intensity excluding frailty. For with , analytic integration yields
Here is the path’s marginal log likelihood, is the Euler gamma function and . The conditional frailty distribution is . The kernel uses integer-count recurrences and stable logarithmic evaluations to avoid cancellation near ; the zero-variance model is available explicitly. The complete derivations and identification conditions are in the methodological manuscript. They include independent subjects, predictable covariates, non-explosion, a valid observation model and sufficient retained state.
Software architecture and numerical algorithms
Figure 1 shows the separation of data contracts, numerical kernels and inferential outputs. The C++ headers do not include R headers. Thin Rcpp bridges translate objects and exceptions [9]; the R layer implements formula handling, S3 classes, case adapters, diagnostics and reporting. This design permits independent standalone kernel tests and avoids duplicating the numerical method inside plotting or data-import code.
Figure 1. Five implemented extensions and their computational dependencies. Arrows transmit data or calculations, not causal effects. Targeting and sensitivity bounds retain distinct observation experiments; every output carries its assumptions and diagnostics.
Data validation and predictable history
as_trajectory() requires a subject identifier, interval start and stop, recurrent mark, terminal indicator and declared time unit. Optional monitoring indicators identify unobserved intervals. It checks finite times, chronological grouping, overlap, event coding and absorption. Zero-length recurrence–death ties are not silently jittered. With a declared rounding resolution, the coarsening engine converts dates into event-time windows and integrates over their admissible histories. Exact fitting rejects gaps that have no observation model. Delayed entry is rejected by the current frailty fitting interface because prior selection of frailty would otherwise be omitted.
build_history() evaluates counts and recency at interval start, before the current interval’s event. Missing recency means that no earlier event is recorded; it is not replaced by a zero waiting time. The model formula cannot contain the interval endpoint or its event outcome. Subject selection must retain complete histories, and the documented missing-value option removes whole affected subjects rather than isolated rows. These checks address temporal leakage and broken risk sets, but cannot validate the scientific meaning of an input code.
The 0.10.1 interface adds the leading class rc_trajectory while retaining surv_trajectory and data.frame inheritance. An optional terminal_cause field declares the absorbing cause; it is separate from recurrent marks and censoring. Attached pattern metadata summarize what was recorded. A dataset with no repeated events does not by itself establish a single-event design, and several event labels do not prove a competing-risk structure. Eligibility, absorption and the observation experiment remain analyst declarations.
The executable replication/standards_mapping.R examples illustrate a selected CDISC ADaM time-to-event parameter and explicitly defined OMOP event concepts [20] (Clinical Data Interchange Standards Consortium 2016; Clinical Data Interchange Standards Consortium 2026). They are source-to-schema transformations, not certified adapters. For ADTTE, the analyst selects the analysis parameter, preserves its duration and censoring derivation, and maps CNSR == 0 to an event indicator. Multiple positive censoring codes must not be converted by 1 - CNSR. For OMOP, concept sets, episode rules, person linkage, observation periods and terminal ascertainment must be specified before records become event histories. Database observation is not proof of complete event ascertainment.
Automatic observation-fibre construction
With observation = "coarsened", the primary fit can call rc_coarsen_fibre() instead of requiring manually expanded paths. The user supplies event marks, windows , a follow-up endpoint and the time unit. A declared rounding unit converts a point date into a positive-width window; the program does not infer date precision. Exact point events retain counting mass, whereas interval times carry Lebesgue integration mass. Event counts and marks are assumed recorded completely within this experiment. An unobserved gap with an unknown number of events remains a different observation model.
Let contain chronological marked histories compatible with observed record . The terminal mark must be last, and nonrepeatable marks obey their eligibility rules. The likelihood and its numerical approximations are
Here is the parameter vector, the complete-history likelihood, a legal history, the product integration measure, a generated history, its integration mass and the number of generated quadrature paths or attempted importance draws. Under sampling, a rejected draw contributes zero and for proposal density . Integration weights are not normalized before likelihood calculation. Importance integration is unbiased for the likelihood when its support covers the fibre and the integrand is integrable; the log likelihood is not unbiased.
Same-mark windows require particular care. Labelled permutations can count one physical marked history repeatedly. The engine assigns each successive occurrence to the available same-mark window with earliest upper endpoint. An exchange of two feasible assignments preserves membership in interval windows and produces this canonical order. Thus overlapping same-mark windows are integrated as a union. Complete enumeration is followed by Gaussian quadrature split at window endpoints and baseline discontinuities. Exceeding max_perms or max_paths triggers seeded importance sampling, with attempted/rejected counts, effective sample size and integration MCSE retained. Enumeration removes permutation error; it does not make a general continuous-time integral analytically exact.
Likelihood, scores and legal coarsening
The low-level rc_loglik() takes expanded marked exposures and a design matrix, returning subject log likelihoods, analytic scores and observed information. coherent4cast() constructs that design, splits intervals at baseline changes and optimizes the marginal likelihood. It reports gradient magnitude, information eigenvalues, optimizer status and parameter-boundary flags. A numerical optimizer’s success code is insufficient to declare a regular fit.
For coarsened observations, generated or explicitly supplied legal complete paths and log integration weights enter rc_coarsen(). With component log likelihoods , scores and observed information , its normalized path weights give
Here indexes legal quadrature or importance paths, is an integration weight and denotes the observed record. Log-sum-exp evaluates the mixture stably. Equation (5) is the missing-information identity (Louis [19]); averaging component information alone would omit the score-variation subtraction. Integration weights are not normalized before likelihood calculation. Refining observation-fibre quadrature remains necessary when continuous event times are integrated numerically.
Ordered propagation and cumulative rewards
Conditional on one frailty value and a sufficient finite state, the generator has nonnegative off-diagonal entries and zero row sums. If , uniformization gives
Here is segment duration, is a Poisson-series index and is the identity. Uniformization replaces the matrix exponential by Poisson-weighted discrete transitions (Rao and Teh [21]). The dense rc_propagate() remains an independent small-state reference. The new rc_generator_csr() stores off-diagonal rates as compressed sparse rows. Probability row vectors and integrated rewards are updated by rc_propagate_sparse() without an intermediate matrix. For states, stored transitions and rewards, each retained Poisson term costs work and working storage is linear in edges and states. The total number of terms and duration chunks depends on rates, horizon and tolerance; no unconditional linear-time claim is made.
The implementation propagates real-arithmetic series-truncation bounds through ordered segments. Roundoff is reported separately as a diagnostic, not as interval-arithmetic certification. It uses duration chunking and explicit geometric tail inequalities; it does not claim to implement the distinct Fox–Glynn algorithm (Fox and Glynn [10]). Term and chunk budgets produce structured errors rather than silently returning an unqualified approximation.
Generators are applied in temporal order across baseline changes. A single frailty component is retained for all segments; averaging transition matrices independently at each segment would change the dependence structure. Frailty integration is performed after each component’s ordered propagation. rc_predict_paths() adds another outer mixture over explicitly supplied compatible pre-landmark histories. It rejects future paths at an earlier assessment time. No single frailty component is substituted for a posterior mixture merely because it would be easier to store.
Targeting through the primary modeling interface
The choice targeting = "finite_path" in coherent4cast() exposes the whole-path missing-at-random (MAR) experiment implemented by rc_target(). Let indicate that a finite path is recorded, be an observed stratum, a vector of target functions, and . The influence function is
Here is the observed unit and is a vector. Subjects define folds. Training-fold nuisance estimates feed one common exponential tilt; the resulting mixture law generates every target. The function returns individual EIF values, their means and variances, recording estimates, fold assignments and score convergence. Double-robust consistency and regular efficiency retain their separate nuisance and remainder conditions. Whole-path MAR does not cover arbitrary intermittent hidden events.
The option targeting = "continuous" fits a finite-state counting-process experiment with explicit right censoring. Let be the remaining conditional value of target at time and retained state , and define the jump contrast . Its observed-data influence function is
Here indexes independent subjects, the finite target vector, the recurrent marks and terminal mark , a baseline stratum, the sufficient pre-jump state, the observation-at-risk indicator, conditional censoring survival, the counting process, its full-history intensity, the target’s immediate jump reward, the assessment horizon and the population target. The jump contrast follows from the backward value equation: a jump earns its immediate reward and changes the remaining expected value. This implementation requires contiguous histories from time zero, conditionally independent right censoring within declared baseline strata, positive , and a sufficient retained state.
Subject-level folds estimate event and censoring nuisances on training subjects. On validation subjects the common fluctuation is
Here and are fold-trained nuisance estimates, is the baseline stratum, is the current value contrast, and is a targeting coefficient. After each update the algorithm recomputes values, gradients and individual EIFs. Event nuisances may use pooled or count-loglinear working intensities; censoring hazards are constant within the declared strata in the exported implementation. Time-grid refinement checks numerical interpolation error. Cross-fitting alone does not supply the nuisance product-rate, regular targeting and stochastic equicontinuity conditions required for regular asymptotic inference.
The fitted object retains one fold-stratum mixture law. Dynamic conditional prediction updates its fold weights using only the observed history through the landmark. Population target intervals use centered subject-level EIF multipliers and a maximum- critical value; bounded targets use a logit transform and nonnegative unbounded burdens use a log transform. Undefined transformed or nonregular results are flagged. These intervals are asymptotic finite-vector approximations. The population EIF is not reused as an individual-history confidence interval, and transformation alone does not establish sparse-cell coverage.
When regular inference is unavailable, observed reward envelopes provide a separate conservative fallback. Suppose for independent identically distributed units and bounded targets . Then
jointly cover with probability at least . Here is the complete target reward, its observable envelopes, its known support endpoints, the bars denote sample means and is the familywise error level. Hoeffding’s inequality [14] bounds each of the one-sided deviations by ; the union bound and establish the claim. Terminal risk uses observed death as its lower envelope and adds censoring before the horizon to its upper envelope. Restricted survival uses observed follow-up as its lower envelope and the horizon as its upper envelope when censored. This is a coarsening outer set, not a sharp sensitivity bound or a substitute EIF confidence interval. It allows informative censoring; uncapped burdens return .
For this unconditional finite-sample statement, request interval = "projection" throughout the prespecified analysis. Automatic data-dependent switching between approximate Gaussian and projection intervals does not inherit either unconditional finite-sample coverage for the combined procedure or selection-conditional coverage after its branch is chosen. The same qualification applies to the automatic zero-event fallback.
Baseline treatment effects
rc_causal() implements the static baseline binary-treatment extension in Supplement S12 of Adetunji and Adetunji [1]. Let be treatment (denoted in that supplement), baseline confounders, the potential complete history under assignment , and the recurrence-count, terminal-risk or restricted-survival reward. The intervention mean is
Here indexes the outcome coordinate and is its arm-specific backward value at baseline. Identification requires consistency and no interference, treatment exchangeability conditional on , positive treatment probabilities, and conditionally independent right censoring with positive censor survival. The package checks input support and estimated overlap; it cannot verify exchangeability. Both arms are standardized over the same empirical distribution of .
For independent subject , the estimated arm gradient follows the continuous-time targeting principle of Rytgaard, Gerds, and van der Laan [24]:
Here is the observed history, the arm probability, the observation-at-risk indicator, arm-specific censor survival, an event mark, its counting process, the retained state, its eligible intensity, the backward jump contrast and the fixed horizon. Every subject contributes the baseline-value term in both arms; the event-martingale term uses only the subject’s observed arm. Subjects without a record in an arm are therefore not dropped from its standardization population.
The treatment- and censoring-weighted update is
Here identifies the arm, the retained history with baseline part , the target coordinate, the event mark and its fluctuation coefficient; hats denote fold-trained nuisances or the current backward contrast. The positive multiplier preserves zero ineligible intensities and terminal absorption. Event, treatment and censoring nuisances are trained outside each subject’s fold. The pooled validation score determines the targeting update; the updated law is not itself described as an entirely training-fold fit.
The baseline treatment contrast retains the covariance between arms:
Here is the number of independent subjects, a subject, a target, the arm-1 minus arm-0 effect, and the covariance matrix of its estimator. rc_causal_contrast() also returns ratios and log ratios, using the delta-method gradient and positive log-scale limits for ratios.
A ratio of expected counts is a burden ratio, not a hazard ratio. Gaussian multipliers over the small joint covariance matrix give simultaneous asymptotic intervals for regular coordinates without allocating a draws-by-cohort-size matrix.
The exported implementation uses at most 30 prespecified discrete baseline strata, six recurrent marks and 128 living states. Default event nuisances are pooled or log-linear in retained counts; censor hazards are constant within arm and baseline stratum. Out-of-fold event-rate arrays can vary over the declared time grid. Treatment probabilities may be known by design or supplied as fold-by-stratum estimates. No automatic propensity clipping is used. The retained count cap summarizes state dependence; it does not truncate accumulated recurrence rewards.
Consistency of the augmented estimating function requires correct event intensities or a correct product of treatment probability and censor survival. Correct propensity alone does not repair a misspecified censor model. Efficiency and normal inference additionally require the product-rate and regularity conditions in Supplement S12. Zero-event, nonconverged or zero-variance coordinates retain their estimates and diagnostic flags but receive no regular confidence limits. The prognostic recording-sensitivity and observed-envelope intervals are not substituted for causal treatment bounds. Time-varying treatment, unmeasured treatment-confounding sensitivity and coarsened causal histories require further estimators and are outside this entry point.
Large-support sensitivity optimization
rc_bounds() takes a recorded-category distribution, a known recording fraction , complete-path target vectors and optional coarsening fibres. Recorded and missing masses satisfy a marginal recording-odds restriction with sensitivity parameter . A conditional target has the form . The Charnes–Cooper transformation sets and , so that and the objective becomes ([3]). The solver checks primal feasibility and dual agreement and returns endpoint-attaining laws. Optional recorded counts produce simultaneous binomial confidence constraints and an outer confidence projection. EIF scores do not replace these recorded-law constraints. Positive conditioning denominators, finite declared support and the known recording fraction are essential.
For large supports, rc_bounds_sparse() avoids the dense Charnes–Cooper tableau by exploiting the existing recording-odds constraints. Within a recording fibre, the linear objective can concentrate on its maximizing atom. A two-resource sorted allocation solves the resulting recorded/unrecorded mass problem. Parametric fractional iterations ([8]) supply feasible endpoint laws and reconstructible dual certificates. The outward endpoint is checked against an attained value. Work per iteration is and memory for complete atoms and recorded categories. This exact structural reduction permits arbitrary partition fibres and the implemented recorded-mass confidence boxes; it is not a generic solver for additional arbitrary cross-fibre restrictions. A conditioning denominator bounded away from zero is required for the fractional certificate. The explicitly labelled support-envelope fallback remains for a zero denominator lower bound.
Future covariate evolution
Future evolution is selected by covariate_evolution. The default "freeze" uses landmark values throughout the horizon. The option "locf" without a future schedule agrees with freeze; with newdata_future, each declared update is applied prospectively and held until the next update. Such schedules are forecast scenarios, not retrospectively imported future measurements. Generator segments split at their update times, and one frailty draw is retained across the complete ordered propagation.
For "joint_submodel", rc_covariate_model() estimates Gaussian linear random-coefficient models by ML or REML, following the longitudinal framework of Laird and Ware [18]. Prediction requires covariate_history with actual measurement times through the landmark. Repeated event-interval rows and latent quadrature times are not treated as additional biomarker measurements. For one covariate the conditional random-effect distribution is
Here is the past measurement vector for subject , and are fixed- and random-effect design matrices, the fixed coefficient vector, the random intercept and optional slope, its covariance, measurement noise, its variance, the identity and the marginal measurement covariance. These , are local mixed-model matrices, not the frailty or intensity notation in § 3. Gaussian conditioning gives the displayed distribution. Drawn future latent covariate curves are propagated and averaged; the reported Monte Carlo error is conditional on estimated submodel parameters. Independent covariate submodels, no feedback from future events and correctly specified evolution remain assumptions. This is not a jointly estimated measurement-error survival model, and it does not automatically include longitudinal parameter uncertainty.
Alternative frailty laws and diagnostics
The choice frailty = "gamma", "lognormal" or "discrete" changes the mixing distribution while retaining a mean-one scale. Gamma integration remains analytic. Lognormal integration uses Gauss–Hermite nodes with and , where is frailty and its variance. The discrete option estimates two to eight mass points and their weights. With unconstrained weight parameters and log-locations , it uses
Here is the chosen number of points, index those points, is a probability, a positive frailty value and the random frailty. The construction imposes . Estimated mass-point mixing follows the motivation of Heckman and Singer [13], but a fixed finite number of points is not an unrestricted nonparametric distribution estimator. Derivatives of weights and normalized locations enter the likelihood score and observed information; Louis’s correction integrates both path and frailty uncertainty. Near-coincident points or vanishing weights can yield nonregular fits and are not declared regular merely because the optimizer stops. Lognormal fitting doubles quadrature nodes with warm-started optimization and checks changes in individual log likelihoods and mean scores. Reaching the declared maximum without convergence marks integration unresolved. This is a numerical refinement diagnostic, not a rigorous quadrature error bound.
rc_frailty_diagnose() fits the zero-variance null and forms a nuisance-adjusted one-sided variance score. Its half-point-mass/half- reference is used only under a correctly specified regular null with an identifiable scalar variance direction, consistent with the boundary principles of Self and Liang [25]. The null nuisance fit itself must converge with full-rank positive information, small mean score and no numerical coefficient-bound contact; otherwise the diagnostic retains its statistic but reports no value. Nonunit case weights are derivative-biased nuisance correction and require fixed or exogenous weights and a valid weighted-score central limit theorem. Alternative fits retain the same weights. Gamma, lognormal and estimated discrete alternatives are nonnested or singular comparisons. The interface reports their likelihoods, parameter counts, AIC and regularity flags; it does not assign an ordinary chi-square likelihood-ratio reference to those comparisons. AIC is descriptive, particularly for nonregular mixtures; weighted objective values need not have ordinary AIC’s risk interpretation. The verification supplement gives both weighting branches.
Calibration and sparse-risk uncertainty
rc_regularize() adds one-half the log determinant of observed information to an eligible exact-history gamma likelihood. The update stays inside a positive-information domain, uses an analytic trace score and estimates penalized curvature by central differences. It is a local regularizer; automatic first-order Firth bias cancellation for this nonlinear frailty family is not asserted. rc_band() draws Gaussian parameter perturbations using a supplied sandwich covariance, evaluates the nonlinear forecast and forms simultaneous maximum- bands on the logit or identity scale. It is a frequentist approximation, not a literal posterior. Invalid draws cause a visible failure and are not clipped or replaced.
Weighted conformal inversion is supplied by rc_conformal(). It retains the candidate’s weight and handles score ties, following the weighted-exchangeability formulation of Tibshirani, Barber, Candès, and Ramdas [27]. Known weights, estimated weights and externally certified weight bands have different output labels. Estimated weights alone do not confer exact coverage. The routine inverts a supplied candidate grid; it is not a general continuous-outcome set-search engine. rc_pivot() instead inverts a model-specific exact pivot for independent uncensored terminal times with known dispersion and constant baseline. rc_cornish_fisher() implements an explicitly asymptotic quantile expansion. Their assumptions are intentionally not hidden behind a single generic confidence argument.
Using coherent4cast
The source distribution installs with a C++17 toolchain and Rcpp. Suggested packages support public-data examples, plots and vignettes. The three synthetic datasets are small and distributed with the package. The following complete example uses monthly time and an explicit assessment origin:
R> library("coherent4cast")
R> data("sim_perinatal")
R> fit <- coherent4cast(~ x, sim_perinatal, event_types = c("1", "2"),
+ time_unit = "months")
R> glance(fit)
R> one <- sim_perinatal[sim_perinatal$id == 1, ]
R> pred <- predict(fit, one, landmark = 0,
+ horizon = c(0.25, 0.5, 1), type = "all")
R> pred[, c("unit", "horizon", "target", "estimate")]
Table 2 is generated by this workflow. The three numerical domains use the same data contract, with different declared units and generating rates. Domain names are illustrative and do not imply that the simulated covariate is a clinically measured exposure or a validated engineering failure mode.
| Horizon | Terminal risk | Survival | Burden 1 | Burden 2 | Time alive |
| 0.25 | 0.0547 | 0.9453 | 0.1478 | 0.0729 | 0.2431 |
| 0.50 | 0.1062 | 0.8938 | 0.2917 | 0.1436 | 0.4729 |
| 1.00 | 0.2000 | 0.8000 | 0.5660 | 0.2774 | 0.8958 |
Table 2. Forecasts for the first synthetic perinatal subject at the assessment origin. Burdens are expected counts; restricted survival is in months.
The fitted object supports standard S3 methods, including print(), summary(), coef(), vcov() and logLik(). The additional tidy(), glance() and augment() interfaces organize coefficients, model summaries and forecasts. Predictions include target names, units and numerical diagnostics; plots preserve these labels. Audit metadata record the call, omitted units, data fingerprint and assumptions. The fingerprint is an integrity check, not a cryptographic privacy guarantee.
The 0.10.1 wrappers expose the no-frailty, exact-observation special case without changing the numerical core. rc_surv() accepts either a one-sided predictor formula with named time/status columns or a supported Surv(time, status) response. The binary status is zero for censoring and one for the event. The model is piecewise-exponential proportional hazards, using the full likelihood; it is not Cox partial-likelihood estimation. The explicit frailty="none" alias fixes frailty variance at zero in the main interface. Start–stop data require a unit identifier and contiguous observation from the origin; delayed entry remains unsupported by these wrappers.
rc_competing() fits no-frailty cause-specific hazards for declared mutually exclusive absorbing causes. It combines every fitted cause hazard in one sparse generator, returning cif_<cause>, survival, all-cause risk and rmst. Thus cumulative incidence is not obtained by treating each cause’s isolated survival complement as its probability. A declared cause with no observed events fails visibly instead of receiving a regular fitted interval. The joint sandwich covariance uses aligned subject scores; conditional CIF confidence bands are not generated automatically. Competing forecasts support frozen covariates or explicit future schedules, not a latent longitudinal submodel.
For data frames d and dc containing the declared columns, the calls are:
R> fit_s <- rc_surv(~ x, d, time = "time", status = "status",
+ unit = "id", time_unit = "years")
R> fit_c <- rc_competing(~ x, dc, time = "time", status = "cause",
+ unit = "id", causes = c("1", "2"),
+ censor_code = 0, time_unit = "years")
R> predict(fit_c, landmark = 0, horizon = 1, type = "all")
Here dc$cause uses zero for censoring and the declared labels for absorption. Forecast tables add the rc_forecast class while retaining coherent4cast_prediction; forecasts are requested through the existing predict() generic. Covariate-only prediction profiles are permitted when the analyst explicitly supplies eligible event-free profiles at the landmark; their temporary mapping intervals are not observed follow-up.
The competing-object validate() method evaluates one declared cause’s cumulative incidence. Earlier competing events are observed noncases, with censoring weights evaluated at their event times; they are not recoded as loss to follow-up. The default still requires marginal independent censoring. Externally supplied conditional censoring probabilities need the documented event-time and horizon alignment. Metrics remain held-out point estimates rather than automatic CIF confidence bands.
The executable replication/standard_regimes.R checks a two-cause example against closed-form probabilities and applies the single-event wrapper to survival’s lung data. The targeted addendum reports the numerical agreement, held-out metrics and exact data-coding choices; these examples do not add a claim of clinical or causal validation.
A finite-support sensitivity calculation has a different input contract:
R> count <- c(50, 30, 20)
R> sensitivity <- rc_bounds(count / sum(count), c(0, 0, 1),
+ kappa = 2, recording_fraction = 0.7, counts = count)
R> c(sensitivity$lower, sensitivity$upper)
R> c(sensitivity$outer$lower, sensitivity$outer$upper)
The first interval is an identification region at the empirical recorded law; the second adds sampling uncertainty. Figure 2 varies the sensitivity parameter without changing the observed counts. Its widths describe this declared experiment and should not be interpreted as a biological decomposition of uncertainty.
Figure 2. Identification bounds and simultaneous outer confidence limits in a three-atom example. The known recording fraction is 0.7. Wider sensitivity classes admit additional complete laws; sampling uncertainty is projected separately.
From event records to a field-specific report
The reusable object is an event history, not a disease or industry label. The analyst defines the independent unit, time origin, recurrent marks, absorbing endpoint, observation process and forecast horizon before fitting. predict(..., type = "all") then returns terminal risk, survival, expected recurrent counts and restricted time alive from one fitted law. Expected counts are not occurrence probabilities. Table 3 connects those outputs to a report; the companion cross-field guide gives formulas, exact field names, inputs and examples.
| Question | Native output or interface | Minimum reporting context |
| Future endpoint and burden | predict(): risk, survival, burden_*, rmst; estimate | Unit, landmark, horizon, event eligibility, time unit and covariate-evolution rule. |
| Population inference | Targeted predict(): std_error, lower, upper, interval, inference_status | Population target versus individual forecast; regularity, nuisance, censoring and selection qualifications. |
| Recording sensitivity | rc_bounds() or rc_bounds_sparse(): endpoint bounds and optional outer projection | Declared support/fibres, recording fraction, sensitivity parameter, denominator and category counts. |
| Prediction error and ranking | validate(): Brier, AUROC | Independent evaluation units, fixed horizon, observed events and censoring weights. |
| Calibration | CITL, calibration_slope, ICI | Case/control counts, calibration-fit status and local smoothing convention. |
| Threshold decisions | sensitivity, specificity, PPV, NPV, net_benefit | Prespecified threshold, weighted confusion table, censoring model and relevant decision consequences. |
| Numerical reliability | Fit convergence/information; series, mixture-compression and covariate-MC diagnostics | Numerical errors are reported separately from confidence intervals and prediction error. |
| External reporting calculations | Companion reporting functions or analyst code | Cost/utility coefficients, precision–recall convention, bootstrap scope or simulation oracle, as applicable. |
Table 3. A reporting contract for the current package. Native validation has ten metrics. Additional reporting calculations do not become package exports or empirical benefits merely by appearing in a report.
The companion replication archive also contains replication/research_metrics.R, which must be sourced explicitly. Its rc_research_report() adds censoring-weighted average pre-
cision, threshold curves, comparator net benefits and optional fixed misclassification losses; rc_value_burden() translates expected counts into an additive valuation using supplied costs. These functions are companion analysis code, not package exports. The optional independent-validation-unit bootstrap holds the trained predictor fixed, retains undefined draws and withholds intervals when its stated reporting requirements fail. It does not provide simultaneous or exact confidence coverage. Valuation reports no joint uncertainty unless the analyst supplies and propagates appropriate joint forecast draws.
In hospital research, a person can have recurrent admissions or clinically prespecified event marks before death; the report gives expected event counts, time alive and calibrated horizon risk. In trials and policy research, the same outputs can support prognostic stratification, follow-up planning or evaluation of a prespecified prediction rule; randomized origin alone does not turn these predictions into treatment-effect estimates. In economics or banking, an eligible account may have repeated delinquency events before a prespecified absorbing default, while operating assets may experience recurrent faults before irreparable failure in engineering. These are mappings of the data contract, not external bank or industrial validation. Costs, loss given default, quality-of-life weights and intervention effects require additional inputs and an appropriate study design.
Validation distinguishes probability accuracy, ranking and decision consequences. The censoring-weighted Brier score follows survival prediction-error principles ([11]); horizon AUROC concerns event cases by that horizon versus subjects still event-free ([12]). The implemented ICI is a weighted absolute difference from a local calibration curve ([2]); net benefit is a threshold-weighted true-positive/false-positive contrast ((Vickers and Elkin 2006)). None alone demonstrates causal benefit. Native validate() returns point estimates and defined/status flags, not confidence intervals. Validation-set resampling can quantify uncertainty conditional on fitted predictions; model-development uncertainty requires repeating the complete training procedure. Whole-subject splits must prevent history leakage, and evaluation must be repeated in the intended setting before operational use.
Computational verification and benchmarks
Verification has three levels. Algebraic unit tests compare derivatives with independent numerical differences and propagation with closed forms. Cross-language fixtures compare the new routines with unchanged numerical outputs from the Version 5 research implementation. Workflow tests check subject separation, observation restrictions, probability conservation, future-information exclusion and undefined metric handling. Table 4 reports actual discrepancies; small numerical differences verify implementation agreement, not statistical coverage under arbitrary laws.
| Comparison | Maximum absolute difference |
| Likelihood score vs numerical derivative | 2.37e-12 |
| Observed information vs score derivative | 3.45e-13 |
| Louis information vs score derivative | 2.81e-13 |
| Probability vs analytic propagation | 7.77e-16 |
| Reward vs analytic integral | 4.22e-15 |
| Ordered semigroup agreement | 1.67e-16 |
| Finite-path target vs Python oracle | 4.44e-16 |
| Individual EIF vs Python oracle | 2.72e-15 |
| Conditional LP endpoint vs Python oracle | 1.11e-16 |
| Outer projection vs Python oracle | 3.89e-15 |
| Observed-information penalty score vs oracle | 6.68e-15 |
Table 4. Executed numerical checks. Each row concerns its stated fixture and comparison, not a universal accuracy or coverage guarantee.
The cross-fitted fixture has 800 subjects, 13 legal paths and four target functions. The LP fixtures include conditional targets, coarsening fibres and confidence projection. They are deterministic verification examples, not new Monte Carlo coverage studies. Earlier large simulation results in the methodological archive are retained as reference evidence and are not relabelled as new package runs. Table 4–Table 5 and the five case studies preserve the measured 0.9.1 predecessor results; new 0.10.0 verification is reported separately below. The companion script records source hashes before performance measurement.
| Subjects | History (s) | Score (s) | Core fit (s) | Peak GB |
| 1,000 | <0.01 | <0.01 | 0.030 | 0.171 |
| 10,000 | <0.01 | 0.030 | 0.320 | 0.156 |
| 50,000 | <0.01 | 0.150 | 1.660 | 0.234 |
| 250,000 | 0.030 | 0.720 | 8.110 | 0.771 |
Table 5. Median elapsed seconds from five repeated runs at each sample size. History preparation, a likelihood-and-score evaluation and a four-parameter core fit are distinct operations. Memory is peak working set of a fresh process including preparation. An elapsed value below timer resolution is reported as a bound. These are workload measurements on the stated host; they are not timings for all high-level data transformations or arbitrary model sizes.
The performance protocol fixes four sample sizes and five repetitions per size. It times history construction, likelihood-and-score evaluation, and low-level optimization separately. Larger workloads repeat a fixed synthetic history template under distinct unit identifiers; these are computational workloads, not independent Monte Carlo cohorts. The benchmark model has a fixed small coefficient dimension, so its timings should not be extrapolated to a growing-dimensional history design. A separate high-level fit includes R data preparation. The measured machine is an AMD Ryzen 9 3900X with 12 physical cores and 24 logical processors, running Windows 11; the timed numerical workload uses one thread. Table 5 reports medians and Figure 3 displays scaling. Process memory includes preparation and is measured separately from model object size.
Figure 3. Measured elapsed time under the frozen benchmark protocol. Lines connect five-run medians for the specified workload; they are not complexity proofs or comparisons of unmatched statistical models.
The protocol’s two-second and 45-second objectives are evaluated against the matching measured operation, not against a conveniently shorter kernel. The same model’s independent R implementation provides a numerical reference. Companion-package fits are reported only as executable examples because their statistical specifications differ. Five-, 15- and 30-node gamma quadrature calculations quantify sensitivity to integration resolution; agreement at one profile does not certify a uniform quadrature bound. The executed high-level fit at 1000 subjects had a median elapsed time of 1.66 seconds. Larger high-level fits were not timed under this protocol, so the 45-second objective for a full 250,000-subject workflow remains unverified. The small core fit and process-memory measurements must not be substituted for that missing comparison. Five-node gamma quadrature differed from the 30-node reference by at most across the tested coordinates, exceeding the registered tolerance. Fifteen nodes gave a maximum difference of . The default remains 30 nodes; this profile-specific comparison does not certify a uniform integration bound.
Verification of the five extensions
Table 6 distinguishes implementation agreement, numerical integration diagnostics and empirical inferential validation. The automatic fibre generator retained all 929 colon participants and five same-day pairs, producing the same 7,447 paths as the specialized predecessor adapter. Two overlapping same-mark windows were also checked against a direct union integral to detect permutation double counting. In a deliberately large-order fibre, 200 independent importance integrations with 2,000 attempted draws each had empirical standard deviation 0.1513 and mean reported MCSE 0.1502. This diagnostic correctly reveals material integration noise at that budget; it is not confidence coverage for a statistical estimand.
| Module | Recorded comparison or diagnostic | Result |
| Automatic fibres | 929 colon subjects; log likelihood vs specialized adapter | |
| Louis information | Generated paths vs specialized adapter | |
| Sparse bounds | 80 independent HiGHS problems; maximum endpoint difference | |
| Large-support bounds | 50,000 atoms; fractional certificate gap | |
| CSR propagation | 50,000 states; probability series bound | |
| Continuous targeting | Individual EIF vs unchanged V5 oracle | |
| Future schedule | Ordered forecast vs analytic oracle | |
| Lognormal frailty | 40-node log likelihood vs adaptive integration |
Table 6. New 0.10.0 verification. Differences measure numerical agreement; series bounds concern real-arithmetic truncation. They are distinct from empirical confidence coverage.
The large-support solver agreed with 80 independent SciPy/HiGHS Charnes–Cooper problems. Three of these were feasible boxes that the old dense solver had classified as infeasible; the new reduction and independent oracle agreed. Sparse scale checks reached 50,000 atoms and 50,000 states. These deterministic instances establish execution at the declared size, not universal speed across graphs. On this machine, the native 50,000-state calculation used an estimated 4.40 MB workspace and 15 Poisson terms. The end-to-end R bound-plus-projection call at 50,000 atoms took 0.06 seconds in the recorded run; compilation and unrelated data preparation are excluded.
The scheduled-covariate forecast agreed with a closed-form ordered-intensity calculation to . In a Gaussian future-covariate example with 500 common random-effect draws, terminal-risk estimates at grids of 8, 16 and 32 intervals were 0.17273, 0.17339 and 0.17373. Their conditional Monte Carlo standard errors were 0.00088, 0.00089 and 0.00090. Grid refinement and Monte Carlo integration are separate error sources; neither is a confidence interval for the fitted model. At 40 lognormal quadrature nodes, a fixed-parameter log likelihood differed from adaptive numerical integration by .
The separately registered targeting experiment generated 5,000 cohorts in each of four cells: sample sizes 250 and 1,000 crossed with ordinary and sparse event rates. Histories were generated by a history-dependent finite-state law without latent frailty; the fitted event nuisance was pooled and censoring nuisance estimated by baseline stratum. The four simultaneous targets were two recurrent burdens, terminal risk and restricted survival. All 20,000 generated cohorts remain in the denominators, including unsuccessful score or positive-variance checks. No execution exception occurred.
Transformed intervals approached nominal coverage in the ordinary cells but did not repair the sparse-event failures (Table 7 and Figure 4). At 250 sparse subjects, simultaneous coverage was 0.5942 rather than 0.95; at 1,000 it was 0.9254. The simulation therefore supports a qualified regular-regime interface, not universal sparse-cell validity. The public API now withholds regular Gaussian limits when a target has an observed zero-event boundary. This diagnostic is additional to the preserved raw comparison and is not retrospectively scored as improved coverage.
| Regime | Subjects | Raw Wald | Transformed Gaussian | Numerical success |
| Ordinary | 250 | 0.9314 (0.0036) | 0.9510 (0.0031) | 5000/5000 |
| Ordinary | 1000 | 0.9460 (0.0032) | 0.9516 (0.0030) | 5000/5000 |
| Sparse | 250 | 0.5582 (0.0070) | 0.5942 (0.0069) | 4773/5000 |
| Sparse | 1000 | 0.8612 (0.0049) | 0.9254 (0.0037) | 4972/5000 |
Table 7. Simultaneous coverage in the registered 0.10.0 validation. Parentheses give binomial Monte Carlo standard errors. Raw comparisons precede the public zero-event regularity guard; all 5,000 cohorts per cell are retained.
Figure 4. Registered simultaneous-coverage comparison. Error bars are 1.96 Monte Carlo standard errors; the dashed line is the 0.95 nominal level. Sparse failures remain visible.
The public fallback uses observed lower and upper reward envelopes under censoring. For a target with known support, Hoeffding inequalities and a union bound give a simultaneous conservative outer confidence set; this argument requires independent identically distributed units but does not require independent censoring. Terminal-event indicators and restricted survival have such bounds. Uncapped burdens receive the uninformative outer support , rather than a fabricated finite upper limit. The output is labelled bounded_coarsening_projection; it is distinct from the sharp finite-support sensitivity solver and does not recover point identification. Explicit Gaussian requests at a zero-event boundary remain unavailable. For the stated finite-sample guarantee, request interval = "projection" uniformly. Data-dependent automatic switching between approximate Gaussian and projection intervals has neither the unconditional guarantee of the projection-only procedure nor a selection-conditional guarantee from this argument. Numerical integration tolerances, MCSE and confidence coverage remain separate diagnostics. A separately registered envelope experiment generated 5,000 cohorts under each of complete observation, independent censoring and informative censoring. Joint coverage of the bounded coordinates was 0.9992, 1.0000 and 1.0000, respectively. The first estimate has MCSE 0.00040; the two all-covered cells have binomial Monte Carlo lower limits 0.99926, rather than evidence of literal certainty. Median risk widths were 0.2960, 0.6380 and 0.6480, and restricted-survival widths were 0.2406, 0.4291 and 0.4329. These conservative sets trade precision for weaker observation assumptions. The 15,000-cohort check does not replace or retrospectively repair the separate 20,000-cohort Gaussian experiment.
| Case | Time unit | Risk | Burden 1 | Burden 2 | Time alive |
| Perinatal (synthetic) | months | 0.177 | 0.610 | 0.261 | 0.907 |
| Oncology (synthetic) | years | 0.231 | 0.525 | 0.208 | 0.880 |
| Equipment (synthetic) | operating hours | 0.090 | 0.615 | 0.253 | 0.955 |
| Readmission | years | 0.087 | 0.316 | – | 0.951 |
| Colon trial | years | 0.136 | 0.143 | – | 0.929 |
Table 9. Mean held-out forecasts at a duration of one stated time unit. Burden is an expected count; time alive is measured in the indicated unit. A dash denotes an event type absent from that case, not an estimated zero.
Reproducible case studies
Each case records data provenance, an estimand, a forecast summary, held-out validation and a limitation. Table 8 summarizes the fitted samples and diagnostics. The real-data adapters obtain records from their canonical source packages. The software source distribution contains only synthetic records and test fixtures; aggregate case results are sufficient for the manuscript. Figure 5 shows the generated forecast summaries, with time units and eligibility carried from each analysis.
| Case | Subjects | Recurrences | Terminal | Frailty variance | Status |
| Perinatal (synthetic) | 160 | 335 | 59 | 0.485 | converged |
| Oncology (synthetic) | 160 | 248 | 68 | 0.398 | converged |
| Equipment (synthetic) | 160 | 398 | 41 | 0.618 | converged |
| Readmission | 403 | 458 | 109 | 0.751 | converged |
| Colon trial | 929 | 468 | 452 | 0.693 | converged |
Table 8. Full-data case fits. Event counts are source events, not the number of interval rows or quadrature paths. All figures and validation statistics retain the declared observation model.
Figure 5. Common-law forecasts in the five case studies. Curves summarize the generated examples under their stated history and observation specifications. They are prognostic model outputs, not intervention effects. Synthetic cases are explicitly labelled.
Synthetic perinatal histories
The perinatal example contains two recurrent marks and one absorbing endpoint on a monthly scale. Its generating law has shared gamma frailty and capped-count feedback. The applied interpretation is expected additional morbidity episodes and terminal risk over a defined follow-up window, while the data themselves remain simulated rather than maternal records. The forecast table reports all target types from one fitted law. Held-out Brier score and discrimination demonstrate the validation interface; their values in Table 11 concern this generating mechanism only. The marks are deliberately generic and do not establish a clinical sequence between distinct diseases.
| Case | Eligible | Events | Brier | AUROC | CITL | Slope |
| Perinatal (synthetic) | 31 | 3 | 0.114 | 0.379 | -0.611 | -2.058 |
| Oncology (synthetic) | 30 | 6 | 0.135 | 0.701 | -0.196 | 1.811 |
| Equipment (synthetic) | 28 | 2 | 0.075 | 0.557 | -0.016 | -1.401 |
| Readmission | 65 | 6 | 0.066 | 0.743 | 0.170 | 0.733 |
| Colon trial | 173 | 21 | 0.069 | 0.871 | -0.176 | 1.278 |
Table 11. Held-out terminal-risk validation. Every fifth sorted subject identifier is held out; remaining subjects train the model. These small deterministic splits illustrate the workflow and are not external validation. The synthetic perinatal discrimination result is retained despite its low AUROC.
CITL denotes calibration-in-the-large. Forecast duration is one stated time unit; landmarks and censoring assumptions are recorded in the accompanying metrics file. Censoring weights use the marginal Kaplan–Meier estimate. Few observed events make discrimination and calibration imprecise.
Synthetic oncology histories
The oncology demonstration uses years and a different event-rate configuration. It distinguishes recurrent episodes from terminal risk and restricted time alive. The same schema and function calls apply without renaming the mathematical targets. Validation is performed on held-out subjects rather than repeated records from the training subjects. This example Line: mean predicted risk Shade: between-subject interquartile range
Shading is not a confidence band. Forecasts use held-out eligible subjects.
demonstrates transfer of the interface to a different time scale and intensity configuration; it does not establish transportability to a cancer population or identify a treatment effect.
Synthetic equipment histories
The robotics demonstration uses operating hours and recurrent repair-type marks before terminal failure. Expected burden is an expected repair count, and restricted survival is expected operating time before terminal failure within the horizon. This change of interpretation leaves the probability calculation unchanged. A held-out Brier score for terminal failure is reported with the same censoring convention. Real engineering deployment would require a scientifically adequate state, observation model and validation design; generic synthetic labels do not supply those requirements.
Colorectal readmission cohort
The readmission data distributed by frailtypack contain postoperative rehospitalization intervals and a terminal death indicator. rc_readmission() preserves the recurrent episodes and uses the first recorded covariate values for its baseline example; later Charlson values remain available as recorded fields rather than being moved backward in time. Its targets are expected future admissions, death risk and restricted survival. Readmission is a utilization endpoint, not a collection of distinct disease-type marks. The held-out metrics are descriptive internal validation. The public dataset’s observation scheme and limited covariates do not establish complete capture of care outside the observed system.
The new frailty sensitivity fit uses one common readmission design for all three families (Table 10). All three reported fits met their regularity diagnostics. The fitted lognormal model had the smallest AIC in this analysis. The shared zero-variance score statistic was approximately 29.66, with a one-sided boundary-reference value of . This is evidence against the specified no-frailty null, not a test that the preferred mixing distribution is true. The analysis is separate from the predecessor example and retains its own session and fitted objects.
| Frailty | Log likelihood | AIC | Variance | Regular fit |
| gamma | -870.60 | 1775.20 | 1.012 | yes |
| lognormal | -861.76 | 1757.51 | 1.827 | yes |
| discrete | -881.08 | 1798.16 | 0.929 | yes |
Table 10. Revision readmission sensitivity analysis on 403 subjects under a common design and observation scheme. The discrete model has two estimated mass points. AIC compares the fitted working distributions descriptively; no nonnested chi-square test is used.
The lognormal comparison uses the refined fit, not its preliminary 40-node optimizer result. Doubling from 320 to 640 nodes changed individual log likelihoods by at most and mean score components by at most . Earlier refinements failed the declared tolerance and remain in the audit table. Optimizer convergence is therefore not treated as evidence that the mixing integral has converged.
Colon trial with day-coarsened event times
The colon data in survival provide paired recurrence and death outcomes from a randomized adjuvant-treatment trial. The adapter retains all participants and treats recurrence as a non-repeatable mark. The revised automatic generator and the specialized adapter integrate a same-day recurrence and death over the legal region , where is the recorded day. This convention preserves both events; it does not recover their actual within-day times. Integration intervals are split at baseline discontinuities. The application compares the binary node4 covariate with continuous nodes, with missing-value handling stated in the adapter metadata, and checks quadrature refinement.
The trial’s randomized origin does not make these fitted prognostic contrasts causal estimates. The likelihood and forecast still depend on baseline, frailty, observation and eligibility specifications. A forecast at an earlier landmark uses only a pre-landmark fibre. The full-follow-up quadrature paths used to fit the model cannot be reused as if they were already observed at that earlier time. Table 11 and the supplementary output files report validation, convergence and sensitivity diagnostics without excluding difficult fits from their denominators.
A baseline-treatment causal workflow
The companion causal/run_causal.R generates 1,600 synthetic subjects with one observed binary baseline confounder, two recurrent event types, one absorbing event and right censoring. Baseline treatment probability is 0.3 or 0.7 according to the confounder. Event intensities depend on treatment, confounder and retained recurrence counts. Treatment and event generation are explicit; consistency and exchangeability hold by construction. This is an implementation example, not an empirical intervention study.
R> causal_fit <- rc_causal(~x, d, treatment = "treatment",
+ horizon = 1, censor = "censored", time_unit = "years",
+ event_types = c("1", "2"),
+ spec = list(history_cap = 1L, grid = 64L), seed = 81)
R> rc_causal_contrast(causal_fit)
R> rc_causal_contrast(causal_fit, "ratio")
R> rc_audit_report(causal_fit, format = "json")
Here d is the generated start–stop dataset, x the observed confounder and treatment the fixed baseline assignment. The function estimates treatment probabilities within training folds. A known randomized allocation can instead be declared with propensity = 0.5. Terminal events stop both recurrent processes. Baseline confounders and the treatment column are explicit inputs, not inferred from the outcome marks. The maximum absolute mean score is , and doubling the time grid from 64 to 128 changes a contrast by at most . A separate analytic exponential example agrees with the treatment-weighted native EIF to ; setting treatment probability to one reproduces the unchanged prognostic kernel exactly. These are numerical checks, not sampling-coverage guarantees. The supplied remainder check independently simulates one million subjects in each of four nuisance configurations, sharing one generated dataset. When both event and weighting nuisances are misspecified, the observed bias is 0.06987 versus the analytic product remainder 0.07020 (Monte Carlo standard error 0.00044). The all-correct, event-correct and weight-
| Target | Arm 0 | Arm 1 | Difference | Pointwise 95% CI | Oracle difference |
| Type-1 burden | 0.7088 | 0.5659 | -0.1429 | [-0.2423, -0.0435] | -0.1989 |
| Type-2 burden | 0.3113 | 0.3471 | 0.0358 | [-0.0368, 0.1084] | 0.0517 |
| Terminal risk | 0.4078 | 0.3487 | -0.0591 | [-0.1157, -0.0024] | -0.0777 |
| Time alive (years) | 0.7922 | 0.8173 | 0.0250 | [-0.0095, 0.0596] | 0.0439 |
caption: Synthetic baseline-treatment example. Both arms are standardized over the same cohort. Intervals are influence-function normal approximations. The population oracle averages equally over the two confounder strata and is calculated independently by a dense matrix exponential; sampling variation in both baseline composition and outcomes remains in the estimates.
:::
product-correct discrepancies are each below one Monte Carlo standard error. All configurations and numerical outputs are retained; this verifies the stated identity in that design without claiming universal empirical efficiency.
Validation and reproducibility
validate() evaluates supplied held-out risks at an explicit horizon. Cases have a terminal event by the horizon and controls remain observed beyond it. Inverse probabilities of censoring weight the Brier score, AUROC and threshold table. The default Kaplan–Meier censoring estimate requires marginal independent censoring; analysts may instead supply justified conditional censoring probabilities. The function does not estimate such a conditional model automatically.
Calibration-in-the-large is estimated as a logistic intercept with predicted log odds as an offset; a separate slope summarizes their multiplier. The integrated calibration index uses a weighted smooth of observed outcome against predicted risk. Sensitivity, specificity, positive and negative predictive values, and net benefit share a threshold-specific weighted table. Undefined quantities remain labelled rather than being replaced by zeros. These statistics quantify different properties: AUROC does not establish calibration, a Brier improvement does not establish clinical benefit, and an internal held-out estimate does not replace external validation.
The companion code.R entry point reconstructs the manuscript tables and figures from package calculations and the supplied recorded experiment outputs. Its default mode reproduces the article from these outputs; separate fresh-fit and experiment scripts rerun the underlying analyses. It also records session information, source hashes and expected outputs. Runtime and memory are inherently machine dependent; deterministic numerical outputs and tolerances are checked separately. The source distribution includes tutorials, help pages, structured errors and a test suite. Revision checks record their own version and runtime rather than inheriting a predecessor check result. Standalone C++ tests use strict compiler warnings. The supplied check records identify the source revision, platform, compiler and executed tests.
Before the causal addition, the 0.10.1 source archive passed the recorded Windows R CMD check runs with R 4.6.2 and R-devel 4.7.0, using --as-cran --no-manual: zero errors, warnings and notes in each run. A fresh Windows binary installation passed 1,107 test expectations with no failures, warnings or skips. Combined R/C++ line coverage was 95.46236% (2,777 of 2,909 executable lines), without file exclusions. Six standalone C++17 fixtures passed strict compiler checks, and all 23 native source/header/Makevars files matched the preserved 0.10.0 version. These are version-specific computational checks; source-line coverage is distinct from statistical confidence coverage. Hosted R-release and R-devel checks also completed on Linux, macOS and Windows, with 1,107 passing expectations per job and no errors, warnings or notes. Four Linux native jobs passed GCC/Clang strict builds, with and without AddressSanitizer/UndefinedBehaviorSanitizer. The companion check records retain the tested source revision and logs.
The preceding version 0.10.1 causal revision passed a fresh full R CMD check –as-cran under Windows R-devel: 0 errors, 0 warnings and the expected new-submission note. All 1,187 test expectations, five vignettes, examples, and PDF/HTML manual checks passed. Six additional Linux, macOS and Windows jobs passed under R-release and R-devel. All seven standalone native fixtures also passed four GCC/Clang builds, with and without AddressSanitizer and UndefinedBehaviorSanitizer. These checks include the added causal kernel. The submitted archive hash and the tested source commit are recorded in the accompanying check manifest.
The replication materials provide software source, commented scripts, recorded outputs, seeds and session information [16]. Source code is distributed under GPL-3 in the public repository https://github.com/setrojalab/coherent4cast. Installation instructions and documentation are available at https://setrojalab.github.io/coherent4cast/. The release links the source archive, reference manual, article sources and computational supplement. The renamed source archive is supplied for CRAN review; it supersedes the pending submission under the earlier package name. CRAN acceptance is not implied by the availability of a source archive. The same materials accompany the journal submission.
For a version-pinned source installation, use:
remotes::install_github("setrojalab/coherent4cast", subdir = "package",
ref = "main", dependencies = NA, upgrade = "never")
Source installation requires the declared R dependencies and a C++17 toolchain; Windows users require the Rtools version appropriate to their R installation. Installation of the supplied source archive also provides the five prebuilt vignettes.
Audit export, offline execution and study governance
rc_audit_report() exports a list, JSON or text report from a fitted object, optionally summarizing numerical diagnostics from predictions and hashing explicitly supplied source files. SHA-256 fingerprints of version-3 R serialization identify the captured data object; source-file fingerprints identify file bytes. Capture-time/session metadata and report-export metadata are distinguished. Legacy MD5 fingerprints remain labelled for compatibility. A hash establishes an integrity comparison for its stated representation, not data anonymity, a digital signature, immutable storage or regulatory approval.
The model and prediction routines can run offline with a suitable installed R environment, the compiled package and its open-source dependencies. Preparing that environment and obtaining optional datasets are separate steps. Reproducible installation instructions and machine checks support an analyst’s validation record; they do not certify an institution’s operating environment.
ICH E9(R1) asks trial analyses to align with a defined treatment-effect estimand and its intercurrent-event strategy (International Council for Harmonisation [15]). The prognostic APIs do not automatically identify such effects. The separate baseline-treatment interface provides the estimands and assumptions in § 4.6; it does not select an intercurrent-event strategy for the analyst. A submission analysis still needs its protocol, estimand, prespecified analysis, sensitivity strategy, source traceability and fit-for-purpose validation. Schema mappings, software hashes and offline execution do not constitute regulatory qualification. Platform status is reported from executed logs. The targeted addendum and supplied check records distinguish the completed 0.10.1 platform and sanitizer runs from inherited 0.10.0 evidence.
Discussion and development scope
coherent4cast provides a common interface for event-history likelihoods and forecasts while exposing separate observation experiments for targeting, sensitivity inference and prediction calibration. Its main practical benefit is traceability: an analyst can inspect which histories were admitted, which constraints define a bound, which subject contributed an influence-function value, and which numerical approximation produced a forecast. The benchmark and examples demonstrate these computations without interpreting machine precision as empirical validity.
The five engineering requests are implemented as explicit modules. Automatic fibres remove manual order enumeration for the declared complete-count timing experiment. CSR propagation removes dense transition storage, and structural optimization handles large supports for the specified recording constraints. Finite-path and continuous-time targeting are exposed in the main API. Future covariates can follow schedules or estimated Gaussian submodels. Alternative frailty laws and boundary diagnostics make distributional sensitivity inspectable. Their statistical conditions remain consequential. An automatic timing fibre does not reconstruct an unknown number of hidden events. Sparse storage does not make an insufficient retained state Markov. Logit transformation does not guarantee sparse finite-sample coverage. Gaussian evolution requires its own measurement and feedback assumptions, and finite mass-point fits can be nonregular. These boundaries are attached to the relevant outputs so that the analyst can assess applicability rather than infer a guarantee from a function name.
Future work includes richer censoring and longitudinal nuisance models, additional observation adapters and separately verified language interfaces. Cost and quality-of-life valuation require explicit reward definitions. Static baseline treatment contrasts are implemented through rc_causal(). Time-varying policies, preventable fractions and treatment recommendations require additional causal estimands and identification beyond that static extension. New features should retain their own observation contract, independent oracle and validation evidence.
A possible four-package organization is recorded as a development roadmap, not four released packages. coherent4cast would retain event-history likelihoods, common-law forecasting and the shared numerical core; recurbounds would concentrate compatibility sets and sensitivity inference; recurcausal could extend the implemented static baseline-treatment interface to separately justified longitudinal policies; and recurmetrics would organize validation, calibration and decision reporting. In 0.10.1 these names do not split the repository or create new dependencies. The implemented sensitivity and validation interfaces remain in coherent4cast; the additional reporting script remains explicitly sourced companion code. Any later separation must preserve contracts, numerical equivalence, dependency direction and independent tests. The downstream package names remain proposed; the baseline-treatment causal capability described here is implemented in coherent4cast.
Computational details
Package name and version. The software is distributed as coherent4cast version 0.10.2; earlier development releases used the name recurcast. This revision changes the package identity and registration, documentation and links while retaining the numerical kernels. Historical benchmarks describe the same numerical methods. New code uses library(coherent4cast) and coherent4cast(); the earlier fitting and control function names remain compatibility aliases.
The software version described here is 0.10.2; this manuscript was revised on 24 November 2026. The predecessor benchmark and five-case outputs retain their original snapshot 0.9.0.9000 and candidate 0.9.1 provenance under R 4.4.2 UCRT and GCC 14.3 on Windows 11. The 0.10.0 module validations retain their original provenance; the targeted 0.10.1 API checks have a separate record. A C++17 core, GPL-3 source license, LaTeX sources, bibliography, executed causal vignette and generated figures accompany the materials. Recorded results are version-labelled; the original experiment outputs are retained alongside the current interface checks.
Data availability and ethics
The three bundled example datasets are simulated and include generating parameters and seeds. The two clinical examples use data already distributed by the frailtypack and survival packages, loaded through their documented interfaces. The causal example generates an additional synthetic cohort. The additional survival-wrapper example uses survival::lung; it is a worked API example, not an external validation cohort. No new participants were recruited. The analyses use the public example datasets as distributed by their source packages; no institutional ethics determination is asserted here. Patient-level clinical records are excluded from the software repository materials.
Funding and competing interests
The authors report no funding and no competing interests.
Affiliation:
Sunday A. Adetunji Department of Biostatistics and Epidemiology College of Health, Oregon State University Corvallis, OR, USA Corresponding author: [email protected]
Oluwatimileyin A. Adetunji Department of Economics College of Management and Social Sciences, Bowen University Iwo, Osun State, Nigeria E-mail: [email protected]
References
- [1]Adetunji SA, Adetunji OA (2026). “Coherent Survival Modelling and Dynamic Forecasting of History-Dependent Multitype Recurrent Events and Terminal Risk Under Incomplete Observation.” Unpublished methodological manuscript, Version 13, with Supplement S12.
- [2]Austin PC, Steyerberg EW (2019). “The Integrated Calibration Index (ICI) and Related Metrics for Quantifying the Calibration of Logistic Regression Models.” Statistics in Medicine, 38(21), 4051–4065. doi:10.1002/sim.8281.DOI
- [3]Charnes A, Cooper WW (1962). “Programming with Linear Fractional Functionals.” Naval Research Logistics Quarterly, 9(3–4), 181–186. doi:10.1002/nav.3800090303.DOI
- [4]Chiou SH, Xu G, Yan J, Huang CY (2023). “Regression Modeling for Recurrent Events Possibly with an Informative Terminal Event Using R Package reReg.” Journal of Statistical Software, 105(5), 1–34. doi:10.18637/jss.v105.i05.DOI
- [7]de Wreede LC, Fiocco M, Putter H (2011). “mstate: An R Package for the Analysis of Competing Risks and Multi-State Models.” Journal of Statistical Software, 38(7), 1–30. doi:10.18637/jss.v038.i07.DOI
- [8]Dinkelbach W (1967). “On Nonlinear Fractional Programming.” Management Science, 13(7), 492–498. doi:10.1287/mnsc.13.7.492.DOI
- [9]Eddelbuettel D, François R (2011). “Rcpp: Seamless R and C++ Integration.” Journal of Statistical Software, 40(8), 1–18. doi:10.18637/jss.v040.i08.
- [10]Fox BL, Glynn PW (1988). “Computing Poisson Probabilities.” Communications of the ACM, 31(4), 440–445. doi:10.1145/42404.42409.DOI
- [11]Graf E, Schmoor C, Sauerbrei W, Schumacher M (1999). “Assessment and Comparison of Prognostic Classification Schemes for Survival Data.” Statistics in Medicine, 18(17–18), 2529–2545. doi:10.1002/(SICI)1097-0258(19990915/30)18:17/18<2529::AID-SIM274>3.0.CO;2-5.doi.org/10.1002/(sici)1097-0258(19990915/30)18:17/18<2529::aid-sim274>3.0.co;2-5
- [12]Heagerty PJ, Lumley T, Pepe MS (2000). “Time-Dependent ROC Curves for Censored Survival Data and a Diagnostic Marker.” Biometrics, 56(2), 337–344. doi:10.1111/j.0006-341X.2000.00337.x.DOI
- [13]Heckman JJ, Singer B (1984). “A Method for Minimizing the Impact of Distributional Assumptions in Econometric Models for Duration Data.” Econometrica, 52(2), 271–320. doi:10.2307/1911491.DOI
- [14]Hoeffding W (1963). “Probability Inequalities for Sums of Bounded Random Variables.” Journal of the American Statistical Association, 58(301), 13–30. doi:10.1080/01621459.1963.10500830.DOI
- [15]International Council for Harmonisation (2019). E9(R1): Addendum on Estimands and Sensitivity Analysis in Clinical Trials. Final guideline adopted November 20, 2019, URL https://database.ich.org/sites/default/files/E9-R1_Step4_Guideline_2019_1203.pdf.
- [17]Król A, Mauguen A, Mazroui Y, Laurent A, Michiels S, Rondeau V (2017). “Tutorial in Joint Modeling and Prediction: A Statistical Software for Correlated Longitudinal Outcomes, Recurrent Events and a Terminal Event.” Journal of Statistical Software, 81(3), 1–52. doi:10.18637/jss.v081.i03.DOI
- [18]Laird NM, Ware JH (1982). “Random-Effects Models for Longitudinal Data.” Biometrics, 38(4), 963–974. doi:10.2307/2529876.DOI
- [19]Louis TA (1982). “Finding the Observed Information Matrix When Using the EM Algorithm.” Journal of the Royal Statistical Society B, 44(2), 226–233. doi:10.1111/j.2517-6161.1982.tb01203.x.DOI
- [20]Observational Health Data Sciences and Informatics (2026). OMOP Common Data Model, Version 5.4. Version-specific specification; accessed November 23, 2026, URL https://ohdsi.github.io/CommonDataModel/cdm54.html.
- [21]Rao V, Teh YW (2013). “Fast MCMC Sampling for Markov Jump Processes and Extensions.” Journal of Machine Learning Research, 14(103), 3295–3320. URL https://www.jmlr.org/papers/v14/rao13a.html.arxiv.org/abs/1208.4818
- [22]Rizopoulos D, Miranda-Afonso P, Papageorgiou G (2026). JMbayes2: Extended Joint Models for Longitudinal and Time-to-Event Data. Package documentation, version 0.6-6, URL https://cran.r-project.org/web/packages/JMbayes2/refman/JMbayes2.html.
- [23]Rondeau V, Mazroui Y, Gonzalez JR (2012). “frailtypack: An R Package for the Analysis of Correlated Survival Data with Frailty Models Using Penalized Likelihood Estimation or Parametrical Estimation.” Journal of Statistical Software, 47(4), 1–28. doi:10.18637/jss.v047.i04.DOI
- [24]Rytgaard HC, Gerds TA, van der Laan MJ (2022). “Continuous-time targeted minimum loss-based estimation of intervention-specific mean outcomes.” The Annals of Statistics, 50(5), 2469–2491. doi:10.1214/21-AOS2114.DOI
- [25]Self SG, Liang KY (1987). “Asymptotic Properties of Maximum Likelihood Estimators and Likelihood Ratio Tests under Nonstandard Conditions.” Journal of the American Statistical Association, 82(398), 605–610. doi:10.1080/01621459.1987.10478472.DOI
- [26]Therneau TM (2026). survival: A Package for Survival Analysis in R. URL https://CRAN.R-project.org/package=survival.
- [27]Tibshirani RJ, Barber RF, Candès EJ, Ramdas A (2019). “Conformal Prediction Under Covariate Shift.” In Advances in Neural Information Processing Systems, volume 32. URL https://proceedings.neurips.cc/paper_files/paper/2019/hash/8fb21ee7a2207526da55a679f0332de2-Abstract.html.arxiv.org/abs/1904.06019




