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, DifferentiableObjective, 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            if x[j] < self.bounds.low[j] || x[j] > self.bounds.high[j] {
258                continue;
259            }
260            let (lo, hi) = (self.bounds.low[j], self.bounds.high[j]);
261            let span = if hi > lo { hi - lo } else { 1.0 };
262            let t = self.unit(j, x[j]);
263            let dgdt = cheb_basis_deriv(t, self.degree).dot(&self.coeffs.row(j));
264            g[j] = dgdt * (2.0 / span); // chain rule dt/dx = 2/span
265        }
266        g
267    }
268
269    /// Draw `n` independence proposals from the tempered surrogate density
270    /// `exp(-(f - f_min)/T)` by per-coordinate inverse-CDF sampling on an
271    /// `grid_m`-point grid. Each coordinate is sampled independently (the
272    /// separable factorisation), with a uniform within-cell jitter for
273    /// continuity. Returns an `n x d` array of points inside the box.
274    pub fn sample<R: Rng + ?Sized>(
275        &self,
276        n: usize,
277        temperature: f64,
278        grid_m: usize,
279        rng: &mut R,
280    ) -> Array2<f64> {
281        let dim = self.bounds.dims;
282        let temp = temperature.max(1e-12);
283        let mut out = Array2::<f64>::zeros((n, dim));
284        let grid_m = grid_m.max(2);
285        for j in 0..dim {
286            let (lo, hi) = (self.bounds.low[j], self.bounds.high[j]);
287            let span = hi - lo;
288            // grid coordinates and energies for this axis
289            let mut energy = vec![0.0f64; grid_m];
290            let mut emin = f64::INFINITY;
291            for (g, e) in energy.iter_mut().enumerate() {
292                let frac = g as f64 / (grid_m - 1) as f64;
293                let t = 2.0 * frac - 1.0;
294                let value = cheb_basis(t, self.degree).dot(&self.coeffs.row(j));
295                *e = value;
296                if value.is_finite() {
297                    emin = emin.min(value);
298                }
299            }
300            if !emin.is_finite() {
301                for s in 0..n {
302                    out[[s, j]] = lo + rng.random::<f64>() * span;
303                }
304                continue;
305            }
306            // tempered weights and their normalised CDF
307            let mut cdf = vec![0.0f64; grid_m];
308            let mut acc = 0.0;
309            for g in 0..grid_m {
310                let weight = if energy[g].is_finite() {
311                    let z = ((energy[g] - emin) / temp).clamp(0.0, 700.0);
312                    (-z).exp()
313                } else {
314                    0.0
315                };
316                if weight.is_finite() {
317                    acc += weight;
318                }
319                cdf[g] = acc;
320            }
321            if !acc.is_finite() || acc <= 0.0 {
322                for s in 0..n {
323                    out[[s, j]] = lo + rng.random::<f64>() * span;
324                }
325                continue;
326            }
327            let cell = if grid_m > 1 {
328                span / (grid_m - 1) as f64
329            } else {
330                span
331            };
332            for s in 0..n {
333                let u = rng.random::<f64>() * acc;
334                // first grid index with cdf >= u
335                let mut idx = match cdf.binary_search_by(|v| v.total_cmp(&u)) {
336                    Ok(i) => i,
337                    Err(i) => i,
338                };
339                if idx >= grid_m {
340                    idx = grid_m - 1;
341                }
342                let frac = idx as f64 / (grid_m - 1) as f64;
343                let centre = lo + frac * span;
344                let jitter = (rng.random::<f64>() - 0.5) * cell;
345                out[[s, j]] = (centre + jitter).clamp(lo, hi);
346            }
347        }
348        out
349    }
350}
351
352impl Objective<f64> for AdditiveSurrogate {
353    fn eval(&self, x: ArrayView1<f64>) -> f64 {
354        self.value(x)
355    }
356
357    fn bounds(&self) -> &Bounds<f64> {
358        &self.bounds
359    }
360
361    fn dim(&self) -> usize {
362        self.bounds.dims
363    }
364}
365
366impl Gradient<f64> for AdditiveSurrogate {
367    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
368        // The public `gradient` method is the analytic native gradient
369        // (Ceres style).  We delegate for the trait.
370        self.gradient(x)
371    }
372    fn dim(&self) -> usize {
373        self.bounds.dims
374    }
375}
376
377impl DifferentiableObjective<f64> for AdditiveSurrogate {}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382    use rand::SeedableRng;
383    use rand::rngs::StdRng;
384
385    fn box_bounds(dim: usize, lo: f64, hi: f64) -> Bounds<f64> {
386        Bounds::new(Array1::from_elem(dim, lo), Array1::from_elem(dim, hi), 0.0)
387    }
388
389    // Styblinski-Tang is separable: 0.5 sum(x^4 - 16 x^2 + 5 x).
390    fn styb(x: ArrayView1<f64>) -> f64 {
391        0.5 * x
392            .iter()
393            .map(|&v| v.powi(4) - 16.0 * v * v + 5.0 * v)
394            .sum::<f64>()
395    }
396
397    #[test]
398    fn fit_recovers_separable_value() {
399        let dim = 5;
400        let bounds = box_bounds(dim, -5.0, 5.0);
401        let mut rng = StdRng::seed_from_u64(0);
402        let n = 400;
403        let mut x = Array2::<f64>::zeros((n, dim));
404        let mut y = Array1::<f64>::zeros(n);
405        for i in 0..n {
406            for j in 0..dim {
407                x[[i, j]] = rng.random::<f64>() * 10.0 - 5.0;
408            }
409            y[i] = styb(x.row(i));
410        }
411        let surr = AdditiveSurrogate::fit(x.view(), y.view(), bounds, 8);
412        // surrogate value tracks the true separable objective at fresh points
413        let mut max_rel = 0.0f64;
414        for _ in 0..50 {
415            let mut p = Array1::<f64>::zeros(dim);
416            for j in 0..dim {
417                p[j] = rng.random::<f64>() * 10.0 - 5.0;
418            }
419            let truth = styb(p.view());
420            let approx = surr.value(p.view());
421            let rel = (truth - approx).abs() / (1.0 + truth.abs());
422            max_rel = max_rel.max(rel);
423        }
424        assert!(max_rel < 1e-6, "separable fit rel-err too large: {max_rel}");
425    }
426
427    #[test]
428    fn gradient_matches_finite_difference() {
429        let dim = 4;
430        let bounds = box_bounds(dim, -5.0, 5.0);
431        let mut rng = StdRng::seed_from_u64(1);
432        let n = 300;
433        let mut x = Array2::<f64>::zeros((n, dim));
434        let mut y = Array1::<f64>::zeros(n);
435        for i in 0..n {
436            for j in 0..dim {
437                x[[i, j]] = rng.random::<f64>() * 10.0 - 5.0;
438            }
439            y[i] = styb(x.row(i));
440        }
441        let surr = AdditiveSurrogate::fit(x.view(), y.view(), bounds, 8);
442        let p = Array1::from_vec(vec![1.0, -2.0, 0.5, 3.0]);
443        let g = surr.gradient(p.view());
444        let h = 1e-6;
445        for j in 0..dim {
446            let mut pp = p.clone();
447            let mut pm = p.clone();
448            pp[j] += h;
449            pm[j] -= h;
450            let fd = (surr.value(pp.view()) - surr.value(pm.view())) / (2.0 * h);
451            assert!((g[j] - fd).abs() < 1e-3, "grad[{j}] {} vs fd {}", g[j], fd);
452        }
453    }
454
455    #[test]
456    fn gradient_is_zero_outside_clipped_coordinates() {
457        let bounds = box_bounds(1, -1.0, 1.0);
458        let x = Array2::from_shape_vec((8, 1), vec![-1.0, -0.7, -0.4, -0.1, 0.2, 0.5, 0.8, 1.0])
459            .unwrap();
460        let y = Array1::from_iter(x.column(0).iter().map(|&v| v * v));
461        let surrogate = AdditiveSurrogate::fit(x.view(), y.view(), bounds, 2);
462        assert_eq!(surrogate.gradient(Array1::from_vec(vec![2.0]).view())[0], 0.0);
463    }
464
465    #[test]
466    fn tempered_sample_concentrates_at_low_energy() {
467        // At a low temperature the separable sampler should place each
468        // coordinate near the Styblinski-Tang single-well minimum -2.903534.
469        let dim = 6;
470        let bounds = box_bounds(dim, -5.0, 5.0);
471        let mut rng = StdRng::seed_from_u64(2);
472        let n = 500;
473        let mut x = Array2::<f64>::zeros((n, dim));
474        let mut y = Array1::<f64>::zeros(n);
475        for i in 0..n {
476            for j in 0..dim {
477                x[[i, j]] = rng.random::<f64>() * 10.0 - 5.0;
478            }
479            y[i] = styb(x.row(i));
480        }
481        let surr = AdditiveSurrogate::fit(x.view(), y.view(), bounds, 8);
482        let draws = surr.sample(2000, 0.5, 129, &mut rng);
483        let mean0 = draws.column(0).mean().unwrap();
484        // the global single-well min dominates the tempered density
485        assert!(
486            (mean0 - (-2.903534)).abs() < 0.7,
487            "low-T sample mean {mean0} not near the well -2.9035"
488        );
489    }
490
491    #[test]
492    fn tempered_sample_handles_nonfinite_axis_energy() {
493        let dim = 2;
494        let bounds = box_bounds(dim, -1.0, 1.0);
495        let surr = AdditiveSurrogate {
496            bounds,
497            intercept: 0.0,
498            coeffs: Array2::from_shape_vec((dim, 2), vec![f64::NAN, 0.0, 0.0, 0.0]).unwrap(),
499            col_means: Array2::zeros((dim, 2)),
500            degree: 2,
501        };
502        let mut rng = StdRng::seed_from_u64(3);
503
504        let draws = surr.sample(32, 0.5, 17, &mut rng);
505
506        assert_eq!(draws.nrows(), 32);
507        assert_eq!(draws.ncols(), dim);
508        assert!(draws.iter().all(|v| v.is_finite()));
509        assert!(draws.iter().all(|v| (-1.0..=1.0).contains(v)));
510    }
511}