-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeneticAlgorithmClass.cpp
More file actions
373 lines (320 loc) · 11.3 KB
/
GeneticAlgorithmClass.cpp
File metadata and controls
373 lines (320 loc) · 11.3 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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// ************************************************************************ //
// Genetic Algorithm Class source code
// ************************************************************************ //
#include <iostream>
using namespace std;
#include <fstream>
#include <exception>
using std::fstream;
#include "ChromosomeClass.h"
#include "GeneticAlgorithmClass.h"
#include "GlobalConstants.h"
bool GeneticAlgorithmClass::initializePopulation(int &popSize,
ParameterClass ¶m)
{
while(popSize <= 0 || popSize > MAX_POPULATION)
{
cout << "ERROR: Population size invalid." << endl;
cout << "Input population size: ";
cin >> popSize;
}
populationSize = popSize;
population = new ChromosomeClass[populationSize];
int i; // counter for population
int g; // counter for genes
double *singleChromosome; // chromosome to be initialized
double *loBounds; // minimum values for this chromosome
double *upBounds; // maximum values for this chromosome
singleChromosome = new double[NUM_GENES];
loBounds = new double[NUM_GENES];
upBounds = new double[NUM_GENES];
// Define lower bounds for each gene
loBounds[LENGTH_INDEX] = param.getMinLength();
loBounds[BEAM_INDEX] = param.getMinBeam();
loBounds[DRAFT_INDEX] = param.getMinDraft();
loBounds[BLOCK_COEFF_INDEX] = MIN_BLOCK_COEFF;
// Define upper bounds for each gene
upBounds[LENGTH_INDEX] = param.getMaxLength();
upBounds[BEAM_INDEX] = param.getMaxBeam();
upBounds[DRAFT_INDEX] = param.getMaxDraft();
upBounds[BLOCK_COEFF_INDEX] = MAX_BLOCK_COEFF;
for(i = 0; i < populationSize; i++)
{
singleChromosome[LENGTH_INDEX] = chooseDouble(param.getMinLength(),
param.getMaxLength());
singleChromosome[BEAM_INDEX] = chooseDouble(param.getMinBeam(),
param.getMaxBeam());
singleChromosome[DRAFT_INDEX] = chooseDouble(param.getMinDraft(),
param.getMaxDraft());
singleChromosome[BLOCK_COEFF_INDEX] = chooseDouble(MIN_BLOCK_COEFF,
MAX_BLOCK_COEFF);
// create a chromosome using the random values and upper/lower bounds
population[i].setChromosome(singleChromosome,loBounds,upBounds);
}
return(1);
}
bool GeneticAlgorithmClass::setGenerations(int &gen)
{
while( gen < 0)
{
cout << "ERROR: Generations not valid." << endl;
cout << "Input number of generations: ";
cin >> gen;
}
if(gen > MAX_GENERATIONS)
{
cout << "ERROR: Generations exceeds maximum allowable." << endl
<< "Max allowed is: " << MAX_GENERATIONS << endl;
generations = MAX_GENERATIONS;
cout << "Number of generations set to: " << MAX_GENERATIONS << endl;
}
else
{
generations = gen;
}
return(1);
}
bool GeneticAlgorithmClass::setMutation(double &mutation)
{
while(mutation < 0 || mutation > MAX_MUTATION)
{
cout << "ERROR: Invalid Mutation Percentage." << endl;
cout << "Input Mutation Percent (0 to 0.1): ";
cin >> mutation;
}
mutationPct = mutation;
return(1);
}
bool GeneticAlgorithmClass::setCrossover(double &crossover)
{
while(crossover < 0 || crossover > MAX_CROSSOVER)
{
cout << "ERROR: Invalid Crossover Percentage." << endl;
cout << "Input Crossover Percent (0 to 1): ";
cin >> crossover;
}
crossoverPct = crossover;
return(1);
}
int GeneticAlgorithmClass::getPopSize() const
{
return(populationSize);
}
void GeneticAlgorithmClass::runGeneticAlgorithm(ParameterClass ¶meters)
{
cout.unsetf(ios::floatfield);
cout.setf(ios::showpoint);
cout.precision(1);
cout << fixed;
int i; // loop variable
bool stop = false; // stop variable for while-loop
int counter = 1; // count through the generations
int print = 0; // print to screen variable
ofstream outFile; // create a text file for output from the GA
string GAoutput = "GAoutput.txt";
outFile.open(GAoutput.c_str());
if(outFile.fail())
{
cout << "ERROR: Unable to open " << GAoutput << endl
<< "Populations will not be written to file." << endl;
}
else
{
cout << "Population will be printed to " << GAoutput << endl;
}
cout << "Print Populations To Screen? (1-yes, 2-no): ";
cin >> print;
while(!stop)
{
if(print == 1)
{
// Evaluate Fitness of Each Chromosome
cout << "*****************************************************"
<< endl << "Generation Number " << counter << endl;
for(i = 0; i < populationSize; i++)
{
population[i].calcFitness(parameters);
cout << "Member " << i+1
<< " L: " << population[i].getLength()
<< " B: " << population[i].getBeam()
<< " T: " << population[i].getDraft()
<< " Cb: "<< population[i].getBlockCoeff()
<< " Fitness: ";
cout.precision(4);
cout << population[i].getFitness() << endl;
cout.precision(1);
}
}
else
{
for(i = 0; i < populationSize; i++)
{
population[i].calcFitness(parameters);
}
}
for(i = 0; i < populationSize; i++) // write to text file each gen.
{
outFile << counter << " "
<< population[i].getLength() << " "
<< population[i].getBeam() << " "
<< population[i].getDraft() << " "
<< population[i].getBlockCoeff() << " "
<< population[i].getFitness() << "\n";
if(outFile.fail())
{
cout << "ERROR: Unable to write to " << GAoutput << endl
<< "Populations will not be written to file." << endl;
}
}
if(counter < generations) // Do not select/cross/mutate on the last round
{
selectionOp();
crossoverOp();
mutationOp();
}
if(counter == generations) // Check stopping conditions
{
stop = true;
}
counter++;
}
double bestIndividual = population[0].getFitness(); // fittest member
int bestIndex = 0; // track member #
for(i = 0; i < populationSize; i++)
{
if(population[i].getFitness() < bestIndividual)
{
bestIndividual = population[i].getFitness();
bestIndex = i;
}
}
cout << endl
<< "*****************************************************" << endl
<< "Best Individual is: " << endl
<< "Member " << bestIndex+1
<< " L: " << population[bestIndex].getLength()
<< " B: " << population[bestIndex].getBeam();
if(parameters.getHulls() == 2)
{
cout << " BOA: " << population[bestIndex].getLength()*0.3
+ population[bestIndex].getBeam();
}
cout << " T: " << population[bestIndex].getDraft()
<< " Cb: "<< population[bestIndex].getBlockCoeff()
<< " Fitness: ";
cout.precision(4);
cout << population[bestIndex].getFitness() << endl;
cout.precision(1);
cout << "Resistance (Newtons): " << getResistance(
population[bestIndex].getLength(),
population[bestIndex].getBeam(),
population[bestIndex].getDraft(),
population[bestIndex].getBlockCoeff(),
parameters.getVelocity(),
parameters.getHulls()) << endl
<< "Required Power (Horsepower): " << getResistance(
population[bestIndex].getLength(),
population[bestIndex].getBeam(),
population[bestIndex].getDraft(),
population[bestIndex].getBlockCoeff(),
parameters.getVelocity(),
parameters.getHulls())
*0.51444*parameters.getVelocity()
*0.001341*2 << endl;
outFile.close();
}
//Uses a Roulette Wheel Operator as a selection tool
void GeneticAlgorithmClass::selectionOp()
{
double popResistance[populationSize]; //resistance of each member of the
// population
double percentTotal[populationSize]; //individual percent of the of the
// total resistance
double cumulPercent[populationSize]; //cumualative percent of each
// individual
double cumulTotal = 0; //total percent
int i = 0; //counter integer
int j = 0; //counter integer
double randomPct = 0; //random percentage
double maxFitness = 0; // used for converting to minimization problem
for(i = 0; i < populationSize; i++) // determine the worst fitness value
{
if(population[i].getFitness() > maxFitness)
{
maxFitness = population[i].getFitness();
}
}
for(i = 0; i < populationSize; i++) // determine the cumulative %'s
{
popResistance[i] = population[i].getFitness() - maxFitness;
cumulTotal += popResistance[i];
}
for(i = 0; i < populationSize; i++) // determine % assigned to each member
{
percentTotal[i] = popResistance[i] / cumulTotal;
if( i == 0)
{
cumulPercent[i] = percentTotal[i];
}
else
{
cumulPercent[i] = percentTotal[i]+ cumulPercent[i-1];
}
}
// Used to store chromosomes that are selected for next generation
ChromosomeClass *TempPopulation;
TempPopulation = new ChromosomeClass[populationSize];
for(i = 0; i < populationSize; i++) // perform Roulette Wheel Selection
{
randomPct = getRand();
j = 0;
while(j < populationSize - 1 && randomPct > cumulPercent[j])
{
j++;
}
TempPopulation[i] = population[j];
}
for(i = 0; i < populationSize; i++)
{
population[i] = TempPopulation[i]; // Assign selected chromosomes
}
delete TempPopulation; // Free dynamically allocated memory
}
void GeneticAlgorithmClass::crossoverOp()
{
int i = 0; // loop variables
int j = 0;
int swapTo = 0; // choose which chromosome in pop. to swap with
for(i = 0; i < populationSize; i++)
{
swapTo = chooseInt(0, populationSize - 1);
while(swapTo == i) // make sure it doesnt swap with itself
{
swapTo = chooseInt(0, populationSize - 1);
}
ChromosomeClass temp = population[swapTo];
population[swapTo] = population[i];
population[i] = temp;
}
double numToCrossover = populationSize * crossoverPct;
numToCrossover = floor(numToCrossover / 2.0);// 2 parents => 1 cross
for(i = 0; i < numToCrossover; i++)
{
population[2*i].crossover(population[2*i+1]);
}
}
void GeneticAlgorithmClass::mutationOp()
{
int geneToMutate = chooseInt(0,3); // Choose gene 1 thru 4
int i = 0;
double mutateRand = 0;
for(i = 0; i < populationSize; i++)
{
mutateRand = getRand();
if(mutateRand <= mutationPct)
{
geneToMutate = chooseInt(0,NUM_GENES);
population[i].mutate(geneToMutate); // Mutate correct gene in chromosome
}
}
}