-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathga.c++
307 lines (266 loc) · 6.86 KB
/
ga.c++
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
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include "ga.h"
#undef NOISY
const long cMaxGen = 1000; // max # generations to try
int cBest; // how many fittest members to keep each gen.
const int MAXPOP = 1000; // maximum population
void* rgpop = NULL;
int cbMember = 0;
double zFitnessMax, zFitnessMin;
void (*GenerateRandom)(void* pv);
void (*MutateRandom)(void* pv, long cIter);
void (*Tweak)(void* pv);
double (*ComputeSuitability)(void* pv);
double suitability[MAXPOP];
int nexti[MAXPOP]; // Chain of indices into rgpop. (Valid members.)
int nextfast[MAXPOP];
inline int Rand(int x) { return random() % x; }
inline void* PvFromI(int i)
{ return (void*)((char *)rgpop + i * cbMember); }
void AllocPopulation(int cMember)
{ rgpop = calloc(cMember, cbMember); }
void FreePopulation(void)
{ free(rgpop); }
inline int fMembersEQ(int i, int j)
{ return memcmp(PvFromI(i), PvFromI(j), cbMember) == 0; }
void Breed(int c1, int c2, int p1, int p2)
{
long lMask;
int cbLeft = cbMember;
long* plc1 = (long*)PvFromI(c1);
long* plc2 = (long*)PvFromI(c2);
long* plp1 = (long*)PvFromI(p1);
long* plp2 = (long*)PvFromI(p2);
while (cbLeft > 0)
{
lMask = random();
*plc1++ = (*plp1 & lMask) | (*plp2 & ~lMask);
*plc2++ = (*plp2++ & lMask) | (*plp1++ & ~lMask);
cbLeft -= sizeof(long);
}
if (Tweak)
{
Tweak(PvFromI(c1));
Tweak(PvFromI(c2));
}
}
void NewMemberAt(int i)
{
GenerateRandom(PvFromI(i));
suitability[i] = 0.;
nexti[i] = -1;
}
void ProduceInitialMembers(int cInitPop)
{
for (int i = 0; i < cInitPop; i++)
NewMemberAt(i);
}
int iBestMember;
static int cFittest;
int RankAndCalculateFitness(int cPop, int cTopMost)
{
int i;
int c;
int bi;
double bv;
int iLast;
iBestMember = 0;
cFittest = cTopMost; // for next function's use
// cFittest should not be 0.
for(i = 0; i < cPop; i++)
nexti[i] = -1;
for(i = 0; i < cPop; i++)
{
suitability[i] = ComputeSuitability(PvFromI(i));
if (std::isnan(suitability[i])) {
printf("Corrupt suitability.\n");
return -1;
}
// optimization: cache retval of ComputeSuitability with a checksum on arg using cbMemberArg.
if (suitability[i] == zFitnessMax)
{
iBestMember = i;
return i; // a correct solution was found!
}
}
iLast = -1;
for (c = 0; c < cTopMost; c++)
{
bv = zFitnessMin; // best value
bi = -1; // best index
for (i = 0; i < cPop; i++) // find the next most suitable member
{
if (nexti[i] == -1 && suitability[i] > bv)
{
bv = suitability[i];
bi = i;
}
}
if (bi == -1)
{
cFittest = c;
if (cFittest == 0)
{
printf("\n\n\n\t\t\tcoredump imminent 1\n\n");
}
break;
}
if (iLast == -1) // if first one, remember that
iBestMember = bi;
else // else put member into list
nexti[iLast] = bi;
// if you want to count how many times it is in the top, here's where to do it
iLast = bi;
nexti[bi] = -2; // so you don't pick this one again
}
return -1;
}
// parents are chosen from the top individuals (ranked by previous function)
// all unranked members are replaced with new members
int BreedNewMembers(int cCurrPop, int cEndPop)
{
int i, j;
int n1, n2;
int c1, c2;
static int wCrud = 0;
LRestart:
for (i = cCurrPop; i < cEndPop; i++)
nexti[i] = -1;
// find duplicates, set suitability to -1
// this is expensive, so do it rarely.
if (++wCrud > 7)
{
wCrud = 0;
int cCrud = 0;
for (i = 0; i < cCurrPop; i++)
{
if (suitability[i] != zFitnessMin)
for (j = i+1; j < cCurrPop; j++)
{
if (fMembersEQ(i, j))
{
suitability[i] = zFitnessMin;
break;
}
}
if (suitability[i] == zFitnessMin)
cCrud++;
}
// For all members with suitability == -1, generate a new random member.
// NewMemberAt() cuts the nexti[] chain, forcing a RankAndCalculateFitness(),
// so do this only if there's a lot of crud (suitability == -1).
if (cCrud > cCurrPop / 5)
{
#ifdef NOISY
printf("decrud %d ", cCrud);
#endif
for (i = 0; i < cCurrPop; i++)
if (suitability[i] == zFitnessMin)
NewMemberAt(i);
(void)RankAndCalculateFitness(cCurrPop, cBest);
goto LRestart;
}
}
j = iBestMember;
for (i = 0; i < cFittest; i++)
{
nextfast[i] = j;
j = nexti[j];
}
c1 = -1;
for (i = 0; i < cEndPop; i++)
{
if (nexti[i] != -1) // skip who we're going to keep
continue;
if (c1 == -1) // find two places for new children
{
c1 = i;
continue;
}
c2 = i;
n1 = Rand(cFittest);
do n2 = Rand(cFittest);
while (n2 == n1);
Breed(c1, c2, nextfast[n1], nextfast[n2]);
c1 = -1; // to find two new children
}
return cEndPop;
}
void Mutate(int count, int cPop, long cIter)
{
for (int i = 0; i < count; i++)
{
// make one mutation in the list
MutateRandom(PvFromI(Rand(cPop)), cIter);
}
}
// Caller free()s the return value.
void* GA(
int cbMemberArg,
void (*pfnGenerateRandom)(void* pv),
void (*pfnMutateRandom)(void* pv, long cIter),
void (*pfnTweak)(void* pv),
double (*pfnComputeSuitability)(void* pv),
double zSuitabilityMaxArg,
int cBestArg,
double tMaxSec
)
{
using namespace std::chrono;
const auto tQuit = system_clock::now() + microseconds(long(tMaxSec * 1e6));
cbMember = cbMemberArg;
if (cbMember % sizeof(long) != 0)
{
// round up cbMember to nearest long.
cbMember += sizeof(long) - (cbMember % sizeof(long));
}
GenerateRandom = pfnGenerateRandom;
MutateRandom = pfnMutateRandom;
Tweak = pfnTweak;
ComputeSuitability = pfnComputeSuitability;
zFitnessMax = zSuitabilityMaxArg;
zFitnessMin = -std::numeric_limits<double>::max();
double BestSuitEver = zFitnessMin;
cBest = cBestArg;
AllocPopulation(MAXPOP);
srandom(42);
int cPopulation = MAXPOP;
ProduceInitialMembers(cPopulation);
int iSolution = RankAndCalculateFitness(cPopulation, cBest);
#ifdef NOISY
if (iSolution != -1)
printf("found it right away.\n");
#endif
const auto pbBuf = malloc(cbMember);
long cIter = 0L;
while(iSolution == -1 && cIter <= cMaxGen)
{
cIter++;
cBest = (int)(cBestArg / (1 + sqrt((double)cIter+5.)*.08));
cPopulation = BreedNewMembers(cPopulation, MAXPOP);
Mutate((int)(cBest * .4), MAXPOP, cIter);
iSolution = RankAndCalculateFitness(cPopulation, cBest);
if (suitability[iBestMember] > BestSuitEver)
{
BestSuitEver = suitability[iBestMember];
#ifdef NOISY
printf("\n\tbest: %.3g ", zFitnessMax-BestSuitEver);
#endif
memcpy(pbBuf, PvFromI(iBestMember), cbMember);
}
if (system_clock::now() > tQuit)
{
#ifdef NOISY
printf("\ntimeout\n");
#endif
break;
}
}
FreePopulation();
return pbBuf;
}