Skip to main content

eindir_core/
reduced.rs

1//! Dimension-collapse and Chebyshev surrogate components for the typed algebra.
2//!
3//! These two primitives are `Obj`-transforms: each takes the objective slot of
4//! the typed component algebra and returns another objective, so any sampler
5//! built on the algebra (single-chain SA, the MCMC variants, parallel
6//! tempering, or the HMC point) consumes them through the same `Objective`
7//! trait without modification. A high-dimensional objective is made tractable
8//! by collapsing the search to a low-dimensional active subspace
9//! (`ReducedObjective`) and, after a pilot phase, replacing the restricted
10//! objective by a cheap total-degree Chebyshev model with an analytic gradient
11//! (`ChebyshevSurrogate`). Because both are objectives, the same collapse and
12//! surrogate serve every point of the algebra at once.
13
14use crate::{Bounds, DifferentiableObjective, Objective, gradient::Gradient};
15use ndarray::{Array1, Array2, ArrayView1};
16
17/// Affine dimension-collapse of an inner objective onto a `k`-dimensional box.
18///
19/// Given a full-space origin `x0 in R^n` and a basis `W in R^{n x k}` whose
20/// columns span the retained subspace (for example the dominant eigenvectors
21/// of the pilot gradient covariance, an active subspace), the reduced
22/// coordinate `r in R^k` decodes to `x = clip(x0 + W r)` in the inner box. The
23/// reduced objective evaluates the inner objective at the decoded point, so a
24/// sampler searches in `R^k` while every value is the true objective.
25pub struct ReducedObjective<O: Objective<f64>> {
26    inner: O,
27    origin: Array1<f64>,
28    basis: Array2<f64>,
29    bounds: Bounds<f64>,
30}
31
32impl<O: Objective<f64>> ReducedObjective<O> {
33    /// Builds a reduced objective from an inner objective, a full-space origin,
34    /// an `n x k` basis, and the reduced box `bounds` in `R^k`.
35    ///
36    /// Panics when the shapes disagree: `origin.len()` and `basis.nrows()` must
37    /// equal `inner.dim()`, and `basis.ncols()` must equal `bounds.dims`.
38    pub fn new(inner: O, origin: Array1<f64>, basis: Array2<f64>, bounds: Bounds<f64>) -> Self {
39        assert_eq!(
40            origin.len(),
41            inner.dim(),
42            "origin length must match inner dim"
43        );
44        assert_eq!(
45            basis.nrows(),
46            inner.dim(),
47            "basis rows must match inner dim"
48        );
49        assert_eq!(
50            basis.ncols(),
51            bounds.dims,
52            "basis cols must match reduced dim"
53        );
54        Self {
55            inner,
56            origin,
57            basis,
58            bounds,
59        }
60    }
61
62    /// Decodes a reduced coordinate `r in R^k` to a full point `x in R^n`,
63    /// clipped to the inner objective's box.
64    pub fn decode(&self, r: ArrayView1<f64>) -> Array1<f64> {
65        let lifted = &self.origin + self.basis.dot(&r);
66        self.inner.bounds().clip(lifted.view())
67    }
68
69    /// Borrows the wrapped full-dimensional objective.
70    pub fn inner(&self) -> &O {
71        &self.inner
72    }
73}
74
75impl<O: Objective<f64>> Objective<f64> for ReducedObjective<O> {
76    fn dim(&self) -> usize {
77        self.bounds.dims
78    }
79
80    fn bounds(&self) -> &Bounds<f64> {
81        &self.bounds
82    }
83
84    fn eval(&self, r: ArrayView1<f64>) -> f64 {
85        self.inner.eval(self.decode(r).view())
86    }
87}
88
89/// Total-degree Chebyshev surrogate objective on a box in `R^k`.
90///
91/// The surrogate stores a list of multi-indices `terms` (each a length-`k`
92/// degree vector with total degree at most the fit degree) and a matching
93/// coefficient per term. A point `x` in the box `[low, high]` maps coordinate
94/// by coordinate to `t in [-1, 1]^k`; the surrogate value is
95/// `sum_j coeff_j * prod_d T_{terms_j[d]}(t_d)`, where `T_n` is the Chebyshev
96/// polynomial of the first kind. Coefficients are fit elsewhere (least squares
97/// on pilot samples in the reduced box); this type supplies the cheap value
98/// and the analytic gradient that the HMC point consumes.
99pub struct ChebyshevSurrogate {
100    bounds: Bounds<f64>,
101    terms: Vec<Vec<usize>>,
102    coeffs: Array1<f64>,
103}
104
105impl ChebyshevSurrogate {
106    /// Builds a surrogate from a reduced box, the total-degree multi-index set,
107    /// and one coefficient per multi-index.
108    ///
109    /// Panics when `terms.len() != coeffs.len()` or when any multi-index length
110    /// differs from `bounds.dims`.
111    pub fn new(bounds: Bounds<f64>, terms: Vec<Vec<usize>>, coeffs: Array1<f64>) -> Self {
112        assert_eq!(
113            terms.len(),
114            coeffs.len(),
115            "one coefficient per term required"
116        );
117        assert!(
118            terms.iter().all(|t| t.len() == bounds.dims),
119            "every multi-index must have length bounds.dims",
120        );
121        Self {
122            bounds,
123            terms,
124            coeffs,
125        }
126    }
127
128    /// Maps a box coordinate to `[-1, 1]`; degenerate intervals map to zero.
129    fn to_unit(&self, d: usize, xd: f64) -> f64 {
130        let lo = self.bounds.low[d];
131        let hi = self.bounds.high[d];
132        let span = hi - lo;
133        if span.abs() <= f64::EPSILON {
134            0.0
135        } else {
136            (2.0 * (xd - lo) / span - 1.0).clamp(-1.0, 1.0)
137        }
138    }
139
140    /// Chebyshev value and `d/dt` derivative up to `n` by the standard
141    /// recurrences `T_{m+1} = 2 t T_m - T_{m-1}` and `T'_{m+1} = 2 T_m + 2 t
142    /// T'_m - T'_{m-1}`.
143    fn cheb_with_deriv(n: usize, t: f64) -> (Vec<f64>, Vec<f64>) {
144        let mut vals = vec![0.0; n + 1];
145        let mut ders = vec![0.0; n + 1];
146        vals[0] = 1.0;
147        ders[0] = 0.0;
148        if n >= 1 {
149            vals[1] = t;
150            ders[1] = 1.0;
151        }
152        for m in 1..n {
153            vals[m + 1] = 2.0 * t * vals[m] - vals[m - 1];
154            ders[m + 1] = 2.0 * vals[m] + 2.0 * t * ders[m] - ders[m - 1];
155        }
156        (vals, ders)
157    }
158
159    /// Per-dimension Chebyshev value/derivative tables for a point `x`.
160    fn tables(&self, x: ArrayView1<f64>) -> (Vec<Vec<f64>>, Vec<Vec<f64>>) {
161        let k = self.bounds.dims;
162        let max_deg: Vec<usize> = (0..k)
163            .map(|d| self.terms.iter().map(|t| t[d]).max().unwrap_or(0))
164            .collect();
165        let mut vals = Vec::with_capacity(k);
166        let mut ders = Vec::with_capacity(k);
167        for d in 0..k {
168            let (v, dv) = Self::cheb_with_deriv(max_deg[d], self.to_unit(d, x[d]));
169            vals.push(v);
170            ders.push(dv);
171        }
172        (vals, ders)
173    }
174
175    /// Analytic gradient of the surrogate at `x`, in box coordinates.
176    pub fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
177        let k = self.bounds.dims;
178        let (vals, ders) = self.tables(x);
179        let mut g = Array1::<f64>::zeros(k);
180        for (term, &c) in self.terms.iter().zip(self.coeffs.iter()) {
181            for j in 0..k {
182                if x[j] < self.bounds.low[j] || x[j] > self.bounds.high[j] {
183                    continue;
184                }
185                let span = self.bounds.high[j] - self.bounds.low[j];
186                if span.abs() <= f64::EPSILON {
187                    continue;
188                }
189                let dt_dx = 2.0 / span;
190                let mut prod = ders[j][term[j]] * dt_dx;
191                for (d, item) in term.iter().enumerate() {
192                    if d != j {
193                        prod *= vals[d][*item];
194                    }
195                }
196                g[j] += c * prod;
197            }
198        }
199        g
200    }
201}
202
203impl Objective<f64> for ChebyshevSurrogate {
204    fn dim(&self) -> usize {
205        self.bounds.dims
206    }
207
208    fn bounds(&self) -> &Bounds<f64> {
209        &self.bounds
210    }
211
212    fn eval(&self, x: ArrayView1<f64>) -> f64 {
213        let (vals, _) = self.tables(x);
214        let mut acc = 0.0;
215        for (term, &c) in self.terms.iter().zip(self.coeffs.iter()) {
216            let mut prod = c;
217            for (d, &deg) in term.iter().enumerate() {
218                prod *= vals[d][deg];
219            }
220            acc += prod;
221        }
222        acc
223    }
224}
225
226impl Gradient<f64> for ChebyshevSurrogate {
227    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
228        // Delegate to the existing analytic implementation (Ceres-style
229        // native gradient).  The inherent `grad` remains for back-compat.
230        ChebyshevSurrogate::grad(self, x)
231    }
232    fn dim(&self) -> usize {
233        self.bounds.dims
234    }
235}
236
237impl<O: Objective<f64> + Gradient<f64>> Gradient<f64> for ReducedObjective<O> {
238    fn grad(&self, r: ArrayView1<f64>) -> Array1<f64> {
239        // Chain rule through the affine decoder: g_r = W^T @ g_full(decode(r))
240        let lifted = &self.origin + self.basis.dot(&r);
241        let x = self.decode(r);
242        let g_full = self.inner.grad(x.view());
243        let mut clipped_grad = g_full;
244        for i in 0..clipped_grad.len() {
245            let bounds = self.inner.bounds();
246            if lifted[i] < bounds.low[i] || lifted[i] > bounds.high[i] {
247                clipped_grad[i] = 0.0;
248            }
249        }
250        self.basis.t().dot(&clipped_grad)
251    }
252    fn dim(&self) -> usize {
253        self.bounds.dims
254    }
255}
256
257impl DifferentiableObjective<f64> for ChebyshevSurrogate {}
258
259impl<O: Objective<f64> + Gradient<f64>> DifferentiableObjective<f64> for ReducedObjective<O> {}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::objectives::StybTang2D;
265    use ndarray::{Array1, Array2, array};
266
267    fn reduced_box(k: usize, lo: f64, hi: f64) -> Bounds<f64> {
268        Bounds::new(Array1::from_elem(k, lo), Array1::from_elem(k, hi), 1e-9)
269    }
270
271    #[test]
272    fn reduced_decodes_and_evaluates_inner() {
273        // Collapse the 2D Styblinski-Tang onto the x1 = x2 diagonal: a single
274        // reduced coordinate r maps to (r, r).
275        let inner = StybTang2D::new();
276        let origin = array![0.0, 0.0];
277        let basis = Array2::from_shape_vec((2, 1), vec![1.0, 1.0]).unwrap();
278        let reduced = ReducedObjective::new(inner, origin, basis, reduced_box(1, -5.0, 5.0));
279        assert_eq!(Objective::dim(&reduced), 1);
280        // Decode is the diagonal lift.
281        let x = reduced.decode(array![2.0].view());
282        assert!((x[0] - 2.0).abs() < 1e-12 && (x[1] - 2.0).abs() < 1e-12);
283        // Value equals the inner objective on the diagonal.
284        let direct = StybTang2D::new().eval(array![2.0, 2.0].view());
285        assert!((reduced.eval(array![2.0].view()) - direct).abs() < 1e-12);
286    }
287
288    #[test]
289    fn reduced_gradient_is_zero_through_clipped_coordinates() {
290        let inner = StybTang2D::new();
291        let origin = array![0.0, 0.0];
292        let basis = Array2::from_shape_vec((2, 1), vec![1.0, 0.0]).unwrap();
293        let reduced = ReducedObjective::new(inner, origin, basis, reduced_box(1, -10.0, 10.0));
294
295        let gradient = reduced.grad(array![6.0].view());
296        assert!(gradient[0].abs() < 1e-12);
297    }
298
299    #[test]
300    fn chebyshev_reproduces_a_known_polynomial() {
301        // f(x) = 3 + 2*T_1(t) on [-1, 1] equals 3 + 2x; check value and slope.
302        let terms = vec![vec![0usize], vec![1usize]];
303        let coeffs = array![3.0, 2.0];
304        let s = ChebyshevSurrogate::new(reduced_box(1, -1.0, 1.0), terms, coeffs);
305        assert!((s.eval(array![0.5].view()) - 4.0).abs() < 1e-12);
306        assert!((s.grad(array![0.5].view())[0] - 2.0).abs() < 1e-9);
307    }
308
309    #[test]
310    fn chebyshev_gradient_matches_finite_difference() {
311        // A two-dimensional mixed-degree surrogate; compare the analytic
312        // gradient to a central finite difference.
313        let terms = vec![vec![2, 0], vec![1, 1], vec![0, 2]];
314        let coeffs = array![0.7, -1.3, 0.4];
315        let s = ChebyshevSurrogate::new(reduced_box(2, -2.0, 3.0), terms, coeffs);
316        let x = array![0.6, 1.1];
317        let g = s.grad(x.view());
318        let h = 1e-6;
319        for j in 0..2 {
320            let mut xp = x.clone();
321            let mut xm = x.clone();
322            xp[j] += h;
323            xm[j] -= h;
324            let fd = (s.eval(xp.view()) - s.eval(xm.view())) / (2.0 * h);
325            assert!(
326                (g[j] - fd).abs() < 1e-5,
327                "dim {j}: analytic {} vs fd {}",
328                g[j],
329                fd
330            );
331        }
332    }
333
334    #[test]
335    fn chebyshev_gradient_is_zero_outside_clipped_coordinates() {
336        let s = ChebyshevSurrogate::new(reduced_box(1, -1.0, 1.0), vec![vec![1]], array![2.0]);
337        assert_eq!(s.grad(array![2.0].view())[0], 0.0);
338    }
339}