Skip to main content

eindir_core/objectives/
styblinski_tang.rs

1//! Styblinski-Tang 2D: a non-convex benchmark with a single global minimum.
2
3use crate::{Bounds, DifferentiableObjective, FPair, Objective, gradient::Gradient};
4use ndarray::{Array1, ArrayView1};
5use std::sync::OnceLock;
6
7/// 2D Styblinski-Tang objective `(1/2) * sum_i (x_i^4 - 16 x_i^2 + 5 x_i)`.
8///
9/// Domain `[-5, 5]^2`. Global minimum at `x = (-2.903534, -2.903534)` with
10/// value `-39.16599 * 2 = -78.33198`.
11pub struct StybTang2D {
12    bounds: Bounds<f64>,
13    min: OnceLock<FPair<f64>>,
14}
15
16impl StybTang2D {
17    /// Constructs the canonical 2D Styblinski-Tang objective.
18    pub fn new() -> Self {
19        Self {
20            bounds: Bounds::new(
21                Array1::from_vec(vec![-5.0, -5.0]),
22                Array1::from_vec(vec![5.0, 5.0]),
23                1e-9,
24            ),
25            min: OnceLock::new(),
26        }
27    }
28}
29
30impl Default for StybTang2D {
31    fn default() -> Self {
32        Self::new()
33    }
34}
35
36impl Objective<f64> for StybTang2D {
37    fn dim(&self) -> usize {
38        2
39    }
40
41    fn bounds(&self) -> &Bounds<f64> {
42        &self.bounds
43    }
44
45    fn eval(&self, x: ArrayView1<f64>) -> f64 {
46        x.iter()
47            .map(|xi| xi.powi(4) - 16.0 * xi.powi(2) + 5.0 * xi)
48            .sum::<f64>()
49            / 2.0
50    }
51
52    fn global_min(&self) -> Option<&FPair<f64>> {
53        Some(self.min.get_or_init(|| FPair {
54            pos: Array1::from_vec(vec![-2.903534, -2.903534]),
55            val: -39.16599 * 2.0,
56        }))
57    }
58}
59
60impl Gradient<f64> for StybTang2D {
61    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
62        // Analytic gradient of the normalized Styblinski-Tang.
63        // f = 1/2 * sum (x^4 -16x^2 +5x)  =>  df/dxi = 2x^3 -16x +2.5
64        x.mapv(|xi| 2.0 * xi.powi(3) - 16.0 * xi + 2.5)
65    }
66    fn dim(&self) -> usize {
67        2
68    }
69}
70
71impl DifferentiableObjective<f64> for StybTang2D {}