Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR prepares bmstate 0.4.0, a correctness-focused minor release addressing statistical, prediction, numerical, pharmacokinetic, and performance issues found during a package audit.
The most consequential defect placed the empirical baseline-hazard prior location on the wrong scale. Other fixes affect joint posterior-draw alignment, spline identifiability, transition-probability prediction, state-visit probabilities, path simulation, and PK calculations.
Rerun requirement
Fits and experiments produced with affected bmstate versions must be rerun before their numerical results are reported or cited.
The main reasons are:
For example, a natural-scale reference rate of
0.001was previously used as the location oflog_w0, centering the conditional median hazard nearexp(0.001) = 1.001rather than0.001. This was a real scale error, not merely a misleading variable name.Statistical and prediction corrections
Correct the baseline-hazard prior scale. The public R API stores positive natural-scale reference rates, whereas Stan models the baseline intercept on the log-hazard scale. Stan-data construction now applies
log()exactly once at the R–Stan boundary, and the data field is renamed frommu_w0tomu_log_w0.Make empirical hazard calibration explicit. The former Cox/Breslow-based summary could silently omit transitions with no events and then average transition-specific log rates within a transition type. Calibration now pools observed event counts and exact at-risk time within transition type and uses the resulting count/person-time rate as the natural-scale prior reference location. It is documented as a reference rate, not an arithmetic prior mean.
Reject unsupported transitions before fitting. Every transition retained in a non-PK-only hazard model must have at least one observed occurrence and positive at-risk time. Validation now stops before Stan is called and names the affected transitions. There is no half-event regularization or prior-only estimation of an unobserved transition.
Keep prediction-data validation separate from fitting. Out-of-sample subjects need not experience or be at risk for every transition represented by the already fitted model. Generic Stan-data construction therefore permits absent transition rows for prediction, while
fit_stan()applies the stricter support validation before fitting. Stan fitting retains positive event and risk counts and contains no zero-count likelihood branches.Preserve joint posterior-draw alignment. Baseline-hazard arrays were previously repeated in a different draw/subject order from hazard multipliers and prediction metadata. This could combine spline coefficients and intercepts from one posterior draw with covariate effects from another. All prediction inputs now use one explicit draw-major ordering.
Return explicit zero state-visit probabilities.
p_state_visit()previously constructed results only from observed event rows, silently omitting requested subjects or groups with no visit to an event state. It now completes the state-by-group grid, computes denominators separately, and returns explicit zero counts and probabilities.Separate spline shape from baseline level. Because the intercept-containing B-spline basis partitions unity, adding a common value to every spline coefficient and subtracting it from
log_w0left the likelihood unchanged. Realized spline coefficients are now centered to sum to zero, leaving the baseline intercept to carry the constant level. The raw hierarchy remains full-dimensional, so this removes likelihood-level confounding rather than every prior-only nuisance direction.Numerical and simulation corrections
Keep simulated paths inside their requested horizon. Applying
min_t_stepcould move a genuine event to or beyondt_max, after which the row was labeled as censoring while retaining a nonzero transition index. Genuine pre-horizon events are now preserved, censoring rows always use transition index zero, reversed horizons are rejected, and zero-length horizons return a valid one-row censored path.Retain the intended fast thinning approximation. Path simulation continues to use the maximum hazard evaluated on a 100-point grid, inflated by
1.05, and skips transitions whose inflated envelope is at most1e-9. Bounds are now calculated only for transitions possible from the current state, non-finite bounds are rejected, and the approximation is documented explicitly. This is not described as a mathematically guaranteed envelope.Construct exactly the declared integration grid. For noninteger model horizons, the old
seq()construction could create more values than the declaredN_griddimension. The grid is now formed directly from exactlyN_gridmidpoint indices.Honor delayed prediction start times.
solve_trans_prob_matrix()previously initialized the forward equation at the first requested output time rather than att_start. It now includest_startin the integration times, returns only the requested output rows, and validates dimensions even for a zero-duration identity result.Return the requested PK interval width. The PK summary helper divided the tail probability by two twice, so an 80% request returned a 90% interval. Quantiles now use
(1 - ci_alpha) / 2and its complement directly.Pharmacokinetic corrections
Stabilize the oral one-compartment solution near equal rates. Direct Bateman-function evaluation divided by
ka - keand could produce cancellation,0 / 0, or0 * Inf. The implementation now uses sign-awareexpm1()factorizations and the continuous equal-rate limit for transient and steady-state calculations.Limit parameter-dependent branching to the numerical PK guard. Structural and validation branches introduced elsewhere depend only on data or model dimensions. The equal-rate PK branch is parameter-dependent, but its limiting expression is value- and first-derivative-matched at equality to minimize discontinuity while avoiding the singular direct formula.
Tighten PK input validation. The package now rejects nonpositive absorption, clearance, volume, dosing-interval, concentration-bound, and exposure-normalization values before they reach numerically invalid operations.
Stan gradient performance
Hazard covariates are time invariant, but the previous Stan program expanded them over every interval and rebuilt the complete hazard-multiplier matrix inside each transition loop.
The revised program differentiates one predictor per subject and transition type and then gathers the required values at event and at-risk indices. This is algebraically equivalent but constructs a substantially smaller reverse-mode graph.
In a representative benchmark with 500 subjects, 10,000 intervals, six transitions, two transition types, and four covariates, repeated gradient time decreased from approximately 1.93 seconds to 1.19 seconds, a reduction of about 38%. Log densities agreed exactly and maximum gradient differences were below
5e-13. No measurable regression was found when every interval belonged to a different subject.Additional edge-case fixes
Compatibility
0.3.3to0.4.0.options(bmstate_stan_file = ...)must renamemu_w0tomu_log_w0and interpret it as a log-scale location.Validation
git diff --checkpasses.Known limitations
1e-9simulation cutoff is deliberately retained for speed and is meaningful only relative to the package’s intended time scale.(0, 3)log-intercept scale remains very broad and implies no finite marginal arithmetic mean hazard after integrating over the scale.