Skip to main content

gam_problem/
block_spec.rs

1//! Data model for the blockwise carrier (subset moved down to `gam-problem`):
2//! parameter-block specs, the effective-Jacobian and channel-Hessian
3//! abstractions, per-block working sets and states, and the block geometry
4//! directional derivative.
5//!
6//! The coefficient-group/label/prior types, `custom_family_block_role`, and the
7//! blockspec validators remain in the family crate because they depend on
8//! `CoefficientGroupPrior`/`RhoPrior`/`BlockRole`/`CustomFamilyError`.
9
10use std::ops::Range;
11use std::sync::Arc;
12
13use ndarray::{Array1, Array2};
14
15use crate::PenaltyMatrix;
16use gam_linalg::matrix::{DesignMatrix, SymmetricMatrix};
17
18/// Per-subject channel Hessian provider for multi-output families.
19///
20/// The Fisher information decomposition for multi-output families is
21///
22/// ```text
23/// I(β) = Σ_i  J_iᵀ W_i J_i
24/// ```
25///
26/// where `J_i` is the channel-stacked Jacobian (shape `n_outputs × p` for
27/// subject `i`) and `W_i` is the `n_outputs × n_outputs` per-subject channel
28/// Hessian of the row negative log-likelihood (the second-derivative block of
29/// `−log L_i(u_i)` at a pilot β, PSD-clamped).
30///
31/// For single-output families this is the scalar IRLS weight; for multi-output
32/// families (survival marginal-slope: `n_outputs = 4`; location-scale:
33/// `n_outputs = 2`) it carries full cross-channel curvature.
34///
35/// The identifiability canonicalisation step uses the `n_outputs`-channel
36/// weighted joint design `W_joint = Σ_i sqrt(W_i) ⊗ J_i` to detect
37/// block-against-block aliasing.  When this trait is present on
38/// `ParameterBlockSpec::channel_hessian`, `canonicalize_for_identifiability`
39/// routes through `audit_identifiability_channel_aware`; when absent it falls
40/// back to the scalar-weight flat audit.
41///
42/// # W-metric rank theorem
43///
44/// The canonicalisation computes `rank(J^T W J)` where `W_blkdiag =
45/// block-diagonal of per-subject W_i`.  This rank equals
46///
47/// ```text
48/// rank(J) − dim(range(J) ∩ ker(W_blkdiag))
49/// ```
50///
51/// i.e. columns of `J` that lie in the kernel of `W_blkdiag` (flat directions
52/// in the curvature landscape at the pilot β) are correctly identified as
53/// curvature-redundant and may be dropped.
54pub trait FamilyChannelHessian: Send + Sync {
55    /// Number of output channels `n_outputs` (= K in the row Jacobian).
56    fn n_outputs(&self) -> usize;
57
58    /// Number of subjects (rows).
59    fn n_subjects(&self) -> usize;
60
61    /// Fill the `n_outputs × n_outputs` per-subject channel Hessian `W_i`
62    /// into `out` (row-major, length `n_outputs * n_outputs`) for subject `i`.
63    /// Negative eigenvalues must be clamped to zero (PSD projection) before
64    /// or inside this call.
65    fn fill_subject(&self, i: usize, out: &mut [f64]);
66
67    /// Materialise the full `(n_subjects × n_outputs × n_outputs)` tensor.
68    /// Default implementation calls `fill_subject` for each row.
69    fn evaluate_full(&self) -> ndarray::Array3<f64> {
70        let n = self.n_subjects();
71        let k = self.n_outputs();
72        let mut out = ndarray::Array3::<f64>::zeros((n, k, k));
73        let mut buf = vec![0.0_f64; k * k];
74        for i in 0..n {
75            self.fill_subject(i, &mut buf);
76            for a in 0..k {
77                for b in 0..k {
78                    out[[i, a, b]] = buf[a * k + b];
79                }
80            }
81        }
82        out
83    }
84
85}
86
87/// β-linearization state passed to [`BlockEffectiveJacobian::effective_jacobian_at`].
88///
89/// At pre-fit initialization, pass `beta = &[]` / zeros and `family_scalars = None`.
90/// Families that need β-dependent scalars (e.g. survival marginal-slope's q0, q1,
91/// g, c, z) store them in `family_scalars` as a concrete type behind
92/// `Arc<dyn Any + Send + Sync>` and downcast inside their impl.
93pub struct FamilyLinearizationState<'a> {
94    pub beta: &'a [f64],
95    /// Optional family-shared scalars at this β linearization.
96    /// Downcast via `state.family_scalars.as_ref().and_then(|a| a.downcast_ref::<T>())`.
97    pub family_scalars: Option<Arc<dyn std::any::Any + Send + Sync>>,
98    /// Optional per-subject channel Hessian for multi-output families.
99    /// When `Some`, the identifiability canonicalisation step and the Gram
100    /// builder use the channel-stacked Fisher information instead of the
101    /// scalar-weight approximation.  Single-output families leave this `None`.
102    pub channel_hessian: Option<Arc<dyn FamilyChannelHessian>>,
103    /// Probit frailty scale factor `s_f = 1/√(1+σ²)`.
104    ///
105    /// For survival marginal-slope families the logslope η contribution is
106    /// `s_f · g · z`, so any Jacobian callback that depends on g or z must
107    /// read `s_f` from here rather than from a captured-at-construction value.
108    /// When σ = 0 (no frailty) or for non-frailty families, set this to 1.0.
109    ///
110    /// Since σ is always **fixed** (not jointly optimised with β) in the
111    /// survival family, `s_f` is a static scalar for the entire inner fit;
112    /// `∂s_f/∂σ` never appears in the β-Jacobian.  The field is nonetheless
113    /// carried through state so that Jacobian callbacks are not required to
114    /// capture `s_f` at spec-construction time — they can read it at
115    /// evaluation time and thus stay correct across outer-loop σ updates.
116    pub probit_frailty_scale: f64,
117}
118
119/// β-dependent Jacobian callback for a parameter block.
120///
121/// Principled long-term contract for expressing how a block contributes to
122/// the stacked linear predictor at a given β:
123///
124/// ```text
125/// J(β) ∈ ℝ^{n_rows · n_outputs × p_block}
126/// ```
127///
128/// - Single-output linear block: returns `design.clone()`.
129/// - Row-scaled block (`RowScaledJacobian`): returns `diag(eta_scaling) · design` (still linear in β).
130/// - Multi-output block (e.g. survival marginal-slope with η0, η1, ad1):
131///   stacks `∂eta_r/∂β_k` for `r ∈ 0..n_outputs`, row-major ordering.
132///
133/// The default impl on [`ParameterBlockSpec::effective_jacobian_at`] is:
134/// - `jacobian_callback = None` → `design.clone()`.
135/// - `jacobian_callback = Some(cb)` → delegates to `cb.effective_jacobian_at`.
136pub trait BlockEffectiveJacobian: Send + Sync {
137    /// Stacked multi-output Jacobian for a contiguous observation row range.
138    ///
139    /// Shape: `(rows.len() * n_outputs, p_block)`, with the same channel-major
140    /// layout as [`Self::effective_jacobian_at`]: row
141    /// `channel * rows.len() + local_row` is `rows.start + local_row` in that
142    /// output channel. Implementations should keep this as the single source of
143    /// row math so large construction-time audits can stream chunks instead of
144    /// materialising all `n * p * K` entries at once.
145    fn effective_jacobian_rows(
146        &self,
147        state: &FamilyLinearizationState<'_>,
148        rows: Range<usize>,
149    ) -> Result<Array2<f64>, String>;
150
151    /// Stacked multi-output Jacobian at the current β.
152    ///
153    /// Shape: `(n_rows * n_outputs, p_block)`, **channel-major**: rows
154    /// `r * n_rows .. (r + 1) * n_rows` carry output channel `r`'s row
155    /// Jacobian, so `stacked[r * n_rows + i, j]` is observation `i`'s row at
156    /// output `r` and coefficient column `j`.  Every consumer that destacks
157    /// this matrix (audit, canonicaliser, fit) relies on this layout — see
158    /// `BlockJacobianAsRowOp::from_callback` for the destacking transpose.
159    /// For `n_outputs = 1` this is identical to the `(n_rows, p_block)` effective
160    /// design used by the flat identifiability audit.
161    fn effective_jacobian_at(
162        &self,
163        state: &FamilyLinearizationState<'_>,
164    ) -> Result<Array2<f64>, String> {
165        let full = self.effective_jacobian_rows(state, 0..usize::MAX)?;
166        Ok(full)
167    }
168
169    /// Number of stacked output channels. 1 for most blocks.
170    fn n_outputs(&self) -> usize {
171        1
172    }
173
174    /// Returns the per-row scaling vector when this callback is a simple
175    /// diagonal-scaling block (`RowScaledJacobian`).  Used by the
176    /// identifiability audit's skewness-aware bias correction (T25).
177    ///
178    /// Returns `None` for all blocks except `RowScaledJacobian`.
179    fn eta_row_scaling_for_skewness(&self) -> Option<Arc<[f64]>> {
180        None
181    }
182
183    /// Whether the identifiability canonicaliser must keep this block at its
184    /// full raw column width instead of column-reducing it.
185    ///
186    /// The `#933` reduction path wraps a `jacobian_callback` block in a
187    /// gauge-composed Jacobian so the family fits in a reduced section — sound
188    /// only when the family's effective geometry is DERIVED from the callback
189    /// (multinomial softmax, marginal-slope logslope). It is NOT sound for a
190    /// callback whose effective Jacobian is a **fixed nonlinear functional
191    /// basis** recomputed at the raw coefficient width on every evaluation
192    /// (the survival marginal-slope monotone time-wiggle time block): its
193    /// downstream likelihood reads raw-width internal designs and asserts
194    /// `beta.len() == p_raw`, so a reduced β desynchronises that layout — the
195    /// same failure mode the competing-risks dead-column veto already guards.
196    /// Such a block returns `true` so the canonicaliser keeps it at raw width
197    /// (its own penalty nullspace regularises the weak directions instead).
198    ///
199    /// Defaults to `false`: every existing callback reduces safely.
200    fn locks_raw_width_reduction(&self) -> bool {
201        false
202    }
203}
204
205/// A [`BlockEffectiveJacobian`] for any block that contributes linearly to
206/// exactly one output of a multi-output family.
207///
208/// `own_output` is the zero-based output index that this block drives.
209/// `n_family_outputs` is the total number of outputs (e.g. 2 for location-scale).
210/// `design` is the block's effective design matrix (n × p_block).
211///
212/// The returned Jacobian has shape `(n_family_outputs * n, p_block)`:
213/// rows `own_output * n .. (own_output + 1) * n` contain `design`,
214/// all other rows are zero.
215pub struct AdditiveBlockJacobian {
216    pub design: Array2<f64>,
217    pub own_output: usize,
218    pub n_family_outputs: usize,
219}
220
221impl BlockEffectiveJacobian for AdditiveBlockJacobian {
222    fn effective_jacobian_rows(
223        &self,
224        state: &FamilyLinearizationState<'_>,
225        rows: Range<usize>,
226    ) -> Result<Array2<f64>, String> {
227        let n = self.design.nrows();
228        let p = self.design.ncols();
229        let rows = clamp_jacobian_rows(rows, n);
230        // Additive (linear) block: Jacobian is β-independent — design does
231        // not depend on state.beta. Verify beta contains no NaN when provided.
232        if !state.beta.is_empty() && state.beta.iter().any(|v| v.is_nan()) {
233            return Err(
234                "AdditiveBlockJacobian::effective_jacobian_at: beta contains NaN".to_string(),
235            );
236        }
237        let chunk = rows.end - rows.start;
238        let total_rows = self.n_family_outputs * chunk;
239        let mut jac = Array2::<f64>::zeros((total_rows, p));
240        let row_start = self.own_output * chunk;
241        jac.slice_mut(ndarray::s![row_start..row_start + chunk, ..])
242            .assign(&self.design.slice(ndarray::s![rows.start..rows.end, ..]));
243        Ok(jac)
244    }
245
246    fn n_outputs(&self) -> usize {
247        self.n_family_outputs
248    }
249}
250
251/// A [`BlockEffectiveJacobian`] for a single-output block whose contribution
252/// to the linear predictor is `diag(eta_scaling) · design` (row-wise scaling).
253///
254/// This is the canonical replacement for the former `eta_row_scaling` field on
255/// [`ParameterBlockSpec`].  The identifiability audit's skewness-aware bias
256/// correction can recover the scaling vector via
257/// [`BlockEffectiveJacobian::eta_row_scaling_for_skewness`].
258pub struct RowScaledJacobian {
259    pub design: Arc<Array2<f64>>,
260    pub eta_scaling: Arc<[f64]>,
261}
262
263impl BlockEffectiveJacobian for RowScaledJacobian {
264    fn effective_jacobian_rows(
265        &self,
266        state: &FamilyLinearizationState<'_>,
267        rows: Range<usize>,
268    ) -> Result<Array2<f64>, String> {
269        let n = self.design.nrows();
270        let rows = clamp_jacobian_rows(rows, n);
271        if self.eta_scaling.len() != n {
272            return Err(format!(
273                "RowScaledJacobian: eta_scaling length {} != design nrows {}",
274                self.eta_scaling.len(),
275                n,
276            ));
277        }
278        // Row-scaled blocks are β-linear; verify the linearization point
279        // contains no NaN when β is provided (sanity check on caller state).
280        if !state.beta.is_empty() && state.beta.iter().any(|v| v.is_nan()) {
281            return Err(
282                "RowScaledJacobian::effective_jacobian_at: state.beta contains NaN".to_string(),
283            );
284        }
285        let mut scaled = self
286            .design
287            .slice(ndarray::s![rows.start..rows.end, ..])
288            .to_owned();
289        for local_i in 0..scaled.nrows() {
290            let s = self.eta_scaling[rows.start + local_i];
291            for j in 0..scaled.ncols() {
292                scaled[[local_i, j]] *= s;
293            }
294        }
295        Ok(scaled)
296    }
297
298    fn eta_row_scaling_for_skewness(&self) -> Option<Arc<[f64]>> {
299        Some(Arc::clone(&self.eta_scaling))
300    }
301}
302
303pub(crate) fn clamp_jacobian_rows(rows: Range<usize>, n: usize) -> Range<usize> {
304    let start = rows.start.min(n);
305    let end = rows.end.min(n);
306    start..end.max(start)
307}
308
309/// A [`BlockEffectiveJacobian`] that composes an inner callback's raw-width
310/// effective Jacobian with a fixed reduced→raw block transform `T_b`
311/// (`p_raw × r_reduced`), so the family sees the **reduced** coordinates by
312/// construction (#933).
313///
314/// The inner callback emits its row Jacobian in the raw coordinate system
315/// (`(rows · k) × p_raw`), the layout every `BlockEffectiveJacobian` impl
316/// produces — channel-major rows, raw columns. Post-multiplying each row by
317/// `T_b` rotates those raw columns into the reduced section: the effective
318/// reduced Jacobian is `J_raw · T_b`, with `r_reduced` columns. On the model
319/// `η = J_raw · β_raw = (J_raw · T_b) · θ` this is the exact reduced operator
320/// for the reduced coefficient θ, and the family lifts θ back to β_raw through
321/// the SAME `T_b` via the one [`Gauge`](crate::Gauge).
322///
323/// This is the inversion #933 calls for: instead of forwarding a raw-width
324/// callback alongside a column-selection `T_i` (which leaves the family
325/// asserting raw column counts on a reduced spec and panicking), the callback
326/// is wrapped so its output already has the reduced width — the family captures
327/// the reduced design and its row-Hessian column-count assertions hold by
328/// construction. A column-selection `T_b` (zero/one entries) makes this exactly
329/// the audit's drop; a general orthonormal `T_b` makes it any gauge section.
330pub struct GaugeComposedJacobian {
331    inner: Arc<dyn BlockEffectiveJacobian>,
332    /// Reduced→raw block transform `T_b`, shape `(p_raw × r_reduced)`.
333    t_block: Arc<Array2<f64>>,
334}
335
336impl GaugeComposedJacobian {
337    /// Wrap `inner` so its effective Jacobian is post-multiplied by `t_block`
338    /// (`p_raw × r_reduced`). `t_block.nrows()` must equal the inner callback's
339    /// raw column count.
340    pub fn new(inner: Arc<dyn BlockEffectiveJacobian>, t_block: Arc<Array2<f64>>) -> Self {
341        Self { inner, t_block }
342    }
343}
344
345impl BlockEffectiveJacobian for GaugeComposedJacobian {
346    fn effective_jacobian_rows(
347        &self,
348        state: &FamilyLinearizationState<'_>,
349        rows: Range<usize>,
350    ) -> Result<Array2<f64>, String> {
351        let raw_width = self.t_block.nrows();
352        let reduced_width = self.t_block.ncols();
353        let lifted_beta;
354        let lifted_state;
355        let zero_raw_beta;
356        let delegate_state = if state.beta.len() == raw_width {
357            state
358        } else if state.beta.len() == reduced_width {
359            lifted_beta = self.t_block.dot(&ndarray::ArrayView1::from(state.beta));
360            lifted_state = FamilyLinearizationState {
361                beta: lifted_beta
362                    .as_slice()
363                    .expect("GaugeComposedJacobian lifted beta is contiguous"),
364                family_scalars: state.family_scalars.clone(),
365                channel_hessian: state.channel_hessian.clone(),
366                probit_frailty_scale: state.probit_frailty_scale,
367            };
368            &lifted_state
369        } else if state.beta.is_empty() {
370            zero_raw_beta = ndarray::Array1::<f64>::zeros(raw_width);
371            lifted_state = FamilyLinearizationState {
372                beta: zero_raw_beta
373                    .as_slice()
374                    .expect("GaugeComposedJacobian zero raw beta is contiguous"),
375                family_scalars: state.family_scalars.clone(),
376                channel_hessian: state.channel_hessian.clone(),
377                probit_frailty_scale: state.probit_frailty_scale,
378            };
379            &lifted_state
380        } else {
381            return Err(format!(
382                "GaugeComposedJacobian: beta has length {}, expected raw width {} \
383                 or reduced width {}; this wrapper cannot infer a block slice from a joint \
384                 coefficient vector",
385                state.beta.len(),
386                raw_width,
387                reduced_width,
388            ));
389        };
390        let j_raw = self.inner.effective_jacobian_rows(delegate_state, rows)?;
391        if j_raw.ncols() != self.t_block.nrows() {
392            return Err(format!(
393                "GaugeComposedJacobian: inner Jacobian has {} columns but T_b has {} rows",
394                j_raw.ncols(),
395                self.t_block.nrows(),
396            ));
397        }
398        // (rows·k × p_raw) · (p_raw × r_reduced) = (rows·k × r_reduced).
399        Ok(j_raw.dot(self.t_block.as_ref()))
400    }
401
402    fn n_outputs(&self) -> usize {
403        self.inner.n_outputs()
404    }
405
406    // Skewness scaling is a raw-row property; reducing the column space does not
407    // change the per-row scaling, so it is forwarded unchanged when present.
408    fn eta_row_scaling_for_skewness(&self) -> Option<Arc<[f64]>> {
409        self.inner.eta_row_scaling_for_skewness()
410    }
411}
412
413#[cfg(test)]
414mod gauge_composed_jacobian_tests {
415    use super::*;
416    use ndarray::array;
417
418    struct BetaScaledJacobian {
419        design: Array2<f64>,
420    }
421
422    impl BlockEffectiveJacobian for BetaScaledJacobian {
423        fn effective_jacobian_rows(
424            &self,
425            state: &FamilyLinearizationState<'_>,
426            rows: Range<usize>,
427        ) -> Result<Array2<f64>, String> {
428            let n = self.design.nrows();
429            let rows = rows.start.min(n)..rows.end.min(n);
430            let mut out = self.design.slice(ndarray::s![rows, ..]).to_owned();
431            for col in 0..out.ncols() {
432                let scale = 1.0 + state.beta.get(col).copied().unwrap_or(0.0);
433                out.column_mut(col).mapv_inplace(|v| v * scale);
434            }
435            Ok(out)
436        }
437
438        fn n_outputs(&self) -> usize {
439            1
440        }
441    }
442
443    #[test]
444    fn gauge_composed_jacobian_lifts_reduced_block_beta_before_delegating() {
445        let inner: Arc<dyn BlockEffectiveJacobian> = Arc::new(BetaScaledJacobian {
446            design: array![[2.0, 3.0], [5.0, 7.0]],
447        });
448        let t_block = Arc::new(array![[0.0], [1.0]]);
449        let wrapped = GaugeComposedJacobian::new(inner, Arc::clone(&t_block));
450
451        let theta = [4.0];
452        let reduced_state = FamilyLinearizationState {
453            beta: &theta,
454            family_scalars: None,
455            channel_hessian: None,
456            probit_frailty_scale: 1.0,
457        };
458        let reduced = wrapped
459            .effective_jacobian_rows(&reduced_state, 0..2)
460            .expect("reduced beta should be lifted through T before inner callback");
461
462        let raw_beta = [0.0, 4.0];
463        let raw_state = FamilyLinearizationState {
464            beta: &raw_beta,
465            family_scalars: None,
466            channel_hessian: None,
467            probit_frailty_scale: 1.0,
468        };
469        let raw = wrapped
470            .effective_jacobian_rows(&raw_state, 0..2)
471            .expect("raw beta state remains valid");
472
473        assert_eq!(reduced, raw);
474        assert_eq!(reduced, array![[15.0], [35.0]]);
475    }
476
477    struct StrictRawWidthJacobian {
478        design: Array2<f64>,
479    }
480
481    impl BlockEffectiveJacobian for StrictRawWidthJacobian {
482        fn effective_jacobian_rows(
483            &self,
484            state: &FamilyLinearizationState<'_>,
485            rows: Range<usize>,
486        ) -> Result<Array2<f64>, String> {
487            if state.beta.len() != self.design.ncols() {
488                return Err(format!(
489                    "StrictRawWidthJacobian expected raw beta len {}, got {}",
490                    self.design.ncols(),
491                    state.beta.len(),
492                ));
493            }
494            Ok(self.design.slice(ndarray::s![rows, ..]).to_owned())
495        }
496    }
497
498    #[test]
499    fn gauge_composed_jacobian_lifts_zero_reduced_beta_before_delegating() {
500        let inner: Arc<dyn BlockEffectiveJacobian> = Arc::new(StrictRawWidthJacobian {
501            design: array![[2.0, 3.0], [5.0, 7.0]],
502        });
503        let wrapped = GaugeComposedJacobian::new(inner, Arc::new(array![[0.0], [1.0]]));
504
505        let theta = [0.0];
506        let reduced_state = FamilyLinearizationState {
507            beta: &theta,
508            family_scalars: None,
509            channel_hessian: None,
510            probit_frailty_scale: 1.0,
511        };
512
513        let reduced = wrapped
514            .effective_jacobian_rows(&reduced_state, 0..2)
515            .expect("zero reduced beta must still be lifted to raw width");
516
517        assert_eq!(reduced, array![[3.0], [7.0]]);
518    }
519
520    #[test]
521    fn gauge_composed_jacobian_rejects_nonzero_unknown_beta_layout() {
522        let inner: Arc<dyn BlockEffectiveJacobian> = Arc::new(BetaScaledJacobian {
523            design: array![[2.0, 3.0]],
524        });
525        let wrapped = GaugeComposedJacobian::new(inner, Arc::new(array![[0.0], [1.0]]));
526        let joint_like_beta = [1.0, 0.0, 0.0];
527        let state = FamilyLinearizationState {
528            beta: &joint_like_beta,
529            family_scalars: None,
530            channel_hessian: None,
531            probit_frailty_scale: 1.0,
532        };
533
534        let err = wrapped
535            .effective_jacobian_rows(&state, 0..1)
536            .expect_err("nonzero joint-layout beta cannot be inferred from one block T");
537        assert!(
538            err.contains("cannot infer a block slice"),
539            "unexpected error: {err}"
540        );
541    }
542}
543
544/// Static specification for one parameter block in a custom family.
545///
546/// `design` and `stacked_design` are two structurally distinct operators:
547///
548/// * `design` is the **canonical, single-channel, n-observation operator**.
549///   `design.nrows()` ALWAYS equals `n_obs` (one row per training
550///   observation).  This is the matrix the identifiability audit, the
551///   shape policy, and every "what shape is this block?" reader inspect.
552///   For most blocks `design` is also the eta-producing operator used by
553///   the solver — see [`Self::solver_design`].
554/// * `stacked_design`, when `Some`, is the **multi-channel eta-producing
555///   operator** used by the solver.  Survival time-varying blocks stack
556///   `[exit; entry; deriv]` into a `(3·n × p)` operator here so the
557///   solver can produce a `3·n`-long `eta` in one mat-vec; the audit
558///   never sees this matrix.  When `None`, the solver uses `design` (the
559///   single-channel default).
560///
561/// The single contract that downstream code can rely on:
562/// `design.nrows() == n_obs`.  No more dual semantics on `design`.
563///
564/// Read access:
565/// * Audit / canonicalize / "n_obs is the row count" code → `&spec.design`.
566/// * Eta-producing solver code → [`Self::solver_design`].
567#[derive(Clone)]
568pub struct ParameterBlockSpec {
569    pub name: String,
570    pub design: DesignMatrix,
571    pub offset: Array1<f64>,
572    /// Block-local penalty matrices (all p_block x p_block).
573    pub penalties: Vec<PenaltyMatrix>,
574    /// Structural nullspace dimension of each penalty matrix (same length as `penalties`).
575    /// Used by the penalty pseudo-logdet to determine rank without numerical thresholds.
576    /// If empty, falls back to eigenvalue-based rank detection.
577    pub nullspace_dims: Vec<usize>,
578    /// Initial log-smoothing parameters for this block (same length as `penalties`).
579    pub initial_log_lambdas: Array1<f64>,
580    /// Optional initial coefficients (defaults to zeros if omitted).
581    pub initial_beta: Option<Array1<f64>>,
582    /// Gauge ownership priority. Higher = more likely to retain a
583    /// redundant direction during canonical-gauge reparameterisation.
584    /// Defaults to 100. Set higher for blocks that should "own" shared
585    /// affine/null-space directions (e.g. baseline time in survival).
586    pub gauge_priority: u8,
587    /// Full β-dependent Jacobian callback.  When `Some`, this is the
588    /// authoritative source for `effective_jacobian_at`.  For simple
589    /// single-output row-scaled blocks use [`RowScaledJacobian`].
590    pub jacobian_callback: Option<Arc<dyn BlockEffectiveJacobian>>,
591    /// Optional multi-channel eta-producing operator used by the solver.
592    ///
593    /// When `Some`, the solver consumes this matrix (typically
594    /// `(k·n × p)` for `k` stacked channels — e.g. survival
595    /// `[exit; entry; deriv]` with `k = 3`) to evaluate `eta = stacked · β + stacked_offset`.
596    /// The audit and shape policy NEVER read this field; they only ever
597    /// inspect `design` (which always has `n_obs` rows).
598    ///
599    /// When `None`, the solver falls back to `design` — the correct
600    /// behavior for every single-channel block (i.e. all non-survival
601    /// time-varying blocks).
602    ///
603    /// Read this field via [`Self::solver_design`], never directly.
604    ///
605    /// Invariant: when `stacked_design = Some(_)`, `stacked_offset` MUST
606    /// also be `Some(_)` and its length MUST equal `stacked_design.nrows()`.
607    pub stacked_design: Option<DesignMatrix>,
608    /// Optional offset paired with [`Self::stacked_design`]. Same Option
609    /// state as `stacked_design` (both `Some` or both `None`).
610    /// Read via [`Self::solver_offset`].
611    pub stacked_offset: Option<Array1<f64>>,
612}
613
614impl std::fmt::Debug for ParameterBlockSpec {
615    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
616        f.debug_struct("ParameterBlockSpec")
617            .field("name", &self.name)
618            .field("design", &self.design)
619            .field("offset", &self.offset)
620            .field("penalties", &self.penalties)
621            .field("nullspace_dims", &self.nullspace_dims)
622            .field("initial_log_lambdas", &self.initial_log_lambdas)
623            .field("initial_beta", &self.initial_beta)
624            .field("gauge_priority", &self.gauge_priority)
625            .field(
626                "jacobian_callback",
627                &self
628                    .jacobian_callback
629                    .as_ref()
630                    .map(|_| "<BlockEffectiveJacobian>"),
631            )
632            .finish()
633    }
634}
635
636impl ParameterBlockSpec {
637    /// Returns a ParameterBlockSpec with sensible defaults for all optional
638    /// fields. Callers using struct literal syntax can use
639    /// `..ParameterBlockSpec::defaults()` to fill in any fields added after
640    /// the literal was written.
641    pub fn defaults() -> Self {
642        Self {
643            name: String::new(),
644            design: DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(
645                ndarray::Array2::<f64>::zeros((0, 0)),
646            )),
647            offset: ndarray::Array1::<f64>::zeros(0),
648            penalties: Vec::new(),
649            nullspace_dims: Vec::new(),
650            initial_log_lambdas: ndarray::Array1::<f64>::zeros(0),
651            initial_beta: None,
652            gauge_priority: 100,
653            jacobian_callback: None,
654            stacked_design: None,
655            stacked_offset: None,
656        }
657    }
658
659    /// Returns the eta-producing operator used by the solver.
660    ///
661    /// Resolution order:
662    ///   1. `stacked_design = Some(d)` → return `d` (multi-channel
663    ///      operator, e.g. `(3n × p)` for survival time-varying blocks).
664    ///   2. otherwise → return `&self.design` (the single-channel default).
665    ///
666    /// Solver code that needs `eta = D · β` MUST call this accessor;
667    /// reading `&self.design` directly silently breaks multi-channel
668    /// (survival LS time-varying) blocks because `self.design.nrows()`
669    /// always equals `n_obs`, never `3·n_obs`.
670    pub fn solver_design(&self) -> &DesignMatrix {
671        self.stacked_design.as_ref().unwrap_or(&self.design)
672    }
673
674    /// Returns the offset paired with [`Self::solver_design`]. When
675    /// `stacked_offset = Some(o)` this returns `&o`; otherwise it falls
676    /// back to `&self.offset`.
677    pub fn solver_offset(&self) -> &Array1<f64> {
678        self.stacked_offset.as_ref().unwrap_or(&self.offset)
679    }
680
681    /// Returns the effective design `D_eff` for this block at β = 0 with no
682    /// family scalars — a convenience wrapper around [`Self::effective_jacobian_at`]
683    /// for the single-output (n_outputs = 1) case.
684    ///
685    /// Callers that need multi-output Jacobians or β-dependent scalars should
686    /// call `effective_jacobian_at` directly with the appropriate state.
687    ///
688    /// Returns `Err` if the design cannot be densified.
689    pub fn effective_design(&self, caller: &str) -> Result<ndarray::Array2<f64>, String> {
690        let p = self.design.ncols();
691        let zeros = vec![0.0f64; p];
692        let state = FamilyLinearizationState {
693            beta: &zeros,
694            family_scalars: None,
695            channel_hessian: None,
696            probit_frailty_scale: 1.0,
697        };
698        self.effective_jacobian_at(caller, &state)
699    }
700
701    /// Returns the β-dependent stacked Jacobian `J(β)` for this block.
702    ///
703    /// Shape: `(n_rows * n_outputs, p_block)`.  For most blocks `n_outputs = 1`
704    /// and the result is the familiar `(n_rows, p_block)` effective design.
705    ///
706    /// Dispatch order:
707    ///   1. `jacobian_callback = Some(cb)` → `cb.effective_jacobian_at(state)`.
708    ///   2. `jacobian_callback = None` → `design.clone()` (ignores `beta` and `family_scalars`).
709    ///
710    /// Returns `Err` if the design cannot be densified.
711    pub fn effective_jacobian_at(
712        &self,
713        caller: &str,
714        state: &FamilyLinearizationState<'_>,
715    ) -> Result<ndarray::Array2<f64>, String> {
716        if let Some(cb) = self.jacobian_callback.as_ref() {
717            return cb.effective_jacobian_at(state);
718        }
719        self.design
720            .try_to_dense_arc(&format!(
721                "{caller}::effective_jacobian_at block '{}'",
722                self.name
723            ))
724            .map(|arc| arc.as_ref().clone())
725    }
726}
727
728/// Current state for a parameter block.
729#[derive(Clone, Debug)]
730pub struct ParameterBlockState {
731    pub beta: Array1<f64>,
732    pub eta: Array1<f64>,
733}
734
735#[derive(Clone)]
736pub struct BlockGeometryDirectionalDerivative {
737    /// Directional derivative of the block design matrix along a coefficient-space direction.
738    pub d_design: Option<Array2<f64>>,
739    /// Directional derivative of the block offset along the same direction.
740    pub d_offset: Array1<f64>,
741}
742
743/// Working quantities supplied by a custom family for one block.
744///
745/// # Observed vs expected information (see response.md Section 3)
746///
747/// For the outer REML/LAML criterion, the Hessian used in log|H| and trace terms
748/// must be the **observed** (actual) Hessian at the mode, not the expected Fisher.
749///
750/// - `ExactNewton`: provides -nabla^2 log L directly, which is the observed Hessian
751///   by construction. This is always correct.
752///
753/// - `Diagonal`: provides IRLS working weights W such that the per-block Hessian
754///   is X'WX. For canonical links (logit-Binomial, log-Poisson), W_obs = W_Fisher.
755///   For supported non-canonical diagonal links, W must be the observed weight
756///   W_obs = W_Fisher - (y-mu)*B so the outer REML uses the exact Laplace
757///   Hessian. The matching `CustomFamily::diagonalworking_weights_directional_derivative`
758///   callback must differentiate the same observed W surface; silently using Fisher
759///   weights or zero `dW` would change the criterion into a PQL-type surrogate.
760#[derive(Clone, Debug)]
761pub enum BlockWorkingSet {
762    /// Standard IRLS/GLM-style diagonal working set for eta-space updates.
763    Diagonal {
764        /// IRLS pseudo-response for this block's linear predictor.
765        working_response: Array1<f64>,
766        /// IRLS working curvature for this block (finite signed values, length n).
767        ///
768        /// For the inner solver, Fisher or observed weights both find the same mode.
769        /// For the outer REML/LAML log|H| term, observed weights are the correct
770        /// Laplace choice (see response.md Section 3). Canonical-link families need
771        /// no correction since observed = Fisher.
772        working_weights: Array1<f64>,
773    },
774    /// Exact Newton block update in coefficient space.
775    ///
776    /// `gradient` is nabla log L wrt block coefficients.
777    /// `hessian` is -nabla^2 log L wrt block coefficients (positive semidefinite near optimum).
778    ///
779    /// This is the observed Hessian by construction (actual second derivative of the
780    /// log-likelihood), which is the correct quantity for the outer REML Laplace
781    /// approximation.
782    ExactNewton {
783        gradient: Array1<f64>,
784        hessian: SymmetricMatrix,
785    },
786}
787
788impl BlockWorkingSet {
789    /// Construct a `Diagonal` working set with its length and finite-value
790    /// invariants enforced at the type boundary. Signed observed curvature is
791    /// preserved exactly; stabilization belongs to the assembled matrix.
792    #[inline]
793    pub fn diagonal_checked(
794        working_response: Array1<f64>,
795        working_weights: Array1<f64>,
796    ) -> Result<Self, String> {
797        if working_response.len() != working_weights.len() {
798            return Err(format!(
799                "BlockWorkingSet::Diagonal length mismatch: working_response={}, working_weights={}",
800                working_response.len(),
801                working_weights.len(),
802            ));
803        }
804        if let Some((row, value)) = working_response
805            .iter()
806            .chain(working_weights.iter())
807            .enumerate()
808            .find(|(_, value)| !value.is_finite())
809        {
810            return Err(format!(
811                "BlockWorkingSet::Diagonal contains a non-finite value at flattened index {row}: {value}"
812            ));
813        }
814        Ok(Self::Diagonal {
815            working_response,
816            working_weights,
817        })
818    }
819}