Skip to main content

eindir_core/objectives/
rosenbrock.rs

1//! N-dimensional Rosenbrock: classic banana-shaped valley benchmark.
2
3use crate::{Bounds, DifferentiableObjective, FPair, Objective, gradient::Gradient};
4use ndarray::{Array1, ArrayView1};
5use std::sync::OnceLock;
6
7/// N-dimensional Rosenbrock: `sum_{i=0}^{D-2} (100 * (x_{i+1} - x_i^2)^2 + (1 - x_i)^2)`.
8/// Domain `[-2.048, 2.048]^D`. Global minimum at `x = (1, 1, ..., 1)` with value `0`.
9pub struct Rosenbrock<const D: usize> {
10    bounds: Bounds<f64>,
11    min: OnceLock<FPair<f64>>,
12}
13
14impl<const D: usize> Rosenbrock<D> {
15    /// Constructs a Rosenbrock objective in `D` dimensions.
16    pub fn new() -> Self {
17        assert!(D > 0, "Rosenbrock requires at least one dimension");
18        Self {
19            bounds: Bounds::new(
20                Array1::from_vec(vec![-2.048; D]),
21                Array1::from_vec(vec![2.048; D]),
22                1e-9,
23            ),
24            min: OnceLock::new(),
25        }
26    }
27}
28
29impl<const D: usize> Default for Rosenbrock<D> {
30    fn default() -> Self {
31        Self::new()
32    }
33}
34
35impl<const D: usize> Objective<f64> for Rosenbrock<D> {
36    fn dim(&self) -> usize {
37        D
38    }
39
40    fn bounds(&self) -> &Bounds<f64> {
41        &self.bounds
42    }
43
44    fn eval(&self, x: ArrayView1<f64>) -> f64 {
45        (0..D - 1)
46            .map(|i| 100.0 * (x[i + 1] - x[i].powi(2)).powi(2) + (1.0 - x[i]).powi(2))
47            .sum()
48    }
49
50    fn global_min(&self) -> Option<&FPair<f64>> {
51        Some(self.min.get_or_init(|| FPair {
52            pos: Array1::ones(D),
53            val: 0.0,
54        }))
55    }
56}
57
58impl<const D: usize> Gradient<f64> for Rosenbrock<D> {
59    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
60        // Standard Rosenbrock gradient (general D).
61        let mut g = Array1::<f64>::zeros(D);
62        if D <= 1 {
63            return g;
64        }
65        // First variable
66        let t0 = x[1] - x[0].powi(2);
67        g[0] = -400.0 * x[0] * t0 + 2.0 * (x[0] - 1.0);
68        // Middle variables
69        for i in 1..D - 1 {
70            let t_prev = x[i] - x[i - 1].powi(2);
71            let t_i = x[i + 1] - x[i].powi(2);
72            g[i] = 200.0 * t_prev - 400.0 * x[i] * t_i + 2.0 * (x[i] - 1.0);
73        }
74        // Last variable
75        if D > 1 {
76            let t_last = x[D - 1] - x[D - 2].powi(2);
77            g[D - 1] = 200.0 * t_last;
78        }
79        g
80    }
81    fn dim(&self) -> usize {
82        D
83    }
84}
85
86impl<const D: usize> DifferentiableObjective<f64> for Rosenbrock<D> {}