fugue-evo 0.1.0

A Probabilistic Genetic Algorithm Library for Rust
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Adaptive control mechanisms
//!
//! These mechanisms adapt parameters based on feedback from the search process.
//!
//! **Integration status (EV-21):** the types in this module
//! ([`OneFifthRule`], [`AdaptiveOperatorSelection`], [`AdaptiveMutationRate`],
//! [`DiversityBasedAdaptation`], [`SlidingWindowStats`]) are *unintegrated
//! building blocks*. No default algorithm's run loop consumes them — grep
//! confirms they are referenced only within this module and its unit tests, so
//! treat them as a toolkit you drive yourself, not as an active adaptive-control
//! offering. The adaptation mechanism that *is* wired into a built-in algorithm
//! is the Thompson-sampling bandit
//! ([`SimpleGA::run_adaptive`](crate::algorithms::simple_ga::SimpleGA::run_adaptive));
//! self-adaptive step sizes are wired into the Evolution Strategy path.

use rand::distributions::WeightedIndex;
use rand::prelude::Distribution;
use rand::Rng;
use std::collections::VecDeque;

/// Rechenberg's 1/5 success rule for step-size adaptation
///
/// If the success rate is above 1/5, increase step size (more exploration)
/// If the success rate is below 1/5, decrease step size (more exploitation)
///
/// Reference: Rechenberg, I. (1973). Evolutionsstrategie.
#[derive(Clone, Debug)]
pub struct OneFifthRule {
    /// Factor to increase step size (typically 1.22 ≈ e^(1/5))
    pub increase_factor: f64,
    /// Factor to decrease step size (typically 0.82 ≈ e^(-1/5))
    pub decrease_factor: f64,
    /// Window size for computing success rate
    pub window_size: usize,
    /// Target success rate (default: 0.2)
    pub target_success_rate: f64,
    /// History of success/failure outcomes
    success_history: VecDeque<bool>,
}

impl OneFifthRule {
    /// Create a new 1/5 rule adapter with default parameters
    pub fn new() -> Self {
        Self {
            increase_factor: 1.22,
            decrease_factor: 0.82,
            window_size: 10,
            target_success_rate: 0.2,
            success_history: VecDeque::with_capacity(10),
        }
    }

    /// Set custom factors
    pub fn with_factors(mut self, increase: f64, decrease: f64) -> Self {
        self.increase_factor = increase;
        self.decrease_factor = decrease;
        self
    }

    /// Set window size
    pub fn with_window_size(mut self, size: usize) -> Self {
        self.window_size = size;
        self.success_history = VecDeque::with_capacity(size);
        self
    }

    /// Set target success rate
    pub fn with_target_rate(mut self, rate: f64) -> Self {
        self.target_success_rate = rate;
        self
    }

    /// Record a mutation outcome
    pub fn record(&mut self, success: bool) {
        self.success_history.push_back(success);
        if self.success_history.len() > self.window_size {
            self.success_history.pop_front();
        }
    }

    /// Get current success rate
    pub fn success_rate(&self) -> Option<f64> {
        if self.success_history.is_empty() {
            return None;
        }
        let successes = self.success_history.iter().filter(|&&s| s).count();
        Some(successes as f64 / self.success_history.len() as f64)
    }

    /// Adapt a step size based on current success rate
    pub fn adapt(&self, sigma: f64) -> f64 {
        if self.success_history.len() < self.window_size {
            return sigma;
        }

        let success_rate = self.success_rate().unwrap_or(self.target_success_rate);

        if success_rate > self.target_success_rate {
            sigma * self.increase_factor
        } else if success_rate < self.target_success_rate {
            sigma * self.decrease_factor
        } else {
            sigma
        }
    }

    /// Reset the history
    pub fn reset(&mut self) {
        self.success_history.clear();
    }
}

impl Default for OneFifthRule {
    fn default() -> Self {
        Self::new()
    }
}

/// Adaptive operator selection using fitness-based credit assignment
///
/// Tracks performance of multiple operators and adjusts selection probabilities
/// based on the fitness improvements they produce.
#[derive(Clone, Debug)]
pub struct AdaptiveOperatorSelection {
    /// Number of operators
    pub num_operators: usize,
    /// Selection weights for each operator
    pub weights: Vec<f64>,
    /// Learning rate for weight updates
    pub learning_rate: f64,
    /// Minimum probability for any operator
    pub min_probability: f64,
    /// Decay factor for old rewards
    pub decay: f64,
}

impl AdaptiveOperatorSelection {
    /// Create a new adaptive operator selection with uniform initial weights
    pub fn new(num_operators: usize) -> Self {
        assert!(num_operators > 0, "Must have at least one operator");
        Self {
            num_operators,
            weights: vec![1.0 / num_operators as f64; num_operators],
            learning_rate: 0.1,
            min_probability: 0.05,
            decay: 0.99,
        }
    }

    /// Set learning rate
    pub fn with_learning_rate(mut self, rate: f64) -> Self {
        self.learning_rate = rate;
        self
    }

    /// Set minimum probability
    pub fn with_min_probability(mut self, prob: f64) -> Self {
        self.min_probability = prob;
        self
    }

    /// Set decay factor
    pub fn with_decay(mut self, decay: f64) -> Self {
        self.decay = decay;
        self
    }

    /// Select an operator index
    pub fn select<R: Rng>(&self, rng: &mut R) -> usize {
        let dist = WeightedIndex::new(&self.weights).unwrap();
        dist.sample(rng)
    }

    /// Update weights based on fitness improvement from an operator
    pub fn update(&mut self, operator_idx: usize, fitness_improvement: f64) {
        assert!(operator_idx < self.num_operators);

        // Apply decay to all weights
        for w in &mut self.weights {
            *w *= self.decay;
        }

        // Credit assignment based on fitness improvement
        let reward = fitness_improvement.max(0.0);
        self.weights[operator_idx] += self.learning_rate * reward;

        // Normalize and enforce minimum probability
        self.normalize_weights();
    }

    /// Normalize weights to sum to 1 while enforcing minimums
    fn normalize_weights(&mut self) {
        let sum: f64 = self.weights.iter().sum();
        if sum <= 0.0 {
            // Reset to uniform if weights collapsed
            for w in &mut self.weights {
                *w = 1.0 / self.num_operators as f64;
            }
            return;
        }

        // Normalize
        for w in &mut self.weights {
            *w /= sum;
        }

        // Enforce minimum probability
        let n = self.num_operators as f64;
        let mut deficit = 0.0;
        let mut excess_count = 0;

        for w in &mut self.weights {
            if *w < self.min_probability / n {
                deficit += self.min_probability / n - *w;
                *w = self.min_probability / n;
            } else {
                excess_count += 1;
            }
        }

        // Redistribute deficit from weights above minimum
        if deficit > 0.0 && excess_count > 0 {
            let reduction = deficit / excess_count as f64;
            for w in &mut self.weights {
                if *w > self.min_probability / n + reduction {
                    *w -= reduction;
                }
            }
        }

        // Final normalization
        let sum: f64 = self.weights.iter().sum();
        for w in &mut self.weights {
            *w /= sum;
        }
    }

    /// Get current selection probabilities
    pub fn probabilities(&self) -> &[f64] {
        &self.weights
    }

    /// Reset weights to uniform
    pub fn reset(&mut self) {
        for w in &mut self.weights {
            *w = 1.0 / self.num_operators as f64;
        }
    }
}

/// Sliding window statistics tracker
#[derive(Clone, Debug)]
pub struct SlidingWindowStats {
    /// Window of values
    values: VecDeque<f64>,
    /// Maximum window size
    window_size: usize,
}

impl SlidingWindowStats {
    /// Create a new sliding window tracker
    pub fn new(window_size: usize) -> Self {
        Self {
            values: VecDeque::with_capacity(window_size),
            window_size,
        }
    }

    /// Add a value to the window
    pub fn push(&mut self, value: f64) {
        self.values.push_back(value);
        if self.values.len() > self.window_size {
            self.values.pop_front();
        }
    }

    /// Get the mean of values in the window
    pub fn mean(&self) -> Option<f64> {
        if self.values.is_empty() {
            return None;
        }
        Some(self.values.iter().sum::<f64>() / self.values.len() as f64)
    }

    /// Get the variance of values in the window
    pub fn variance(&self) -> Option<f64> {
        if self.values.len() < 2 {
            return None;
        }
        let mean = self.mean()?;
        let sum_sq: f64 = self.values.iter().map(|v| (v - mean).powi(2)).sum();
        Some(sum_sq / (self.values.len() - 1) as f64)
    }

    /// Get the standard deviation
    pub fn std_dev(&self) -> Option<f64> {
        self.variance().map(|v| v.sqrt())
    }

    /// Get the minimum value in the window
    pub fn min(&self) -> Option<f64> {
        self.values.iter().copied().reduce(f64::min)
    }

    /// Get the maximum value in the window
    pub fn max(&self) -> Option<f64> {
        self.values.iter().copied().reduce(f64::max)
    }

    /// Check if window is full
    pub fn is_full(&self) -> bool {
        self.values.len() >= self.window_size
    }

    /// Get number of values in window
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Clear the window
    pub fn clear(&mut self) {
        self.values.clear();
    }
}

/// Fitness-based adaptive mutation rate
///
/// Adapts mutation rate based on whether mutations are producing improvements.
#[derive(Clone, Debug)]
pub struct AdaptiveMutationRate {
    /// Current mutation rate
    pub rate: f64,
    /// Minimum mutation rate
    pub min_rate: f64,
    /// Maximum mutation rate
    pub max_rate: f64,
    /// Increase factor when improvements are rare
    pub increase_factor: f64,
    /// Decrease factor when improvements are common
    pub decrease_factor: f64,
    /// Statistics tracker
    stats: SlidingWindowStats,
    /// Improvement threshold
    improvement_threshold: f64,
}

impl AdaptiveMutationRate {
    /// Create a new adaptive mutation rate
    pub fn new(initial_rate: f64) -> Self {
        Self {
            rate: initial_rate,
            min_rate: 0.001,
            max_rate: 0.5,
            increase_factor: 1.1,
            decrease_factor: 0.9,
            stats: SlidingWindowStats::new(20),
            improvement_threshold: 0.3, // Target 30% improvement rate
        }
    }

    /// Record a mutation outcome
    pub fn record(&mut self, improved: bool) {
        self.stats.push(if improved { 1.0 } else { 0.0 });
    }

    /// Adapt the mutation rate based on recent history
    pub fn adapt(&mut self) {
        if !self.stats.is_full() {
            return;
        }

        let improvement_rate = self.stats.mean().unwrap_or(0.0);

        if improvement_rate < self.improvement_threshold {
            // Not enough improvements, increase mutation rate
            self.rate = (self.rate * self.increase_factor).min(self.max_rate);
        } else if improvement_rate > self.improvement_threshold * 1.5 {
            // Too many improvements (might be too disruptive), decrease
            self.rate = (self.rate * self.decrease_factor).max(self.min_rate);
        }
    }

    /// Get current rate
    pub fn current_rate(&self) -> f64 {
        self.rate
    }
}

/// Population diversity-based parameter adaptation
#[derive(Clone, Debug)]
pub struct DiversityBasedAdaptation {
    /// Window for tracking diversity
    diversity_history: SlidingWindowStats,
    /// Target diversity level
    pub target_diversity: f64,
    /// Tolerance around target
    pub tolerance: f64,
}

impl DiversityBasedAdaptation {
    /// Create a new diversity-based adapter
    pub fn new(target_diversity: f64) -> Self {
        Self {
            diversity_history: SlidingWindowStats::new(10),
            target_diversity,
            tolerance: 0.1,
        }
    }

    /// Record current diversity
    pub fn record_diversity(&mut self, diversity: f64) {
        self.diversity_history.push(diversity);
    }

    /// Get recommended mutation rate multiplier
    ///
    /// Returns > 1.0 if diversity is too low, < 1.0 if too high
    pub fn mutation_multiplier(&self) -> f64 {
        let Some(current_diversity) = self.diversity_history.mean() else {
            return 1.0;
        };

        if current_diversity < self.target_diversity * (1.0 - self.tolerance) {
            // Diversity too low, increase mutation
            1.5
        } else if current_diversity > self.target_diversity * (1.0 + self.tolerance) {
            // Diversity too high, decrease mutation
            0.8
        } else {
            1.0
        }
    }

    /// Get recommended selection pressure multiplier
    ///
    /// Returns > 1.0 if diversity is too high, < 1.0 if too low
    pub fn selection_pressure_multiplier(&self) -> f64 {
        let Some(current_diversity) = self.diversity_history.mean() else {
            return 1.0;
        };

        if current_diversity < self.target_diversity * (1.0 - self.tolerance) {
            // Diversity too low, reduce selection pressure
            0.8
        } else if current_diversity > self.target_diversity * (1.0 + self.tolerance) {
            // Diversity too high, increase selection pressure
            1.2
        } else {
            1.0
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_one_fifth_rule_increase() {
        let mut rule = OneFifthRule::new().with_window_size(5);

        // All successes -> increase
        for _ in 0..5 {
            rule.record(true);
        }

        let sigma = 1.0;
        let new_sigma = rule.adapt(sigma);
        assert!(new_sigma > sigma);
    }

    #[test]
    fn test_one_fifth_rule_decrease() {
        let mut rule = OneFifthRule::new().with_window_size(5);

        // All failures -> decrease
        for _ in 0..5 {
            rule.record(false);
        }

        let sigma = 1.0;
        let new_sigma = rule.adapt(sigma);
        assert!(new_sigma < sigma);
    }

    #[test]
    fn test_one_fifth_rule_at_target() {
        let mut rule = OneFifthRule::new()
            .with_window_size(5)
            .with_target_rate(0.2);

        // Exactly 1/5 success rate
        rule.record(true);
        for _ in 0..4 {
            rule.record(false);
        }

        let sigma = 1.0;
        let new_sigma = rule.adapt(sigma);
        assert!((new_sigma - sigma).abs() < 1e-10);
    }

    #[test]
    fn test_adaptive_operator_selection() {
        let mut aos = AdaptiveOperatorSelection::new(3);
        let mut rng = rand::thread_rng();

        // Initially uniform
        assert_eq!(aos.probabilities().len(), 3);
        for &p in aos.probabilities() {
            assert!((p - 1.0 / 3.0).abs() < 1e-10);
        }

        // Update with reward for operator 0
        aos.update(0, 10.0);

        // Operator 0 should have higher weight now
        assert!(aos.probabilities()[0] > aos.probabilities()[1]);

        // Selection should work
        let _ = aos.select(&mut rng);
    }

    #[test]
    fn test_sliding_window_stats() {
        let mut stats = SlidingWindowStats::new(5);

        assert!(stats.mean().is_none());

        stats.push(1.0);
        stats.push(2.0);
        stats.push(3.0);

        assert!((stats.mean().unwrap() - 2.0).abs() < 1e-10);
        assert!((stats.min().unwrap() - 1.0).abs() < 1e-10);
        assert!((stats.max().unwrap() - 3.0).abs() < 1e-10);

        // Fill window
        stats.push(4.0);
        stats.push(5.0);
        assert!(stats.is_full());

        // Add more, should drop oldest
        stats.push(6.0);
        assert_eq!(stats.len(), 5);
        assert!((stats.min().unwrap() - 2.0).abs() < 1e-10);
    }

    #[test]
    fn test_adaptive_mutation_rate() {
        let mut amr = AdaptiveMutationRate::new(0.1);

        // Record no improvements
        for _ in 0..25 {
            amr.record(false);
        }
        amr.adapt();

        // Rate should increase
        assert!(amr.current_rate() > 0.1);
    }

    #[test]
    fn test_diversity_based_adaptation() {
        let mut dba = DiversityBasedAdaptation::new(0.5);

        // Record low diversity
        for _ in 0..10 {
            dba.record_diversity(0.2);
        }

        // Should recommend higher mutation
        assert!(dba.mutation_multiplier() > 1.0);
        // Should recommend lower selection pressure
        assert!(dba.selection_pressure_multiplier() < 1.0);
    }
}