Skip to main content

optde_nonlinear_constraints/
optde_nonlinear_constraints.rs

1use math_audio_optimisation::{
2    Crossover, DEConfigBuilder, NonlinearConstraintHelper, Strategy, differential_evolution,
3};
4use ndarray::Array1;
5use std::str::FromStr;
6use std::sync::Arc;
7
8fn main() {
9    // Himmelblau as objective, but with nonlinear constraints to demonstrate helper
10    let himmelblau =
11        |x: &Array1<f64>| (x[0] * x[0] + x[1] - 11.0).powi(2) + (x[0] + x[1] * x[1] - 7.0).powi(2);
12
13    // Bounds
14    let bounds = [(-6.0, 6.0), (-6.0, 6.0)];
15
16    // Nonlinear vector function f(x) with 2 components
17    // 1) Circle-ish constraint: x0^2 + x1^2 <= 10  -> f0(x) = x0^2 + x1^2,  lb=-inf, ub=10
18    // 2) Sum equality: x0 + x1 = 1  -> f1(x) = x0 + x1,  lb=1, ub=1
19    let fun =
20        Arc::new(|x: &Array1<f64>| Array1::from(vec![x[0] * x[0] + x[1] * x[1], x[0] + x[1]]));
21    let lb = Array1::from(vec![-f64::INFINITY, 1.0]);
22    let ub = Array1::from(vec![10.0, 1.0]);
23    let nlc = NonlinearConstraintHelper { fun, lb, ub };
24
25    // Strategy parsing from string
26    let strategy = Strategy::from_str("best1exp").unwrap_or(Strategy::Best1Exp);
27
28    let mut cfg = DEConfigBuilder::new()
29        .seed(456)
30        .maxiter(800)
31        .popsize(30)
32        .strategy(strategy)
33        .recombination(0.9)
34        .crossover(Crossover::Exponential)
35        .build()
36        .expect("popsize must be >= 4");
37
38    // Apply nonlinear constraints with penalties
39    nlc.apply_to(&mut cfg, 1e3, 1e3);
40
41    let rep = differential_evolution(&himmelblau, &bounds, cfg).expect("optimization failed");
42    println!(
43        "success={} message=\"{}\"\nbest f={:.6e}\nbest x={:?}",
44        rep.success, rep.message, rep.fun, rep.x
45    );
46}