Skip to main content

samyama_optimization/algorithms/
itlbo.rs

1use crate::common::{Individual, OptimizationResult, Problem, SolverConfig};
2use ndarray::Array1;
3use rand::prelude::*;
4use rayon::prelude::*;
5
6pub struct ITLBOSolver {
7    pub config: SolverConfig,
8    pub elite_size: usize,
9}
10
11impl ITLBOSolver {
12    pub fn new(config: SolverConfig) -> Self {
13        let elite_size = std::cmp::max(1, config.population_size / 10); // 10% elite
14        Self { config, elite_size }
15    }
16
17    pub fn solve<P: Problem>(&self, problem: &P) -> OptimizationResult {
18        let mut rng = thread_rng();
19        let dim = problem.dim();
20        let (lower, upper) = problem.bounds();
21
22        // Initialize population
23        let mut population: Vec<Individual> = (0..self.config.population_size)
24            .map(|_| {
25                let mut vars = Array1::zeros(dim);
26                for i in 0..dim {
27                    vars[i] = rng.gen_range(lower[i]..upper[i]);
28                }
29                let fitness = problem.fitness(&vars);
30                Individual::new(vars, fitness)
31            })
32            .collect();
33
34        let mut history = Vec::with_capacity(self.config.max_iterations);
35
36        for iter in 0..self.config.max_iterations {
37            if iter % 10 == 0 {
38                println!("ITLBO Solver: Iteration {}/{}", iter, self.config.max_iterations);
39            }
40            // Sort to find elites
41            population.sort_by(|a, b| a.fitness.partial_cmp(&b.fitness).unwrap());
42            
43            // Save elites
44            let elites: Vec<Individual> = population.iter().take(self.elite_size).cloned().collect();
45            
46            let best_fitness = population[0].fitness;
47            let teacher_vars = population[0].variables.clone();
48            let mean_vars = self.calculate_mean(&population, dim);
49
50            history.push(best_fitness);
51
52            // 1. Teacher Phase
53            population = population
54                .into_par_iter()
55                .map(|mut ind| {
56                    let mut local_rng = thread_rng();
57                    // Adaptive TF: Usually between 1 and 2. 
58                    let tf: f64 = local_rng.gen_range(1.0..2.0); 
59                    
60                    let mut new_vars = Array1::zeros(dim);
61                    for j in 0..dim {
62                        let r: f64 = local_rng.gen();
63                        let delta = r * (teacher_vars[j] - tf * mean_vars[j]);
64                        new_vars[j] = (ind.variables[j] + delta).clamp(lower[j], upper[j]);
65                    }
66
67                    let new_fitness = problem.fitness(&new_vars);
68                    if new_fitness < ind.fitness {
69                        ind.variables = new_vars;
70                        ind.fitness = new_fitness;
71                    }
72                    ind
73                })
74                .collect();
75
76            // 2. Learner Phase (Enhanced)
77            let pop_len = population.len();
78            
79            // Note: Parallel learner phase needs safe random access. 
80            // We'll clone the "old" population for reading to allow parallel updates.
81            let old_population = population.clone();
82            
83            population = population
84                .into_par_iter()
85                .enumerate()
86                .map(|(i, mut ind)| {
87                    let mut local_rng = thread_rng();
88                    
89                    let mut learner_j_idx;
90                    loop {
91                        learner_j_idx = local_rng.gen_range(0..pop_len);
92                        if learner_j_idx != i { break; }
93                    }
94                    let ind_j = &old_population[learner_j_idx];
95
96                    let mut new_vars = Array1::zeros(dim);
97                    for k in 0..dim {
98                        let r: f64 = local_rng.gen();
99                        let delta = if ind.fitness < ind_j.fitness {
100                            r * (&ind.variables[k] - &ind_j.variables[k])
101                        } else {
102                            r * (&ind_j.variables[k] - &ind.variables[k])
103                        };
104                        new_vars[k] = (ind.variables[k] + delta).clamp(lower[k], upper[k]);
105                    }
106
107                    let new_fitness = problem.fitness(&new_vars);
108                    if new_fitness < ind.fitness {
109                        ind.variables = new_vars;
110                        ind.fitness = new_fitness;
111                    }
112                    ind
113                })
114                .collect();
115
116            // 3. Elitism: Replace worst individuals with preserved elites
117            // We need to sort again to find the worst
118            population.sort_by(|a, b| a.fitness.partial_cmp(&b.fitness).unwrap());
119            
120            let len = population.len();
121            for k in 0..self.elite_size {
122                // If the elite is better than the worst
123                if elites[k].fitness < population[len - 1 - k].fitness {
124                    population[len - 1 - k] = elites[k].clone();
125                }
126            }
127        }
128
129        let best_idx = 0; // Sorted
130        let final_best = &population[best_idx];
131
132        OptimizationResult {
133            best_variables: final_best.variables.clone(),
134            best_fitness: final_best.fitness,
135            history,
136        }
137    }
138
139    fn calculate_mean(&self, population: &[Individual], dim: usize) -> Array1<f64> {
140        let mut mean = Array1::zeros(dim);
141        for ind in population {
142            mean += &ind.variables;
143        }
144        mean / (population.len() as f64)
145    }
146}