GALib-Parallel
Header-only C++ library for parallel evolutionary algorithms
Loading...
Searching...
No Matches
ArithmeticCrossover.h
Go to the documentation of this file.
1#ifndef ARITHMETIC_CROSSOVER_H
2#define ARITHMETIC_CROSSOVER_H
3
4#pragma once
5
6#include "Crossover.h"
7#include <random>
8#include <stdexcept>
9#include <utility>
10
11namespace galib {
12
23 template <typename GeneType>
24 class ArithmeticCrossover : public Crossover<GeneType> {
25 public:
33 std::pair<Individual<GeneType>, Individual<GeneType>>
35 const Individual<GeneType>& parent2) override {
36
37 if (parent1.size() != parent2.size()) {
38 throw std::invalid_argument("Parents must have the same genotype size");
39 }
40
41 thread_local static std::random_device rd;
42 thread_local static std::mt19937 gen(rd());
43 thread_local static std::uniform_real_distribution<double> alpha_dist(0.0, 1.0);
44
45 double alpha = alpha_dist(gen);
46
47 Individual<GeneType> child1(parent1.size());
48 Individual<GeneType> child2(parent2.size());
49
50 const auto& g1 = parent1.getGenotype();
51 const auto& g2 = parent2.getGenotype();
52
53 auto& c1 = child1.getGenotype();
54 auto& c2 = child2.getGenotype();
55
56 for (std::size_t i = 0; i < g1.size(); ++i) {
57 c1[i] = static_cast<GeneType>(alpha * g1[i] + (1.0 - alpha) * g2[i]);
58 c2[i] = static_cast<GeneType>(alpha * g2[i] + (1.0 - alpha) * g1[i]);
59 }
60
61 return {child1, child2};
62 }
63 };
64
65}
66
67#endif // ARITHMETIC_CROSSOVER_H
Performs arithmetic (convex) crossover.
std::pair< Individual< GeneType >, Individual< GeneType > > crossover(const Individual< GeneType > &parent1, const Individual< GeneType > &parent2) override
Produces children via linear interpolation of parent genes.
Interface for crossover (recombination) operators.
Definition Crossover.h:20
Represents a single candidate solution in the population.
Definition Individual.h:23
std::size_t size() const
Returns the number of genes in the genotype.
Definition Individual.h:47
std::vector< GeneType > & getGenotype()
Returns a reference to the genotype vector.
Definition Individual.h:53