puggles 0.3.0

Multi-objective evolutionary optimization: NSGA-II and NSGA-III over continuous, integer, and binary variables, with constraint handling, Rayon parallelism, and optional GPU evaluation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use crate::core::{Encoding, Solution};
use crate::gatypes::SolutionDataTypes;
use std::collections::HashMap;
use std::sync::Arc;
use rand::Rng;
use rand::rngs::SmallRng;

/// Trait for mutation operations. `rng` is threaded through so a seeded run is reproducible.
///
/// [`MutationManager`] mutates a child in place, gene by gene, so `parent` is that child: an
/// implementation should read only gene `index` (genes before it may already be mutated).
pub trait Mutation: Send + Sync {
    fn mutate(&self, parent: &Solution, index: usize, rng: &mut SmallRng) -> f64;
}
/// MutationManager to manage and apply mutations
pub struct MutationManager {
    default_mutations: HashMap<&'static str, Arc<dyn Mutation>>,
    /// Per-gene swap probability used when the problem uses permutation encoding.
    permutation_swap_probability: f64,
}

/// Swap mutation for permutation-encoded solutions: each position may exchange with another
/// random position. Preserves the permutation, which per-gene mutation cannot — resampling a
/// single gene duplicates one value and drops another.
pub fn swap_mutation(solution: &mut [f64], probability: f64, rng: &mut SmallRng) {
    let n = solution.len();
    if n < 2 {
        return;
    }
    for i in 0..n {
        if rng.gen::<f64>() < probability {
            let j = rng.gen_range(0..n);
            solution.swap(i, j);
        }
    }
}

impl MutationManager {
    /// Standard NSGA-II defaults for a problem with `solution_length` decision variables:
    /// polynomial mutation (eta=20) for Real and Integer genes and bit-flip for BitBinary,
    /// all at the conventional per-gene rate `1/n`.
    ///
    /// The rate has to be `1/n`, not 1.0: mutating every gene each generation replaces the
    /// whole genome with a fresh random one, which is random search, not evolution.
    pub fn new(solution_length: usize) -> Self {
        let rate = 1.0 / solution_length.max(1) as f64;
        let polynomial: Arc<dyn Mutation> = Arc::new(PolynomialMutation::new(Some(rate), Some(20.0)));
        let mut default_mutations: HashMap<&'static str, Arc<dyn Mutation>> = HashMap::new();
        default_mutations.insert("BitBinary", Arc::new(BitFlipMutation { probability: rate }));
        default_mutations.insert("Real", Arc::clone(&polynomial));
        default_mutations.insert("Integer", polynomial);

        Self { default_mutations, permutation_swap_probability: rate }
    }

    /// Per-gene swap probability for permutation-encoded problems (defaults to `1/n`).
    pub fn set_permutation_swap_probability(&mut self, probability: f64) {
        self.permutation_swap_probability = probability;
    }

    pub fn set_default_real_mutation(&mut self, mutation: Arc<dyn Mutation>) {
        self.default_mutations.insert("Real", mutation);
    }

    pub fn set_default_integer_mutation(&mut self, mutation: Arc<dyn Mutation>) {
        self.default_mutations.insert("Integer", mutation);
    }

    pub fn set_default_binary_mutation(&mut self, mutation: Arc<dyn Mutation>) {
        self.default_mutations.insert("BitBinary", mutation);
    }

    pub fn mutate(&self, parent: &Solution, rng: &mut SmallRng) -> Solution {
        self.mutate_owned(parent.clone(), rng)
    }

    /// [`mutate`](Self::mutate) on a child you already own (e.g. fresh from crossover), with
    /// no extra clone. Bit-identical to `mutate`: each operator reads only its own gene.
    pub fn mutate_owned(&self, mut child: Solution, rng: &mut SmallRng) -> Solution {
        // Permutation encoding: mutate the whole vector so it stays a permutation.
        if child.problem.encoding == Encoding::Permutation {
            swap_mutation(&mut child.solution, self.permutation_swap_probability, rng);
            child.feasible = false;
            child.evaluated = false;
            return child;
        }

        // Resolve the three operators once, not with a map lookup per gene.
        let binary = self.default_mutations.get("BitBinary");
        let real = self.default_mutations.get("Real");
        let integer = self.default_mutations.get("Integer");
        let problem = Arc::clone(&child.problem);
        for (i, solution_type) in problem.solution_data_types.iter().enumerate() {
            let mutation = match solution_type {
                SolutionDataTypes::BitBinary(_) => binary,
                SolutionDataTypes::Real(_) => real,
                SolutionDataTypes::Integer(_) => integer,
            };
            if let Some(mutation) = mutation {
                let value = mutation.mutate(&child, i, rng);
                child.solution[i] = value;
            }
        }
        child.feasible = false;
        child.evaluated = false;
        child
    }
}


/// Helper trait to retrieve bounds for solution data types
pub trait SolutionTypeBounds {
    fn get_lower_bound(&self) -> Option<f64>;
    fn get_upper_bound(&self) -> Option<f64>;
}

impl SolutionTypeBounds for SolutionDataTypes {
    fn get_lower_bound(&self) -> Option<f64> {
        match self {
            SolutionDataTypes::Real(real) => real.lower_bound,
            SolutionDataTypes::Integer(integer) => integer.lower_bound.map(|v| v as f64),
            _ => None,
        }
    }

    fn get_upper_bound(&self) -> Option<f64> {
        match self {
            SolutionDataTypes::Real(real) => real.upper_bound,
            SolutionDataTypes::Integer(integer) => integer.upper_bound.map(|v| v as f64),
            _ => None,
        }
    }
}

/// Bit Flip Mutation
pub struct BitFlipMutation {
    pub probability: f64,
}

impl Default for BitFlipMutation {
    /// Conservative standalone default. The GA uses `MutationManager::new(n)`, which sets the
    /// conventional `1/n` rate instead.
    fn default() -> Self {
        Self { probability: 0.1 }
    }
}

impl Mutation for BitFlipMutation {
    fn mutate(&self, parent: &Solution, index: usize, rng: &mut SmallRng) -> f64 {
        if rng.gen::<f64>() < self.probability {
            1.0 - parent.solution[index]
        } else {
            parent.solution[index]
        }
    }
}

/// Uniform Mutation
pub struct UniformMutation {
    pub probability: f64,
}

impl Default for UniformMutation {
    fn default() -> Self {
        Self { probability: 1.0 }
    }
}

impl Mutation for UniformMutation {
    fn mutate(&self, parent: &Solution, index: usize, rng: &mut SmallRng) -> f64 {
        match &parent.problem.solution_data_types[index] {
            SolutionDataTypes::Integer(integer) => {
                let lower_bound = integer.lower_bound.unwrap_or(i64::MIN) as f64;
                let upper_bound = integer.upper_bound.unwrap_or(i64::MAX) as f64;

                if rng.gen::<f64>() < self.probability {
                    rng.gen_range(lower_bound..=upper_bound).round() // Ensures result is an integer
                } else {
                    parent.solution[index]
                }
            }
            SolutionDataTypes::Real(real) => {
                let lower_bound = real.lower_bound.unwrap_or(f64::MIN);
                let upper_bound = real.upper_bound.unwrap_or(f64::MAX);

                if rng.gen::<f64>() < self.probability {
                    rng.gen_range(lower_bound..=upper_bound)
                } else {
                    parent.solution[index]
                }
            }
            _ => parent.solution[index], // No mutation for other types
        }
    }
}

pub struct PolynomialMutation {
    pub probability: f64,
    pub distribution_index: f64,
}

impl PolynomialMutation {
    pub fn new(probability: Option<f64>, distribution_index: Option<f64>) -> Self {
        Self {
            probability: probability.unwrap_or(1.0),
            distribution_index: distribution_index.unwrap_or(20.0),
        }
    }
}

impl Mutation for PolynomialMutation {
    fn mutate(&self, parent: &Solution, index: usize, rng: &mut SmallRng) -> f64 {
        match &parent.problem.solution_data_types[index] {
            SolutionDataTypes::Integer(integer) => {
                let lower_bound = integer.lower_bound.unwrap_or(i64::MIN) as f64;
                let upper_bound = integer.upper_bound.unwrap_or(i64::MAX) as f64;

                if rng.gen::<f64>() < self.probability {
                    let u = rng.gen::<f64>();
                    let dx = upper_bound - lower_bound;
                    let delta = if u < 0.5 {
                        let bl = (parent.solution[index] - lower_bound) / dx;
                        (2.0 * u + (1.0 - 2.0 * u) * (1.0 - bl).powf(self.distribution_index + 1.0))
                            .powf(1.0 / (self.distribution_index + 1.0))
                            - 1.0
                    } else {
                        let bu = (upper_bound - parent.solution[index]) / dx;
                        (2.0 * (1.0 - u) + 2.0 * (u - 0.5) * (1.0 - bu).powf(self.distribution_index + 1.0))
                            .powf(1.0 / (self.distribution_index + 1.0))
                            - 1.0
                    };
                    (parent.solution[index] + delta * dx).round().clamp(lower_bound, upper_bound)
                } else {
                    parent.solution[index]
                }
            }
            SolutionDataTypes::Real(real) => {
                let lower_bound = real.lower_bound.unwrap_or(f64::MIN);
                let upper_bound = real.upper_bound.unwrap_or(f64::MAX);

                if rng.gen::<f64>() < self.probability {
                    let u = rng.gen::<f64>();
                    let dx = upper_bound - lower_bound;
                    let delta = if u < 0.5 {
                        let bl = (parent.solution[index] - lower_bound) / dx;
                        (2.0 * u + (1.0 - 2.0 * u) * (1.0 - bl).powf(self.distribution_index + 1.0))
                            .powf(1.0 / (self.distribution_index + 1.0))
                            - 1.0
                    } else {
                        let bu = (upper_bound - parent.solution[index]) / dx;
                        (2.0 * (1.0 - u) + 2.0 * (u - 0.5) * (1.0 - bu).powf(self.distribution_index + 1.0))
                            .powf(1.0 / (self.distribution_index + 1.0))
                            - 1.0
                    };
                    (parent.solution[index] + delta * dx).clamp(lower_bound, upper_bound)
                } else {
                    parent.solution[index]
                }
            }
            _ => parent.solution[index], // No mutation for other types
        }
    }
}

/// Gaussian Mutation
pub struct GaussianMutation {
    pub probability: f64,
    pub standard_deviation: f64,
}

impl GaussianMutation {
    pub fn new(probability: Option<f64>, standard_deviation: Option<f64>) -> Self {
        Self {
            probability: probability.unwrap_or(1.0),
            standard_deviation: standard_deviation.unwrap_or(0.1),
        }
    }
}

impl Mutation for GaussianMutation {
    fn mutate(&self, parent: &Solution, index: usize, rng: &mut SmallRng) -> f64 {
        let lower_bound = parent.problem.solution_data_types[index]
            .get_lower_bound()
            .unwrap_or(f64::MIN);
        let upper_bound = parent.problem.solution_data_types[index]
            .get_upper_bound()
            .unwrap_or(f64::MAX);

        if rng.gen::<f64>() < self.probability {
            // Box-Muller: two uniforms -> one standard normal. `rand`'s uniform is [0,1), so
            // clamp u1 off zero before the log.
            let u1: f64 = rng.gen::<f64>().max(f64::MIN_POSITIVE);
            let u2: f64 = rng.gen();
            let z = (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos();
            (parent.solution[index] + z * self.standard_deviation).clamp(lower_bound, upper_bound)
        } else {
            parent.solution[index]
        }
    }
}
// Tests
#[cfg(test)]
mod tests {
    use super::*;
    use rand::SeedableRng;
    fn test_rng() -> SmallRng { SmallRng::seed_from_u64(0) }
    use std::sync::Arc;
    use crate::core::{EvalFn, Problem, Solution};
    use crate::gatypes::{SolutionDataTypes, Real, Integer, BitBinary};

    fn setup_problem() -> Problem {
        Problem {
            solution_length: 5,
            number_of_objectives: 1,
            objective_constraint: Some(vec![Some(10.0)]),
            objective_constraint_operands: Some(vec![Some("<".to_string())]),
            direction: Some(vec![1]),
            solution_data_types: vec![
                SolutionDataTypes::BitBinary(BitBinary::new()),
                SolutionDataTypes::Integer(Integer::new(Some(-2000), Some(2000))),
                SolutionDataTypes::Real(Real::new(Some(-100.0), Some(1000.0))),
                SolutionDataTypes::Real(Real::new(Some(-100.0), Some(1000.0))),
                SolutionDataTypes::Real(Real::new(Some(-100.0), Some(1000.0))),
            ],
            variable_constraints: None,
            encoding: crate::core::Encoding::PerGene,
            eval_fn: EvalFn::Single(|x| vec![x.iter().sum()]),
        }
    }

    fn setup_solution(problem: Arc<Problem>) -> Solution {
        Solution {
            problem,
            solution: vec![1.0, 10.0, 10.0, 10.0, 10.0],
            objective_fitness_values: Default::default(),
            constraint_values: Default::default(),
            constraint_violation: 0,
            constraint_violation_magnitude: 0.0,
            feasible: false,
            evaluated: false,
        }
    }


    /// The defaults must mutate *sparingly* — around 1/n of the genes per call. Mutating every
    /// gene rebuilds the genome from scratch each generation, which is random search; that was
    /// the original defect here, and the old version of this test asserted it.
    #[test]
    fn test_default_mutation_manager() {
        let problem = Arc::new(setup_problem());
        let parent = setup_solution(Arc::clone(&problem));
        let mutation_manager = MutationManager::new(problem.solution_length);
        let mut rng = test_rng();

        let n = problem.solution_length; // 5 genes -> expected rate 1/5
        let trials = 400;
        let mut changed = 0usize;
        for _ in 0..trials {
            let child = mutation_manager.mutate(&parent, &mut rng);
            assert!(child.solution[0] == 0.0 || child.solution[0] == 1.0, "binary gene stays a bit");
            changed += (0..n).filter(|&i| child.solution[i] != parent.solution[i]).count();
        }
        let rate = changed as f64 / (trials * n) as f64;
        assert!(
            rate > 0.05 && rate < 0.45,
            "per-gene mutation rate {rate:.3} should sit near 1/n = {:.3}, not ~0 or ~1",
            1.0 / n as f64
        );
    }

    #[test]
    fn test_bit_flip_mutation() {
        let problem = Arc::new(setup_problem());
        let mutation = BitFlipMutation{probability: 1.0};
        let parent1 = setup_solution(Arc::clone(&problem));
        let mut parent2 = setup_solution(Arc::clone(&problem));
        parent2.solution[0] = 0.0;
        let child1 = mutation.mutate(&parent1, 0, &mut test_rng());
        let child2 = mutation.mutate(&parent2, 0, &mut test_rng());
        assert!(child1 == 0.0);
        assert!(child2 == 1.0);
    }
    #[test]
    fn test_polynomial_mutation_with_integer_and_real() {
        let problem = Arc::new(setup_problem());

        let parent = setup_solution(Arc::clone(&problem));


        let mutation = PolynomialMutation::new(Some(1.0), Some(20.0));
        let child_solution_0 = mutation.mutate(&parent, 1, &mut test_rng()); // Integer mutation
        let child_solution_1 = mutation.mutate(&parent, 2, &mut test_rng()); // Real mutation
        let child_solution_2 = mutation.mutate(&parent, 3, &mut test_rng()); // Real mutation
        let child_solution_3 = mutation.mutate(&parent, 4, &mut test_rng()); // Real mutation

        assert!(child_solution_0 >= -2000.0 && child_solution_0 <= 2000.0);
        assert!(child_solution_1 >= -100.0 && child_solution_1 <= 1000.0);
        assert!(child_solution_2 >= -100.0 && child_solution_2 <= 1000.0);
        assert!(child_solution_3 >= -100.0 && child_solution_3 <= 1000.0);
        // assert new solution is mutated
        assert!(child_solution_0 != parent.solution[1]);
        assert!(child_solution_1 != parent.solution[2]);
        assert!(child_solution_2 != parent.solution[3]);
        assert!(child_solution_3 != parent.solution[4]);

    }

    #[test]
    fn test_uniform_mutation_with_integer_and_real() {
        let problem = Arc::new(setup_problem());

        let parent = setup_solution(Arc::clone(&problem));

        let mutation = UniformMutation::default();
        let child_solution_0 = mutation.mutate(&parent, 1, &mut test_rng()); // Integer mutation
        let child_solution_1 = mutation.mutate(&parent, 2, &mut test_rng()); // Real mutation
        let child_solution_2 = mutation.mutate(&parent, 3, &mut test_rng()); // Real mutation
        let child_solution_3 = mutation.mutate(&parent, 4, &mut test_rng()); // Real mutation

        assert!(child_solution_0 >= -2000.0 && child_solution_0 <= 2000.0);
        assert!(child_solution_1 >= -100.0 && child_solution_1 <= 1000.0);
        assert!(child_solution_2 >= -100.0 && child_solution_2 <= 1000.0);
        assert!(child_solution_3 >= -100.0 && child_solution_3 <= 1000.0);
        // assert new solution is mutated
        assert!(child_solution_0 != parent.solution[1]);
        assert!(child_solution_1 != parent.solution[2]);
        assert!(child_solution_2 != parent.solution[3]);
        assert!(child_solution_3 != parent.solution[4]);

    }

    #[test]
    fn test_gaussian_mutation_with_integer_and_real() {
        let problem = Arc::new(setup_problem());

        let parent = setup_solution(Arc::clone(&problem));

        let mutation = GaussianMutation::new(Some(1.0), Some(0.1));
        let child_solution_0 = mutation.mutate(&parent, 1, &mut test_rng()); // Integer mutation
        let child_solution_1 = mutation.mutate(&parent, 2, &mut test_rng()); // Real mutation
        let child_solution_2 = mutation.mutate(&parent, 3, &mut test_rng()); // Real mutation
        let child_solution_3 = mutation.mutate(&parent, 4, &mut test_rng()); // Real mutation

        assert!(child_solution_0 >= -2000.0 && child_solution_0 <= 2000.0);
        assert!(child_solution_1 >= -100.0 && child_solution_1 <= 1000.0);
        assert!(child_solution_2 >= -100.0 && child_solution_2 <= 1000.0);
        assert!(child_solution_3 >= -100.0 && child_solution_3 <= 1000.0);
        // assert new solution is mutated
        assert!(child_solution_0 != parent.solution[1]);
        assert!(child_solution_1 != parent.solution[2]);
        assert!(child_solution_2 != parent.solution[3]);
        assert!(child_solution_3 != parent.solution[4]);
    }


}