-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.cc
executable file
·97 lines (77 loc) · 1.87 KB
/
engine.cc
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
/*****************************************************************
** SGAL Simple Genetic Algorithm Library
**
** Copyright (c) 1995, Neal A. Sanche
*****************************************************************/
#include <iostream>
#include "pRandom.h"
#include "engine.h"
CEngine::CEngine (int poolsize, int chromlen, double scalefactor)
{
nGenerations = 0;
nChildren = 0;
pool = new CPool(poolsize, chromlen, scalefactor);
opSel = 0;
opMutate = 0;
opCross = 0;
}
CEngine::~CEngine()
{
delete pool;
}
void CEngine::Generation()
{
// Check if we've got all our operators
if (opSel && opMutate && opCross) {
CPool newpool(*pool); // Create a new pool
opSel->Preselect(*pool); // Do preselection
for (int i = 0; i < pool->GetPoolSize(); i += 2) {
CChromosomeBase &child1 = newpool[i];
CChromosomeBase &child2 = newpool[i+1];
child1 = opSel->Select(*pool);
child2 = opSel->Select(*pool);
// Mutate and crossover
opCross->Crossover(child1, child2);
opMutate->Mutate(child1);
opMutate->Mutate(child2);
nChildren += 2;
}
// Be an elitist
int loc = Random.uniform_int(0,pool->GetPoolSize()-1);
newpool[loc] = pool->GetBest();
newpool.CalcPoolFitness(); // Do fitness calculations
*pool = newpool; // Copy the new pool back
nGenerations++;
}
else {
std::cerr << "void CEngine::Generation() not enough operators" << std::endl;
}
}
CPool &CEngine::GetPool()
{
return *pool;
}
COperator &CEngine::GetSelectionOp()
{
return *opSel;
}
COperator &CEngine::GetMutateOp()
{
return *opMutate;
}
COperator &CEngine::GetCrossoverOp()
{
return *opCross;
}
void CEngine::SetSelectionOp(COpSelect &select)
{
opSel = &select;
}
void CEngine::SetMutateOp(COpMutate &mutate)
{
opMutate = &mutate;
}
void CEngine::SetCrossoverOp(COpCrossover &cross)
{
opCross = ✗
}