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.
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.
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():
blrm()’s own Ncens counts and the data sent to
Stan assumed an outdated 1..k integer-only y convention
that no longer matched Ocens2ord()’s actual
-Inf/Inf censoring sentinels — censored fits
were silently broken. Fixed by converting to the exact
-1/k+1 sentinel convention
rms::orm.fit() uses before calling
ormIdx().lrmconppo.stan/ lrmconppot.stan left-censoring
branch applied a frozen pposcore[2] non-PO score regardless
of the actual censoring bound, instead of varying with it like every
other branch. The new unified ia/ia2-indexed
formula applies pposcore[ia+1] uniformly, eliminating this
branch-specific bug by construction rather than patching it.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.
Ncens1/Ncens2, matching
rms::orm.fit()’s own conventionThe 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.
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.
docon(), shareddocon() (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.
npcontrast’s
ycut actually workingblrm()’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.
borm(): the new
functionborm() 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:
blrm(), which also supports a
flat/t-distribution prior via lrmconppot.stan) — per
simulations showing that other intercept priors slow sampling badly once
the number of distinct Y values is large, the regime borm()
is meant for.pcontrast, reusing
blrm()’s exact mechanism unchanged.rms::orm.rfit()’s random-intercept
extensions — the single-sigma case and the dual-sigma
(mix_re) case. mix_re is a
mix_re() formula special used together with
cluster(), exactly as rms::orm() itself
handles it, not a borm() argument.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).
ormcon.stanThe 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:
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.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.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.
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.
inv_Phi’s domain check crashed on legitimate rounding
noiseThe 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.
ydep: Y-dependent
effectsborm() 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.
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:
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.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).
tau’s
back-transform, and tausd’s unitstau 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.
predict.borm(), contrasts, and the methods that don’t yet
support ydeppredict.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.
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:
borm(y~x) (no yde at all) on
the same data also shows poor mixing.adapt_delta/max_treedepth, not extra
regularization. Raising
adapt_delta/max_treedepth
(sampling.args=list(control=list(adapt_delta=0.995, max_treedepth=15)))
substantially cut divergences in the cases tested, while leaving
posterior means essentially unchanged — confirmed to be a “free” fix in
this sense. A tighter tausd or a weak
pcontrast on beta reduces divergences too, but
— unlike adapt_delta — measurably shrinks the posterior
mean toward 0, i.e. it is a real bias-for-stability trade, not a free
lunch. Because of this asymmetry,
adapt_delta/max_treedepth is documented in
sampling.args’s own help as the recommended remedy, but was
not made a new global default: on an ordinary, well-behaved fit
with zero divergences either way, raising it by default made sampling
2.4x slower for no benefit, confirmed directly.ytrans
(which, by adding a second, unconstrained degree of freedom, made
sampling markedly worse, not better, settling the question):
tau’s leverage on the likelihood grows linearly and
unboundedly with Y, so the small number of extreme, sparse,
one-sided-group Y categories dominate the information tau
receives, while the bulk of the data is nearly silent on it — a
separation effect concentrated in a few high-leverage observations
rather than spread across the dataset, with no basis-function
misspecification involved (the linear form is exactly the right one for
a true location-scale effect, confirmed algebraically and by exact
correspondence with ordinal::clm()’s own multiplicative
scale model).normcppo=TRUE now warns. The
centering/beta-confound issue found for ytrans (§4.2) has
an exact blrm-side analog in cppo when
normcppo=TRUE is set — confirmed by an identical pair of
tests (the ×1000-scale check, and a direct before/after centering
comparison showing the same ~40%-of-magnitude shift in
beta). Unlike ytrans, cppo’s
centering/scaling is opt-in and already defaults to FALSE
(so most existing usage is unaffected), and it is a pre-existing,
documented option on an established function, so rather than changing
its behavior, blrm() now warns when
normcppo=TRUE is used together with cppo,
explaining the trade-off.init= was silently ignored for the
rstan backend. Found while investigating whether
seeding from the optimizer helps (§5): init=inits was
omitted entirely from the rstan backend’s sampling args in
both borm.r and blrm.r (only the
cmdstan branch set it), so any user-supplied
init was silently ignored whenever
backend='rstan'. Confirmed directly: passing a specific
init list had zero effect until this fix.standata=TRUE returned an incomplete Stan data
list. borm()’s
cn2/C2/cmus2/csds2
(npcontrast defaults) were set only after the
standata=TRUE early return, so that path’s result was
invalid for the real Stan model whenever npcontrast was not
used. Confirmed directly by feeding standata=TRUE’s own
result back into rstan::optimizing(), which errored with
“variable does not exist … variable name=cn2”.loo failures were silent about the real
cause. The generic “loo failed” message now includes the actual
underlying error (e.g. “All input values must be finite or -Inf”)
instead of discarding it. The specific failure mode that originally
prompted this — a fork-related crash in some IDEs — was traced to
loo()’s own default of forking whenever
cores>1, controlled by the ambient mc.cores
option set for unrelated reasons (chain parallelism). A new
cores_loo argument (default 1) decouples
loo()’s own parallelism from mc.cores.print.borm() table
formattingThe 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.)
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.
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).