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
// 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.

//! # Sphere function
//!
//! Defined as
//!
//! `f(x) = \sum_{i=1}^n x_i^2`
//!
//! where `x_i \in (-\infty, \infty)`
//!
//! The minimum is at `f(x_1, x_2, ..., x_n) = f(0, 0, ..., 0) = 0`.

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

/// Sphere test function
///
/// Defined as
///
/// `f(x_1, x_2, ..., x_n) = \sum_{i=1}^n x_i^2
///
/// where `x_i \in (-\infty, \infty)` and `n > 0`.
///
/// The global minimum is at `f(x_1, x_2, ..., x_n) = f(0, 0, ..., 0) = 0`.
pub fn sphere<T>(param: &[T]) -> T
where
    T: Float + FromPrimitive + Sum,
{
    param.iter().map(|x| x.powi(2)).sum()
}

/// Derivative of sphere test function
///
/// Defined as
///
/// `f(x_1, x_2, ..., x_n) = (2 * x_1, 2 * x_2, ... 2 * x_n)`
///
/// where `x_i \in (-\infty, \infty)` and `n > 0`.
pub fn sphere_derivative<T>(param: &[T]) -> Vec<T>
where
    T: Float + FromPrimitive,
{
    let num2 = T::from_f64(2.0).unwrap();
    param.iter().map(|x| num2 * *x).collect()
}

/// Derivative of sphere test function
///
/// Defined as
///
/// `f(x_1, x_2, ..., x_n) = (2 * x_1, 2 * x_2, ... 2 * x_n)`
///
/// where `x_i \in (-\infty, \infty)` and `n > 0`.
///
/// This is the const generics version, which requires the number of parameters to be known
/// at compile time.
pub fn sphere_derivative_const<const N: usize, T>(param: &[T; N]) -> [T; N]
where
    T: Float + FromPrimitive,
{
    let num2 = T::from_f64(2.0).unwrap();
    let mut deriv = [T::from_f64(0.0).unwrap(); N];
    for i in 0..N {
        deriv[i] = num2 * param[i];
    }
    deriv
}

/// Hessian of sphere test function
pub fn sphere_hessian<T>(param: &[T]) -> Vec<Vec<T>>
where
    T: Float + FromPrimitive,
{
    let n = param.len();
    let mut hessian = vec![vec![T::from_f64(0.0).unwrap(); n]; n];
    for (i, row) in hessian.iter_mut().enumerate().take(n) {
        row[i] = T::from_f64(2.0).unwrap();
    }
    hessian
}

/// Hessian of sphere test function
///
/// This is the const generics version, which requires the number of parameters to be known
/// at compile time.
pub fn sphere_hessian_const<const N: usize, T>(_param: &[T; N]) -> [[T; N]; N]
where
    T: Float + FromPrimitive,
{
    let mut hessian = [[T::from_f64(0.0).unwrap(); N]; N];
    for (i, row) in hessian.iter_mut().enumerate().take(N) {
        row[i] = T::from_f64(2.0).unwrap();
    }
    hessian
}

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

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

    proptest! {
        #[test]
        fn test_sphere(a in -10.0..10.0,
                       b in -10.0..10.0,
                       c in -10.0..10.0,
                       d in -10.0..10.0,
                       e in -10.0..10.0,
                       f in -10.0..10.0,
                       g in -10.0..10.0,
                       h in -10.0..10.0) {
            let param: [f64; 8] = [a, b, c, d, e, f, g, h];
            let v1 = sphere(&param);
            let v2 = a.powi(2) + b.powi(2) + c.powi(2) + d.powi(2) + e.powi(2) + f.powi(2) + g.powi(2) + h.powi(2);
            assert_relative_eq!(v1, v2, epsilon = f64::EPSILON);
        }
    }

    proptest! {
        #[test]
        fn test_sphere_derivative(a in -10.0..10.0,
                                  b in -10.0..10.0,
                                  c in -10.0..10.0,
                                  d in -10.0..10.0,
                                  e in -10.0..10.0,
                                  f in -10.0..10.0,
                                  g in -10.0..10.0,
                                  h in -10.0..10.0) {
            let param = [a, b, c, d, e, f, g, h];
            let derivative = sphere_derivative(&param);
            let derivative_fd =
                [2.0 * a, 2.0 * b, 2.0 * c, 2.0 * d, 2.0 * e, 2.0 * f, 2.0 * g, 2.0 * h];
            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_sphere_derivative_const(a in -10.0..10.0,
                                        b in -10.0..10.0,
                                        c in -10.0..10.0,
                                        d in -10.0..10.0,
                                        e in -10.0..10.0,
                                        f in -10.0..10.0,
                                        g in -10.0..10.0,
                                        h in -10.0..10.0) {
            let param = [a, b, c, d, e, f, g, h];
            let derivative = sphere_derivative_const(&param);
            let derivative_fd =
                [2.0 * a, 2.0 * b, 2.0 * c, 2.0 * d, 2.0 * e, 2.0 * f, 2.0 * g, 2.0 * h];
            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_sphere_derivative_finitediff(a in -10.0..10.0,
                                             b in -10.0..10.0,
                                             c in -10.0..10.0,
                                             d in -10.0..10.0,
                                             e in -10.0..10.0,
                                             f in -10.0..10.0,
                                             g in -10.0..10.0,
                                             h in -10.0..10.0) {
            let param = [a, b, c, d, e, f, g, h];
            let derivative = sphere_derivative(&param);
            let derivative_fd = Vec::from(param).central_diff(&|x| sphere(&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_sphere_derivative_const_finitediff(a in -10.0..10.0,
                                                   b in -10.0..10.0,
                                                   c in -10.0..10.0,
                                                   d in -10.0..10.0,
                                                   e in -10.0..10.0,
                                                   f in -10.0..10.0,
                                                   g in -10.0..10.0,
                                                   h in -10.0..10.0) {
            let param = [a, b, c, d, e, f, g, h];
            let derivative = sphere_derivative_const(&param);
            let derivative_fd = Vec::from(param).central_diff(&|x| sphere(&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_sphere_hessian(a in -10.0..10.0,
                                  b in -10.0..10.0,
                                  c in -10.0..10.0,
                                  d in -10.0..10.0,
                                  e in -10.0..10.0,
                                  f in -10.0..10.0,
                                  g in -10.0..10.0,
                                  h in -10.0..10.0) {
            let param = [a, b, c, d, e, f, g, h];
            let hessian = sphere_hessian(&param);
            for i in 0..hessian.len() {
                for j in 0..hessian.len() {
                    if i == j {
                        assert_relative_eq!(hessian[i][j], 2.0, epsilon = f64::EPSILON);
                    } else {
                        assert_relative_eq!(hessian[i][j], 0.0, epsilon = f64::EPSILON);
                    }
                }
            }
        }
    }

    proptest! {
        #[test]
        fn test_sphere_hessian_const(a in -10.0..10.0,
                                     b in -10.0..10.0,
                                     c in -10.0..10.0,
                                     d in -10.0..10.0,
                                     e in -10.0..10.0,
                                     f in -10.0..10.0,
                                     g in -10.0..10.0,
                                     h in -10.0..10.0) {
            let param = [a, b, c, d, e, f, g, h];
            let hessian = sphere_hessian_const(&param);
            for i in 0..hessian.len() {
                for j in 0..hessian.len() {
                    if i == j {
                        assert_relative_eq!(hessian[i][j], 2.0, epsilon = f64::EPSILON);
                    } else {
                        assert_relative_eq!(hessian[i][j], 0.0, epsilon = f64::EPSILON);
                    }
                }
            }
        }
    }

    proptest! {
        #[test]
        fn test_sphere_hessian_finitediff(a in -10.0..10.0,
                                          b in -10.0..10.0,
                                          c in -10.0..10.0,
                                          d in -10.0..10.0,
                                          e in -10.0..10.0,
                                          f in -10.0..10.0,
                                          g in -10.0..10.0,
                                          h in -10.0..10.0) {
            let param = [a, b, c, d, e, f, g, h];
            let hessian = sphere_hessian(&param);
            let hessian_fd = Vec::from(param).central_hessian(&|x| sphere_derivative(&x));
            for i in 0..hessian.len() {
                for j in 0..hessian.len() {
                    assert_relative_eq!(
                        hessian[i][j],
                        hessian_fd[i][j],
                        epsilon = 1e-5,
                        max_relative = 1e-2
                    );
                }
            }
        }
    }

    proptest! {
        #[test]
        fn test_sphere_hessian_const_finitediff(a in -10.0..10.0,
                                                b in -10.0..10.0,
                                                c in -10.0..10.0,
                                                d in -10.0..10.0,
                                                e in -10.0..10.0,
                                                f in -10.0..10.0,
                                                g in -10.0..10.0,
                                                h in -10.0..10.0) {
            let param = [a, b, c, d, e, f, g, h];
            let hessian = sphere_hessian_const(&param);
            let hessian_fd = Vec::from(param).central_hessian(&|x| sphere_derivative(&x));
            for i in 0..hessian.len() {
                for j in 0..hessian.len() {
                    assert_relative_eq!(
                        hessian[i][j],
                        hessian_fd[i][j],
                        epsilon = 1e-5,
                        max_relative = 1e-2
                    );
                }
            }
        }
    }
}