-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOrganism.cpp
More file actions
300 lines (244 loc) · 8.97 KB
/
Organism.cpp
File metadata and controls
300 lines (244 loc) · 8.97 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
/*
* File: Organism.cpp
* Author: d-savant
*
* Created on 20 September 2013, 9:55 PM
* The MIT License (MIT)
Copyright (c) 2013 korn101
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "Organism.h"
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <stdexcept>
using namespace std;
//Background:
//An organism is an object which contains chromosomes, chromosomes are made of genes which determine traits.
//This organism only has one chromosome. But it is fairly easy to implement a chromosome object and use an array to have multiple.
namespace {
const int kDefaultNoOfGenes = 2;
}
const float Organism::mutRate = 1.0f;
Organism::Organism() : noOfGenes(kDefaultNoOfGenes)
{
//first initialize chromosome.
//creation of an organisms chromosomes, assign genes to chromosome with genes being random integers of a seed.
//for the sake of pseudo-randomness we use a seed. (set in the main)
//allocate dynamic array of default chromosome length size.
chromosome = new binaryNumber[noOfGenes];
//determine number of possible integer values that can be represented:
int iRange = static_cast<int>(pow(2, binaryNumber::numBits));
//initialize genes to random values
for (int i = 0; i < noOfGenes; i++)
chromosome[i] = binaryNumber(rand() % iRange); // should be 10
}
Organism::Organism(int geneCount)
{
if (geneCount <= 0)
error("Gene count must be greater than zero.");
noOfGenes = geneCount;
chromosome = new binaryNumber[noOfGenes];
int iRange = static_cast<int>(pow(2, binaryNumber::numBits));
for (int i = 0; i < noOfGenes; i++)
chromosome[i] = binaryNumber(rand() % iRange);
}
Organism::Organism(int gene1, int gene2) : noOfGenes(2)
{
chromosome = new binaryNumber[noOfGenes];
//constructor that initializes an organism with the given integer representation of genes.
chromosome[0] = binaryNumber(gene1);
chromosome[1] = binaryNumber(gene2);
}
Organism::Organism(const int arr[], int count)
{
if (count <= 0)
error("Array-backed chromosome construction requires a positive count.");
noOfGenes = count;
chromosome = new binaryNumber[noOfGenes];
// now allocate genes:
for (int i = 0; i < noOfGenes; i++)
chromosome[i] = binaryNumber(arr[i]);
}
Organism::Organism(const Organism& other) : noOfGenes(other.noOfGenes)
{
chromosome = new binaryNumber[noOfGenes];
for (int i = 0; i < other.noOfGenes; i++)
chromosome[i] = other.chromosome[i];
}
Organism::Organism(string geneCode) // initialise an organism with a genetic code in form of a string.
{
if (geneCode.length() == 0 || geneCode.length() % binaryNumber::numBits != 0)
error("Chromosome genecode length must be a non-zero multiple of gene size.");
noOfGenes = geneCode.length() / binaryNumber::numBits;
chromosome = new binaryNumber[noOfGenes];
// The loop splits the chromosome string into fixed-size genes and validates each via binaryNumber(string).
for (int i = 0; i < noOfGenes; i++)
{
string gene = geneCode.substr(i * binaryNumber::numBits, binaryNumber::numBits);
chromosome[i] = binaryNumber(gene);
}
}
Organism::~Organism()
{
if (chromosome)
delete[] chromosome;
}
int Organism::getNoOfGenes() const
{
return noOfGenes;
}
int Organism::getMaxFitness() const
{
// return the total length of the chromosome. ie. 8 if 2 * 4bit genes.
return (binaryNumber::numBits * noOfGenes);
}
void Organism::mutate()
{
if (mutRate < 0.1 || mutRate > 100)
error("Organism mutation rate was set out of bounds");
// this function forces chance mutation determined by a determined probability (declared in the Organism header)
// iterate through the bits, generate a random number between 0-1000 and if it is 1, then perform a mutation/flip.
for (int i = 0; i < noOfGenes; i++)
for (int k = 0; k < binaryNumber::numBits; k++)
{
//check the probability:
int random = (rand() % 1000); //produce a number between 0-999
bool doMut = 0;
if (random <= mutRate * 10) // high mutation rate is 10 = 1%, low would be 1 which is = 0.1%
doMut = 1;
if (doMut == 1) //if the generated number is within probability
{
chromosome[i][k] = !chromosome[i][k]; // flip the bit, yo
}
}
}
void Organism::printChromosome() const
{
//iterate through genes and print them.
for (int i = 0; i < noOfGenes - 1; i++)
{
chromosome[i].print();
cout << SEPERATOR;
}
chromosome[noOfGenes - 1].print(); //simply prevents dangling '-' in print.
}
int compare(const Organism& first, const Organism& second)
{
// count number of shared bits, and return result:
int count = 0;
//check that organisms are of same chromosome lengths:
if (first.noOfGenes != second.noOfGenes)
{
throw runtime_error("Invalid comparison of differing organism chromosome lengths.");
}
else
{
for (int i = 0; i < first.noOfGenes; i++)
for (int k = 0; k < binaryNumber::numBits; k++)
if (first.chromosome[i][k] == second.chromosome[i][k])
++count;
}
return count;
}
void crossover(Organism& first, Organism& second)
{
Organism temp(first);
//Choose a random bit along the length of the chromosomes, and swap from that point.
int crossPoint = rand() % (first.noOfGenes * binaryNumber::numBits);
// note that crossPoint is an index! ie. 0-7 not 1-8.
//loop through crossing over up till the crossover point.
for (int i = 0; i <= crossPoint; i++) {
bool temp;
temp = first[i];
first[i] = second[i];
second[i] = temp;
}
// for the sake of diversity, say the crossover produces the same organism once again -> Then mutate it, just for diversity.
if ((compare(temp, first) == (binaryNumber::numBits * first.noOfGenes))) {
first.mutate();
}
}
void mate(Organism& first, Organism& second)
{
//the mate function mates two organisms.
//first, a genetic crossover is applied with the crossover() function.
//second, chance mutation is invoked with the mutate() function.
//the result being a replacement of the two passed organisms with their offspring.
crossover(first, second);
first.mutate();
second.mutate();
}
Organism reproduce(const Organism& first, const Organism& second)
{
Organism temp1(first);
Organism temp2(second);
mate(temp1, temp2);
int toRet = rand() % 2;
if (toRet == 0)
{
return (temp1);
}
else
{
return temp2;
}
}
void Organism::validateBitIndex(int index) const
{
int chromosomeSize = binaryNumber::numBits * noOfGenes;
if (index < 0 || index >= chromosomeSize)
error("Chromosome bit index out of bounds.");
}
bool& Organism::operator[](int index)
{
validateBitIndex(index);
int geneIndex = index / binaryNumber::numBits;
int bitIndex = index % binaryNumber::numBits;
return chromosome[geneIndex][bitIndex];
}
bool Organism::operator[](int index) const
{
validateBitIndex(index);
int geneIndex = index / binaryNumber::numBits;
int bitIndex = index % binaryNumber::numBits;
return chromosome[geneIndex][bitIndex];
}
Organism& Organism::operator=(const Organism& other)
{
if (this == &other)
return *this;
if (noOfGenes != other.noOfGenes)
{
delete[] chromosome;
noOfGenes = other.noOfGenes;
chromosome = new binaryNumber[noOfGenes];
}
for (int i = 0; i < other.noOfGenes; i++)
chromosome[i] = other.chromosome[i];
return *this;
}
void Organism::printDetails() const
{
cout << "No. of Genes: " << noOfGenes << endl;
cout << "Gene Size (bits): " << binaryNumber::numBits << endl;
cout << "Chromosome size (bits): " << noOfGenes * binaryNumber::numBits << endl;
cout << "Chromosome: ";
//iterate through genes and print them.
for (int i = 0; i < noOfGenes; i++)
chromosome[i].print();
cout << endl;
}