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 _ in 0..self.config.max_iterations {
37            // Sort to find elites
38            population.sort_by(|a, b| a.fitness.partial_cmp(&b.fitness).unwrap());
39            
40            // Save elites
41            let elites: Vec<Individual> = population.iter().take(self.elite_size).cloned().collect();
42            
43            let best_fitness = population[0].fitness;
44            let teacher_vars = population[0].variables.clone();
45            let mean_vars = self.calculate_mean(&population, dim);
46
47            history.push(best_fitness);
48
49            // 1. Teacher Phase
50            population = population
51                .into_par_iter()
52                .map(|mut ind| {
53                    let mut local_rng = thread_rng();
54                    // Adaptive TF: Usually between 1 and 2. 
55                    let tf: f64 = local_rng.gen_range(1.0..2.0); 
56                    
57                    let mut new_vars = Array1::zeros(dim);
58                    for j in 0..dim {
59                        let r: f64 = local_rng.gen();
60                        let delta = r * (teacher_vars[j] - tf * mean_vars[j]);
61                        new_vars[j] = (ind.variables[j] + delta).clamp(lower[j], upper[j]);
62                    }
63
64                    let new_fitness = problem.fitness(&new_vars);
65                    if new_fitness < ind.fitness {
66                        ind.variables = new_vars;
67                        ind.fitness = new_fitness;
68                    }
69                    ind
70                })
71                .collect();
72
73            // 2. Learner Phase (Enhanced)
74            let pop_len = population.len();
75            
76            // Note: Parallel learner phase needs safe random access. 
77            // We'll clone the "old" population for reading to allow parallel updates.
78            let old_population = population.clone();
79            
80            population = population
81                .into_par_iter()
82                .enumerate()
83                .map(|(i, mut ind)| {
84                    let mut local_rng = thread_rng();
85                    
86                    let mut learner_j_idx;
87                    loop {
88                        learner_j_idx = local_rng.gen_range(0..pop_len);
89                        if learner_j_idx != i { break; }
90                    }
91                    let ind_j = &old_population[learner_j_idx];
92
93                    let mut new_vars = Array1::zeros(dim);
94                    for k in 0..dim {
95                        let r: f64 = local_rng.gen();
96                        let delta = if ind.fitness < ind_j.fitness {
97                            r * (&ind.variables[k] - &ind_j.variables[k])
98                        } else {
99                            r * (&ind_j.variables[k] - &ind.variables[k])
100                        };
101                        new_vars[k] = (ind.variables[k] + delta).clamp(lower[k], upper[k]);
102                    }
103
104                    let new_fitness = problem.fitness(&new_vars);
105                    if new_fitness < ind.fitness {
106                        ind.variables = new_vars;
107                        ind.fitness = new_fitness;
108                    }
109                    ind
110                })
111                .collect();
112
113            // 3. Elitism: Replace worst individuals with preserved elites
114            // We need to sort again to find the worst
115            population.sort_by(|a, b| a.fitness.partial_cmp(&b.fitness).unwrap());
116            
117            let len = population.len();
118            for k in 0..self.elite_size {
119                // If the elite is better than the worst
120                if elites[k].fitness < population[len - 1 - k].fitness {
121                    population[len - 1 - k] = elites[k].clone();
122                }
123            }
124        }
125
126        let best_idx = 0; // Sorted
127        let final_best = &population[best_idx];
128
129        OptimizationResult {
130            best_variables: final_best.variables.clone(),
131            best_fitness: final_best.fitness,
132            history,
133        }
134    }
135
136    fn calculate_mean(&self, population: &[Individual], dim: usize) -> Array1<f64> {
137        let mut mean = Array1::zeros(dim);
138        for ind in population {
139            mean += &ind.variables;
140        }
141        mean / (population.len() as f64)
142    }
143}