Skip to main content

graphmind_optimization/algorithms/
qojaya.rs

1use crate::common::{Individual, OptimizationResult, Problem, SolverConfig};
2use ndarray::Array1;
3use rand::prelude::*;
4use rayon::prelude::*;
5
6pub struct QOJayaSolver {
7    pub config: SolverConfig,
8}
9
10impl QOJayaSolver {
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        // Apply Quasi-Oppositional Based Learning (QOBL) to initial population
33        // Generate QO population and pick best N
34        let mut qo_population: Vec<Individual> = population
35            .par_iter()
36            .map(|ind| {
37                let mut new_vars = Array1::zeros(dim);
38                let mut local_rng = thread_rng();
39
40                for j in 0..dim {
41                    // Center point c = (a+b)/2
42                    let c = (lower[j] + upper[j]) / 2.0;
43                    // Opposite point xo = a + b - x
44                    let xo = lower[j] + upper[j] - ind.variables[j];
45
46                    // Quasi-opposite point xqo is rand(c, xo)
47                    let xqo = if c < xo {
48                        local_rng.gen_range(c..xo)
49                    } else {
50                        local_rng.gen_range(xo..c)
51                    };
52
53                    new_vars[j] = xqo.clamp(lower[j], upper[j]);
54                }
55
56                let fitness = problem.fitness(&new_vars);
57                Individual::new(new_vars, fitness)
58            })
59            .collect();
60
61        population.append(&mut qo_population);
62        population.sort_by(|a, b| a.fitness.partial_cmp(&b.fitness).unwrap());
63        population.truncate(self.config.population_size);
64
65        let mut history = Vec::with_capacity(self.config.max_iterations);
66
67        for iter in 0..self.config.max_iterations {
68            if iter % 10 == 0 {
69                println!(
70                    "QOJaya Solver: Iteration {}/{}",
71                    iter, self.config.max_iterations
72                );
73            }
74            let (best_idx, worst_idx) = self.find_best_worst(&population);
75            let best_vars = population[best_idx].variables.clone();
76            let worst_vars = population[worst_idx].variables.clone();
77            let best_fitness = population[best_idx].fitness;
78
79            history.push(best_fitness);
80
81            // Jaya Update + QOBL
82            population = population
83                .into_par_iter()
84                .map(|mut ind| {
85                    let mut local_rng = thread_rng();
86                    let mut new_vars = Array1::zeros(dim);
87
88                    let r1: f64 = local_rng.gen();
89                    let r2: f64 = local_rng.gen();
90
91                    // 1. Jaya Update
92                    for j in 0..dim {
93                        let val = ind.variables[j] + r1 * (best_vars[j] - ind.variables[j].abs())
94                            - r2 * (worst_vars[j] - ind.variables[j].abs());
95                        new_vars[j] = val.clamp(lower[j], upper[j]);
96                    }
97
98                    let jaya_fitness = problem.fitness(&new_vars);
99                    if jaya_fitness < ind.fitness {
100                        ind.variables = new_vars.clone();
101                        ind.fitness = jaya_fitness;
102                    }
103
104                    // 2. QOBL on the updated individual
105                    // Only apply with some probability (jumping rate), e.g., 0.05?
106                    // The standard QOJaya applies it to the whole population occasionally or per individual.
107                    // We'll apply it per individual.
108
109                    let mut qo_vars = Array1::zeros(dim);
110                    for j in 0..dim {
111                        let c = (lower[j] + upper[j]) / 2.0;
112                        let xo = lower[j] + upper[j] - ind.variables[j];
113                        let xqo = if c < xo {
114                            local_rng.gen_range(c..xo)
115                        } else {
116                            local_rng.gen_range(xo..c)
117                        };
118                        qo_vars[j] = xqo.clamp(lower[j], upper[j]);
119                    }
120
121                    let qo_fitness = problem.fitness(&qo_vars);
122                    if qo_fitness < ind.fitness {
123                        ind.variables = qo_vars;
124                        ind.fitness = qo_fitness;
125                    }
126
127                    ind
128                })
129                .collect();
130        }
131
132        let (final_best_idx, _) = self.find_best_worst(&population);
133        let final_best = &population[final_best_idx];
134
135        OptimizationResult {
136            best_variables: final_best.variables.clone(),
137            best_fitness: final_best.fitness,
138            history,
139        }
140    }
141
142    fn find_best_worst(&self, population: &[Individual]) -> (usize, usize) {
143        let mut best_idx = 0;
144        let mut worst_idx = 0;
145        for (i, ind) in population.iter().enumerate() {
146            if ind.fitness < population[best_idx].fitness {
147                best_idx = i;
148            }
149            if ind.fitness > population[worst_idx].fitness {
150                worst_idx = i;
151            }
152        }
153        (best_idx, worst_idx)
154    }
155}