-
Notifications
You must be signed in to change notification settings - Fork 0
/
genalg.h
73 lines (62 loc) · 2.07 KB
/
genalg.h
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
#ifndef GENALG
#define GENALG
#include "neuralnet.h"
#include <QVector>
struct Neuron;
struct Genome
{
QVector<Neuron> neurons;
double fitness;
Genome(Genome&& other);
Genome(const Genome& other);
Genome() : neurons(), fitness(0.0) {}
Genome(QVector<Neuron> neurons, double fitness) : neurons(neurons), fitness(fitness){}
Genome& operator=(const Genome& other);
// overload '<' for sorting
friend bool operator<(const Genome& lhs, const Genome& rhs)
{
return lhs.fitness < rhs.fitness;
}
};
class GenAlg
{
private:
//************ Member vars ********************
// Probability that a genome bits will mutate
double m_mutation_rate;
// Probability of crossover
double m_crossover_rate;
// Size of the population in each generation
int m_population_size;
double m_total_fitness;
double m_best_fitness;
double m_average_fitness;
// Generation counter
int m_generation;
// All genomes representing ANN's are held here
QVector<Genome> m_population;
//************ Member Functions *****************
/**
* @brief Picks out two cross over points in the list of neurons.
* The baby genome will receive neurons from mom in the region
* outside of the cross over points, while inside the crossover
* points baby will get dad's neurons.
* @param mom - genome
* @param dad - genome
* @return new genome which is a cross of mom and dad
*/
Genome cross_over(Genome& mom, Genome& dad);
void mutate(Genome& genome);
Genome& select_roulette();
void grab_N_best(int N, int copies, QVector<Genome>& population) const;
void calculate_stats();
void reset();
public:
GenAlg(double mutation_rate, double crossover_rate, int population_size);
QVector<Genome> epoch(QVector<Genome> prev_generation);
void increment_generation() { ++m_generation; }
double best_fitness() const { return m_best_fitness; }
double average_fitness() const { return m_average_fitness; }
int generation() const { return m_generation; }
};
#endif // GENALG