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, 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                let span = self.bounds.high[j] - self.bounds.low[j];
183                if span.abs() <= f64::EPSILON {
184                    continue;
185                }
186                let dt_dx = 2.0 / span;
187                let mut prod = ders[j][term[j]] * dt_dx;
188                for (d, item) in term.iter().enumerate() {
189                    if d != j {
190                        prod *= vals[d][*item];
191                    }
192                }
193                g[j] += c * prod;
194            }
195        }
196        g
197    }
198}
199
200impl Objective<f64> for ChebyshevSurrogate {
201    fn dim(&self) -> usize {
202        self.bounds.dims
203    }
204
205    fn bounds(&self) -> &Bounds<f64> {
206        &self.bounds
207    }
208
209    fn eval(&self, x: ArrayView1<f64>) -> f64 {
210        let (vals, _) = self.tables(x);
211        let mut acc = 0.0;
212        for (term, &c) in self.terms.iter().zip(self.coeffs.iter()) {
213            let mut prod = c;
214            for (d, &deg) in term.iter().enumerate() {
215                prod *= vals[d][deg];
216            }
217            acc += prod;
218        }
219        acc
220    }
221}
222
223impl Gradient<f64> for ChebyshevSurrogate {
224    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
225        // Delegate to the existing analytic implementation (Ceres-style
226        // native gradient).  The inherent `grad` remains for back-compat.
227        ChebyshevSurrogate::grad(self, x)
228    }
229    fn dim(&self) -> usize {
230        self.bounds.dims
231    }
232}
233
234impl<O: Objective<f64> + Gradient<f64>> Gradient<f64> for ReducedObjective<O> {
235    fn grad(&self, r: ArrayView1<f64>) -> Array1<f64> {
236        // Chain rule through the affine decoder: g_r = W^T @ g_full(decode(r))
237        let x = self.decode(r);
238        let g_full = self.inner.grad(x.view());
239        self.basis.t().dot(&g_full)
240    }
241    fn dim(&self) -> usize {
242        self.bounds.dims
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use crate::objectives::StybTang2D;
250    use ndarray::{Array1, Array2, array};
251
252    fn reduced_box(k: usize, lo: f64, hi: f64) -> Bounds<f64> {
253        Bounds::new(Array1::from_elem(k, lo), Array1::from_elem(k, hi), 1e-9)
254    }
255
256    #[test]
257    fn reduced_decodes_and_evaluates_inner() {
258        // Collapse the 2D Styblinski-Tang onto the x1 = x2 diagonal: a single
259        // reduced coordinate r maps to (r, r).
260        let inner = StybTang2D::new();
261        let origin = array![0.0, 0.0];
262        let basis = Array2::from_shape_vec((2, 1), vec![1.0, 1.0]).unwrap();
263        let reduced = ReducedObjective::new(inner, origin, basis, reduced_box(1, -5.0, 5.0));
264        assert_eq!(Objective::dim(&reduced), 1);
265        // Decode is the diagonal lift.
266        let x = reduced.decode(array![2.0].view());
267        assert!((x[0] - 2.0).abs() < 1e-12 && (x[1] - 2.0).abs() < 1e-12);
268        // Value equals the inner objective on the diagonal.
269        let direct = StybTang2D::new().eval(array![2.0, 2.0].view());
270        assert!((reduced.eval(array![2.0].view()) - direct).abs() < 1e-12);
271    }
272
273    #[test]
274    fn chebyshev_reproduces_a_known_polynomial() {
275        // f(x) = 3 + 2*T_1(t) on [-1, 1] equals 3 + 2x; check value and slope.
276        let terms = vec![vec![0usize], vec![1usize]];
277        let coeffs = array![3.0, 2.0];
278        let s = ChebyshevSurrogate::new(reduced_box(1, -1.0, 1.0), terms, coeffs);
279        assert!((s.eval(array![0.5].view()) - 4.0).abs() < 1e-12);
280        assert!((s.grad(array![0.5].view())[0] - 2.0).abs() < 1e-9);
281    }
282
283    #[test]
284    fn chebyshev_gradient_matches_finite_difference() {
285        // A two-dimensional mixed-degree surrogate; compare the analytic
286        // gradient to a central finite difference.
287        let terms = vec![vec![2, 0], vec![1, 1], vec![0, 2]];
288        let coeffs = array![0.7, -1.3, 0.4];
289        let s = ChebyshevSurrogate::new(reduced_box(2, -2.0, 3.0), terms, coeffs);
290        let x = array![0.6, 1.1];
291        let g = s.grad(x.view());
292        let h = 1e-6;
293        for j in 0..2 {
294            let mut xp = x.clone();
295            let mut xm = x.clone();
296            xp[j] += h;
297            xm[j] -= h;
298            let fd = (s.eval(xp.view()) - s.eval(xm.view())) / (2.0 * h);
299            assert!(
300                (g[j] - fd).abs() < 1e-5,
301                "dim {j}: analytic {} vs fd {}",
302                g[j],
303                fd
304            );
305        }
306    }
307}