samyama_optimization/algorithms/
tlbo.rs

1use crate::common::{Individual, OptimizationResult, Problem, SolverConfig};
2use ndarray::Array1;
3use rand::prelude::*;
4use rayon::prelude::*;
5
6pub struct TLBOSolver {
7    pub config: SolverConfig,
8}
9
10impl TLBOSolver {
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        // Initialize population
21        let mut population: Vec<Individual> = (0..self.config.population_size)
22            .map(|_| {
23                let mut vars = Array1::zeros(dim);
24                for i in 0..dim {
25                    vars[i] = rng.gen_range(lower[i]..upper[i]);
26                }
27                let fitness = problem.fitness(&vars);
28                Individual::new(vars, fitness)
29            })
30            .collect();
31
32        let mut history = Vec::with_capacity(self.config.max_iterations);
33
34        for _ in 0..self.config.max_iterations {
35            let best_idx = self.find_best(&population);
36            let teacher_vars = population[best_idx].variables.clone();
37            let best_fitness = population[best_idx].fitness;
38            let mean_vars = self.calculate_mean(&population, dim);
39
40            history.push(best_fitness);
41
42            // 1. Teacher Phase
43            population = population
44                .into_par_iter()
45                .map(|mut ind| {
46                    let mut local_rng = thread_rng();
47                    let tf: f64 = local_rng.gen_range(1..3) as f64; // Teaching Factor (1 or 2)
48                    let mut new_vars = Array1::zeros(dim);
49
50                    for j in 0..dim {
51                        let r: f64 = local_rng.gen();
52                        let delta = r * (teacher_vars[j] - tf * mean_vars[j]);
53                        new_vars[j] = (ind.variables[j] + delta).clamp(lower[j], upper[j]);
54                    }
55
56                    let new_fitness = problem.fitness(&new_vars);
57                    if new_fitness < ind.fitness {
58                        ind.variables = new_vars;
59                        ind.fitness = new_fitness;
60                    }
61                    ind
62                })
63                .collect();
64
65            // 2. Learner Phase
66            let pop_len = population.len();
67            for i in 0..pop_len {
68                let mut learner_j_idx;
69                loop {
70                    learner_j_idx = rng.gen_range(0..pop_len);
71                    if learner_j_idx != i { break; }
72                }
73
74                let ind_i = &population[i];
75                let ind_j = &population[learner_j_idx];
76                
77                let mut new_vars = Array1::zeros(dim);
78                for k in 0..dim {
79                    let r: f64 = rng.gen();
80                    let delta = if ind_i.fitness < ind_j.fitness {
81                        r * (&ind_i.variables[k] - &ind_j.variables[k])
82                    } else {
83                        r * (&ind_j.variables[k] - &ind_i.variables[k])
84                    };
85                    new_vars[k] = (ind_i.variables[k] + delta).clamp(lower[k], upper[k]);
86                }
87
88                let new_fitness = problem.fitness(&new_vars);
89                if new_fitness < population[i].fitness {
90                    population[i].variables = new_vars;
91                    population[i].fitness = new_fitness;
92                }
93            }
94        }
95
96        let final_best_idx = self.find_best(&population);
97        let final_best = &population[final_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
116    fn calculate_mean(&self, population: &[Individual], dim: usize) -> Array1<f64> {
117        let mut mean = Array1::zeros(dim);
118        for ind in population {
119            mean += &ind.variables;
120        }
121        mean / (population.len() as f64)
122    }
123}