graphmind_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!(
42 "DE Solver: Iteration {}/{}",
43 iter, self.config.max_iterations
44 );
45 }
46 let best_idx = self.find_best(&population);
47 history.push(population[best_idx].fitness);
48
49 let old_pop = population.clone();
52
53 population = population
54 .into_par_iter()
55 .enumerate()
56 .map(|(i, mut target)| {
57 let mut local_rng = thread_rng();
58
59 let mut idxs = [0; 3];
61 for k in 0..3 {
62 loop {
63 let r = local_rng.gen_range(0..old_pop.len());
64 if r != i && !idxs[0..k].contains(&r) {
65 idxs[k] = r;
66 break;
67 }
68 }
69 }
70
71 let a = &old_pop[idxs[0]];
72 let b = &old_pop[idxs[1]];
73 let c = &old_pop[idxs[2]];
74
75 let mut trial_vars = Array1::zeros(dim);
77 let r_idx = local_rng.gen_range(0..dim); for j in 0..dim {
80 if local_rng.gen::<f64>() < self.cr || j == r_idx {
81 let val = a.variables[j] + self.f * (b.variables[j] - c.variables[j]);
82 trial_vars[j] = val.clamp(lower[j], upper[j]);
83 } else {
84 trial_vars[j] = target.variables[j];
85 }
86 }
87
88 let trial_fitness = problem.fitness(&trial_vars);
90 if trial_fitness < target.fitness {
91 target.variables = trial_vars;
92 target.fitness = trial_fitness;
93 }
94 target
95 })
96 .collect();
97 }
98
99 let best_idx = self.find_best(&population);
100 let final_best = &population[best_idx];
101
102 OptimizationResult {
103 best_variables: final_best.variables.clone(),
104 best_fitness: final_best.fitness,
105 history,
106 }
107 }
108
109 fn find_best(&self, population: &[Individual]) -> usize {
110 let mut best_idx = 0;
111 for (i, ind) in population.iter().enumerate() {
112 if ind.fitness < population[best_idx].fitness {
113 best_idx = i;
114 }
115 }
116 best_idx
117 }
118}