-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPopulation.hpp
99 lines (86 loc) · 2.61 KB
/
Population.hpp
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
/*
* Name: GGA - Generic Genetic Algorithm
* Author: Lucas Costa Campos
* Email: [email protected]
* Version: 0.1
* License: GNU General Public License
* Copyright: 2013 Lucas Costa Campos
* Website: https://github.com/LucasCampos/
*/
/*
* This file is part of GGA
*
* POPS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* */
#ifndef POPULATION_HPP
#define POPULATION_HPP
#include <vector>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <tuple>
#include <algorithm>
template <class Ind>
struct Population {
std::vector<Ind> individuals;
std::vector<Ind> newIndividuals;
int N;
int hN;
double mutateProb;
Population(const std::vector<Ind>& ind, double mp):individuals(ind), mutateProb(mp){
N=ind.size();
newIndividuals.reserve(N);
hN=N/2;
#ifdef DEBUG
if ((N%2==1))
std::cout << "Set an even number of individuals" << std::endl;
#endif
}
std::tuple<Ind,Ind> MakeChildren(const Ind& parA, const Ind& parB) const {
Ind chlA,chlB;
std::array<Ind,4> ind = parA.CrossOver(parB);
std::sort(ind.begin(),ind.end(),[](const Ind& x, const Ind& y){return x.fitness > y.fitness;});
return std::make_tuple(ind[0],ind[1]);
}
void CrossEveryone() {
Ind g1, g2;
for (int i=0; i<hN; i++) {
const int idx1 = rand()%N;
const int idx2 = rand()%N; //Not guaranteed to be diff from idx1
std::tie(g1,g2) = MakeChildren(individuals[idx1],individuals[idx2]);
newIndividuals.push_back(g1);
newIndividuals.push_back(g2);
}
}
void MutateEveryone() {
for (int i=0; i<N; i++) {
newIndividuals[i].Mutate(mutateProb);
}
}
void MakeNewGen() {
newIndividuals.clear();
CrossEveryone();
MutateEveryone();
individuals = newIndividuals;
}
std::vector<double> GetAnswers() {
std::vector<double> ans; ans.reserve(N);
std::transform(individuals.begin(),individuals.end(),ans.begin(),[](const Ind& x){return x.fitness;});
std::sort(ans.begin(), ans.end());
return ans;
}
};
#endif