Skip to main content

eindir_core/objectives/
rosenbrock.rs

1//! N-dimensional Rosenbrock: classic banana-shaped valley benchmark.
2
3use crate::{Bounds, 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        Self {
18            bounds: Bounds::new(
19                Array1::from_vec(vec![-2.048; D]),
20                Array1::from_vec(vec![2.048; D]),
21                1e-9,
22            ),
23            min: OnceLock::new(),
24        }
25    }
26}
27
28impl<const D: usize> Default for Rosenbrock<D> {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl<const D: usize> Objective<f64> for Rosenbrock<D> {
35    fn dim(&self) -> usize {
36        D
37    }
38
39    fn bounds(&self) -> &Bounds<f64> {
40        &self.bounds
41    }
42
43    fn eval(&self, x: ArrayView1<f64>) -> f64 {
44        (0..D - 1)
45            .map(|i| 100.0 * (x[i + 1] - x[i].powi(2)).powi(2) + (1.0 - x[i]).powi(2))
46            .sum()
47    }
48
49    fn global_min(&self) -> Option<&FPair<f64>> {
50        Some(self.min.get_or_init(|| FPair {
51            pos: Array1::ones(D),
52            val: 0.0,
53        }))
54    }
55}
56
57impl<const D: usize> Gradient<f64> for Rosenbrock<D> {
58    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
59        // Standard Rosenbrock gradient (general D).
60        let mut g = Array1::<f64>::zeros(D);
61        if D <= 1 {
62            return g;
63        }
64        // First variable
65        let t0 = x[1] - x[0].powi(2);
66        g[0] = -400.0 * x[0] * t0 + 2.0 * (x[0] - 1.0);
67        // Middle variables
68        for i in 1..D - 1 {
69            let t_prev = x[i] - x[i - 1].powi(2);
70            let t_i = x[i + 1] - x[i].powi(2);
71            g[i] = 200.0 * t_prev - 400.0 * x[i] * t_i + 2.0 * (x[i] - 1.0);
72        }
73        // Last variable
74        if D > 1 {
75            let t_last = x[D - 1] - x[D - 2].powi(2);
76            g[D - 1] = 200.0 * t_last;
77        }
78        g
79    }
80    fn dim(&self) -> usize {
81        D
82    }
83}