gam_solve/pirls/state.rs
1use crate::active_set::ConstraintKktDiagnostics;
2use crate::estimate::EstimationError;
3use gam_linalg::matrix::{
4 DesignMatrix, PsdWeightsView, ReparamOperator, SignedWeightsView, SymmetricMatrix,
5};
6use gam_problem::LinearInequalityConstraints;
7use gam_problem::{Coefficients, GlmLikelihoodSpec, InverseLink, LinearPredictor, RidgePassport};
8use gam_terms::construction::ReparamResult;
9use ndarray::{ArcArray1, Array1, Array2, ArrayView1};
10use serde::{Deserialize, Serialize};
11use std::sync::Arc;
12
13use super::{compute_observed_hessian_curvature_arrays, computeworkingweight_derivatives_from_eta};
14
15/// Whether the solve operates in sparse-native or dense-transformed coordinates.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum PirlsLinearSolvePath {
18 DenseTransformed,
19 SparseNative,
20}
21
22/// Coordinate frame for the PIRLS inner iteration.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum PirlsCoordinateFrame {
25 TransformedQs,
26 OriginalSparseNative,
27}
28
29/// Firth bias-reduction diagnostics at convergence.
30#[derive(Debug, Clone, Default)]
31pub enum FirthDiagnostics {
32 #[default]
33 Inactive,
34 Active {
35 jeffreys_logdet: f64,
36 hat_diag: Array1<f64>,
37 },
38}
39
40impl FirthDiagnostics {
41 #[inline]
42 pub fn jeffreys_logdet(&self) -> Option<f64> {
43 match self {
44 Self::Inactive => None,
45 Self::Active {
46 jeffreys_logdet, ..
47 } => Some(*jeffreys_logdet),
48 }
49 }
50}
51
52/// Which information matrix the penalized Hessian carries at the current
53/// PIRLS iterate.
54///
55/// Canonical links (logit-Binomial, log-Poisson) have W_obs == W_Fisher, so
56/// the two choices coincide. Non-canonical links (probit, cloglog, mixture,
57/// flexible, Gamma-log, ...) need observed information W_obs = W_Fisher -
58/// (y - mu) * B for the outer REML/Laplace log|H| and trace terms to be
59/// exact; Fisher weights alone yield a PQL-type surrogate. We fall back to
60/// `Fisher` only when the observed-information Hessian fails the
61/// positive-definiteness check, since the inner Newton step must be SPD.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63pub enum HessianCurvatureKind {
64 /// Expected (Fisher) information: W_Fisher = h'^2 / (phi * V(mu)).
65 /// Used as the inner iteration matrix when observed curvature fails (non-SPD).
66 Fisher,
67 /// Observed information: W_obs = W_Fisher - (y - mu) * B.
68 /// Required for the outer REML log|H| and trace terms (exact Laplace).
69 Observed,
70}
71
72/// The exported Laplace curvature kind used for the outer REML criterion.
73#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
74pub enum ExportedLaplaceCurvature {
75 ObservedExact,
76 ExpectedInformationSurrogate,
77 InvalidObservedCurvature {
78 min_eigenvalue: f64,
79 pd_tolerance: f64,
80 gradient_norm: f64,
81 },
82}
83
84/// Working state at a PIRLS iterate: gradient, Hessian, deviance, etc.
85#[derive(Debug, Clone)]
86pub struct WorkingState {
87 pub eta: LinearPredictor,
88 pub gradient: Array1<f64>,
89 pub hessian: gam_linalg::matrix::SymmetricMatrix,
90 /// Inner data log-kernel. A profiled Gaussian stores exactly `-D/2` for
91 /// conventional deviance `D`; likelihoods with a resolved physical scale
92 /// store the strict eta-space log-likelihood omitting response constants.
93 pub log_likelihood: f64,
94 pub deviance: f64,
95 pub penalty_term: f64,
96 pub firth: FirthDiagnostics,
97 // Ridge added to ensure positive definiteness of the penalized Hessian.
98 // `penalty_term` stores the full quadratic form contribution
99 // ridge * ||beta||^2. The optimization objective uses
100 // 0.5 * (deviance + penalty_term), so this corresponds to
101 // 0.5 * ridge * ||beta||^2 on the log-likelihood scale.
102 pub ridge_used: f64,
103 pub hessian_curvature: HessianCurvatureKind,
104 // Natural scale of the penalized gradient, used to form a scale-invariant
105 // KKT certificate. Equal to ||X'(weighted_residual)||_2 + ||S*beta||_2
106 // (+ ridge*||beta||_2 when a stabilizing ridge is active). Under
107 // stochastic noise the score component scales as O(sqrt(n)), so an
108 // absolute ||g||_2 < tol test rejects fits whose normalized stationarity
109 // residual is already negligible. Convergence uses ||g||_2 / (1 + this).
110 pub gradient_natural_scale: f64,
111}
112
113impl WorkingState {
114 /// Value minimized by PIRLS for this fully evaluated state.
115 #[inline]
116 pub fn penalized_objective(&self) -> f64 {
117 0.5 * (self.deviance + self.penalty_term)
118 }
119
120 #[inline]
121 pub fn jeffreys_logdet(&self) -> Option<f64> {
122 self.firth.jeffreys_logdet()
123 }
124
125 /// Scale-invariant relative gradient residual.
126 ///
127 /// Returns ||g||_2 / (1 + ||score||_2 + ||S*beta||_2 + ridge*||beta||_2).
128 /// `g_norm` is the projected/constrained stationarity residual in the
129 /// current PIRLS basis; the denominator is the natural magnitude of the
130 /// penalized gradient and is invariant under uniform rescaling of the
131 /// objective.
132 #[inline]
133 pub fn relative_gradient_norm(&self, g_norm: f64) -> f64 {
134 g_norm / (1.0 + self.gradient_natural_scale)
135 }
136
137 /// Dimension-based scale `√n · max(1, √p)` for the structural KKT bound.
138 ///
139 /// Under standardized columns, the score `Xᵀ(μ − y)` has components of
140 /// order O(√n), so the absolute test ‖g‖ < τ becomes systematically too
141 /// tight at large n. Multiplying τ by this scale restores the advertised
142 /// per-observation meaning.
143 #[inline]
144 pub(crate) fn kkt_dimension_scale(&self) -> f64 {
145 let n = self.eta.len().max(1) as f64;
146 let p = (self.gradient.len() as f64).max(1.0);
147 n.sqrt() * p.sqrt()
148 }
149
150 /// Strict KKT acceptance: `g_norm` certifies stationarity under EITHER
151 /// scale-invariant criterion (dimension-based or data-driven natural-scale).
152 ///
153 /// Both certificates are invariant under uniform rescaling of the objective
154 /// `F → c·F` (in the limit where the natural scale dominates the additive
155 /// `1` floor). Acceptance under either is sufficient because:
156 /// - the natural-scale bound is tighter when the data are well-scaled
157 /// (it tracks actual gradient component magnitudes);
158 /// - the dimension bound is tighter when the design matrix has unusual
159 /// scaling (so the natural scale is dominated by a single component).
160 #[inline]
161 pub fn certifies_kkt(&self, g_norm: f64, tol: f64) -> bool {
162 g_norm < tol * self.kkt_dimension_scale() || self.relative_gradient_norm(g_norm) < tol
163 }
164
165 /// Near-stationary band (10× the strict KKT tolerance) under EITHER
166 /// scale-invariant criterion. Used as a "good-enough" plateau check
167 /// that classifies a fit as `StalledAtValidMinimum` rather than as a
168 /// hard non-convergence. The band is `10 · tol` without a
169 /// floor — a caller asking for `tol = 1e-12` gets a 1e-11 band, not
170 /// the 1e-5 the old `tol.max(1e-6) * 10` formula silently widened it
171 /// to. The 1e-6 floor was masking real convergence regressions
172 /// (e.g. `constant_prior_mean_centers_penalty`'s LM-ridge induced
173 /// 2.5e-8 bias visible only when the user asked for sub-1e-6
174 /// precision).
175 #[inline]
176 pub fn near_stationary_kkt(&self, g_norm: f64, tol: f64) -> bool {
177 let near_tol = tol * 10.0;
178 g_norm <= near_tol * self.kkt_dimension_scale()
179 || self.relative_gradient_norm(g_norm) <= near_tol
180 }
181}
182
183/// Numerically stable Euclidean norm of an `Array1<f64>`.
184///
185/// Used to assemble the penalized-gradient natural scale at every
186/// `WorkingState` construction site (main GAM, identity-link short circuit,
187/// survival, test mocks). Centralizing here avoids drift between sites and
188/// makes the convergence certificate's denominator a single source of truth.
189///
190/// One pass, no allocation, O(p). At p≈10⁴ the cost is ≪ the O(np²) PIRLS
191/// inner work, so this is free in any setting where it matters.
192#[inline]
193pub fn array1_l2_norm(v: &Array1<f64>) -> f64 {
194 v.iter().map(|x| x * x).sum::<f64>().sqrt()
195}
196
197/// Adaptive KKT tolerance parameters for the inner PIRLS convergence test.
198#[derive(Clone, Copy, Debug)]
199pub struct AdaptiveKktTolerance {
200 pub eta: f64,
201 pub floor: f64,
202 pub ceiling: f64,
203 pub outer_grad_norm: f64,
204}
205
206/// Per-iteration PIRLS diagnostic info reported to the callback.
207#[derive(Clone, Debug)]
208pub struct WorkingModelIterationInfo {
209 pub iteration: usize,
210 pub deviance: f64,
211 pub gradient_norm: f64,
212 pub step_size: f64,
213 pub step_halving: usize,
214}
215
216/// Result of the inner `runworking_model_pirls` loop.
217#[derive(Clone)]
218pub struct WorkingModelPirlsResult {
219 pub beta: Coefficients,
220 pub state: WorkingState,
221 pub status: PirlsStatus,
222 pub iterations: usize,
223 pub lastgradient_norm: f64,
224 pub last_deviance_change: f64,
225 pub last_step_size: f64,
226 pub last_step_halving: usize,
227 pub max_abs_eta: f64,
228 pub constraint_kkt: Option<ConstraintKktDiagnostics>,
229 /// Levenberg-Marquardt damping coefficient at the last accepted
230 /// inner iter. Used by the REML runtime to seed the next PIRLS call
231 /// at the same outer fit, avoiding 4-6 iters of damping rediscovery
232 /// when the geometry calls for `λ_LM > 1e-6`.
233 pub final_lm_lambda: f64,
234 /// Gain ratio (`actual_reduction / predicted_reduction`) at the
235 /// last accepted inner iter. `None` when no step was accepted
236 /// (rejection-exhausted, MaxIterationsReached without acceptance).
237 /// Programmatic counterpart to the per-iter `[PIRLS lm-trajectory]`
238 /// log line's `accept_rho` field — the log is grep-only, this
239 /// field is queryable by the outer schedule and convergence guard.
240 /// Values near 1.0 indicate the quadratic model is faithful;
241 /// values much smaller indicate the LM model is over-stating
242 /// predicted reduction and the inner Newton may benefit from
243 /// shorter steps.
244 pub final_accept_rho: Option<f64>,
245 /// Minimum penalized objective (`½(state.deviance + state.penalty_term)`)
246 /// observed across all iterations whose state was computed during the
247 /// inner P-IRLS loop. The penalized objective is monotonically decreasing
248 /// along any descent path the inner solver takes, so this minimum is a
249 /// principled seed-screening proxy that remains meaningful even when the
250 /// solver hit its iteration cap before reaching the mode. `f64::INFINITY`
251 /// when no state was ever computed (paths that synthesize a result
252 /// without iterating, e.g. zero-iteration warm-only paths).
253 pub min_penalized_deviance: f64,
254 pub exported_laplace_curvature: ExportedLaplaceCurvature,
255}
256
257/// The status of the P-IRLS convergence.
258#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
259pub enum PirlsStatus {
260 /// Converged successfully within tolerance.
261 Converged,
262 /// Reached the iteration limit at a near-stationary checkpoint whose local
263 /// gradient/Hessian diagnostics look minimum-like. This remains a
264 /// non-converged checkpoint; only `Converged` may mint a fit.
265 StalledAtValidMinimum,
266 /// Reached maximum iterations without converging.
267 MaxIterationsReached,
268 /// Levenberg-Marquardt step search exhausted its retry budget (damping λ
269 /// reached its ceiling, attempts counter expired, or λ went non-finite)
270 /// before the projected gradient entered the near-stationary band. Distinct
271 /// from `MaxIterationsReached`, which means the outer iteration counter
272 /// itself ran out — that exhaustion is a "looped 100×, made progress each
273 /// time but never converged" signal, while this one is a "no acceptable
274 /// step direction even after damping" signal pointing at curvature trouble
275 /// or saturated likelihoods.
276 LmStepSearchExhausted,
277 /// Fitting process became unstable, likely due to perfect separation.
278 Unstable,
279}
280
281impl PirlsStatus {
282 /// Whether the inner loop concluded without producing a usable mode.
283 /// Both the iteration-cap and LM-exhausted exits should be treated the
284 /// same by callers that just want to know "did we get a valid solution?".
285 #[inline]
286 pub const fn is_failed_max_iterations(self) -> bool {
287 matches!(
288 self,
289 PirlsStatus::MaxIterationsReached | PirlsStatus::LmStepSearchExhausted
290 )
291 }
292
293 /// Short human-readable label for reports and diagnostics. Stable text
294 /// (not the `Debug` rendering) so report output does not silently change if
295 /// the variant identifiers are ever renamed.
296 #[inline]
297 pub const fn label(self) -> &'static str {
298 match self {
299 PirlsStatus::Converged => "Converged",
300 PirlsStatus::StalledAtValidMinimum => "Stalled at valid minimum",
301 PirlsStatus::MaxIterationsReached => "Max iterations reached",
302 PirlsStatus::LmStepSearchExhausted => "LM step search exhausted",
303 PirlsStatus::Unstable => "Unstable (possible separation)",
304 }
305 }
306
307 /// Whether this status represents a clean convergence to the mode. Only
308 /// `Converged` qualifies; every other state carries a caveat a reader
309 /// should see flagged.
310 #[inline]
311 pub const fn is_converged(self) -> bool {
312 matches!(self, PirlsStatus::Converged)
313 }
314}
315
316/// Holds the result of a converged P-IRLS inner loop for a fixed rho.
317///
318/// # Basis of Returned Tensors
319///
320/// **IMPORTANT:** All vector and matrix outputs in this struct (`beta_transformed`,
321/// `penalized_hessian_transformed`) are in the **stable, transformed basis**
322/// that was computed for the given set of smoothing parameters.
323///
324/// To obtain coefficients in the original, interpretable basis, the caller must
325/// back-transform them using the `qs` matrix from the `reparam_result` field:
326/// `beta_original = reparam_result.qs.dot(&beta_transformed)`
327///
328/// # Fields
329///
330/// * `beta_transformed`: The estimated coefficient vector in the STABLE, TRANSFORMED basis.
331/// * `penalized_hessian_transformed`: The penalized Hessian matrix at convergence
332/// (`X'W_H X + S_λ`, with `W_H` equal to Fisher or observed curvature,
333/// depending on the accepted PIRLS step) in the STABLE, TRANSFORMED basis.
334/// * `deviance`: The final deviance value. This is family-specific:
335/// - Gaussian identity: weighted residual sum of squares.
336/// - Binomial families: binomial deviance.
337/// - Poisson log: Poisson deviance.
338/// - Gamma log: Gamma unit deviance scaled by the fitted Gamma shape.
339/// * `finalweights`: The final Hessian-side working weights at convergence.
340/// * `solveweights`: The final score-side Fisher weights used in
341/// `X'W(z-eta) - S beta`.
342/// * `reparam_result`: Contains the transformation matrix (`qs`) and other reparameterization data.
343///
344/// # Point Estimate: Posterior Mode (MAP)
345///
346/// The coefficients returned by PIRLS are the **posterior mode** (Maximum A Posteriori estimate),
347/// not the posterior mean. For risk predictions, the posterior mean is theoretically preferable
348/// mode ≈ mean and it doesn't matter. For asymmetric posteriors (rare events, boundary effects),
349/// the mean would give more accurate calibrated probabilities. To obtain the posterior mean,
350/// one would need MCMC sampling from the posterior and average f(patient, β) over samples.
351#[derive(Clone)]
352pub struct PirlsResult {
353 pub likelihood: GlmLikelihoodSpec,
354 // Coefficients and Hessian are now in the STABLE, TRANSFORMED basis
355 pub beta_transformed: Coefficients,
356 pub penalized_hessian_transformed: SymmetricMatrix,
357 // Single stabilized Hessian for consistent cost/gradient computation
358 pub stabilizedhessian_transformed: SymmetricMatrix,
359 /// Canonical ridge metadata passport consumed by outer objective/gradient code.
360 pub ridge_passport: RidgePassport,
361
362 // The unpenalized deviance, calculated from mu and y
363 pub deviance: f64,
364
365 // Effective degrees of freedom at the solution
366 pub edf: f64,
367
368 // The penalty term, calculated stably within P-IRLS.
369 // This is beta_transformed' * S_transformed * beta_transformed, plus
370 // ridge_used * ||beta||^2 when stabilization is active so that the
371 // penalized deviance matches the stabilized Hessian.
372 pub stable_penalty_term: f64,
373
374 /// Firth diagnostics in the converged PIRLS state.
375 pub firth: FirthDiagnostics,
376
377 // Diagonal weights defining the Hessian surface returned to outer REML/LAML.
378 //
379 // For canonical links Fisher = Observed identically. For non-canonical links,
380 // PIRLS always recomputes observed weights at the accepted β̂ in a
381 // post-convergence finalization step (see "Post-convergence Laplace curvature
382 // finalization"), so `finalweights` carries the *observed-information* diagonal
383 // whenever the model supports it — even if the inner LM loop ended on Fisher
384 // due to a fallback. Exact label of what these represent is in
385 // `exported_laplace_curvature`; do not infer the kind from `hessian_curvature`
386 // (which records what the inner loop's last accepted step happened to use).
387 // #1868: the length-`n` row fields are `ArcArray1` (reference-counted
388 // ndarray, O(1) clone) so the n-free κ-trial skip path can SHARE the
389 // once-built frozen row bundle across every trial instead of
390 // re-materialising these placeholders per callback. On the exact path they
391 // are built owned and moved into the shared representation via
392 // `.into_shared()` (O(1) — no element copy). `ArcArray1` is an `ArrayBase`,
393 // so reads (indexing, iteration, `.dot`, `&a - &b`, `.len`, `.view`) work
394 // unchanged; only sites needing an owned `Array1`/`&Array1` take
395 // `.to_owned()`/`.view()`.
396 pub finalweights: ArcArray1<f64>,
397 // Additional PIRLS state captured at the accepted step to support
398 // cost/gradient consistency in the outer optimization
399 pub final_offset: ArcArray1<f64>,
400 pub final_eta: ArcArray1<f64>,
401 pub finalmu: ArcArray1<f64>,
402 /// Score-side Fisher weights used in `X'W(z-eta) - S beta`.
403 pub solveweights: ArcArray1<f64>,
404 pub solveworking_response: ArcArray1<f64>,
405 pub solvemu: ArcArray1<f64>,
406 pub solve_dmu_deta: ArcArray1<f64>,
407 pub solve_d2mu_deta2: ArcArray1<f64>,
408 pub solve_d3mu_deta3: ArcArray1<f64>,
409 /// First eta-derivative of the diagonal Hessian curvature W_H(eta):
410 /// c_i := dW_i/deta_i at the accepted PIRLS solution.
411 ///
412 /// This carries 3rd-order likelihood information used in exact dH/dρ
413 /// terms for outer LAML derivatives.
414 pub solve_c_array: ArcArray1<f64>,
415 /// Exact certificate that at least one entry of `solve_c_array` is nonzero.
416 ///
417 /// Assembly uses this to choose the intrinsic-Hessian correction. Carrying
418 /// the fact from row finalization prevents every value-only REML probe from
419 /// rescanning all observations; Gaussian identity stamps `false`
420 /// analytically because its working curvature is eta-invariant (#2435).
421 pub solve_c_nontrivial: bool,
422 /// Second eta-derivative of the diagonal Hessian curvature W_H(eta):
423 /// d_i := d²W_i/deta_i² at the accepted PIRLS solution.
424 ///
425 /// This carries 4th-order likelihood information used in exact d²H/dρ²
426 /// terms for the outer LAML Hessian.
427 pub solve_d_array: ArcArray1<f64>,
428 /// True when `solve_c_array` / `solve_d_array` are placeholders rather
429 /// than supported likelihood derivatives.
430 pub derivatives_unsupported: bool,
431
432 // Keep all other fields as they are
433 pub status: PirlsStatus,
434 pub iteration: usize,
435 pub max_abs_eta: f64,
436 pub lastgradient_norm: f64,
437 /// Natural scale of the penalized gradient at the accepted PIRLS state,
438 /// equal to ‖Xᵀ(weighted residual)‖₂ + ‖Sβ‖₂ (+ ridge·‖β‖₂ when active).
439 /// Mirrors `WorkingState::gradient_natural_scale` so that callers reading
440 /// `PirlsResult` directly (e.g. seed-screening cost augmentation) can form
441 /// the scale-invariant residual r_g = ‖g‖ / (1 + this) without rebuilding
442 /// the score and penalty norms.
443 pub gradient_natural_scale: f64,
444 /// Penalized inner KKT residual `r = ∇_β L_pen(β̂) = Sβ̂ − ∇ℓ(β̂) (+ridge·β̂)`
445 /// at the accepted P-IRLS iterate, in the STABLE/TRANSFORMED coefficient
446 /// basis (the same frame as `beta_transformed` and the transformed penalized
447 /// Hessian). This is the exact vector whose L2 norm `lastgradient_norm`
448 /// records (see `WorkingState::gradient`, assembled as `Xᵀ(η−z)·w + Sβ`,
449 /// which equals `Sβ − ∇ℓ` because `Xᵀ(η−z)·w = −∇ℓ`). Storing the vector —
450 /// not just its norm — lets the outer REML/LAML evaluator engage the
451 /// inner-KKT envelope correction `Ṽ = V − ½·rᵀH⁻¹r` on design-moving
452 /// flexible-link and ψ/anisotropy paths, where the outer optimizer may
453 /// accept β̂ at a first-order inner cap short of exact stationarity. The
454 /// correction and its θ-gradient vanish as `r → 0`, so a fully-converged
455 /// fit is unchanged. See [`crate::model_types::ProjectedKktResidual`].
456 pub penalized_gradient_transformed: Array1<f64>,
457 pub last_deviance_change: f64,
458 pub last_step_halving: usize,
459 pub hessian_curvature: HessianCurvatureKind,
460 pub exported_laplace_curvature: ExportedLaplaceCurvature,
461 /// Levenberg-Marquardt damping coefficient at the converged inner
462 /// iter. Cached by the REML runtime so the next PIRLS call in the
463 /// same outer optimization can seed `λ_LM` to this value instead
464 /// of cold-starting at `1e-6`. Mirrors `WorkingModelPirlsResult::final_lm_lambda`.
465 pub final_lm_lambda: f64,
466 /// Gain ratio of the last accepted LM step inside this PIRLS solve,
467 /// `None` when no step was accepted (e.g. zero-iteration synthesis,
468 /// rejection-exhausted, MaxIterations without acceptance). Mirrors
469 /// `WorkingModelPirlsResult::final_accept_rho`. Programmatic
470 /// counterpart to the per-iter `[PIRLS lm-trajectory]` log line's
471 /// `accept_rho` field, queryable by outer consumers (cap schedule,
472 /// convergence guard) for inner-Newton model-fidelity decisions.
473 pub final_accept_rho: Option<f64>,
474 /// Optional KKT diagnostics when inequality constraints were active.
475 pub constraint_kkt: Option<ConstraintKktDiagnostics>,
476 /// Linear inequality system enforced in transformed PIRLS coordinates:
477 /// `A * beta_transformed >= b`.
478 pub linear_constraints_transformed: Option<LinearInequalityConstraints>,
479
480 // Pass through the entire reparameterization result for use in the gradient
481 pub reparam_result: ReparamResult,
482 // Cached X·Qs for this PIRLS result (transformed design matrix)
483 pub x_transformed: DesignMatrix,
484 pub coordinate_frame: PirlsCoordinateFrame,
485 /// True when this fixed-rho inner solve completed on a GPU path.
486 pub used_device: bool,
487 /// True when this result was compacted for REML LRU storage and needs
488 /// cold artifacts (for example `x_transformed`) rehydrated before exact
489 /// bundle construction.
490 pub cache_compacted: bool,
491 /// Minimum penalized objective observed across the inner P-IRLS loop.
492 /// Mirrors `WorkingModelPirlsResult::min_penalized_deviance`. Used as the
493 /// seed-screening ranking proxy: the penalized objective descends monotonically
494 /// along any inner descent path, so the per-seed minimum tells the outer
495 /// cascade "how good a fit this rho's neighbourhood can support" even
496 /// when the inner solver was capped before reaching the mode.
497 pub min_penalized_deviance: f64,
498}
499
500impl PirlsResult {
501 /// Export the stabilized transformed Hessian as an exact dense matrix for
502 /// downstream solve paths that require explicit Hessians.
503 ///
504 /// The returned matrix is the convergence Hessian already used by PIRLS and
505 /// REML (`X'W_HX + S_λ`, plus the explicit stabilization ridge when active).
506 /// Sparse-native fits are materialized from their assembled sparse Hessian;
507 /// no numerical Hessian approximation or compatibility fallback is used.
508 pub fn dense_stabilizedhessian_transformed(
509 &self,
510 context: &str,
511 ) -> Result<Array2<f64>, EstimationError> {
512 self.stabilizedhessian_transformed
513 .try_to_dense_exact(context)
514 .map_err(EstimationError::InvalidInput)
515 }
516
517 #[inline]
518 pub fn jeffreys_logdet(&self) -> Option<f64> {
519 self.firth.jeffreys_logdet()
520 }
521
522 /// Typed view of the Hessian-side working weight diagonal stored on this
523 /// result, sign-honest. `finalweights` carries the observed-information
524 /// diagonal whenever the model supports it (see `exported_laplace_curvature`),
525 /// and observed weights `W_obs = W_F - (y - μ) · B` can be negative for
526 /// non-canonical links. Consumers feeding this into the asymmetric
527 /// `X_iᵀ W X_j` path, `weighted_crossprod_dense_rows`, or
528 /// `xt_diag_x_signed_op` must use this typed view rather than borrowing
529 /// the raw `Array1<f64>` so the function-boundary type contract from
530 /// `linalg/matrix.rs` is construction-enforced.
531 #[inline]
532 pub fn final_weights_signed(&self) -> SignedWeightsView<'_> {
533 SignedWeightsView::new(self.finalweights.view())
534 }
535
536 /// Typed view of the score-side Fisher weights `W_F = h'²/(φ V(μ)) ≥ 0`
537 /// stored on this result, PSD-by-construction. Used by PSD-Gram kernels
538 /// (`dense_xtwx_view`, `sparse_csr_weighted_xtwx_*`, `xt_diag_x_psd_op`)
539 /// without a runtime sign scan; the PSD obligation is discharged
540 /// algebraically by the Fisher formula at the construction site in
541 /// `solver/pirls/mod.rs`. New callers that need the same diagonal under
542 /// a sign-honest API should route through `as_signed()` on the returned
543 /// view rather than reconstructing from the raw array.
544 #[inline]
545 pub fn solve_weights_psd(&self) -> PsdWeightsView<'_> {
546 PsdWeightsView::from_view_unchecked(self.solveweights.view())
547 }
548
549 /// Scale-invariant relative gradient residual at the accepted PIRLS state.
550 ///
551 /// Returns ‖g‖ / (1 + ‖score‖ + ‖Sβ‖ + ridge·‖β‖). Numerator is
552 /// `lastgradient_norm`; denominator is `1 + gradient_natural_scale`.
553 /// This is the "r_g" used by seed-screening cost augmentation.
554 #[inline]
555 pub fn relative_gradient_norm(&self) -> f64 {
556 self.lastgradient_norm / (1.0 + self.gradient_natural_scale)
557 }
558
559 pub(crate) fn compact_for_reml_cache(&self) -> Self {
560 Self {
561 likelihood: self.likelihood.clone(),
562 beta_transformed: self.beta_transformed.clone(),
563 penalized_hessian_transformed: self.penalized_hessian_transformed.clone(),
564 stabilizedhessian_transformed: self.stabilizedhessian_transformed.clone(),
565 ridge_passport: self.ridge_passport,
566 deviance: self.deviance,
567 edf: self.edf,
568 stable_penalty_term: self.stable_penalty_term,
569 firth: self.firth.clone(),
570 finalweights: ArcArray1::zeros(0),
571 final_offset: ArcArray1::zeros(0),
572 final_eta: self.final_eta.clone(),
573 finalmu: ArcArray1::zeros(0),
574 solveweights: self.solveweights.clone(),
575 solveworking_response: self.solveworking_response.clone(),
576 solvemu: self.solvemu.clone(),
577 solve_dmu_deta: ArcArray1::zeros(0),
578 solve_d2mu_deta2: ArcArray1::zeros(0),
579 solve_d3mu_deta3: ArcArray1::zeros(0),
580 solve_c_array: self.solve_c_array.clone(),
581 solve_c_nontrivial: self.solve_c_nontrivial,
582 solve_d_array: self.solve_d_array.clone(),
583 derivatives_unsupported: self.derivatives_unsupported,
584 status: self.status,
585 iteration: self.iteration,
586 max_abs_eta: self.max_abs_eta,
587 lastgradient_norm: self.lastgradient_norm,
588 gradient_natural_scale: self.gradient_natural_scale,
589 // Length-p vector; carried across compaction/rehydration so the
590 // inner-KKT envelope correction survives an LRU round-trip without
591 // rebuilding the score from the (dropped) transformed design.
592 penalized_gradient_transformed: self.penalized_gradient_transformed.clone(),
593 last_deviance_change: self.last_deviance_change,
594 last_step_halving: self.last_step_halving,
595 hessian_curvature: self.hessian_curvature,
596 exported_laplace_curvature: self.exported_laplace_curvature.clone(),
597 final_lm_lambda: self.final_lm_lambda,
598 final_accept_rho: self.final_accept_rho,
599 constraint_kkt: self.constraint_kkt.clone(),
600 linear_constraints_transformed: self.linear_constraints_transformed.clone(),
601 reparam_result: self.reparam_result.clone(),
602 x_transformed: DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(
603 Array2::zeros((0, 0)),
604 )),
605 coordinate_frame: self.coordinate_frame,
606 used_device: self.used_device,
607 cache_compacted: true,
608 min_penalized_deviance: self.min_penalized_deviance,
609 }
610 }
611
612 pub(crate) fn rehydrate_after_reml_cache(
613 &self,
614 x_original: &DesignMatrix,
615 y: ArrayView1<'_, f64>,
616 priorweights: ArrayView1<'_, f64>,
617 offset: ArrayView1<'_, f64>,
618 inverse_link: &InverseLink,
619 ) -> Result<Self, EstimationError> {
620 if !self.cache_compacted {
621 return Ok(self.clone());
622 }
623
624 // #1868: cold LRU rehydration path — materialise the compacted rows from
625 // the frozen link/derivatives and re-wrap into the shared `ArcArray1`
626 // fields (`.into()`, O(1) once owned).
627 let final_eta_owned = self.final_eta.to_owned();
628 let (score_c_array, score_d_array, solve_dmu_deta, solve_d2mu_deta2, solve_d3mu_deta3) =
629 computeworkingweight_derivatives_from_eta(
630 &self.likelihood,
631 inverse_link,
632 &final_eta_owned,
633 priorweights,
634 )?;
635 let (finalweights, solve_c_array, solve_d_array): (
636 ArcArray1<f64>,
637 ArcArray1<f64>,
638 ArcArray1<f64>,
639 ) = if self.hessian_curvature == HessianCurvatureKind::Observed {
640 let (fw, sc, sd) = compute_observed_hessian_curvature_arrays(
641 &self.likelihood,
642 inverse_link,
643 &final_eta_owned,
644 y,
645 &self.solveweights.to_owned(),
646 priorweights,
647 )?;
648 (fw.into(), sc.into(), sd.into())
649 } else {
650 (
651 self.solveweights.clone(),
652 score_c_array.clone().into(),
653 score_d_array.clone().into(),
654 )
655 };
656 // Lazy rehydration: wrap in ReparamOperator instead of materializing X·Qs.
657 let qs_arc = Arc::new(self.reparam_result.qs.clone());
658 Ok(Self {
659 likelihood: self.likelihood.clone(),
660 beta_transformed: self.beta_transformed.clone(),
661 penalized_hessian_transformed: self.penalized_hessian_transformed.clone(),
662 stabilizedhessian_transformed: self.stabilizedhessian_transformed.clone(),
663 ridge_passport: self.ridge_passport,
664 used_device: self.used_device,
665 deviance: self.deviance,
666 edf: self.edf,
667 stable_penalty_term: self.stable_penalty_term,
668 firth: self.firth.clone(),
669 finalweights,
670 final_offset: offset.to_owned().into(),
671 final_eta: self.final_eta.clone(),
672 finalmu: self.solvemu.clone(),
673 solveweights: self.solveweights.clone(),
674 solveworking_response: self.solveworking_response.clone(),
675 solvemu: self.solvemu.clone(),
676 solve_dmu_deta: solve_dmu_deta.into(),
677 solve_d2mu_deta2: solve_d2mu_deta2.into(),
678 solve_d3mu_deta3: solve_d3mu_deta3.into(),
679 solve_c_array,
680 solve_c_nontrivial: self.solve_c_nontrivial,
681 solve_d_array,
682 derivatives_unsupported: self.derivatives_unsupported,
683 status: self.status,
684 iteration: self.iteration,
685 max_abs_eta: self.max_abs_eta,
686 lastgradient_norm: self.lastgradient_norm,
687 gradient_natural_scale: self.gradient_natural_scale,
688 // Length-p vector; carried across compaction/rehydration so the
689 // inner-KKT envelope correction survives an LRU round-trip without
690 // rebuilding the score from the (dropped) transformed design.
691 penalized_gradient_transformed: self.penalized_gradient_transformed.clone(),
692 last_deviance_change: self.last_deviance_change,
693 last_step_halving: self.last_step_halving,
694 hessian_curvature: self.hessian_curvature,
695 exported_laplace_curvature: self.exported_laplace_curvature.clone(),
696 final_lm_lambda: self.final_lm_lambda,
697 final_accept_rho: self.final_accept_rho,
698 constraint_kkt: self.constraint_kkt.clone(),
699 linear_constraints_transformed: self.linear_constraints_transformed.clone(),
700 reparam_result: self.reparam_result.clone(),
701 x_transformed: DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(
702 Arc::new(ReparamOperator::new(x_original.clone(), qs_arc)),
703 )),
704 coordinate_frame: self.coordinate_frame,
705 cache_compacted: false,
706 min_penalized_deviance: self.min_penalized_deviance,
707 })
708 }
709}