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