forked from jm-armijo/genetic-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
106 lines (93 loc) · 2.88 KB
/
Copy pathmain.cpp
File metadata and controls
106 lines (93 loc) · 2.88 KB
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
#include "Population.hpp"
#include <iostream>
class Simulator {
private:
unsigned m_num_generations;
unsigned m_num_args;
unsigned m_num_genes;
unsigned m_pop_size;
unsigned m_mutation_rate;
std::vector<std::vector<double>> m_args_list;
std::vector<double> m_expected_vals;
public:
Simulator(unsigned num_generations, unsigned num_args, unsigned num_genes, unsigned pop_size, unsigned mutation_rate) :
m_num_generations(num_generations),
m_num_args(num_args),
m_num_genes(num_genes),
m_pop_size(pop_size),
m_mutation_rate(mutation_rate)
{
// Test sets
m_args_list.push_back({7.0, 2.0});
m_args_list.push_back({3.0, 4.0});
m_args_list.push_back({8.0, 2.0});
m_args_list.push_back({9.0, 2.0});
m_args_list.push_back({0.0, 3.0});
m_args_list.push_back({1.0, 3.0});
m_args_list.push_back({2.0, 3.0});
m_args_list.push_back({3.0, 3.0});
m_args_list.push_back({4.0, 3.0});
for (const auto& args : m_args_list) {
m_expected_vals.push_back(misteryFunc(args[0], args[1]));
}
Individual::init(num_args, num_genes);
Gene::init(num_args, num_genes);
}
void printGenNum(int i)
{
std::string prev = std::to_string(i);
for (auto i = 0u; i<prev.length(); ++i) {
std::cout << "\b";
}
std::cout << (i+1);
fflush(stdout);
}
void run()
{
// initialise
std::cout << "Processing generation : ";
Population pop(m_pop_size, m_mutation_rate);
unsigned i;
for (i = 0; ; ++i) {
printGenNum(i);
for (unsigned j {0}; j < m_expected_vals.size(); ++j) {
pop.fitness(m_args_list[j], m_expected_vals[j]);
}
// |
// V
if (pop.checkEndCondition() || i>=m_num_generations-1) {
break; // Stop
}
// | No stop
// V
auto selected = pop.select();
// |
// V
pop.crossover(selected);
// |
// V
pop.mutate();
// |
// V
}
std::cout << std::endl << std::endl;
std::cout << "Stopped after " << (i+1) << " generations." << std::endl;
std::cout << "Fitness best individual: " << pop.getTopScore() << std::endl;
pop.printTopIndividual();
}
private:
double misteryFunc(double x0, double x1)
{
return 2.25 + x0/x1 + x0*x0*x0*x0;
}
};
int main() {
auto num_generations = 50u;
auto num_args = 2u;
auto num_genes = 18u;
auto pop_size = 5000u;
auto mutation_rate = 5u; // 5%
Simulator s(num_generations, num_args, num_genes, pop_size, mutation_rate);
s.run();
return 0;
}