Skip to main content

eindir_core/
additive.rs

1//! Separable rank-1 surrogate: the base case of the functional tensor train.
2//!
3//! A high-dimensional objective is modelled additively,
4//! `f(x) ~= c + sum_j g_j(x_j)`, with each `g_j` a first-kind Chebyshev energy
5//! in one coordinate. This is a rank-1 functional tensor train in the *full*
6//! `d` coordinates, so it carries no active-subspace collapse and the tempered
7//! Gibbs density `exp(-f/T)` factorises across coordinates exactly when `f` is
8//! separable. That factorisation is what the [`AdditiveSurrogate::sample`]
9//! independence proposal exploits: each coordinate is drawn from its own 1D
10//! tempered marginal `exp(-g_j/T)/Z_j(T)` by inverse-CDF, in `O(d m)` with no
11//! curse of dimensionality, so a single draw places every coordinate at its
12//! tempered optimum at once -- the regime an active-subspace surrogate cannot
13//! reach.
14//!
15//! Like [`crate::reduced::ChebyshevSurrogate`], the surrogate is an
16//! `Obj`-transform: it implements [`Objective`], so every point of the sampling
17//! algebra consumes it through the same trait. The fit decouples per coordinate
18//! (one `degree x degree` solve each), which keeps it linear in `d` and usable
19//! at native CUTEst sizes. A Metropolis accept against the true objective
20//! debiases the mean-field error when the objective is not separable.
21
22use crate::{Bounds, Objective, gradient::Gradient};
23use ndarray::{Array1, Array2, ArrayView1, ArrayView2};
24use rand::Rng;
25
26/// First-kind Chebyshev values `T_1..T_degree` at a unit coordinate `t` in
27/// `[-1, 1]` (the constant `T_0` is carried by a shared intercept and omitted).
28fn cheb_basis(t: f64, degree: usize) -> Array1<f64> {
29    let mut out = Array1::zeros(degree);
30    if degree == 0 {
31        return out;
32    }
33    let mut tm1 = 1.0; // T_0
34    let mut tm = t; // T_1
35    out[0] = tm;
36    for m in 1..degree {
37        let next = 2.0 * t * tm - tm1;
38        out[m] = next;
39        tm1 = tm;
40        tm = next;
41    }
42    out
43}
44
45/// Derivatives `T_1'..T_degree'` at unit coordinate `t`, via the coupled
46/// recurrence `T'_{m+1} = 2 T_m + 2 t T'_m - T'_{m-1}`.
47fn cheb_basis_deriv(t: f64, degree: usize) -> Array1<f64> {
48    let mut dv = Array1::zeros(degree);
49    if degree == 0 {
50        return dv;
51    }
52    // values needed for the derivative recurrence
53    let mut v_m1 = 1.0; // T_0
54    let mut v_m = t; // T_1
55    let mut d_m1 = 0.0; // T_0'
56    let mut d_m = 1.0; // T_1'
57    dv[0] = d_m;
58    for m in 1..degree {
59        let d_next = 2.0 * v_m + 2.0 * t * d_m - d_m1;
60        dv[m] = d_next;
61        let v_next = 2.0 * t * v_m - v_m1;
62        v_m1 = v_m;
63        v_m = v_next;
64        d_m1 = d_m;
65        d_m = d_next;
66    }
67    dv
68}
69
70/// Cholesky factor `L` (lower) of a symmetric positive-(semi)definite `a` with a
71/// small Tikhonov floor; `a` is `p x p` with `p = degree` tiny. The ridge keeps
72/// the normal equations solvable when a coordinate's pilot design is
73/// rank-deficient (e.g. a near-constant column).
74fn cholesky_ridged(mut a: Array2<f64>) -> Array2<f64> {
75    let p = a.nrows();
76    let ridge = 1e-10 * (1.0 + (0..p).map(|i| a[[i, i]]).fold(0.0, f64::max));
77    for i in 0..p {
78        a[[i, i]] += ridge;
79    }
80    let mut l = Array2::<f64>::zeros((p, p));
81    for i in 0..p {
82        for j in 0..=i {
83            let mut s = a[[i, j]];
84            for k in 0..j {
85                s -= l[[i, k]] * l[[j, k]];
86            }
87            if i == j {
88                l[[i, j]] = s.max(ridge).sqrt();
89            } else {
90                l[[i, j]] = s / l[[j, j]];
91            }
92        }
93    }
94    l
95}
96
97/// Solve `a x = b` given the Cholesky factor `l` of `a` (`a = L L^T`).
98fn chol_solve(l: &Array2<f64>, b: Array1<f64>) -> Array1<f64> {
99    let p = l.nrows();
100    // forward solve L y = b
101    let mut y = Array1::<f64>::zeros(p);
102    for i in 0..p {
103        let mut s = b[i];
104        for k in 0..i {
105            s -= l[[i, k]] * y[k];
106        }
107        y[i] = s / l[[i, i]];
108    }
109    // back solve L^T x = y
110    let mut x = Array1::<f64>::zeros(p);
111    for i in (0..p).rev() {
112        let mut s = y[i];
113        for k in (i + 1)..p {
114            s -= l[[k, i]] * x[k];
115        }
116        x[i] = s / l[[i, i]];
117    }
118    x
119}
120
121/// A separable rank-1 Chebyshev energy model `c + sum_j g_j(x_j)`.
122pub struct AdditiveSurrogate {
123    bounds: Bounds<f64>,
124    intercept: f64,
125    /// `(dim, degree)` per-coordinate Chebyshev coefficients for `T_1..T_degree`.
126    coeffs: Array2<f64>,
127    /// `(dim, degree)` pilot column means of each coordinate's basis. Under
128    /// uniform sampling the even-degree Chebyshev columns have nonzero mean
129    /// (`E[T_2] = -1/3`, ...), so the per-coordinate fit is consistent only on
130    /// mean-centred columns; the offset is folded into `intercept` and
131    /// subtracted back in [`value`](Self::value).
132    col_means: Array2<f64>,
133    degree: usize,
134}
135
136impl AdditiveSurrogate {
137    /// Fit the surrogate to pilot points `x` (`n x d`) and values `y` (`n`) with
138    /// a default of 12 backfitting passes.
139    pub fn fit(x: ArrayView2<f64>, y: ArrayView1<f64>, bounds: Bounds<f64>, degree: usize) -> Self {
140        Self::fit_backfit(x, y, bounds, degree, 12)
141    }
142
143    /// Fit by backfitting (Gauss-Seidel over coordinates).
144    ///
145    /// The intercept is the pilot mean. Each coordinate's Chebyshev coefficients
146    /// are refit in turn against the *partial* residual `y - intercept -
147    /// sum_{l != j} g_l`, on a mean-centred design so the fit is consistent
148    /// under uniform sampling. Sweeping all coordinates `n_passes` times removes
149    /// the finite-sample cross-coordinate contamination that an independent
150    /// per-coordinate fit leaves behind, converging to the joint least-squares
151    /// additive model while staying `O(n_passes d (n degree + degree^3))` --
152    /// linear in `d`, unlike the joint solve. Each coordinate's Gram factor is
153    /// cached, so a pass costs only one triangular solve per coordinate.
154    ///
155    /// Panics when shapes disagree or `degree == 0`.
156    pub fn fit_backfit(
157        x: ArrayView2<f64>,
158        y: ArrayView1<f64>,
159        bounds: Bounds<f64>,
160        degree: usize,
161        n_passes: usize,
162    ) -> Self {
163        assert!(degree >= 1, "degree must be at least 1");
164        let n = x.nrows();
165        let dim = x.ncols();
166        assert_eq!(n, y.len(), "x rows must match y length");
167        assert_eq!(dim, bounds.dims, "x cols must match bounds dims");
168        assert!(n > degree, "need at least degree+1 pilot points");
169
170        let mean_y = y.sum() / n as f64;
171        let mut col_means = Array2::<f64>::zeros((dim, degree));
172        let low = &bounds.low;
173        let high = &bounds.high;
174
175        // Precompute each coordinate's centred design B_j and the Cholesky
176        // factor of its Gram; only the right-hand side changes between passes.
177        let mut designs: Vec<Array2<f64>> = Vec::with_capacity(dim);
178        let mut chols: Vec<Array2<f64>> = Vec::with_capacity(dim);
179        for j in 0..dim {
180            let span = {
181                let w = high[j] - low[j];
182                if w > 0.0 { w } else { 1.0 }
183            };
184            let mut d = Array2::<f64>::zeros((n, degree));
185            for i in 0..n {
186                let t = 2.0 * (x[[i, j]] - low[j]) / span - 1.0;
187                d.row_mut(i).assign(&cheb_basis(t.clamp(-1.0, 1.0), degree));
188            }
189            let means: Array1<f64> = d.mean_axis(ndarray::Axis(0)).unwrap();
190            col_means.row_mut(j).assign(&means);
191            for mut row in d.rows_mut() {
192                row -= &means;
193            }
194            chols.push(cholesky_ridged(d.t().dot(&d)));
195            designs.push(d);
196        }
197
198        // Backfitting: maintain each coordinate's fitted contribution over the
199        // pilot and the running total, so the partial residual is one subtraction.
200        let target: Array1<f64> = y.to_owned() - mean_y;
201        let mut coeffs = Array2::<f64>::zeros((dim, degree));
202        let mut fitted: Vec<Array1<f64>> = vec![Array1::zeros(n); dim];
203        let mut total: Array1<f64> = Array1::zeros(n);
204        for _ in 0..n_passes.max(1) {
205            for j in 0..dim {
206                let partial = &target - &(&total - &fitted[j]);
207                let rhs = designs[j].t().dot(&partial);
208                let c = chol_solve(&chols[j], rhs);
209                let new_fit = designs[j].dot(&c);
210                total = &total - &fitted[j] + &new_fit;
211                fitted[j] = new_fit;
212                coeffs.row_mut(j).assign(&c);
213            }
214        }
215        Self {
216            bounds,
217            intercept: mean_y,
218            coeffs,
219            col_means,
220            degree,
221        }
222    }
223
224    /// Search-space box of the surrogate.
225    pub fn bounds(&self) -> &Bounds<f64> {
226        &self.bounds
227    }
228
229    fn unit(&self, j: usize, xj: f64) -> f64 {
230        let (lo, hi) = (self.bounds.low[j], self.bounds.high[j]);
231        let span = if hi > lo { hi - lo } else { 1.0 };
232        (2.0 * (xj - lo) / span - 1.0).clamp(-1.0, 1.0)
233    }
234
235    /// Energy contribution `g_j(xj)` of one coordinate (no intercept), centred
236    /// by the pilot column means so the per-coordinate fit is consistent.
237    fn coord_energy(&self, j: usize, xj: f64) -> f64 {
238        let t = self.unit(j, xj);
239        let basis = cheb_basis(t, self.degree);
240        (&basis - &self.col_means.row(j)).dot(&self.coeffs.row(j))
241    }
242
243    /// Surrogate value at full point `x`.
244    pub fn value(&self, x: ArrayView1<f64>) -> f64 {
245        let mut acc = self.intercept;
246        for j in 0..self.bounds.dims {
247            acc += self.coord_energy(j, x[j]);
248        }
249        acc
250    }
251
252    /// Analytic gradient of the separable surrogate at `x`.
253    pub fn gradient(&self, x: ArrayView1<f64>) -> Array1<f64> {
254        let dim = self.bounds.dims;
255        let mut g = Array1::<f64>::zeros(dim);
256        for j in 0..dim {
257            let (lo, hi) = (self.bounds.low[j], self.bounds.high[j]);
258            let span = if hi > lo { hi - lo } else { 1.0 };
259            let t = self.unit(j, x[j]);
260            let dgdt = cheb_basis_deriv(t, self.degree).dot(&self.coeffs.row(j));
261            g[j] = dgdt * (2.0 / span); // chain rule dt/dx = 2/span
262        }
263        g
264    }
265
266    /// Draw `n` independence proposals from the tempered surrogate density
267    /// `exp(-(f - f_min)/T)` by per-coordinate inverse-CDF sampling on an
268    /// `grid_m`-point grid. Each coordinate is sampled independently (the
269    /// separable factorisation), with a uniform within-cell jitter for
270    /// continuity. Returns an `n x d` array of points inside the box.
271    pub fn sample<R: Rng + ?Sized>(
272        &self,
273        n: usize,
274        temperature: f64,
275        grid_m: usize,
276        rng: &mut R,
277    ) -> Array2<f64> {
278        let dim = self.bounds.dims;
279        let temp = temperature.max(1e-12);
280        let mut out = Array2::<f64>::zeros((n, dim));
281        let grid_m = grid_m.max(2);
282        for j in 0..dim {
283            let (lo, hi) = (self.bounds.low[j], self.bounds.high[j]);
284            let span = hi - lo;
285            // grid coordinates and energies for this axis
286            let mut energy = vec![0.0f64; grid_m];
287            let mut emin = f64::INFINITY;
288            for (g, e) in energy.iter_mut().enumerate() {
289                let frac = g as f64 / (grid_m - 1) as f64;
290                let t = 2.0 * frac - 1.0;
291                let value = cheb_basis(t, self.degree).dot(&self.coeffs.row(j));
292                *e = value;
293                if value.is_finite() {
294                    emin = emin.min(value);
295                }
296            }
297            if !emin.is_finite() {
298                for s in 0..n {
299                    out[[s, j]] = lo + rng.random::<f64>() * span;
300                }
301                continue;
302            }
303            // tempered weights and their normalised CDF
304            let mut cdf = vec![0.0f64; grid_m];
305            let mut acc = 0.0;
306            for g in 0..grid_m {
307                let weight = if energy[g].is_finite() {
308                    let z = ((energy[g] - emin) / temp).clamp(0.0, 700.0);
309                    (-z).exp()
310                } else {
311                    0.0
312                };
313                if weight.is_finite() {
314                    acc += weight;
315                }
316                cdf[g] = acc;
317            }
318            if !acc.is_finite() || acc <= 0.0 {
319                for s in 0..n {
320                    out[[s, j]] = lo + rng.random::<f64>() * span;
321                }
322                continue;
323            }
324            let cell = if grid_m > 1 {
325                span / (grid_m - 1) as f64
326            } else {
327                span
328            };
329            for s in 0..n {
330                let u = rng.random::<f64>() * acc;
331                // first grid index with cdf >= u
332                let mut idx = match cdf.binary_search_by(|v| v.total_cmp(&u)) {
333                    Ok(i) => i,
334                    Err(i) => i,
335                };
336                if idx >= grid_m {
337                    idx = grid_m - 1;
338                }
339                let frac = idx as f64 / (grid_m - 1) as f64;
340                let centre = lo + frac * span;
341                let jitter = (rng.random::<f64>() - 0.5) * cell;
342                out[[s, j]] = (centre + jitter).clamp(lo, hi);
343            }
344        }
345        out
346    }
347}
348
349impl Objective<f64> for AdditiveSurrogate {
350    fn eval(&self, x: ArrayView1<f64>) -> f64 {
351        self.value(x)
352    }
353
354    fn bounds(&self) -> &Bounds<f64> {
355        &self.bounds
356    }
357
358    fn dim(&self) -> usize {
359        self.bounds.dims
360    }
361}
362
363impl Gradient<f64> for AdditiveSurrogate {
364    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
365        // The public `gradient` method is the analytic native gradient
366        // (Ceres style).  We delegate for the trait.
367        self.gradient(x)
368    }
369    fn dim(&self) -> usize {
370        self.bounds.dims
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use rand::SeedableRng;
378    use rand::rngs::StdRng;
379
380    fn box_bounds(dim: usize, lo: f64, hi: f64) -> Bounds<f64> {
381        Bounds::new(Array1::from_elem(dim, lo), Array1::from_elem(dim, hi), 0.0)
382    }
383
384    // Styblinski-Tang is separable: 0.5 sum(x^4 - 16 x^2 + 5 x).
385    fn styb(x: ArrayView1<f64>) -> f64 {
386        0.5 * x
387            .iter()
388            .map(|&v| v.powi(4) - 16.0 * v * v + 5.0 * v)
389            .sum::<f64>()
390    }
391
392    #[test]
393    fn fit_recovers_separable_value() {
394        let dim = 5;
395        let bounds = box_bounds(dim, -5.0, 5.0);
396        let mut rng = StdRng::seed_from_u64(0);
397        let n = 400;
398        let mut x = Array2::<f64>::zeros((n, dim));
399        let mut y = Array1::<f64>::zeros(n);
400        for i in 0..n {
401            for j in 0..dim {
402                x[[i, j]] = rng.random::<f64>() * 10.0 - 5.0;
403            }
404            y[i] = styb(x.row(i));
405        }
406        let surr = AdditiveSurrogate::fit(x.view(), y.view(), bounds, 8);
407        // surrogate value tracks the true separable objective at fresh points
408        let mut max_rel = 0.0f64;
409        for _ in 0..50 {
410            let mut p = Array1::<f64>::zeros(dim);
411            for j in 0..dim {
412                p[j] = rng.random::<f64>() * 10.0 - 5.0;
413            }
414            let truth = styb(p.view());
415            let approx = surr.value(p.view());
416            let rel = (truth - approx).abs() / (1.0 + truth.abs());
417            max_rel = max_rel.max(rel);
418        }
419        assert!(max_rel < 1e-6, "separable fit rel-err too large: {max_rel}");
420    }
421
422    #[test]
423    fn gradient_matches_finite_difference() {
424        let dim = 4;
425        let bounds = box_bounds(dim, -5.0, 5.0);
426        let mut rng = StdRng::seed_from_u64(1);
427        let n = 300;
428        let mut x = Array2::<f64>::zeros((n, dim));
429        let mut y = Array1::<f64>::zeros(n);
430        for i in 0..n {
431            for j in 0..dim {
432                x[[i, j]] = rng.random::<f64>() * 10.0 - 5.0;
433            }
434            y[i] = styb(x.row(i));
435        }
436        let surr = AdditiveSurrogate::fit(x.view(), y.view(), bounds, 8);
437        let p = Array1::from_vec(vec![1.0, -2.0, 0.5, 3.0]);
438        let g = surr.gradient(p.view());
439        let h = 1e-6;
440        for j in 0..dim {
441            let mut pp = p.clone();
442            let mut pm = p.clone();
443            pp[j] += h;
444            pm[j] -= h;
445            let fd = (surr.value(pp.view()) - surr.value(pm.view())) / (2.0 * h);
446            assert!((g[j] - fd).abs() < 1e-3, "grad[{j}] {} vs fd {}", g[j], fd);
447        }
448    }
449
450    #[test]
451    fn tempered_sample_concentrates_at_low_energy() {
452        // At a low temperature the separable sampler should place each
453        // coordinate near the Styblinski-Tang single-well minimum -2.903534.
454        let dim = 6;
455        let bounds = box_bounds(dim, -5.0, 5.0);
456        let mut rng = StdRng::seed_from_u64(2);
457        let n = 500;
458        let mut x = Array2::<f64>::zeros((n, dim));
459        let mut y = Array1::<f64>::zeros(n);
460        for i in 0..n {
461            for j in 0..dim {
462                x[[i, j]] = rng.random::<f64>() * 10.0 - 5.0;
463            }
464            y[i] = styb(x.row(i));
465        }
466        let surr = AdditiveSurrogate::fit(x.view(), y.view(), bounds, 8);
467        let draws = surr.sample(2000, 0.5, 129, &mut rng);
468        let mean0 = draws.column(0).mean().unwrap();
469        // the global single-well min dominates the tempered density
470        assert!(
471            (mean0 - (-2.903534)).abs() < 0.7,
472            "low-T sample mean {mean0} not near the well -2.9035"
473        );
474    }
475
476    #[test]
477    fn tempered_sample_handles_nonfinite_axis_energy() {
478        let dim = 2;
479        let bounds = box_bounds(dim, -1.0, 1.0);
480        let surr = AdditiveSurrogate {
481            bounds,
482            intercept: 0.0,
483            coeffs: Array2::from_shape_vec((dim, 2), vec![f64::NAN, 0.0, 0.0, 0.0]).unwrap(),
484            col_means: Array2::zeros((dim, 2)),
485            degree: 2,
486        };
487        let mut rng = StdRng::seed_from_u64(3);
488
489        let draws = surr.sample(32, 0.5, 17, &mut rng);
490
491        assert_eq!(draws.nrows(), 32);
492        assert_eq!(draws.ncols(), dim);
493        assert!(draws.iter().all(|v| v.is_finite()));
494        assert!(draws.iter().all(|v| (-1.0..=1.0).contains(v)));
495    }
496}