Skip to main content

eindir_core/
gradient.rs

1//! `Gradient<T>` and `DifferentiableObjective<T>`: first-derivative support
2//! for the typed `Obj` algebra.
3//!
4//! This is the "native gradient" path, modeled on how Ceres accepts analytic
5//! derivatives: when a caller (HMC, projected-gradient polish, GLE with
6//! optimal drift, NEB/saddle search in sibling crates, ...) can supply a
7//! true derivative it is used directly; otherwise an explicit
8//! `FiniteDiffGradient` adapter falls back to central differences (costing
9//! 2·dim extra objective evaluations per gradient).
10//!
11//! The separation (value-only `Objective` vs. `Gradient` provider) mirrors
12//! Stan's log-density / gradient split and Ceres' residual + optional
13//! Jacobian in a single Evaluate.  A type can implement both (via
14//! `DifferentiableObjective`) and supply an efficient fused
15//! `value_and_gradient` to avoid redundant work.
16//!
17//! Surrogates (`ChebyshevSurrogate`, `AdditiveSurrogate`, `ReducedObjective`)
18//! implement the traits analytically where possible.  Built-in test
19//! objectives ship with closed-form gradients.  Python callables can
20//! provide a matching `grad_fn` at construction time of `PyObjective`.
21
22use crate::Objective;
23use ndarray::{Array1, ArrayView1};
24use num_traits::Float;
25
26/// First-derivative interface.  Types that know an analytic gradient
27/// implement this directly (or via `DifferentiableObjective`).
28///
29/// When only a black-box `Objective` is available, wrap it with
30/// `FiniteDiffGradient`.  When a closure or Python grad callable is known,
31/// use `AnalyticGradient` (or construct a `PyObjective` with `grad_fn`).
32pub trait Gradient<T: Float>: Send + Sync {
33    /// Gradient of the underlying scalar field at `x`.
34    fn grad(&self, x: ArrayView1<T>) -> Array1<T>;
35
36    /// Number of input dimensions (must match the paired `Objective::dim`).
37    fn dim(&self) -> usize;
38}
39
40/// An `Objective` that can also supply its gradient (natively or via adapter).
41///
42/// Blanket impl for any `O: Objective<T> + Gradient<T>`.  Concrete types
43/// (surrogates, PyObjective with grad, builtins) can override
44/// `value_and_gradient` for a fused implementation that re-uses
45/// intermediate work (exactly as a Ceres CostFunction computes residuals
46/// and Jacobians in one shot).
47pub trait DifferentiableObjective<T: Float>: Objective<T> + Gradient<T> {
48    /// Returns `(f(x), ∇f(x))`.  Default calls the two methods separately;
49    /// analytic implementations should override for efficiency.
50    fn value_and_gradient(&self, x: ArrayView1<T>) -> (T, Array1<T>) {
51        (self.eval(x), self.grad(x))
52    }
53}
54
55impl<T: Float, O> DifferentiableObjective<T> for O where O: Objective<T> + Gradient<T> {}
56
57/// Closure-based analytic gradient (the common case for user Rust code
58/// that has a hand-derived or AD-produced `x |-> ∇f(x)`).
59pub struct AnalyticGradient<F>
60where
61    F: Fn(ArrayView1<f64>) -> Array1<f64> + Send + Sync,
62{
63    /// User-supplied analytic gradient callback.
64    pub grad_fn: F,
65    /// Number of input dimensions accepted by `grad_fn`.
66    pub dim: usize,
67}
68
69impl<F> AnalyticGradient<F>
70where
71    F: Fn(ArrayView1<f64>) -> Array1<f64> + Send + Sync,
72{
73    /// Constructs an analytic-gradient adapter from a dimension and callback.
74    pub fn new(dim: usize, grad_fn: F) -> Self {
75        Self { grad_fn, dim }
76    }
77}
78
79impl<F> Gradient<f64> for AnalyticGradient<F>
80where
81    F: Fn(ArrayView1<f64>) -> Array1<f64> + Send + Sync,
82{
83    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
84        (self.grad_fn)(x)
85    }
86    fn dim(&self) -> usize {
87        self.dim
88    }
89}
90
91/// Central-difference adapter around any `Objective<f64>`.
92/// Use only when no native gradient is available.
93pub struct FiniteDiffGradient<O: Objective<f64>> {
94    /// Objective evaluated by the central-difference stencil.
95    pub obj: O,
96    /// Symmetric perturbation step.
97    pub h: f64,
98}
99
100impl<O: Objective<f64>> FiniteDiffGradient<O> {
101    /// Constructs a central-difference adapter with a conservative default step.
102    pub fn new(obj: O) -> Self {
103        Self { obj, h: 1e-5 }
104    }
105    /// Constructs a central-difference adapter with a caller-selected step.
106    pub fn with_step(obj: O, h: f64) -> Self {
107        assert!(h > 0.0, "h must be positive");
108        Self { obj, h }
109    }
110}
111
112impl<O: Objective<f64> + Send + Sync> Gradient<f64> for FiniteDiffGradient<O> {
113    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
114        let n = x.len();
115        let mut g = Array1::zeros(n);
116        let mut xp = x.to_owned();
117        let mut xm = x.to_owned();
118        for i in 0..n {
119            xp[i] = x[i] + self.h;
120            xm[i] = x[i] - self.h;
121            g[i] = (self.obj.eval(xp.view()) - self.obj.eval(xm.view())) / (2.0 * self.h);
122            xp[i] = x[i];
123            xm[i] = x[i];
124        }
125        g
126    }
127    fn dim(&self) -> usize {
128        self.obj.dim()
129    }
130}