mahf 0.1.0

A framework for modular construction and evaluation of metaheuristics.
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! Common mutation components.

use std::marker::PhantomData;

use eyre::{ensure, WrapErr};
use itertools::multizip;
use rand::{
    distributions::{Distribution, Uniform},
    seq::{IteratorRandom, SliceRandom},
    Rng,
};
use rand_distr::Normal;
use serde::{Deserialize, Serialize};

use crate::{
    component::ExecResult,
    components::{
        mutation::{functional as f, MutationRate, MutationStrength},
        Component,
    },
    identifier::{Global, Identifier},
    population::AsSolutionsMut,
    problems::{LimitedVectorProblem, VectorProblem},
    State,
};

/// Mutates each dimension with a delta from a normal distribution `N(0, std_dev)`
/// depending on the mutation probability `rm`.
///
/// # Adapting parameters
///
/// Adapting the `std_dev` and `rm` is possible through modifying the respective states:
/// - `std_dev`: [`MutationStrength<NormalMutation<I>>`]
/// - `rm`: [`MutationRate<NormalMutation<I>>`]
///
/// # Errors
///
/// Returns an `Err` if the [`MutationStrength`] or [`MutationRate`] contain invalid values.
#[derive(Clone, Serialize, Deserialize)]
pub struct NormalMutation<I: Identifier = Global> {
    /// Standard deviation of the normal distribution.
    pub std_dev: f64,
    /// Mutation rate.
    pub rm: f64,
    phantom: PhantomData<I>,
}

impl<I: Identifier> NormalMutation<I> {
    pub fn from_params(std_dev: f64, rm: f64) -> Self {
        Self {
            std_dev,
            rm,
            phantom: PhantomData,
        }
    }

    pub fn new_with_id<P>(std_dev: f64, rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = f64>,
    {
        Box::new(Self::from_params(std_dev, rm))
    }
}

impl NormalMutation<Global> {
    pub fn new<P>(std_dev: f64, rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = f64>,
    {
        Self::new_with_id(std_dev, rm)
    }

    /// Creates the `NormalMutation` with a mutation rate of 1.
    pub fn new_dev<P>(std_dev: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = f64>,
    {
        Self::new(std_dev, 1.0)
    }
}

impl<P, I> Component<P> for NormalMutation<I>
where
    P: VectorProblem<Element = f64>,
    I: Identifier,
{
    fn init(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        state.insert(MutationStrength::<Self>::new(self.std_dev));
        state.insert(MutationRate::<Self>::new(self.rm));
        Ok(())
    }

    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        let distr = Normal::new(0., state.get_value::<MutationStrength<Self>>())
            .wrap_err("invalid mutation strength")?;

        let rm = state.borrow::<MutationRate<Self>>().value()?;

        for solution in populations.current_mut().as_solutions_mut() {
            for x in solution {
                if rng.gen_bool(rm) {
                    *x += distr.sample(&mut *rng);
                }
            }
        }
        Ok(())
    }
}

/// Mutates each dimension with a delta from a uniform distribution `[-bound, bound]`
/// depending on the mutation probability `rm`.
///
/// # Adapting parameters
///
/// Adapting the `bound` and `rm` is possible through modifying the respective states:
/// - `bound`: [`MutationStrength<UniformMutation<I>>`]
/// - `rm`: [`MutationRate<UniformMutation<I>>`]
///
/// # Errors
///
/// Returns an `Err` if the [`MutationStrength`] or [`MutationRate`] contain invalid values.
#[derive(Clone, Serialize, Deserialize)]
pub struct UniformMutation<I: Identifier = Global> {
    /// Bound of the uniform distribution `[-bound, bound]`.
    pub bound: f64,
    /// Mutation rate.
    pub rm: f64,
    phantom: PhantomData<I>,
}

impl<I: Identifier> UniformMutation<I> {
    pub fn from_params(bound: f64, rm: f64) -> Self {
        Self {
            bound,
            rm,
            phantom: PhantomData,
        }
    }

    pub fn new_with_id<P>(bound: f64, rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = f64>,
    {
        Box::new(Self::from_params(bound, rm))
    }
}

impl UniformMutation<Global> {
    pub fn new<P>(bound: f64, rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = f64>,
    {
        Self::new_with_id(bound, rm)
    }

    pub fn new_bound<P>(bound: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = f64>,
    {
        Self::new(bound, 1.0)
    }
}

impl<P, I> Component<P> for UniformMutation<I>
where
    P: VectorProblem<Element = f64>,
    I: Identifier,
{
    fn init(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        state.insert(MutationStrength::<Self>::new(self.bound));
        state.insert(MutationRate::<Self>::new(self.rm));
        Ok(())
    }

    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        let bound = state.get_value::<MutationStrength<Self>>();
        ensure!(bound >= 0., "bound must be positive");
        let distr = Uniform::new(0., bound);

        let rm = state.borrow::<MutationRate<Self>>().value()?;

        for solution in populations.current_mut().as_solutions_mut() {
            for x in solution {
                if rng.gen_bool(rm) {
                    let sign = *[-1., 1.].choose(&mut *rng).unwrap();
                    *x += sign * distr.sample(&mut *rng);
                }
            }
        }
        Ok(())
    }
}

/// Flips each bit with probability `rm`.
///
/// # Adapting parameters
///
/// Adapting the `rm` is possible through modifying the respective state:
/// - `rm`: [`MutationRate<BitFlipMutation<I>>`]
///
/// # Errors
///
/// Returns an `Err` if the [`MutationRate`] contains an invalid value.
#[derive(Clone, Serialize, Deserialize)]
pub struct BitFlipMutation<I: Identifier = Global> {
    /// Probability of flipping a bit.
    pub rm: f64,
    phantom: PhantomData<I>,
}

impl<I: Identifier> BitFlipMutation<I> {
    pub fn from_params(rm: f64) -> Self {
        Self {
            rm,
            phantom: PhantomData,
        }
    }

    pub fn new_with_id<P>(rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = bool>,
    {
        Box::new(Self::from_params(rm))
    }
}

impl BitFlipMutation<Global> {
    pub fn new<P>(rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = bool>,
    {
        Self::new_with_id(rm)
    }
}

impl<P, I> Component<P> for BitFlipMutation<I>
where
    P: VectorProblem<Element = bool>,
    I: Identifier,
{
    fn init(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        state.insert(MutationRate::<Self>::new(self.rm));
        Ok(())
    }

    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        let rm = state.borrow::<MutationRate<Self>>().value()?;

        for solution in populations.current_mut().as_solutions_mut() {
            for x in solution {
                if rng.gen_bool(rm) {
                    *x = !*x;
                }
            }
        }
        Ok(())
    }
}

/// Applies a random uniform reset of a position in the solution with probability `rm`.
///
/// # Adapting parameters
///
/// Adapting the `rm` is possible through modifying the respective state:
/// - `rm`: [`MutationRate<PartialRandomSpread<I>>`]
///
/// # Errors
///
/// Returns an `Err` if the [`MutationRate`] contains an invalid value.
#[derive(Clone, Serialize, Deserialize)]
pub struct PartialRandomSpread<I: Identifier = Global> {
    /// Mutation rate.
    pub rm: f64,
    phantom: PhantomData<I>,
}

impl<I: Identifier> PartialRandomSpread<I> {
    pub fn from_params(rm: f64) -> Self {
        Self {
            rm,
            phantom: PhantomData,
        }
    }

    pub fn new_with_id<P>(rm: f64) -> Box<dyn Component<P>>
    where
        P: LimitedVectorProblem<Element = f64>,
    {
        Box::new(Self::from_params(rm))
    }
}

impl PartialRandomSpread<Global> {
    pub fn new<P>(rm: f64) -> Box<dyn Component<P>>
    where
        P: LimitedVectorProblem<Element = f64>,
    {
        Self::new_with_id(rm)
    }

    /// Creates a new `PartialRandomSpread` which fully re-initializes the population in the search space.
    pub fn new_full<P>() -> Box<dyn Component<P>>
    where
        P: LimitedVectorProblem<Element = f64>,
    {
        Self::new(1.)
    }
}

impl<P, I> Component<P> for PartialRandomSpread<I>
where
    P: LimitedVectorProblem<Element = f64>,
    I: Identifier,
{
    fn init(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        state.insert(MutationRate::<Self>::new(self.rm));
        Ok(())
    }

    fn execute(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        let rm = state.borrow::<MutationRate<Self>>().value()?;

        for solution in populations.current_mut().as_solutions_mut() {
            for (x, domain) in multizip((solution, problem.domain())) {
                if rng.gen_bool(rm) {
                    *x = rng.gen_range(domain.clone());
                }
            }
        }
        Ok(())
    }
}

/// Applies a scramble mutation i.e. shuffling with probability `rm`.
///
/// # Adapting parameters
///
/// Adapting the `rm` is possible through modifying the respective state:
/// - `rm`: [`MutationRate<ScrambleMutation<I>>`]
///
/// # Errors
///
/// Returns an `Err` if the [`MutationRate`] contains an invalid value.
#[derive(Clone, Serialize, Deserialize)]
pub struct ScrambleMutation<I: Identifier = Global> {
    pub rm: f64,
    phantom: PhantomData<I>,
}

impl<I: Identifier> ScrambleMutation<I> {
    pub fn from_params(rm: f64) -> Self {
        Self {
            rm,
            phantom: PhantomData,
        }
    }

    pub fn new_with_id<P>(rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem,
        P::Element: 'static,
    {
        Box::new(Self::from_params(rm))
    }
}

impl ScrambleMutation<Global> {
    pub fn new<P>(rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem,
        P::Element: 'static,
    {
        Self::new_with_id(rm)
    }

    /// Creates a new `ScrambleMutation` which scrambles all solutions.
    pub fn new_full<P>() -> Box<dyn Component<P>>
    where
        P: VectorProblem,
        P::Element: 'static,
    {
        Self::new(1.)
    }
}

impl<P, I> Component<P> for ScrambleMutation<I>
where
    P: VectorProblem,
    P::Element: 'static,
    I: Identifier,
{
    fn init(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        state.insert(MutationRate::<Self>::new(self.rm));
        Ok(())
    }

    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        let rm = state.borrow::<MutationRate<Self>>().value()?;

        for solution in populations.current_mut().as_solutions_mut() {
            if rng.gen_bool(rm) {
                solution.shuffle(&mut *rng);
            }
        }
        Ok(())
    }
}

/// Re-samples each bit depending on the mutation rate `rm`, where `p` is the probability
/// of generating a 1 or `true`.
///
/// # Adapting parameters
///
/// Adapting the `rm` is possible through modifying the respective state:
/// - `rm`: [`MutationRate<PartialRandomBitstring<I>>`]
///
/// # Errors
///
/// Returns an `Err` if the [`MutationRate`] contains an invalid value.
#[derive(Clone, Serialize, Deserialize)]
pub struct PartialRandomBitstring<I: Identifier = Global> {
    /// Probability to sample 1 or `true`.
    pub p: f64,
    /// Mutation rate.
    pub rm: f64,
    phantom: PhantomData<I>,
}

impl<I: Identifier> PartialRandomBitstring<I> {
    pub fn from_params(p: f64, rm: f64) -> Self {
        Self {
            p,
            rm,
            phantom: PhantomData,
        }
    }

    pub fn new_with_id<P>(p: f64, rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = bool>,
    {
        Box::new(Self::from_params(p, rm))
    }
}

impl PartialRandomBitstring<Global> {
    pub fn new<P>(p: f64, rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = bool>,
    {
        Self::new_with_id(p, rm)
    }

    pub fn new_uniform<P>(rm: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = bool>,
    {
        Self::new(0.5, rm)
    }

    pub fn new_full<P>(p: f64) -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = bool>,
    {
        Self::new(p, 1.)
    }

    pub fn new_uniform_full<P>() -> Box<dyn Component<P>>
    where
        P: VectorProblem<Element = bool>,
    {
        Self::new(0.5, 1.)
    }
}

impl<P, I> Component<P> for PartialRandomBitstring<I>
where
    P: VectorProblem<Element = bool>,
    I: Identifier,
{
    fn init(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        state.insert(MutationRate::<Self>::new(self.rm));
        Ok(())
    }

    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        let rm = state.borrow::<MutationRate<Self>>().value()?;

        for solution in populations.current_mut().as_solutions_mut() {
            for x in solution {
                if rng.gen_bool(rm) {
                    *x = rng.gen_bool(self.p);
                }
            }
        }
        Ok(())
    }
}

/// Applies a swap mutation to `num_swap` elements.
///
/// For more than two elements the swap is performed circular.
///
/// # Errors
///
/// Returns an `Err` if `num_swap` is greater than the solution length.
#[derive(Clone, Serialize, Deserialize)]
pub struct SwapMutation {
    pub num_swap: u32,
}

impl SwapMutation {
    pub fn from_params(num_swap: u32) -> ExecResult<Self> {
        ensure!(
            num_swap > 2,
            "at least two indices need to be swapped, while {} was provided",
            num_swap
        );
        Ok(Self { num_swap })
    }

    /// Creates a new `SwapMutation`, or returns an `Err` if `num_swap` is less than two,
    /// as it is not possible to swap less than two elements.
    pub fn new<P>(num_swap: u32) -> ExecResult<Box<dyn Component<P>>>
    where
        P: VectorProblem,
        P::Element: 'static,
    {
        Ok(Box::new(Self::from_params(num_swap)?))
    }
}

impl<P> Component<P> for SwapMutation
where
    P: VectorProblem,
    P::Element: 'static,
{
    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        let num_swap = self.num_swap as usize;

        for solution in populations.current_mut().as_solutions_mut() {
            ensure!(
                num_swap < solution.len(),
                "more than {} swaps are not possible on a solution of length {}",
                num_swap,
                solution.len()
            );
            let indices = (0..solution.len()).choose_multiple(&mut *rng, num_swap);
            f::circular_swap(solution, &indices)
        }
        Ok(())
    }
}

/// Applies a inversion mutation to the solution, i.e. taking a random slice of the solution
/// and inverting it.
#[derive(Clone, Serialize, Deserialize)]
pub struct InversionMutation;

impl InversionMutation {
    pub fn from_params() -> Self {
        Self
    }

    pub fn new<P, D>() -> Box<dyn Component<P>>
    where
        P: VectorProblem,
        P::Element: 'static,
    {
        Box::new(Self::from_params())
    }
}

impl<P> Component<P> for InversionMutation
where
    P: VectorProblem,
    P::Element: 'static,
{
    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        for solution in populations.current_mut().as_solutions_mut() {
            let [start, end]: [_; 2] = (0..solution.len())
                .choose_multiple(&mut *state.random_mut(), 2)
                .try_into()
                .unwrap();
            solution[start..end].reverse();
        }
        Ok(())
    }
}

/// Applies a insertion mutation to the solution, i.e. removing a random element
/// from the solution and inserting it on a random position.
#[derive(Clone, Serialize, Deserialize)]
pub struct InsertionMutation;

impl InsertionMutation {
    pub fn from_params() -> Self {
        Self
    }

    pub fn new<P>() -> Box<dyn Component<P>>
    where
        P: VectorProblem,
        P::Element: 'static,
    {
        Box::new(Self::from_params())
    }
}

impl<P> Component<P> for InsertionMutation
where
    P: VectorProblem,
    P::Element: 'static,
{
    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        for solution in populations.current_mut().as_solutions_mut() {
            let element = rng.gen_range(0..solution.len());
            let index = rng.gen_range(0..solution.len());
            f::translocate_slice(solution, element..element + 1, index);
        }
        Ok(())
    }
}

/// Applies a translocation mutation to the solution, i.e. removing a random slice
/// from solution and inserting it on a random position.
#[derive(Clone, Serialize, Deserialize)]
pub struct TranslocationMutation;

impl TranslocationMutation {
    pub fn from_params() -> Self {
        Self
    }

    pub fn new<P>() -> Box<dyn Component<P>>
    where
        P: VectorProblem,
        P::Element: 'static,
    {
        Box::new(Self::from_params())
    }
}

impl<P> Component<P> for TranslocationMutation
where
    P: VectorProblem,
    P::Element: 'static,
{
    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        for solution in populations.current_mut().as_solutions_mut() {
            let [start, end]: [_; 2] = (0..solution.len())
                .choose_multiple(&mut *state.random_mut(), 2)
                .try_into()
                .unwrap();
            let index = rng.gen_range(0..start);
            f::translocate_slice(solution, start..end, index);
        }
        Ok(())
    }
}