Skip to main content

optde_basic/
optde_basic.rs

1use math_audio_optimisation::{
2    CallbackAction, Crossover, DEConfig, Mutation, PolishConfig, Strategy, differential_evolution,
3};
4use ndarray::Array1;
5use std::sync::Arc;
6
7fn main() {
8    // Ackley function (2D)
9    let ackley = |x: &Array1<f64>| {
10        let x0 = x[0];
11        let x1 = x[1];
12        let s = 0.5 * (x0 * x0 + x1 * x1);
13        let c = 0.5
14            * ((2.0 * std::f64::consts::PI * x0).cos() + (2.0 * std::f64::consts::PI * x1).cos());
15        -20.0 * (-0.2 * s.sqrt()).exp() - c.exp() + 20.0 + std::f64::consts::E
16    };
17
18    let bounds = [(-5.0, 5.0), (-5.0, 5.0)];
19
20    let mut cfg = DEConfig::default();
21    cfg.maxiter = 300;
22    cfg.popsize = 20;
23    cfg.strategy = Strategy::Best1Bin;
24    cfg.crossover = Crossover::Exponential; // demonstrate exponential crossover
25    cfg.mutation = Mutation::Range { min: 0.5, max: 1.0 }; // dithering
26    cfg.recombination = 0.9;
27    cfg.seed = Some(42);
28
29    // Penalty examples (here just a dummy inequality fc(x) <= 0):
30    // Circle of radius 3: x0^2 + x1^2 - 9 <= 0
31    cfg.penalty_ineq.push((
32        Arc::new(|x: &Array1<f64>| x[0] * x[0] + x[1] * x[1] - 9.0),
33        1e3,
34    ));
35
36    // Callback every generation: stop early when convergence small enough
37    let mut iter_log = 0usize;
38    cfg.callback = Some(Box::new(move |inter| {
39        if iter_log % 25 == 0 {
40            eprintln!(
41                "iter {:4}  best_f={:.6e}  conv(stdE)={:.3e}",
42                inter.iter, inter.fun, inter.convergence
43            );
44        }
45        iter_log += 1;
46        if inter.convergence < 1e-6 {
47            CallbackAction::Stop
48        } else {
49            CallbackAction::Continue
50        }
51    }));
52
53    // Optional polishing with a local optimizer
54    cfg.polish = Some(PolishConfig {
55        enabled: true,
56        algo: "neldermead".into(),
57        maxeval: 400,
58    });
59
60    let report = differential_evolution(&ackley, &bounds, cfg).expect("optimization failed");
61
62    println!(
63        "success={} message=\"{}\"\nbest f={:.6e}\nbest x={:?}",
64        report.success, report.message, report.fun, report.x
65    );
66}