Design: yde/ytrans (Y-dependent effects) in rms::orm()

Status: draft for Frank’s review — no code written. Per claude-code-orm-yde-instructions.txt, this is Step 2 of the two-step process; Step 1’s findings (what the Fortran/R code already does, and contradictions between documents) were reported separately and are not repeated here except where they bear directly on a design choice.

Companion reading: orm-random-effects-implementation.md and orm-random-effects-methodology.md (both already flag yde as a future-work item in their own Section 9 / Section 6), orm_accuracy.md (whose Section 3, “Differencing issues and their relevance to future YDE work,” is directly load-bearing for this design — see a.1/a.5 below, not just background), and web/R/rmsb/borm_development.md (the working implementation of this same mechanism in rmsb::borm(), used throughout as an independent reference).

Model, in one line: for observation \(i\) with yde design row \(Z_i\) (\(1 \times q\)) and ordered Y category \(y_j\), the usual cumulative-probability linear predictor \(\alpha + x_i'\beta\) picks up an additional, category- dependent term

\[e_i(y_j) = Z_i\,\tau\,\mathrm{ytrans}(y_j)' = \sum_{q,m} Z_{iq}\,\tau_{qm}\,\mathrm{ytransmat}_{jm}\]

where \(\tau\) is \(q\times m\) and ytransmat (\(k\times m\)) is ytrans() applied once to the \(k\) distinct Y values. This is exactly rmsb::borm()’s own yde/ytrans/tau mechanism (R/borm.r), and exactly generalizes blrm()’s ppo/cppo (which is the \(q=1,\,m=1\) case, cppo playing the role of ytrans).


a. Log-likelihood, gradient, Hessian

a.1 The existing Fortran hooks already anticipate this

Three pieces of groundwork are already in the codebase, confirmed by direct reading, not inferred:

What is not yet true today: ormll.f90’s own subroutine signature (line 1) has no e1/e2 parameters at all, and orm.fit.r’s current .Fortran(F_ormll, ...) call (R/orm.fit.r:1324) passes only x, not Z/tau. ormatoms’s e1/e2 hooks are exercised today only through their default-0 path. So the plumbing is anticipated but not wired up — Stage 1’s job is to wire it up, not invent it.

a.1’ A measured, non-negotiable accuracy requirement — not optional style

orm_accuracy.md §3.1 already measured (not just argued) the cost of getting this wrong: computing lp1 = lp + e1 and lp2 = lp + e2 as ordinary doubles and passing only those to ormatoms gives roughly 2-5e-15 relative error in the cell probability d if e1/e2 are kept separate all the way to ormatoms, vs. 1-3e-10 if they are pre-summed first — a ~\(10^5\times\) amplification (the 1/width factor from §1 of that document), because lp + e1 rounds to ulp(lp) (≈2e-15 for |lp|$$10) regardless of how small and distinct e1 actually is, and that lost information cannot be recovered downstream by any formula applied to the already-rounded lp1, lp2. Concretely (their example): two valid, different e1 values differing by 8e-16 round lp+e1 (lp=10) to the identical double.

Consequence for Stage 1’s R/Fortran code: whatever builds the y-dependent terms must keep e1 = Z^{(1)}_i\!\cdot\!\mathrm{vec}(\tau)$ ande2as **separate arrays**, passed toormatoms(viaormll's extended signature) alongside the commonlp = offset + x’, never pre-added intolpon the R or Fortran side — this is a correctness requirement with a measured ~5-order-of-magnitude cost if violated, not a style preference. §3.3 of the same document further confirms the score/Hessian side needs exactly what a.2/a.3 above derive: "*s1,s2... are already exactlyD(ell)/D(x1)andD(ell)/D(x2)individually ... a YDE score contribution iss1z1 + s2z2*" and "*h11,h12,h22... are what a YDE Hessian needs, rather than the combinedhee,h1e,h2e`*” — the same conclusion a.3 reached independently via the numerical check, now doubly confirmed.

ormeta.f90’s current R-facing interface is, by its own documentation (orm_accuracy.md §3.2), a pre-summed stopgap — lp1=lp+e1, lp2=lp+e2 already added before the call — “fine today only because e1=e2=0 always holds.” Extending ormeta for real yde+random-effects use (Stage 2) requires changing its own R-facing signature to accept lp, e1, e2 separately (preferred, per that document) rather than inheriting the pre-summed convention — this is additional, concrete confirmation that Stage 2 is a real interface change to ormeta, not a transparent pass-through, reinforcing section c’s conclusion below.

a.2 Likelihood and chain rule

For observation \(i\) with (possibly censored) category spanning intercept indices \(ia(i)\), \(ia2(i)\) (from ormidx, unchanged by yde):

\[x_{1i} = \alpha_{ia(i)} + x_i'\beta + e_i(y_{ia(i)}), \qquad x_{2i} = \alpha_{ia2(i)} + x_i'\beta + e_i(y_{ia2(i)})\]

\[\ell_i = \log\big(F(x_{1i}) - F(x_{2i})\big) \quad\text{(or the one-sided forms at category boundaries, as now)}\]

\(s_{1i} = \partial\ell_i/\partial x_{1i}\), \(s_{2i} = \partial\ell_i/\partial x_{2i}\), \(h_{11,i} = -\partial^2\ell_i/\partial x_{1i}^2\), etc. — exactly what ormatoms/ormeta already compute, for any of the 5 links, unchanged in form; only their arguments (\(x_{1i}, x_{2i}\), now observation- and category-dependent through \(e_i\)) change.

Chain rule to \(\theta = (\alpha, \beta, \mathrm{vec}(\tau))\):

\[\frac{\partial x_{1i}}{\partial \alpha_a} = \mathbb{1}[a=ia(i)], \quad \frac{\partial x_{1i}}{\partial\beta} = x_i, \quad \frac{\partial x_{1i}}{\partial \mathrm{vec}(\tau)} = Z^{(1)}_i := \mathrm{vec}\big(Z_i \otimes \mathrm{ytransmat}_{ia(i),\cdot}\big)\]

and symmetrically for \(x_{2i}\) with \(ia2(i)\), giving \(Z^{(2)}_i\). \(Z^{(1)}_i\), \(Z^{(2)}_i\) are each length \(q\times m\) — exactly rmsb::borm()’s own expandZ()/Zexp construction (R/borm.r, bormPredictYde(): as.vector(outer(Zrow, ytransrow))); reusing that exact convention (not inventing a second one) is recommended for naming/ordering consistency (see b.3).

a.3 Hessian blocks — derived, then confirmed numerically

Writing \(d_1, d_2 \in \mathbb{R}^{k+p+qm}\) for the two chain-rule vectors above (nonzero only in the touched \(\alpha\) slot, the \(p\) beta slots, and the \(qm\) tau slots):

\[H_i = h_{11,i}\,d_1 d_1' + h_{12,i}(d_1 d_2' + d_2 d_1') + h_{22,i}\,d_2 d_2'\]

Block by block:

block formula shape/structure changed by yde?
\(\alpha\)–\(\alpha\) \(\sum_i h_{11,i}\mathbb 1[a{=}ia(i)]\mathbb 1[a'{=}ia(i)] + h_{12,i}(\ldots) + h_{22,i}\mathbb1[a{=}ia2(i)]\mathbb1[a'{=}ia2(i)]\) tri-band / general-sparse \(k\times k\), same nonzero pattern as now no — only the curvature values change (h11/h12/h22 replace hee/h1e/h2e); which \((a,a')\) pairs are touched is determined solely by ia/ia2, untouched by yde
\(\alpha\)–\(\beta\) \(\sum_i [h_{11,i}x_i\mathbb1[a{=}ia(i)]+h_{12,i}x_i\mathbb1[a{=}ia2(i)]] + [\ldots]\) sparse in \(\alpha\) rows (O(1) rows touched/obs), dense in \(p\) columns no change in shape
\(\alpha\)–\(\tau\) same formula, \(x_i \to Z^{(1)}_i/Z^{(2)}_i\) identical sparsity-in-\(\alpha\)-rows pattern as \(\alpha\)–\(\beta\), dense in \(qm\) columns new block, same shape family as \(\alpha\)–\(\beta\)
\(\beta\)–\(\beta\) \(\sum_i (h_{11,i}+2h_{12,i}+h_{22,i})\,x_ix_i'\) dense \(p\times p\) curvature coefficient changes, shape doesn’t
\(\beta\)–\(\tau\) \(\sum_i (h_{11,i}+h_{12,i})x_iZ^{(1)\prime}_i + (h_{12,i}+h_{22,i})x_iZ^{(2)\prime}_i\) dense \(p\times qm\) new
\(\tau\)–\(\tau\) \(\sum_i h_{11,i}Z^{(1)}_iZ^{(1)\prime}_i + h_{12,i}(Z^{(1)}_iZ^{(2)\prime}_i+Z^{(2)}_iZ^{(1)\prime}_i) + h_{22,i}Z^{(2)}_iZ^{(2)\prime}_i\) dense \(qm\times qm\) new

Numerical confirmation (not just asserted): I built a toy \(n{=}40\), \(k{=}4\), \(p{=}1\), \(q{=}1\), \(m{=}2\) uncensored logistic-link model directly in R (script kept at ~/.claude/jobs/1d5582a6/tmp/yde_hessian_check.R, reproducible, no package dependency), wrote the above \(s_1,s_2,h_{11},h_{12},h_{22}\) formulas by hand, and compared against a from-scratch central-difference gradient/Hessian of the direct log-likelihood (not using the chain rule at all — an independent reference). Results:

a.4 Storage / solving strategy for large \(k\)

Because the \(\alpha\)–\(\tau\) block has the same shape as \(\alpha\)–\(\beta\) (sparse-in-\(\alpha\)-rows, dense-in-columns) and \(\beta\)–\(\tau\)/\(\tau\)–\(\tau\) are dense like \(\beta\)–\(\beta\), the natural representation is: define \(b^* = (\beta, \mathrm{vec}(\tau))\), length \(p+qm\), and simply let it occupy infoMxop’s existing b/ab slots (b: \((p+qm)\times(p+qm)\), ab: \(k\times(p+qm)\)). No new matrix-storage class or solve strategy is needed. infoMxop.r’s existing i='x' fast path (R/infoMxop.r:244):

M <- b - Matrix::t(ab) %*% solv(a, ab, tol = tol)

performs exactly one \(k\times k\) sparse solve against a (the tri-band/general-sparse intercept block), with as many right-hand-side columns as ab has. That factorization cost is independent of the number of columns in ab (it is one factorization of a, reused for all RHS columns) — so growing ab/b by \(qm\) columns adds only a cheap, dense \((p+qm)\times(p+qm)\) Schur-complement solve on top of the same \(k\times k\) factorization orm already does today. This is exactly what keeps large \(k\) (\(>10^5\)) feasible: the one place CLAUDE.md flags as segfault-prone (Matrix::solve on the sparse \(k\times k\) system) is completely unaffected in size or structure by adding yde — it is still the same a, same dimension, same sparsity, same solver.


b. infoMxop extension, and vcov/predict/contrast/Predict/summary/anova/nomogram/bootcov/robcov

b.1 infoMxop

infoMxop.r already locates log(sigma)/sigma2 by name within xname, not by position (R/infoMxop.r:70–96, confirmed: “Dropped the positional assumption that log(sigma), when present, is xname’s LAST element — search xname directly”). Recommend appending \(\tau\)’s \(qm\) columns to b/ab/xname the same way, with names following rmsb::borm()’s own existing naming helper bormYdeNames() (R/borm.r) for exact cross-package consistency — e.g. "tau[Zcolname,ytransname]" style names, column-major in \(q\) then \(m\) (matching expandZ()’s outer(Z[i,], ytransrow) ordering, a.4/a.2 above). This is a naming convention choice, not a structural one; flagging it so Frank can confirm or override before Stage 1’s code is written.

b.2 vcov

Falls out of the above with no new code: solve(info) (or infoMxop’s efficient paths) already returns whatever block the caller names, keyed by the grown xname. No special-casing needed beyond whatever currently reads xname/iname to build row/column names on the returned covariance matrix.

b.3 coef()/vcov() ordering

Proposal (Frank’s call to confirm): \(\tau\) appears after \(\beta\) in coef()/vcov(), column-major \(\mathrm{vec}(\tau)\) ordering (\(q\) varies fastest). This matches both (i) infoMxop’s existing append-after-beta convention for log(sigma)/sigma2, and (ii) borm()’s own existing draws <- cbind(alphas, betas, taus) convention and expandZ()’s column-major flattening — i.e. it would make orm’s and borm()’s coefficient-vector conventions for yde/ytrans identical, which should make any shared downstream code (contrast-building, npcontrast-style combined beta+tau contrasts) directly portable between the two.

b.4 predict/contrast/Predict

Recommend porting rmsb::borm()’s own bormPredictYde() logic (R/borm.r) to an analogous ormPredictYde(): it is already link/model-structure-agnostic (keyed off object$link + rms::probabilityFamilies, not hardcoded to a specific family) and does not touch anything Stan/posterior-draws-specific — it only needs a point estimate (coef(fit)) and vcov(fit) in place of posterior draws, which orm already has. The Zmatrix/zcppo-suppression generalization of Xcontrast.r/Predict.s just completed for borm (same session, same pattern: detect isorm && fit$qyde>0 alongside isblrm/isborm) is the direct template for extending those two rms files again once orm itself gains yde — not attempted now, flagged as a Stage-1 follow-on task, not a Stage-1 blocker (predictions can initially go through predict.orm’s own new type='x'/'lp' logic directly, before Xcontrast/Predict are touched a second time).

b.5 summary/anova

Assumption, not yet verified: these iterate over design-matrix columns generically via xname, not a hardcoded column count, so should work for \(\tau\)’s columns once properly named/registered — but this is exactly the kind of claim this project’s culture says not to ship unconfirmed. Action for Stage 1: read summary.rms/anova.rms directly before claiming this works, and add a confirming test instead of relying on inference from infoMxop’s own generality.

b.6 nomogram

Recommend an explicit, informative error for qyde > 0 rather than attempting a nomogram: a nomogram assumes one fixed linear-predictor scale, and a yde effect has no single nomogram-representable contribution per predictor (its contribution varies with the Y value being predicted). Open question for Frank: does blrm’s own ppo/cppo case already error this way in whatever nomogram-adjacent code exists? Not yet checked — flagging rather than guessing.

b.7 bootcov/robcov

bootcov refits orm() on resampled data and collects coef() — should work unchanged as long as orm.fit’s entire theta (now including \(\tau\)) is what ends up in fit$coefficients, which section (d)’s gating design preserves generically (bootcov never special-cases coefficient count). robcov’s sandwich estimator needs the per-observation score vector \(\partial\ell_i/\partial\theta\) — exactly what a.2/a.3 derive, so no new derivation is needed, only confirming robcov’s existing code reads a theta/score vector of generic length rather than one hardcoded to k+p.


c. Random effects interaction

orm-random-effects-implementation.md §9 already lists four open technical questions for yde + cluster()/mre, found during that earlier work, not new here:

  1. Every current orm.rfit.r call site hardcodes lp1=lp2=lp.
  2. clusterModeFind’s score/curvature accumulation (Sg, Sh) assumes one scalar g/h per observation.
  3. agqStep’s pseudo-covariate chain-rule terms assume a single shared linear predictor per observation.
  4. sparseMissingInfo’s Louis’s-identity correction assumes one index set per observation.

What this document’s (a) analysis adds: it resolves part of the ambiguity in how those four questions interact with yde specifically. Since yde’s effect on the Hessian is structurally a beta-like extension (new \(\tau\) block, same shape family as \(\beta\)), not an intercept-structure change — confirmed numerically in a.3, the \(\alpha\)–\(\alpha\) block is exactly unchanged by yde alone — the “tri-band to general sparse” change in this section’s own title is caused by random effects, not by yde; the two are largely orthogonal structural changes to different blocks. The real combined-case difficulty is specifically in ormeta/ormatoms’s per-AGQ-node evaluation: a random intercept \(u\) shifts \(x_1\) and \(x_2\) by the same amount (so \(g=s_1+s_2\), \(h\) a single combined curvature, exactly as ormeta.f90’s own header says: “a random intercept shifts eta identically on both sides”), but yde’s \(\tau\) is a genuinely different direction per observation’s two sides (\(Z^{(1)}_i \neq Z^{(2)}_i\) in general) — meaning clusterModeFind’s scalar Newton step and agqStep’s scalar pseudo-covariate chain rule would need to become 2-vector (\(s_1,s_2\)) / 3-number (\(h_{11},h_{12},h_{22}\)) operations for the mode-finding and AGQ-node computation specifically, not a trivial pass-through. ormeta.f90’s own header comment already states this is exactly how it should be extended (“the R caller should pass the common part and the yde parts instead of pre-summed lp1, lp2”), so the mechanism is anticipated, but the actual rederivation of clusterModeFind/agqStep’s formulas for a joint \((s_1,s_2,h_{11},h_{12},h_{22})\) integrand is new work, not yet done, and not attempted in this document.

Recommendation: defer combining random effects with yde to Stage 2 of the staged plan (section f), treated as its own rederivation task with its own numerical verification (gradient/Hessian vs. finite differences on a small clustered+yde example, analogous to a.3’s check but with a random intercept added) — not a “just pass tau through” assumption.


d. Recommendation: generalize orm.fit/orm.rfit, or write new functions?

Recommendation: generalize in place, gated behind a new yde argument (default NULL/absent ⇒ qyde=0), not a separate function. Evidence:

  1. The extension point already exists and is designed for exactly this. ormatoms’s e1/e2 and ormeta’s lp1/lp2 split (a.1) were put there anticipating this; using them is completion of existing work, not new architecture.
  2. The combined-information-matrix structure needs no new storage class (a.4) — infoMxop’s existing 3-part representation already generalizes by simple column-append, the same mechanism already used for log(sigma)/sigma2.
  3. A separate function would duplicate, and risk desynchronizing from, orm.fit’s existing accuracy work (orm_accuracy.md), censoring handling (Ocens/Ocens2ord), and orm.rfit’s random-effects machinery — exactly the kind of “broad sweep” / gratuitous duplication CLAUDE.md’s “minimal diffs” rule warns against, and a correctness risk in itself (two codepaths to keep in sync as orm.fit continues to evolve).
  4. The “no-yde fits must give the same results as now” constraint is achievable as an exact, not approximate, guarantee, by gating so that when qyde==0 the new e1/e2-forming arithmetic is never executed (not executed-and-found-to-be-zero, but skipped entirely) — e.g. ormll’s new Fortran code calls ormatoms with e1, e2 absent exactly as it does today when qyde==0, so the exact same floating-point operations run. Proposed tolerance: bit-identical (not “close to 1e-8”) for the no-yde path, verified by a dedicated regression test comparing fits bit-for-bit — achievable because nothing about the existing, validated numerical path needs to change when yde is absent; it is a pure extension, not a modification, of the likelihood arithmetic for that case.
  5. Counter-case, steelmanned: a separate function would let Stage 1 ship with zero risk to orm.fit’s CRAN-stable numerics while development is in flux. Given point 4’s bit-identical gating, I believe this risk is already adequately contained within orm.fit, making a separate function an unneeded duplication — but this is exactly the kind of design choice the instructions say is Frank’s to make, not mine to decide unilaterally. Flagging for explicit sign-off.

CRAN/reverse-dependency note: new arguments (yde, ytrans) should be appended at the end of orm()’s and orm.fit’s formal argument lists, never inserted in the middle, so no third-party caller using positional arguments is broken. rmsb itself does not call orm.fit directly (it calls orm() the ordinary user-facing way for its own MLE-comparison tests), so the primary reverse-dependency surface is the public orm()/orm.fit() signatures, not an internal API.


e. (skipped — yde/ytrans are user-given arguments, not a shared-location design question, per instructions)


f. Staged plan

Per the instructions’ explicit ordering — (1) ydep without random effects ... (2) random effects; (3) ytrans — Stage 1/2 intentionally use the simplest ytrans (effectively \(m=1\), e.g. identity) so the Fortran/infoMxop plumbing is proven before generalizing to arbitrary user-supplied, matrix-valued ytrans:

Stage 1 — yde (simple, \(m=1\)), no random effects. Fit, vcov, predictions. - orm()/orm.fit gain yde (formula), ytrans (function, defaulting to identity for this stage) arguments, appended at the end of the signatures. - \(Z\) built from the yde formula independently of the main-formula Design() call (per the explicit instruction that yde/ytrans are “not extra formula-like things but just new arguments” — i.e. not a Design(..., specials=...) entanglement). - ormll.f90 gains e1,e2 as separate arrays passed through to ormatoms unsummed (a.1’, the measured, non-negotiable requirement — never pre-added into lp), plus the Z^{(1)}/Z^{(2)} chain-rule machinery for the new Hessian/gradient blocks in a.3, gated so qyde==0 exercises none of the new code (d.4’s bit-identical requirement). - infoMxop-facing b/ab/xname grow by ncol(Z)*ncol(ytransmat) per b.1–b.3. - Tests (in priority order): (i) bit-identical-when-yde-absent regression test — run first, must pass before anything else is trusted; (ii) gradient/Hessian vs. finite differences on a small problem, extending a.3’s toy-math check into an actual Fortran-level test (compare ormll‘s real output, not a second R reimplementation, against R-level finite differences of the real likelihood); (ii’) a dedicated accuracy test reproducing orm_accuracy.md §3.1’s own measurement on real yde data — confirm relative error in d stays at the ~1e-15 level (e1/e2 kept separate all the way to ormatoms), not the ~1e-10 level pre-summing would produce — i.e. verify the implementation actually followed a.1’, don’t just trust the design; (iii) one-column yde (\(q=1,m=1\)) MLE vs. blrm’s own ppo/cppo near-flat-prior posterior mode on the same data (the mathematical correspondence this relies on was already confirmed empirically for borm vs. blrm, same session: inst/tests/borm-yde.r’s §1 passed with “blrm posterior means … borm posterior means … expect close agreement” — the orm-side version of this same check is new, not yet run); (iv) agreement with borm’s own posterior mode under weak/flat priors, multiple links, with and without censoring. - Stop for Frank’s review.

Stage 2 — random effects (cluster()/mix_re) + Stage 1’s yde together. - Requires the clusterModeFind/agqStep dual-\((s_1,s_2,h_{11},h_{12},h_{22})\) rederivation flagged in section c — explicitly not a mechanical port. - Tests: agreement with borm’s own mix_re+yde posterior under weak priors (borm already supports this combination, inst/tests/borm-yde.r; a good independent reference); bit-identical no-yde-random-effects regression test repeated for this code path. - Stop for review.

Stage 3 — generalize ytrans to arbitrary user-supplied functions returning \(m\geq 1\) columns (full parity with borm’s own ytrans). - Mostly an R-level generalization (building ytransmat, Zexp-style expansion for predictions) once Stage 1/2’s Fortran plumbing already handles a general \(qm\)-width tau block — the Hessian/gradient math in (a) was already derived for general \(m\), not just \(m=1\), so this stage should not require new Fortran-level derivation, only exercising the already-general code with \(m>1\). - Tests: borm’s own matrix-valued-tau recovery test (inst/tests/borm-yde.r §2, “genuine Y-dependent effect recovery”) adapted to orm’s MLE; large-\(m\) sanity check that nothing assumed \(m=1\) silently. - Stop for review.


g. Verification plan


Risk / CRAN flags summary


Open items explicitly for Frank to decide (not mine to assume)

  1. coef()/vcov() ordering/naming of \(\tau\) (b.3) — proposed append- after-beta, column-major, matching borm’s convention; needs sign-off since it’s user-visible and positional code elsewhere could depend on coefficient order.
  2. Generalize-in-place vs. new function (d) — recommended generalize-in- place with bit-identical gating; final call is Frank’s per the instructions.
  3. nomogram() behavior for qyde>0 (b.6) — proposed hard, informative error; not yet checked what blrm’s own ppo case does here, so no precedent confirmed either way.