samyama_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!("BWR Solver: Iteration {}/{}", iter, self.config.max_iterations);
36 }
37 let (best_idx, worst_idx) = self.find_best_worst(&population);
38 let best_vars = population[best_idx].variables.clone();
39 let worst_vars = population[worst_idx].variables.clone();
40 let best_fitness = population[best_idx].fitness;
41
42 history.push(best_fitness);
43
44 population = population
45 .into_par_iter()
46 .map(|mut ind| {
47 let mut local_rng = thread_rng();
48 let mut new_vars = Array1::zeros(dim);
49
50 let r1: f64 = local_rng.gen();
51 let r2: f64 = local_rng.gen();
52 let r3: f64 = local_rng.gen();
53 let r4: f64 = local_rng.gen();
54 let t: f64 = local_rng.gen_range(1..3) as f64;
55
56 let mut rand_vars = Array1::zeros(dim);
57 for j in 0..dim {
58 rand_vars[j] = local_rng.gen_range(lower[j]..upper[j]);
59 }
60
61 if r4 > 0.5 {
62 for j in 0..dim {
63 let delta = r1 * (best_vars[j] - t * rand_vars[j]) - r2 * (worst_vars[j] - rand_vars[j]);
64 new_vars[j] = (ind.variables[j] + delta).clamp(lower[j], upper[j]);
65 }
66 } else {
67 for j in 0..dim {
68 new_vars[j] = (upper[j] - (upper[j] - lower[j]) * r3).clamp(lower[j], upper[j]);
69 }
70 }
71
72 let new_fitness = problem.fitness(&new_vars);
73 if new_fitness < ind.fitness {
74 ind.variables = new_vars;
75 ind.fitness = new_fitness;
76 }
77 ind
78 })
79 .collect();
80 }
81
82 let (final_best_idx, _) = self.find_best_worst(&population);
83 let final_best = &population[final_best_idx];
84
85 OptimizationResult {
86 best_variables: final_best.variables.clone(),
87 best_fitness: final_best.fitness,
88 history,
89 }
90 }
91
92 fn find_best_worst(&self, population: &[Individual]) -> (usize, usize) {
93 let mut best_idx = 0;
94 let mut worst_idx = 0;
95 for (i, ind) in population.iter().enumerate() {
96 if ind.fitness < population[best_idx].fitness {
97 best_idx = i;
98 }
99 if ind.fitness > population[worst_idx].fitness {
100 worst_idx = i;
101 }
102 }
103 (best_idx, worst_idx)
104 }
105}