Skip to main content

graphmind_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 iter in 0..self.config.max_iterations {
35            if iter % 10 == 0 {
36                println!(
37                    "TLBO Solver: Iteration {}/{}",
38                    iter, self.config.max_iterations
39                );
40            }
41            let best_idx = self.find_best(&population);
42            let teacher_vars = population[best_idx].variables.clone();
43            let best_fitness = population[best_idx].fitness;
44            let mean_vars = self.calculate_mean(&population, dim);
45
46            history.push(best_fitness);
47
48            // 1. Teacher Phase
49            population = population
50                .into_par_iter()
51                .map(|mut ind| {
52                    let mut local_rng = thread_rng();
53                    let tf: f64 = local_rng.gen_range(1..3) as f64; // Teaching Factor (1 or 2)
54                    let mut new_vars = Array1::zeros(dim);
55
56                    for j in 0..dim {
57                        let r: f64 = local_rng.gen();
58                        let delta = r * (teacher_vars[j] - tf * mean_vars[j]);
59                        new_vars[j] = (ind.variables[j] + delta).clamp(lower[j], upper[j]);
60                    }
61
62                    let new_fitness = problem.fitness(&new_vars);
63                    if new_fitness < ind.fitness {
64                        ind.variables = new_vars;
65                        ind.fitness = new_fitness;
66                    }
67                    ind
68                })
69                .collect();
70
71            // 2. Learner Phase
72            let pop_len = population.len();
73            for i in 0..pop_len {
74                let mut learner_j_idx;
75                loop {
76                    learner_j_idx = rng.gen_range(0..pop_len);
77                    if learner_j_idx != i {
78                        break;
79                    }
80                }
81
82                let ind_i = &population[i];
83                let ind_j = &population[learner_j_idx];
84
85                let mut new_vars = Array1::zeros(dim);
86                for k in 0..dim {
87                    let r: f64 = rng.gen();
88                    let delta = if ind_i.fitness < ind_j.fitness {
89                        r * (ind_i.variables[k] - ind_j.variables[k])
90                    } else {
91                        r * (ind_j.variables[k] - ind_i.variables[k])
92                    };
93                    new_vars[k] = (ind_i.variables[k] + delta).clamp(lower[k], upper[k]);
94                }
95
96                let new_fitness = problem.fitness(&new_vars);
97                if new_fitness < population[i].fitness {
98                    population[i].variables = new_vars;
99                    population[i].fitness = new_fitness;
100                }
101            }
102        }
103
104        let final_best_idx = self.find_best(&population);
105        let final_best = &population[final_best_idx];
106
107        OptimizationResult {
108            best_variables: final_best.variables.clone(),
109            best_fitness: final_best.fitness,
110            history,
111        }
112    }
113
114    fn find_best(&self, population: &[Individual]) -> usize {
115        let mut best_idx = 0;
116        for (i, ind) in population.iter().enumerate() {
117            if ind.fitness < population[best_idx].fitness {
118                best_idx = i;
119            }
120        }
121        best_idx
122    }
123
124    fn calculate_mean(&self, population: &[Individual], dim: usize) -> Array1<f64> {
125        let mut mean = Array1::zeros(dim);
126        for ind in population {
127            mean += &ind.variables;
128        }
129        mean / (population.len() as f64)
130    }
131}