math_audio_differential_evolution/
metadata.rs1#[cfg(test)]
4mod tests {
5 use crate::{
6 DEConfig, DEConfigBuilder, Mutation, Strategy, differential_evolution,
7 run_recorded_differential_evolution,
8 };
9 use math_audio_test_functions::{get_function_bounds_2d, get_function_bounds_vec, rosenbrock};
10
11 #[test]
13 fn test_de_rosenbrock_with_metadata_bounds() {
14 let bounds = get_function_bounds_2d("rosenbrock", (-5.0, 5.0)); let mut config = DEConfig::default();
18 config.seed = Some(42);
19 config.maxiter = 500;
20 config.popsize = 40;
21 config.recombination = 0.9;
22 config.strategy = Strategy::RandToBest1Exp;
23
24 let result = differential_evolution(&rosenbrock, &bounds, config)
25 .expect("optimization should succeed");
26
27 assert!(result.fun < 1e-3);
29
30 assert!(
32 (result.x[0] - 1.0).abs() < 0.1,
33 "x[0] should be close to 1.0: {}",
34 result.x[0]
35 );
36 assert!(
37 (result.x[1] - 1.0).abs() < 0.1,
38 "x[1] should be close to 1.0: {}",
39 result.x[1]
40 );
41
42 println!("Used bounds: {:?}", bounds);
43 println!(
44 "Found solution: ({:.4}, {:.4}) with f = {:.6}",
45 result.x[0], result.x[1], result.fun
46 );
47 }
48
49 #[test]
50 fn test_de_rosenbrock_recorded_with_metadata() {
51 let bounds = get_function_bounds_vec("rosenbrock", (-5.0, 5.0));
53 let config = DEConfigBuilder::new()
54 .seed(123)
55 .maxiter(500)
56 .popsize(40)
57 .strategy(Strategy::RandToBest1Exp)
58 .mutation(Mutation::Factor(0.7))
59 .recombination(0.9)
60 .build();
61
62 let result =
64 run_recorded_differential_evolution("rosenbrock_metadata", rosenbrock, &bounds, config);
65
66 match result {
67 Ok((report, _csv_path)) => {
68 assert!(report.fun < 1e-3);
69
70 assert!(
72 report.x[0] > 0.9 && report.x[0] < 1.1,
73 "x[0] not close to 1: {}",
74 report.x[0]
75 );
76 assert!(
77 report.x[1] > 0.9 && report.x[1] < 1.1,
78 "x[1] not close to 1: {}",
79 report.x[1]
80 );
81
82 println!("Used bounds: {:?}", bounds);
83 println!(
84 "Found solution: ({:.4}, {:.4}) with f = {:.6}",
85 report.x[0], report.x[1], report.fun
86 );
87 }
88 Err(e) => {
89 panic!(
90 "Test requires AUTOEQ_DIR to be set. Error: {}\nPlease run: export AUTOEQ_DIR=/path/to/autoeq",
91 e
92 );
93 }
94 }
95 }
96}