Skip to main content

spectrafit_trust_region/
problem.rs

1//! The [`TrustRegionProblem`] trait — the only coupling point between this
2//! numerics-only crate and a concrete model/graph.
3//!
4//! An implementor owns the parameter state and is responsible for any
5//! parameterisation-level projection (bounds reflection, expression-tied
6//! parameters) inside [`set_params`](TrustRegionProblem::set_params). The
7//! driver treats the problem as an opaque source of weighted residuals and a
8//! weighted Jacobian written into caller-owned `faer` buffers — no allocation
9//! on the hot path.
10
11use faer::{Mat, MatMut};
12use spectrafit_types::CoreError;
13
14/// A weighted nonlinear least-squares problem driven by the trust-region core.
15///
16/// Conventions:
17/// * "weighted" means residuals and Jacobian already carry the per-point `1/σ`
18///   factor, so the driver minimises `½‖r‖²` directly.
19/// * `n_params` is the number of **free** parameters (tied/fixed excluded).
20/// * Bounds reflection and tied-parameter application live in
21///   [`set_params`](TrustRegionProblem::set_params). A driver that reads
22///   [`bounds`](TrustRegionProblem::bounds) (the LM driver) projects its trial
23///   points onto that box before calling `set_params`; the Δ-radius drivers
24///   only propose raw steps.
25pub trait TrustRegionProblem {
26    /// Number of residual rows `m` (total points across datasets).
27    fn n_residuals(&self) -> usize;
28
29    /// Number of free parameters `p`.
30    fn n_params(&self) -> usize;
31
32    /// Current free-parameter vector (length `p`).
33    ///
34    /// Called after [`set_params`](Self::set_params) so the driver can read back
35    /// the value the problem actually applied (e.g. after bounds reflection).
36    fn params(&self) -> Vec<f64>;
37
38    /// Install a proposed free-parameter vector `p` (length `n_params`).
39    ///
40    /// The implementor applies any reflection / tied-plan here, so a subsequent
41    /// [`params`](Self::params) may differ from `p`.
42    fn set_params(&mut self, p: &[f64]);
43
44    /// Write the weighted residual vector `r` (shape `m × 1`) for the current
45    /// parameters into `r`.
46    fn residuals_into(&mut self, r: MatMut<'_, f64>) -> Result<(), CoreError>;
47
48    /// Write the weighted Jacobian `J` (shape `m × p`) for the current
49    /// parameters into `jac`.
50    fn jacobian_into(&mut self, jac: MatMut<'_, f64>) -> Result<(), CoreError>;
51
52    /// Apply the weighted Jacobian as a linear operator: write `out = J·v`
53    /// (length `m`) for the current parameters, where `v` has length `p`.
54    ///
55    /// This is the **matrix-free** half of the problem contract, intended for
56    /// Krylov subproblem solvers (truncated-CG / Steihaug) that need only
57    /// Jacobian–vector products, never the dense `J`. The default materializes
58    /// `J` via [`jacobian_into`](Self::jacobian_into) and multiplies — correct
59    /// but `O(m·p)` storage per call; a matrix-free implementor overrides both
60    /// operators to avoid forming `J`. Implementations must stay consistent with
61    /// `jacobian_into`: `apply_jacobian(v) == J·v`.
62    ///
63    /// **Reserved API — no driver in this workspace calls it today.** The
64    /// Newton-CG method works on the dense *scaled* `J` through
65    /// `Subproblem::hvec`, not through these operators, so the only exercise
66    /// the default implementations get is the framework's own contract test.
67    /// It is kept because it is the seam a future matrix-free implementor
68    /// needs, not because something behind it is already wired up.
69    fn apply_jacobian(&mut self, v: &[f64], out: &mut [f64]) -> Result<(), CoreError> {
70        let m = self.n_residuals();
71        let p = self.n_params();
72        let mut jac = Mat::<f64>::zeros(m, p);
73        self.jacobian_into(jac.as_mut())?;
74        for (i, o) in out.iter_mut().enumerate().take(m) {
75            let mut s = 0.0;
76            for (c, &vc) in v.iter().enumerate().take(p) {
77                s += jac[(i, c)] * vc;
78            }
79            *o = s;
80        }
81        Ok(())
82    }
83
84    /// Apply the transposed weighted Jacobian: write `out = Jᵀ·u` (length `p`)
85    /// for the current parameters, where `u` has length `m`.
86    ///
87    /// The transpose-multiply companion to [`apply_jacobian`](Self::apply_jacobian)
88    /// (forms the Krylov normal-equation operator `v ↦ Jᵀ(J·v)` without `JᵀJ`).
89    /// The default materializes `J` and multiplies; matrix-free implementors
90    /// override it. Must satisfy `apply_jacobian_transpose(u) == Jᵀ·u`.
91    ///
92    /// **Reserved API** on the same terms as
93    /// [`apply_jacobian`](Self::apply_jacobian): no driver calls it today and
94    /// the default is exercised only by tests.
95    fn apply_jacobian_transpose(&mut self, u: &[f64], out: &mut [f64]) -> Result<(), CoreError> {
96        let m = self.n_residuals();
97        let p = self.n_params();
98        let mut jac = Mat::<f64>::zeros(m, p);
99        self.jacobian_into(jac.as_mut())?;
100        for (c, o) in out.iter_mut().enumerate().take(p) {
101            let mut s = 0.0;
102            for (i, &ui) in u.iter().enumerate().take(m) {
103                s += jac[(i, c)] * ui;
104            }
105            *o = s;
106        }
107        Ok(())
108    }
109
110    /// Per-parameter scale factors (length `p`) used for column scaling of the
111    /// damping diagonal. Defaults to all-ones (Levenberg damping).
112    ///
113    /// This trait method itself has no callers in the workspace today —
114    /// `Parameter.scale` is already wired, but through a different path:
115    /// `spectrafit-solver`'s `LmProblem` (`lm_problem.rs`) holds its own
116    /// `scales` field and applies it directly when assembling the scaled
117    /// working-variable Jacobian, rather than by overriding this method.
118    fn scales(&self) -> Vec<f64> {
119        vec![1.0; self.n_params()]
120    }
121
122    /// Coleman–Li trust-region scaling `v ∈ (0, 1]` per free parameter for the
123    /// current point and gradient `grad`, or `None` when the problem is
124    /// unbounded. `v_i → 0` as parameter `i` approaches the active bound; the
125    /// driver folds `D_i ← D_i / √v_i`, so the trust region shrinks near bounds.
126    /// Default: `None`.
127    fn trust_scaling(&self, _grad: &[f64]) -> Option<Vec<f64>> {
128        None
129    }
130
131    /// Box bounds `(lo, hi)` per free parameter (length `p`), in the same
132    /// working units as [`params`](Self::params) / [`set_params`](Self::set_params),
133    /// or `None` when no free parameter has a finite bound. Infinite entries
134    /// mean "unbounded on that side".
135    ///
136    /// Read by drivers that handle bounds in the step itself (the LM driver's
137    /// active-set projected step) instead of relying only on the projection
138    /// inside [`set_params`](Self::set_params). Default: `None`, which leaves
139    /// such a driver on its unbounded code path.
140    fn bounds(&self) -> Option<Vec<(f64, f64)>> {
141        None
142    }
143}