samyama_optimization/algorithms/
de.rs1use crate::common::{Individual, OptimizationResult, Problem, SolverConfig};
2use ndarray::Array1;
3use rand::prelude::*;
4use rayon::prelude::*;
5
6pub struct DESolver {
7 pub config: SolverConfig,
8 pub f: f64, pub cr: f64, }
11
12impl DESolver {
13 pub fn new(config: SolverConfig) -> Self {
14 Self {
15 config,
16 f: 0.5,
17 cr: 0.9,
18 }
19 }
20
21 pub fn solve<P: Problem>(&self, problem: &P) -> OptimizationResult {
22 let mut rng = thread_rng();
23 let dim = problem.dim();
24 let (lower, upper) = problem.bounds();
25
26 let mut population: Vec<Individual> = (0..self.config.population_size)
27 .map(|_| {
28 let mut vars = Array1::zeros(dim);
29 for i in 0..dim {
30 vars[i] = rng.gen_range(lower[i]..upper[i]);
31 }
32 let fitness = problem.fitness(&vars);
33 Individual::new(vars, fitness)
34 })
35 .collect();
36
37 let mut history = Vec::with_capacity(self.config.max_iterations);
38
39 for iter in 0..self.config.max_iterations {
40 if iter % 10 == 0 {
41 println!("DE Solver: Iteration {}/{}", iter, self.config.max_iterations);
42 }
43 let best_idx = self.find_best(&population);
44 history.push(population[best_idx].fitness);
45
46 let old_pop = population.clone();
49
50 population = population
51 .into_par_iter()
52 .enumerate()
53 .map(|(i, mut target)| {
54 let mut local_rng = thread_rng();
55
56 let mut idxs = [0; 3];
58 for k in 0..3 {
59 loop {
60 let r = local_rng.gen_range(0..old_pop.len());
61 if r != i && !idxs[0..k].contains(&r) {
62 idxs[k] = r;
63 break;
64 }
65 }
66 }
67
68 let a = &old_pop[idxs[0]];
69 let b = &old_pop[idxs[1]];
70 let c = &old_pop[idxs[2]];
71
72 let mut trial_vars = Array1::zeros(dim);
74 let r_idx = local_rng.gen_range(0..dim); for j in 0..dim {
77 if local_rng.gen::<f64>() < self.cr || j == r_idx {
78 let val = a.variables[j] + self.f * (b.variables[j] - c.variables[j]);
79 trial_vars[j] = val.clamp(lower[j], upper[j]);
80 } else {
81 trial_vars[j] = target.variables[j];
82 }
83 }
84
85 let trial_fitness = problem.fitness(&trial_vars);
87 if trial_fitness < target.fitness {
88 target.variables = trial_vars;
89 target.fitness = trial_fitness;
90 }
91 target
92 })
93 .collect();
94 }
95
96 let best_idx = self.find_best(&population);
97 let final_best = &population[best_idx];
98
99 OptimizationResult {
100 best_variables: final_best.variables.clone(),
101 best_fitness: final_best.fitness,
102 history,
103 }
104 }
105
106 fn find_best(&self, population: &[Individual]) -> usize {
107 let mut best_idx = 0;
108 for (i, ind) in population.iter().enumerate() {
109 if ind.fitness < population[best_idx].fitness {
110 best_idx = i;
111 }
112 }
113 best_idx
114 }
115}