graphmind_optimization/algorithms/
bwr.rs1use crate::common::{Individual, OptimizationResult, Problem, SolverConfig};
2use ndarray::Array1;
3use rand::prelude::*;
4use rayon::prelude::*;
5
6pub struct BWRSolver {
7 pub config: SolverConfig,
8}
9
10impl BWRSolver {
11 pub fn new(config: SolverConfig) -> Self {
12 Self { config }
13 }
14
15 pub fn solve<P: Problem>(&self, problem: &P) -> OptimizationResult {
16 let mut rng = thread_rng();
17 let dim = problem.dim();
18 let (lower, upper) = problem.bounds();
19
20 let mut population: Vec<Individual> = (0..self.config.population_size)
21 .map(|_| {
22 let mut vars = Array1::zeros(dim);
23 for i in 0..dim {
24 vars[i] = rng.gen_range(lower[i]..upper[i]);
25 }
26 let fitness = problem.fitness(&vars);
27 Individual::new(vars, fitness)
28 })
29 .collect();
30
31 let mut history = Vec::with_capacity(self.config.max_iterations);
32
33 for iter in 0..self.config.max_iterations {
34 if iter % 10 == 0 {
35 println!(
36 "BWR Solver: Iteration {}/{}",
37 iter, self.config.max_iterations
38 );
39 }
40 let (best_idx, worst_idx) = self.find_best_worst(&population);
41 let best_vars = population[best_idx].variables.clone();
42 let worst_vars = population[worst_idx].variables.clone();
43 let best_fitness = population[best_idx].fitness;
44
45 history.push(best_fitness);
46
47 population = population
48 .into_par_iter()
49 .map(|mut ind| {
50 let mut local_rng = thread_rng();
51 let mut new_vars = Array1::zeros(dim);
52
53 let r1: f64 = local_rng.gen();
54 let r2: f64 = local_rng.gen();
55 let r3: f64 = local_rng.gen();
56 let r4: f64 = local_rng.gen();
57 let t: f64 = local_rng.gen_range(1..3) as f64;
58
59 let mut rand_vars = Array1::zeros(dim);
60 for j in 0..dim {
61 rand_vars[j] = local_rng.gen_range(lower[j]..upper[j]);
62 }
63
64 if r4 > 0.5 {
65 for j in 0..dim {
66 let delta = r1 * (best_vars[j] - t * rand_vars[j])
67 - r2 * (worst_vars[j] - rand_vars[j]);
68 new_vars[j] = (ind.variables[j] + delta).clamp(lower[j], upper[j]);
69 }
70 } else {
71 for j in 0..dim {
72 new_vars[j] =
73 (upper[j] - (upper[j] - lower[j]) * r3).clamp(lower[j], upper[j]);
74 }
75 }
76
77 let new_fitness = problem.fitness(&new_vars);
78 if new_fitness < ind.fitness {
79 ind.variables = new_vars;
80 ind.fitness = new_fitness;
81 }
82 ind
83 })
84 .collect();
85 }
86
87 let (final_best_idx, _) = self.find_best_worst(&population);
88 let final_best = &population[final_best_idx];
89
90 OptimizationResult {
91 best_variables: final_best.variables.clone(),
92 best_fitness: final_best.fitness,
93 history,
94 }
95 }
96
97 fn find_best_worst(&self, population: &[Individual]) -> (usize, usize) {
98 let mut best_idx = 0;
99 let mut worst_idx = 0;
100 for (i, ind) in population.iter().enumerate() {
101 if ind.fitness < population[best_idx].fitness {
102 best_idx = i;
103 }
104 if ind.fitness > population[worst_idx].fitness {
105 worst_idx = i;
106 }
107 }
108 (best_idx, worst_idx)
109 }
110}