rastrigin/
rastrigin.rs

1// Copyright 2016 Martin Ankerl. 
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9extern crate differential_evolution;
10
11use differential_evolution::self_adaptive_de;
12use std::f32::consts::PI;
13use std::env;
14
15// The Rastrigin function is a non-convex function used as a
16// performance test problem for optimization algorithms.
17// see https://en.wikipedia.org/wiki/Rastrigin_function 
18fn rastrigin(pos: &[f32]) -> f32 {
19    pos.iter().fold(0.0, |sum, x| 
20        sum + x * x - 10.0 * (2.0 * PI * x).cos() + 10.0)
21}
22
23fn main() {
24    // command line args: dimension, number of evaluations
25    let args: Vec<String> = env::args().collect();
26    let dim = args[1].parse::<usize>().unwrap();
27
28    // initial search space for each dimension
29    let initial_min_max = vec![(-5.12, 5.12); dim];
30
31    // initialize differential evolution
32    let mut de = self_adaptive_de(initial_min_max, rastrigin);
33
34    // perform optimization for a maximum of 100000 cost evaluations,
35    // or until best cost is below 0.1.
36    de.iter().take(100000).find(|&cost| cost < 0.1);
37
38    // see what we've found
39    println!("{} evaluations done", de.num_cost_evaluations());
40    
41    let (cost, pos) = de.best().unwrap();
42    println!("{} best cost", cost);
43    println!("{:?} best position", pos);
44}