Developing borm(): rmsb’s Bayesian analog of rms::orm()

This document catalogs the design decisions, bugs found and fixed, and numerical/sampling investigations behind borm() and its ydep (Y-dependent effect) mechanism, developed as rmsb 2.0-0. It also covers the blrm()-side fixes discovered along the way, since borm() reuses much of blrm()’s own machinery (ormIdx()-based censoring, docon()-based contrasts, the Dirichlet-prior intercept construction) and several bugs were shared or exposed by working on both at once.

None of this is a tutorial on using borm(); it is a record of why the code is the way it is, what was tried and rejected, and what was confirmed by a real run rather than just reasoned through — the project’s own standing rule for this kind of work.

1. Foundations reused from blrm()

Several pieces of groundwork were done to blrm() itself, ahead of and in service of borm(), since borm() was designed to share rather than duplicate blrm()’s existing machinery wherever the two models agree.

1.1 Precomputed intercept subscripts, via rms::ormIdx()

blrm()’s Stan code (lrmconppo.stan, lrmconppot.stan, lrmcppo.stan) now takes precomputed per-observation intercept subscripts (ia, ia2, sgn) as data, from the same rms::ormIdx() Fortran routine rms::orm.fit() already uses, instead of raw censored y. This removes every censoring-type conditional from the Stan likelihood entirely — the Stan code no longer branches on whether an observation is uncensored, left-, right-, or interval-censored; one formula, applied uniformly via ia/ia2/sgn, covers all four. borm()’s own ormcon.stan uses the identical mechanism from the start.

This refactor surfaced two real, previously-silent bugs in blrm():

The unconstrained PPO model (ppo without cppo) still does not support censored Y, but now fails with an informative error instead of silently corrupting the response via as.integer(-Inf) = NA.

1.2 Ncens1/Ncens2, matching rms::orm.fit()’s own convention

The fit object now stores Ncens1 and Ncens2 (original vs. post-coding censoring counts), taken directly from Ocens2ord()’s own attributes, matching rms::orm.fit() exactly, in place of a single Ncens field that silently matched Ncens2 and could disagree with orm’s own printed count whenever a right-censored point at or beyond the highest uncensored value was reclassified to uncensored at a new tail category. print.blrm() now displays Ncens1, matching print.orm(). This is not backward compatible with fits saved before this change.

1.3 Accurate interior log-likelihood terms

log(inv_logit(ca) - inv_logit(ca1)) was replaced with Stan’s built-in log_inv_logit_diff(ca, ca1) at every uncensored-interior and interval-censored log-likelihood term in lrmconppo.stan, lrmconppot.stan, and lrmcppo.stan. This avoids catastrophic cancellation when both cutpoints are deep in the same tail (large |eta| or many intercepts): measured against an arbitrary-precision (Decimal) reference, the naive formula returned NaN on 14% of a 198-point test grid and up to 2.3% relative error where finite, versus about 1e-15 (machine epsilon) for the built-in.

1.4 docon(), shared

docon() (the pcontrast/npcontrast design-matrix-and-prior builder) was extracted out of a closure inside blrm() into a shared, top-level function in stanMisc.r, now used by both blrm() and borm() — this package’s own standing rule is that a helper needed in more than one file must not live inside another function’s body.

1.5 npcontrast’s ycut actually working

blrm()’s npcontrast accepted and documented a ycut argument (to weight a non-PO contrast’s prior by cppo(ycut)) but silently discarded it, so users had to manually pre-scale sd by cppo(ycut)’s value themselves. Fixed: docon() now applies cppo(ycut) to each named setting’s Z-row automatically. ycut may also now be a named vector giving a different Y cutoff per named setting within one npcontrast specification — e.g. to put a prior directly on the difference between an effect evaluated at two different Y values. This only activates when ycut is explicitly supplied, which previously had no effect at all, so it is backward compatible.

2. borm(): the new function

borm() is the Bayesian analog of rms::orm(), the way blrm() is the Bayesian analog of rms::lrm(). It implements all 5 of orm()’s link families (logistic, probit, log-log, complementary log-log, Cauchy), exact censoring handling via rms::ormIdx(), and:

As with blrm(), covariates are centered and QR-orthogonalized in R before being passed to Stan; the Stan code itself has no knowledge of either transformation.

borm() also implements Spearman’s rho and Somers’ Dxy following rms::orm()’s own censoring rules exactly (rho is NA whenever any censoring is present; Dxy/C are NA only when left- or interval-censoring is present, using rms::Ocens2Surv()/survival::concordancefit() for the right-censoring-only case), each with a highest posterior density interval, via the new bormStats()/print.bormStats() — paralleling blrmStats()/print.blrmStats() but generalized to the actual link family (rms::probabilityFamilies) instead of a hardcoded plogis().

print.borm() gives a family-dependent title and subtitle matching rms::print.orm()’s own family-dependent title switch (prefixed “Bayesian”). predict.borm()/Mean.borm()/Quantile.borm()/ExProb.borm() delegate to the existing blrm() versions for a non-ydep fit, since those are already link-and-model-structure-agnostic (dispatching via object$link/rms::probabilityFamilies) — avoiding a ~400-line duplication.

borm() was verified against rms::orm() MLEs (method='optimizing'): matches closely for all 5 families, including mixed left/right/interval censoring; cluster() and cluster()+mix_re() sample cleanly under real NUTS; pcontrast was confirmed to actually constrain beta (a tight prior pulls it to ~0.0006 vs. ~0.76 under a near-flat one).

3. Numerical correctness in ormcon.stan

3.1 Vectorization and three NaN hazards

The logistic/log-log/complementary-log-log likelihoods were vectorized (no per-observation loop at all; probit/Cauchy remain scalar loops, since their numerically-stable forms — std_normal_lcdf/cauchy_lcdf — exist only as Stan’s summing distribution functions, with no accuracy-preserving elementwise alternative). This “compute both branches, blend by multiplying by 0/1” style of vectorization introduced three distinct 0 .* non-finite = NaN hazards, each confirmed by direct reproduction, not just reasoned through:

  1. The two-component (has2, interval-censored) blend’s dummy index satisfied log_inv_logit_diff/log_diff_exp’s x > y ordering requirement but not finiteness. Fixed by feeding a fixed dummy pair (0, -1), not one derived from the real intercept value.
  2. Log-log/complementary-log-log’s sign (CDF-vs-CCDF) selection could overflow the unused branch at ordinary, non-extreme eta (as low as ~8–9 for complementary-log-log, since its CDF saturates doubly-exponentially fast). Fixed the same way, feeding 0 to the unused branch.
  3. A deeper version of the same issue was an actual segfault/bus error (not just NaN) in the raw exp() calls inside the log-log/ complementary-log-log forms, overflowing during Stan’s reverse-mode autodiff — reproduced in a 1-line standalone model and fixed by capping the argument to exp() at 700 (comfortably below the ~709.78 double-precision overflow point), the same defensive principle Stan’s own log1p_exp/log1m_exp already use.

All three fixes were verified via a full re-run of the 5-link rms::orm()-comparison suite (unaffected) plus targeted regression tests reproducing each original failure.

3.2 The Dirichlet-prior intercept construction used the wrong inverse CDF for 4 of 5 families

alpha, the per-category intercept built from the Dirichlet-prior simplex pi as alpha[j-1] = f(sum(pi[j:k])), used logit() as f() unconditionally, for all 5 link families — but logit() is the correct inverse CDF only for the logistic family. For probit/log-log/ complementary-log-log/Cauchy, this meant alpha was not on the scale the likelihood actually uses it on (e.g. std_normal_lcdf() for probit), so the Dirichlet prior was silently a prior on a different, composed quantity (e.g. Phi(logit(p)) for probit) rather than on the baseline category probabilities it is documented to be, for every non-logistic family.

Fixed by adding per-family inverse-CDF functions (invCDF_logistic, invCDF_probit, invCDF_loglog, invCDF_cloglog, invCDF_cauchit), each exactly inverting the CDF the likelihood actually uses for that family, and dispatching on link when constructing alpha — exactly as the log-likelihood itself already dispatches on link. Verified directly: after the fix, CDF_family(alpha[j-1]) == sum(pi[j:k]) exactly for probit (confirmed numerically to 6 decimal places) and unchanged for logistic (as expected, since logit() was already correct for it); the full borm-vs-orm MLE comparison for all 5 link families was re-run and still matches closely (max coefficient difference from 8e-6 to 9e-5).

This fix also surfaced a stale-build hazard in the package’s own Makefile: stanExports_ormcon.cc is a short, unchanging wrapper that #includes the real generated model code in stanExports_ormcon.h, so editing ormcon.stan (which regenerates the .h via rstantools::rstan_config()) does not by itself trigger a recompile of stanExports_ormcon.o — make’s dependency tracking only sees the .cc file’s own unchanged timestamp. This will recur for any future .stan edit; forcing a recompile requires touching stanExports_ormcon.cc (or deleting the stale .o/.so) as well.

3.3 inv_Phi’s domain check crashed on legitimate rounding noise

The fix above immediately surfaced a crash: inv_Phi’s own domain check rejected sum(pi[j:k]) with “Probability variable is -4.76837e-16, but must be in the interval [0, 1]”. sum(pi[j:k]) is mathematically in (0,1) (pi is a simplex), but summing up to k-1 of its entries in floating point can round microscopically outside that interval; logit() never surfaced this because it has no such check, not because the rounding wasn’t happening. Fixed by clamping the cumulative probability to [1e-10, 1-1e-10] before any invCDF_* call — comfortably above the rounding noise observed (~1e-16) and comfortably below any tail probability borm() actually needs to resolve. Verified directly: the exact failing call ran clean afterward, and the full 5-family MLE comparison was unchanged.

4. ydep: Y-dependent effects

4.1 Design

borm() implements ydep via two new arguments: yde (a formula, paralleling blrm()’s own ppo) and ytrans (a function, paralleling cppo but generalized to return a matrix of one or more columns instead of a single score). A single-column ytrans applied to a single yde predictor reduces mathematically to blrm()’s cppo mechanism exactly, confirmed via direct comparison under real NUTS sampling on identical data.

A genuinely multi-column (m>1) Y-dependent effect was validated on simulated data with a known, strongly Y-dependent true treatment effect: the yde-fitted model’s loo expected log predictive density was far better than the plain proportional-odds model’s (−779 vs. −1253 in the test), confirming real signal recovery, not merely running without error.

ormcon.stan gained q/m/Z/ytransmat/tausd data and a q x m tau parameter matrix. The per-observation Y-dependent contributions are computed inside Stan (transformed parameters), not in R, since they combine a parameter (tau) with data (ytransmat) — the same reasoning already applied to lp = X*beta. The Y-level-specific row of ytransmat is gathered via a +1 shift from alpha-index to Y-level-index, exactly paralleling blrm’s own pposcore[ia+1]/pposcore[ia2+1] convention. yde predictors may (and usually will) overlap the main formula’s own predictors, exactly like ppo’s existing semantics — a Y-dependent effect is normally an extension of an ordinary effect, not a separate one.

4.2 Centering and scaling: a design choice made, then partly reversed

ytrans’s result was originally centered and scaled automatically (independently per column, using the empirical distribution of observed Y), unconditionally, with no opt-out — unlike blrm()’s own cppo-centering, which is opt-in via normcppo (default FALSE). This was later found to be the wrong default, for two separable reasons, each confirmed directly rather than just reasoned through:

  1. Centering ytrans distorted the ordinary coefficient(s) for any predictor appearing in both yde and the main formula — the common case. Centering introduces a term linear in Z but constant across Y, which has no clean home: Z’s own centering is absorbed cleanly into alpha (which already varies freely by Y-level), but this term does not, and silently gets absorbed into beta instead. Confirmed directly on a test dataset: toggling ytrans’s centering off (holding scaling fixed) left tau essentially unchanged but shifted beta by an amount matching the predicted size of this confound almost exactly — beta was absorbing roughly 40% of its own magnitude from it — while costing nothing in sampling (divergence rate was statistically unchanged). Fix: ytrans’s own centering was removed. The result (ytransmat, stored and used everywhere: Stan’s own data, bormStats(), predict.borm()) is ytrans(y) exactly as written, with no centering.
  2. The scaling half, if kept at all, needed tau divided back by it when reporting/storing tau, and this divide was missing. Confirmed directly: fitting with ytrans=function(y) y vs. ytrans=function(y) 1000*y gave the identical stored tau (ratio 0.9998, not ~0.001), because the internal auto-scaling exactly canceled the user’s own scale choice before Stan ever saw it. Fix (see §4.3): tau is now correctly divided by ytrans’s own scale before being stored, so it is reported in the user’s own ytrans(y) units, exactly as beta is already reported in the user’s own covariate units.

The scaling itself (dividing ytrans(y) by its own observed-data SD before giving it to Stan) was kept, for a confirmed numerical-safety reason unrelated to the centering question: without any scaling at all, a ytrans producing values in roughly the hundreds or more crashed R outright (a Stan optimizer segfault), confirmed directly by bisection (values up to the tens did not crash; 100x did).

4.3 tau’s back-transform, and tausd’s units

tau is back-transformed from the QR-rotated Z scale to the original covariate scale (bormYdepBT()), with the corresponding alpha/intercept adjustment implied by Z’s own centering computed per alpha index (it varies by Y-level, unlike blrm’s single constrained-PPO tau’s uniform-across-levels adjustment). This back-transform was extended to also divide by ytrans’s own scale (§4.2, point 2), so that tau as stored is the coefficient on the user’s own raw yde predictor and raw ytrans(y), independent of the sample means or scales of X, Z, or y.

tausd, the prior SD for tau, was reinterpreted the same way. It had applied directly as the Stan-internal-scale SD, which is not portable across datasets: the same number implies a very different effective raw-scale prior width depending purely on y’s own arbitrary units, confirmed directly by comparing two datasets with y on scales differing by 100-fold. tausd is now specified on a raw, dataset-invariant basis — one unit of the (centered) yde predictor, one SD of ytrans(y) over the observed Y values — with borm() converting it internally by dividing by the yde design matrix’s own QR back-transform factor (deliberately not also dividing by ytrans(y)’s own scale this time, since that normalization is already the right, portable one to keep). The default value is unchanged (10) under the new interpretation — a reasonable, round choice clear of the (robustly confirmed) region below about 1 where tau is measurably crushed toward 0 — but it is not a value tuned against NUTS sampling efficiency: a closer look at leapfrog/treedepth counts found them chaotically sensitive to tausd at a resolution far below anything practical to tune against (a 0.001% change in tausd reproducibly swung total leapfrog steps between roughly 200,000 and 350,000), so no specific number can honestly be presented as minimizing them. For a single yde predictor (every case validated here, and ydep’s own primary, blrm-cppo-paralleling use case) the raw-to-internal conversion is exact; for more than one yde predictor it uses a reasonable but not independently validated generalization.

4.4 predict.borm(), contrasts, and the methods that don’t yet support ydep

predict.borm() implements its own ydep-aware type='lp' and type='x' for a yde-fitted model (the two most commonly needed, and the building blocks type='fitted' etc. use internally), generalizing predict.blrm()’s hardcoded single-column cppo logic to tau’s q x m matrix. Other types, and fun=, are not yet implemented for a yde-fitted model and raise an informative error rather than silently ignoring the Y-dependent effect. Mean.borm()/Quantile.borm()/ExProb.borm() likewise now error informatively rather than silently ignoring ydep when delegating to their blrm() counterparts.

npcontrast is implemented for borm() as a combined beta+tau contrast mechanism (bormDoconYdep()), needed because beta and tau are mechanically separate Stan parameter blocks, so a single-design-matrix contrast row (as docon() builds for pcontrast) cannot express a quantity like “the effect of a predictor at a given Y value”, which necessarily mixes both. Each named predictor-setting list in npcontrast may carry an optional ycut (a single Y value applied to every setting, or a named vector giving a different Y value per setting, exactly paralleling blrm’s existing ycut convention); a setting with no ycut contributes a pure-beta row. Confirmed directly: a pure-beta npcontrast (no ycut) gives exactly the same beta-part as an equivalent pcontrast, with its tau-part exactly 0; two settings sharing the same covariate values but different ycut have their beta-parts cancel to exactly 0 in a difference, giving a pure-tau contrast; a mixed contrast populates both parts, with the beta-part identical to the pure-beta case (confirming it is ycut-independent, as the math requires).

rms::contrast.rms()’s own ycut-passing logic was hardcoded to inherits(fit, 'blrm'), so contrast() on a yde-fitted borm() model silently evaluated the Y-dependent effect at the reference intercept regardless of any ycut supplied, while still mislabeling the output as if ycut had been honored — confirmed directly: contrast()’s value was identical with and without an explicit ycut, and differed from the correct value computed via predict(..., type='lp', ycut=...). Fixed by generalizing the check to also recognize a borm() fit with qyde>0, while keeping the separate cppo-requirement check blrm-specific. A yde-fitted borm() fit now requires ycut for contrast(), matching blrm()’s own partial-PO requirement.

5. The sampling-difficulty investigation

A user-reported test dataset (inst/tests/borm-unequal-var.r, modeling a treatment’s effect on both the location and variance of Y) triggers severe Stan sampling pathology — divergent transitions, rejected initial values — for borm() fits on it, with or without yde. Investigating this, systematically rather than by a single plausible-looking fix, established:

6. Smaller fixes found along the way

7. print.borm() table formatting

The stats table’s first column now shows Obs, Distinct Y, Median Y, p, Draws, Chains, Time (plus cluster/sigma information when relevant); the third column now shows only the mean absolute difference between P(Y>=median) and 0.5 (bormStats() gained a pdm statistic for this, computed the same way rms::orm.fit()’s own pdm is). The median row is labeled "Median Y", the exact label rms:::prStats()’s own translation table matches, so it renders with the 0.5 subscripted ($Y_{0.5}$/<i>Y</i><sub>0.5</sub>) under prType='latex'/'html', exactly as rms::print.orm() does, with no new markup needed in borm itself. (The discrimination-index entry for the same statistic was already using this exact mechanism and already rendered correctly.)

8. A real bug found and fixed along the way: bormStats()/print.borm()

print() (and bormStats() directly) on a yde-fitted model crashed with “Error in cbind(1, X) %*% t(beta): non-conformable arguments”. draws has [alphas, betas, taus] when ydep is active, but bormStats()’s column selection silently swept the tau columns in with the betas, leaving X (p+1 columns) non-conformable against the combined beta/tau vector (p+1+qyde*myde columns). Fixed by splitting beta/tau apart and combining tau with the yde design matrix Z (now also stored on the fit object, as z) via ytransmat at the fit’s reference intercept’s Y level — mirroring blrmStats()’s own cppo-weighted handling exactly. Verified numerically: a manual reconstruction of bormStats()’s own linear predictor matches a direct beta + tau %*% ytransmat[reference,] computation exactly.

9. Verification status

Every fix and design decision above was verified by a real run before being adopted, per the project’s own standing rule — not by inspection or reasoning alone. The regression suite (inst/tests/borm-orm.r, borm-blrm.r, borm-yde.r, borm-unequal-var.r) passes, including exact self-consistency checks between predict.borm() and manual reconstructions of the linear predictor, and R CMD check is clean (two environment-only INFO notes unrelated to this work: the mice suggested package being unavailable to check with, and GNU make being a SystemRequirements).