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/// There is no blanket impl: a type that is `Objective + Gradient` must
43/// write `impl DifferentiableObjective<T> for T { }` (empty, default
44/// split eval) or override [`DifferentiableObjective::value_and_gradient`]
45/// for a fused `(f, ∇f)` that reuses intermediate work (Ceres-style
46/// residual + Jacobian in one shot). A blanket impl would make that
47/// override E0119.
48pub trait DifferentiableObjective<T: Float>: Objective<T> + Gradient<T> {
49 /// Returns `(f(x), ∇f(x))`. Default calls the two methods separately;
50 /// analytic implementations should override for efficiency.
51 fn value_and_gradient(&self, x: ArrayView1<T>) -> (T, Array1<T>) {
52 (self.eval(x), self.grad(x))
53 }
54}
55
56/// Closure-based analytic gradient (the common case for user Rust code
57/// that has a hand-derived or AD-produced `x |-> ∇f(x)`).
58pub struct AnalyticGradient<F>
59where
60 F: Fn(ArrayView1<f64>) -> Array1<f64> + Send + Sync,
61{
62 /// User-supplied analytic gradient callback.
63 pub grad_fn: F,
64 /// Number of input dimensions accepted by `grad_fn`.
65 pub dim: usize,
66}
67
68impl<F> AnalyticGradient<F>
69where
70 F: Fn(ArrayView1<f64>) -> Array1<f64> + Send + Sync,
71{
72 /// Constructs an analytic-gradient adapter from a dimension and callback.
73 pub fn new(dim: usize, grad_fn: F) -> Self {
74 Self { grad_fn, dim }
75 }
76}
77
78impl<F> Gradient<f64> for AnalyticGradient<F>
79where
80 F: Fn(ArrayView1<f64>) -> Array1<f64> + Send + Sync,
81{
82 fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
83 (self.grad_fn)(x)
84 }
85 fn dim(&self) -> usize {
86 self.dim
87 }
88}
89
90/// Central-difference adapter around any `Objective<f64>`.
91/// Use only when no native gradient is available.
92pub struct FiniteDiffGradient<O: Objective<f64>> {
93 /// Objective evaluated by the central-difference stencil.
94 pub obj: O,
95 /// Symmetric perturbation step.
96 pub h: f64,
97}
98
99impl<O: Objective<f64>> FiniteDiffGradient<O> {
100 /// Constructs a central-difference adapter with a conservative default step.
101 pub fn new(obj: O) -> Self {
102 Self { obj, h: 1e-5 }
103 }
104 /// Constructs a central-difference adapter with a caller-selected step.
105 pub fn with_step(obj: O, h: f64) -> Self {
106 assert!(h > 0.0, "h must be positive");
107 Self { obj, h }
108 }
109}
110
111impl<O: Objective<f64> + Send + Sync> Gradient<f64> for FiniteDiffGradient<O> {
112 fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
113 let n = x.len();
114 let mut g = Array1::zeros(n);
115 let mut xp = x.to_owned();
116 let mut xm = x.to_owned();
117 for i in 0..n {
118 xp[i] = x[i] + self.h;
119 xm[i] = x[i] - self.h;
120 g[i] = (self.obj.eval(xp.view()) - self.obj.eval(xm.view())) / (2.0 * self.h);
121 xp[i] = x[i];
122 xm[i] = x[i];
123 }
124 g
125 }
126 fn dim(&self) -> usize {
127 self.obj.dim()
128 }
129}
130
131#[cfg(test)]
132mod fused_override_tests {
133 use super::*;
134 use crate::{Bounds, Objective};
135 use ndarray::{Array1, ArrayView1};
136
137 struct Counted;
138 impl Objective<f64> for Counted {
139 fn dim(&self) -> usize {
140 1
141 }
142 fn bounds(&self) -> &Bounds<f64> {
143 static CELL: std::sync::OnceLock<Bounds<f64>> = std::sync::OnceLock::new();
144 CELL.get_or_init(|| Bounds::new(Array1::from_elem(1, -1.0), Array1::from_elem(1, 1.0), 0.0))
145 }
146 fn eval(&self, _x: ArrayView1<f64>) -> f64 {
147 panic!("split eval must not run when value_and_gradient is fused")
148 }
149 }
150 impl Gradient<f64> for Counted {
151 fn dim(&self) -> usize {
152 1
153 }
154 fn grad(&self, _x: ArrayView1<f64>) -> Array1<f64> {
155 panic!("split grad must not run when value_and_gradient is fused")
156 }
157 }
158 impl DifferentiableObjective<f64> for Counted {
159 fn value_and_gradient(&self, x: ArrayView1<f64>) -> (f64, Array1<f64>) {
160 (x[0] * x[0], Array1::from_elem(1, 2.0 * x[0]))
161 }
162 }
163
164 #[test]
165 fn override_is_fused() {
166 let obj = Counted;
167 let x = Array1::from_elem(1, 3.0);
168 let (v, g) = obj.value_and_gradient(x.view());
169 assert_eq!(v, 9.0);
170 assert_eq!(g[0], 6.0);
171 }
172}