1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Copyright 2018-2024 argmin developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! # Rastrigin test function
//!
//! Defined as
//!
//! `f(x_1, x_2, ..., x_n) = a * n + \sum_{i=1}^{n} \left[ x_i^2 - a * cos(2 * pi * x_i) \right]`
//!
//! where `x_i \in [-5.12, 5.12]` and `a = 10`
//!
//! The global minimum is at `f(x_1, x_2, ..., x_n) = f(0, 0, ..., 0) = 0`.

use num::{Float, FromPrimitive};
use std::f64::consts::PI;
use std::iter::Sum;

/// Rastrigin test function
///
/// Defined as
///
/// `f(x_1, x_2, ..., x_n) = a * n + \sum_{i=1}^{n} \left[ x_i^2 - a * cos(2 * pi * x_i) \right]`
///
/// where `x_i \in [-5.12, 5.12]` and `a = 10`
///
/// The global minimum is at `f(x_1, x_2, ..., x_n) = f(0, 0, ..., 0) = 0`.
pub fn rastrigin<T>(param: &[T]) -> T
where
    T: Float + FromPrimitive + Sum,
{
    rastrigin_a(param, T::from_f64(10.0).unwrap())
}

/// Rastrigin test function
///
/// The same as `rastrigin`; however, it allows to set the parameter a.
pub fn rastrigin_a<T>(param: &[T], a: T) -> T
where
    T: Float + FromPrimitive + Sum,
{
    a * T::from_usize(param.len()).unwrap()
        + param
            .iter()
            .map(|&x| x.powi(2) - a * (T::from_f64(2.0 * PI).unwrap() * x).cos())
            .sum()
}

/// Derivative of Rastrigin test function where `a` can be chosen freely
pub fn rastrigin_a_derivative<T>(param: &[T], a: T) -> Vec<T>
where
    T: Float + FromPrimitive + Sum + Into<f64>,
{
    let npi2 = T::from_f64(2.0 * PI).unwrap();
    let n2 = T::from_f64(2.0).unwrap();
    param
        .iter()
        .map(|x| n2 * *x + npi2 * a * T::from_f64(f64::sin((npi2 * *x).into())).unwrap())
        .collect()
}

/// Derivative of Rastrigin test function
pub fn rastrigin_derivative<T>(param: &[T]) -> Vec<T>
where
    T: Float + FromPrimitive + Sum + Into<f64>,
{
    rastrigin_a_derivative(param, T::from_f64(10.0).unwrap())
}

/// Derivative of Rastrigin test function where `a` can be chosen freely
///
/// This is the const generics version, which requires the number of parameters to be known
/// at compile time.
pub fn rastrigin_a_derivative_const<const N: usize, T>(param: &[T; N], a: T) -> [T; N]
where
    T: Float + FromPrimitive + Sum + Into<f64>,
{
    let npi2 = T::from_f64(2.0 * PI).unwrap();
    let n2 = T::from_f64(2.0).unwrap();
    let mut result = [T::from_f64(0.0).unwrap(); N];
    for i in 0..N {
        result[i] =
            n2 * param[i] + npi2 * a * T::from_f64(f64::sin((npi2 * param[i]).into())).unwrap();
    }
    result
}

/// Derivative of Rastrigin test function
///
/// This is the const generics version, which requires the number of parameters to be known
/// at compile time.
pub fn rastrigin_derivative_const<const N: usize, T>(param: &[T; N]) -> [T; N]
where
    T: Float + FromPrimitive + Sum + Into<f64>,
{
    rastrigin_a_derivative_const(param, T::from_f64(10.0).unwrap())
}

/// Hessian of Rastrigin test function where `a` can be chosen freely
pub fn rastrigin_a_hessian<T>(param: &[T], a: T) -> Vec<Vec<T>>
where
    T: Float + FromPrimitive + Sum + Into<f64>,
{
    let npi2 = T::from_f64(2.0 * PI).unwrap();
    let n4pisq = T::from_f64(4.0 * PI.powi(2)).unwrap();
    let n2 = T::from_f64(2.0).unwrap();
    let n0 = T::from_f64(0.0).unwrap();

    let n = param.len();
    let mut hessian = vec![vec![n0; n]; n];

    for i in 0..n {
        hessian[i][i] = n2 + n4pisq * a * T::from_f64(f64::cos((npi2 * param[i]).into())).unwrap();
    }
    hessian
}

/// Hessian of Rastrigin test function
pub fn rastrigin_hessian<T>(param: &[T]) -> Vec<Vec<T>>
where
    T: Float + FromPrimitive + Sum + Into<f64>,
{
    rastrigin_a_hessian(param, T::from_f64(10.0).unwrap())
}

/// Hessian of Rastrigin test function where `a` can be chosen freely
///
/// This is the const generics version, which requires the number of parameters to be known
/// at compile time.
pub fn rastrigin_a_hessian_const<const N: usize, T>(param: &[T], a: T) -> [[T; N]; N]
where
    T: Float + FromPrimitive + Sum + Into<f64>,
{
    let npi2 = T::from_f64(2.0 * PI).unwrap();
    let n4pisq = T::from_f64(4.0 * PI.powi(2)).unwrap();
    let n2 = T::from_f64(2.0).unwrap();
    let n0 = T::from_f64(0.0).unwrap();

    let mut hessian = [[n0; N]; N];

    for i in 0..N {
        hessian[i][i] = n2 + n4pisq * a * T::from_f64(f64::cos((npi2 * param[i]).into())).unwrap();
    }
    hessian
}

/// Hessian of Rastrigin test function
///
/// This is the const generics version, which requires the number of parameters to be known
/// at compile time.
pub fn rastrigin_hessian_const<const N: usize, T>(param: &[T; N]) -> [[T; N]; N]
where
    T: Float + FromPrimitive + Sum + Into<f64>,
{
    rastrigin_a_hessian_const(param, T::from_f64(10.0).unwrap())
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use finitediff::FiniteDiff;
    use proptest::prelude::*;
    use std::{f32, f64};

    #[test]
    fn test_rastrigin_optimum() {
        assert_relative_eq!(rastrigin(&[0.0_f32, 0.0_f32]), 0.0, epsilon = f32::EPSILON);
        assert_relative_eq!(rastrigin(&[0.0_f64, 0.0_f64]), 0.0, epsilon = f64::EPSILON);
    }

    #[test]
    fn test_parameter_a() {
        assert_relative_eq!(
            rastrigin(&[0.0_f32, 0.0_f32]),
            rastrigin_a(&[0.0_f32, 0.0_f32], 10.0),
            epsilon = f32::EPSILON
        );

        assert_relative_eq!(
            rastrigin(&[0.0_f64, 0.0_f64]),
            rastrigin_a(&[0.0_f64, 0.0_f64], 10.0),
            epsilon = f64::EPSILON
        );

        let derivative = rastrigin_derivative(&[1.0_f64, -1.0_f64]);
        let derivative_a = rastrigin_a_derivative(&[1.0_f64, -1.0_f64], 10.0);
        for i in 0..derivative.len() {
            assert_relative_eq!(derivative[i], derivative_a[i], epsilon = f64::EPSILON);
        }

        let derivative = rastrigin_derivative_const(&[1.0_f64, -1.0_f64]);
        let derivative_a = rastrigin_a_derivative_const(&[1.0_f64, -1.0_f64], 10.0);
        for i in 0..derivative.len() {
            assert_relative_eq!(derivative[i], derivative_a[i], epsilon = f64::EPSILON);
        }

        let hessian = rastrigin_hessian(&[1.0_f64, -1.0_f64]);
        let hessian_a = rastrigin_a_hessian(&[1.0_f64, -1.0_f64], 10.0);
        for i in 0..hessian.len() {
            for j in 0..hessian.len() {
                assert_relative_eq!(hessian[i][j], hessian_a[i][j], epsilon = f64::EPSILON);
            }
        }

        let hessian = rastrigin_hessian_const(&[1.0_f64, -1.0_f64]);
        let hessian_a: [[_; 2]; 2] = rastrigin_a_hessian_const(&[1.0_f64, -1.0_f64], 10.0);
        for i in 0..hessian.len() {
            for j in 0..hessian.len() {
                assert_relative_eq!(hessian[i][j], hessian_a[i][j], epsilon = f64::EPSILON);
            }
        }
    }

    #[test]
    fn test_rastrigin_a_derivative_optimum() {
        let derivative = rastrigin_a_derivative(&[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 10.0);
        for elem in derivative {
            assert_relative_eq!(elem, 0.0, epsilon = f64::EPSILON);
        }
    }

    #[test]
    fn test_rastrigin_a_derivative_const_optimum() {
        let derivative =
            rastrigin_a_derivative_const(&[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 10.0);
        for elem in derivative {
            assert_relative_eq!(elem, 0.0, epsilon = f64::EPSILON);
        }
    }

    proptest! {
        #[test]
        fn test_rastrigin_derivative_finitediff(a in -5.12..5.12,
                                                b in -5.12..5.12,
                                                c in -5.12..5.12,
                                                d in -5.12..5.12,
                                                e in -5.12..5.12,
                                                f in -5.12..5.12,
                                                g in -5.12..5.12,
                                                h in -5.12..5.12) {
            let param = [a, b, c, d, e, f, g, h];
            let derivative = rastrigin_derivative(&param);
            let derivative_fd = Vec::from(param).central_diff(&|x| rastrigin(&x));
            for i in 0..derivative.len() {
                assert_relative_eq!(
                    derivative[i],
                    derivative_fd[i],
                    epsilon = 1e-5,
                    max_relative = 1e-2
                );
            }
        }
    }

    proptest! {
        #[test]
        fn test_rastrigin_derivative_const_finitediff(a in -5.12..5.12,
                                                      b in -5.12..5.12,
                                                      c in -5.12..5.12,
                                                      d in -5.12..5.12,
                                                      e in -5.12..5.12,
                                                      f in -5.12..5.12,
                                                      g in -5.12..5.12,
                                                      h in -5.12..5.12) {
            let param = [a, b, c, d, e, f, g, h];
            let derivative = rastrigin_derivative_const(&param);
            let derivative_fd = Vec::from(param).central_diff(&|x| rastrigin(&x));
            for i in 0..derivative.len() {
                assert_relative_eq!(
                    derivative[i],
                    derivative_fd[i],
                    epsilon = 1e-5,
                    max_relative = 1e-2
                );
            }
        }
    }

    proptest! {
        #[test]
        fn test_rastrigin_hessian_finitediff(a in -5.12..5.12,
                                             b in -5.12..5.12,
                                             c in -5.12..5.12,
                                             d in -5.12..5.12,
                                             e in -5.12..5.12,
                                             f in -5.12..5.12,
                                             g in -5.12..5.12,
                                             h in -5.12..5.12) {
            let param = [a, b, c, d, e, f, g, h];
            let hessian = rastrigin_hessian(&param);
            let hessian_fd =
                Vec::from(param).forward_hessian(&|x| rastrigin_derivative(&x));
            let n = hessian.len();
            for i in 0..n {
                assert_eq!(hessian[i].len(), n);
                for j in 0..n {
                    assert_relative_eq!(
                        hessian[i][j],
                        hessian_fd[i][j],
                        epsilon = 1e-4,
                        max_relative = 1e-2
                    );
                }
            }
        }
    }

    proptest! {
        #[test]
        fn test_rastrigin_hessian_const_finitediff(a in -5.12..5.12,
                                                   b in -5.12..5.12,
                                                   c in -5.12..5.12,
                                                   d in -5.12..5.12,
                                                   e in -5.12..5.12,
                                                   f in -5.12..5.12,
                                                   g in -5.12..5.12,
                                                   h in -5.12..5.12) {
            let param = [a, b, c, d, e, f, g, h];
            let hessian = rastrigin_hessian_const(&param);
            let hessian_fd =
                Vec::from(param).forward_hessian(&|x| rastrigin_derivative(&x));
            let n = hessian.len();
            for i in 0..n {
                assert_eq!(hessian[i].len(), n);
                for j in 0..n {
                    assert_relative_eq!(
                        hessian[i][j],
                        hessian_fd[i][j],
                        epsilon = 1e-4,
                        max_relative = 1e-2
                    );
                }
            }
        }
    }
}