-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGeneticAlgorithm.h
211 lines (192 loc) · 7.21 KB
/
GeneticAlgorithm.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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#pragma once
#include <vector>
#include "BackpackObject.h"
#include "RandomObjectsSelector.h"
#include "StartPopulation.h"
#include "Selection.h"
#include "ParentSelector.h"
#include "Crossover.h"
#include "Mutation.h"
#include "NextGenerationGenerator.h"
#include "GenotypeModificationLimitationProcessing.h"
typedef vector<costvalue> costvector;
typedef vector<weightvalue> weightvector;
//typedef vector<BackpackObject> ObjectVector;
using namespace std;
class GeneticAlgorithm
{
vector<ByteVector> GenerateStartPopulation(ObjectVector objectsVector,weightvalue maxWeight) {
vector<ByteVector> startPopulation;
RandomObjectsSelector<AbstractStartPopulationGenerator> generator = RandomObjectsSelector<AbstractStartPopulationGenerator>({
new DancigStartPopulationGenerator(maxWeight),
new RandomStartPopulationGenerator(maxWeight,rand()) });
for (size_t i = 0; i < populationSize; i++)
{
startPopulation.push_back(generator.getRandomObject().Generate(objectsVector));
}
return startPopulation;
}
void printVectorList(vector<ByteVector> list, function funcFitness) {
for (ByteVector vect : list) {
clog << vect <<" weight:"<<funcFitness.calculateWeight(vect) <<" fitness:" << funcFitness.calculateFitness(vect) << endl;
}
}
vector<ByteVector> GenerateChilds(vector<ByteVector> parents, function func){
//Ñãåíåðèðóåì äåòåé ðàçíûìè ñïîñîáàìè
RandomObjectsSelector<AbstractParentSelector> pairParentGenerator = RandomObjectsSelector<AbstractParentSelector>(
{new InbridingParentSelector(),
new OutbridParentSelector(),
new PossibleAssociableParentSelector(func)
});
//Ïðèìåíèì êðîññîâåð äëÿ ïîëó÷åíèÿ ïîòîìêîâ
vector<ByteVector> childs;
int byteLen = parents.at(0).getLen();
RandomObjectsSelector<AbstractCrossover> crossoverGenerator = RandomObjectsSelector<AbstractCrossover>(
{ new OnePointCrossover(),
new TwoPointCrossover((rand() % (byteLen / 2)) + 1),
new RandomCrossover()
});
//Ñãåíåðèðóåì ïàðû ðîäèòåëåé
vector<BytePair> parentPairs;
//clog << "parents" << endl;
for (size_t i = 0; i < childsSize; i++)
{
BytePair parentPair = pairParentGenerator.getRandomObject().SelectParents(parents);
ByteVector child(byteLen);
if (rand() % 2 == 1) {
child = crossoverGenerator.getRandomObject().Crossover(parentPair.first, parentPair.second);
}
else
{
child = crossoverGenerator.getRandomObject().Crossover(parentPair.second, parentPair.first);
}
childs.push_back(child);
// clog << "p:" << endl;
// clog << parentPair.first << endl << parentPair.second << endl;
// clog << "c:"<<endl << child << endl;
}
return childs;
}
vector<ByteVector> GenerateMutants(vector<ByteVector> vectors) {
int byteLen = vectors.at(0).getLen();
RandomObjectsSelector<AbstractMutation> mutantGenerator = RandomObjectsSelector<AbstractMutation>(
{new GeneticPointMutation(),
new InversionMutation(byteLen / 2 + 1),
new ByteInversionMutation(byteLen / 1.5 + 1)
});
vector<ByteVector> mutants;
//clog << "mutants" << endl;
for(ByteVector vect:vectors){
// clog << "n:" << vect << endl;
ByteVector mutant = mutantGenerator.getRandomObject().Mutate(vect);
mutants.push_back(mutant);
// clog << "m:" << mutant << endl;
}
return mutants;
}
ByteVector findMaxInList(vector<ByteVector> list, function funcFitness) {
ByteVector maxVector = list.at(0);
funcvalue maxValue = funcFitness.calculateFitness(maxVector);
for (ByteVector vect : list) {
funcvalue value = funcFitness.calculateFitness(vect);
if (value>maxValue) {
maxValue = value;
maxVector = vect;
}
}
return maxVector;
}
bool VectorIsUnique(vector<ByteVector> vectors) {
ByteVector checkVector = vectors.at(0);
for (ByteVector vector : vectors) {
if (vector != checkVector)return true;
}
return false;
}
int populationSize;
int childsSize;
int mutantSize;
float nextGenerationOverlapCoef;
float cForSelection;
const int steps;
public:
GeneticAlgorithm(int populationSize,int maxsteps):populationSize(populationSize),steps(maxsteps) {
childsSize = populationSize * 15;
mutantSize = 0.25*childsSize;
nextGenerationOverlapCoef = 1.f / 3.f;
cForSelection = 2;
}
ByteVector find(vector<BackpackObject> objectsVector, weightvalue maxWeight) {
ObjectVector convertedVector;
for (size_t i = 0; i < objectsVector.size(); i++)
{
convertedVector.push_back(IndexedBackpackObject(i, objectsVector[i]));
clog << i << " weight:" << objectsVector[i].weight << " cost:" << objectsVector[i].cost << endl;
}
return find(convertedVector, maxWeight);
}
ByteVector find(ObjectVector objectsVector,weightvalue maxWeight) {
//Ãåíåðàòîð ñëåäóþùåãî ïîêîëåíèÿ
//Íàøà ôóíêöèÿ ïðèñïîñîáëåííîñòè
function funcFitness = function(objectsVector);
//Ñåëåêöèÿ
//ProportionalSelection selection = ProportionalSelection(funcFitness, cForSelection);
NextGenerationGenerator nextGenerationGenerator = NextGenerationGenerator(nextGenerationOverlapCoef, funcFitness);
//Ñãåíåðèðóåì íà÷àëüíóþ ïîïóëÿöèþ
vector<ByteVector> currentPopulation = GenerateStartPopulation(objectsVector, maxWeight);
clog << "Start population" << endl;
printVectorList(currentPopulation, funcFitness);
clog << endl;
cout << "Generations" << endl;
for (size_t i = 0; i < steps; i++)
{
{
ByteVector max = findMaxInList(currentPopulation, funcFitness);
cout << i << " generation, max element: " << max << " cost: " << funcFitness.calculateFitness(max) << " weight: " << funcFitness.calculateWeight(max) << endl;
}
if (!VectorIsUnique(currentPopulation)) {
cout << "Population is not unique" << endl;
break; }
vector<ByteVector> childs = GenerateChilds(currentPopulation,funcFitness);
//Âûáåðåì ïîòîìêîâ äëÿ ìóòèðîâàíèÿ
vector<ByteVector> childsForMutation;
for (size_t i = 0; i < mutantSize; i++)
{
int randomIndex = rand() % childs.size();
childsForMutation.push_back(childs.at(randomIndex));
childs.erase(childs.begin() + randomIndex);
}
vector<ByteVector> mutants = GenerateMutants(childsForMutation);
GenotypeModificationLimitationProcessing LimitationProcessor = GenotypeModificationLimitationProcessing(objectsVector, maxWeight);
//Ïðåîáðàçóåì äî äîïóñòèìûõ
/*
clog << "before Childs" << endl;
printVectorList(childs, funcFitness);
clog << "before Mutants" << endl;
printVectorList(mutants, funcFitness);*/
for (size_t i = 0; i < childs.size(); i++)
{
childs[i] = LimitationProcessor.ModifyToAllowed(childs[i]);
}
for (size_t i = 0; i < mutants.size(); i++)
{
mutants[i] = LimitationProcessor.ModifyToAllowed(mutants[i]);
}
/*
clog << "after Childs" << endl;
printVectorList(childs, funcFitness);
clog << "after Mutants" << endl;
printVectorList(mutants, funcFitness);*/
currentPopulation = nextGenerationGenerator.GenerateNextGeneration(currentPopulation, childs, mutants);
clog << "Current population for "<<i+1<<" generation" << endl;
printVectorList(currentPopulation, funcFitness);
clog << endl;
}
{
ByteVector max = findMaxInList(currentPopulation, funcFitness);
cout <<"Max element: " << max << " cost: " << funcFitness.calculateFitness(max) << " weight: " << funcFitness.calculateWeight(max) << endl;
}
return findMaxInList(currentPopulation, funcFitness);
}
~GeneticAlgorithm();
};