-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCga.cpp
More file actions
890 lines (708 loc) · 24.2 KB
/
Cga.cpp
File metadata and controls
890 lines (708 loc) · 24.2 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
#include "Cga.h"
//-------------------------------------------------------------------------
// this constructor creates a base genome from supplied values and creates
// a population of 'size' similar (same topology, varying weights) genomes
//-------------------------------------------------------------------------
Cga::Cga(int size,
int inputs,
int outputs):m_iPopSize(size),
m_iGeneration(0),
m_pInnovation(NULL),
m_iNextGenomeID(0),
m_iNextSpeciesID(0),
m_iFittestGenome(0),
m_dBestEverFitness(0),
m_dTotFitAdj(0),
m_dAvFitAdj(0)
{
//create the population of genomes
for (int i=0; i<m_iPopSize; ++i)
{
m_vecGenomes.push_back(CGenome(m_iNextGenomeID++, inputs, outputs));
}
//create the innovation list. First create a minimal genome
CGenome genome(1, inputs, outputs);
//create the innovations
m_pInnovation = new CInnovation(genome.LinkGenes(), genome.NeuronGenes());
//create the network depth lookup table
vecSplits = Split(0, 1, 0);
}
//------------------------------------- dtor -----------------------------
//
//------------------------------------------------------------------------
Cga::~Cga()
{
if (m_pInnovation)
{
delete m_pInnovation;
m_pInnovation = NULL;
}
}
//-------------------------------CreatePhenotypes-------------------------
//
// cycles through all the members of the population and creates their
// phenotypes. Returns a vector containing pointers to the new phenotypes
//-------------------------------------------------------------------------
vector<CNeuralNet*> Cga::CreatePhenotypes()
{
vector<CNeuralNet*> networks;
for (int i=0; i<m_iPopSize; i++)
{
//calculate max network depth
CalculateNetDepth(m_vecGenomes[i]);
//create new phenotype
CNeuralNet* net = m_vecGenomes[i].CreatePhenotype();
networks.push_back(net);
}
return networks;
}
//-------------------------- CalculateNetDepth ---------------------------
//
// searches the lookup table for the dSplitY value of each node in the
// genome and returns the depth of the network based on this figure
//------------------------------------------------------------------------
void Cga::CalculateNetDepth(CGenome &gen)
{
int MaxSoFar = 0;
for (int nd=0; nd<gen.NumNeurons(); ++nd)
{
for (int i=0; i<vecSplits.size(); ++i)
{
if ((gen.SplitY(nd) == vecSplits[i].val) &&
(vecSplits[i].depth > MaxSoFar))
{
MaxSoFar = vecSplits[i].depth;
}
}
}
gen.SetDepth(MaxSoFar+2);
}
//-----------------------------------AddNeuronID----------------------------
//
// just checks to see if a node ID has already been added to a vector of
// nodes. If not then the new ID gets added. Used in Crossover.
//------------------------------------------------------------------------
void Cga::AddNeuronID(const int nodeID, vector<int> &vec)
{
for (int i=0; i<vec.size(); i++)
{
if (vec[i] == nodeID)
{
//already added
return;
}
}
vec.push_back(nodeID);
return;
}
//------------------------------------- Epoch ----------------------------
//
// This function performs one epoch of the genetic algorithm and returns
// a vector of pointers to the new phenotypes
//------------------------------------------------------------------------
vector<CNeuralNet*> Cga::Epoch(const vector<double> &FitnessScores)
{
//first check to make sure we have the correct amount of fitness scores
if (FitnessScores.size() != m_vecGenomes.size())
{
string s = "scores="+itos(FitnessScores.size())+"/gens="+itos(m_vecGenomes.size());
MessageBox(NULL,s.c_str(),"Error", MB_OK);
}
//reset appropriate values and kill off the existing phenotypes and
//any poorly performing species
ResetAndKill();
//update the genomes with the fitnesses scored in the last run
for (int gen=0; gen<m_vecGenomes.size(); ++gen)
{
m_vecGenomes[gen].SetFitness(FitnessScores[gen]);
}
//sort genomes and keep a record of the best performers
SortAndRecord();
//separate the population into species of similar topology, adjust
//fitnesses and calculate spawn levels
SpeciateAndCalculateSpawnLevels();
/* uncomment the following if you want to output the species info to a filename */
//SpeciesDump("dbg_SpeciesDump.txt");
/* uncomment the following if you want to output the innovation info to a filename */
//m_pInnovation->Write("dbg_Innovations.txt", m_iGeneration);
/* uncomment the following if you want to output the best genome this generation
to a filename */
//WriteGenome("dbg_BestGenome.txt", m_iFittestGenome);
//this will hold the new population of genomes
vector<CGenome> NewPop;
//request the offspring from each species. The number of children to
//spawn is a double which we need to convert to an int.
int NumSpawnedSoFar = 0;
CGenome baby;
//now to iterate through each species selecting offspring to be mated and
//mutated
for (int spc=0; spc<m_vecSpecies.size(); ++spc)
{
//because of the number to spawn from each species is a double
//rounded up or down to an integer it is possible to get an overflow
//of genomes spawned. This statement just makes sure that doesn't
//happen
if (NumSpawnedSoFar < CParams::iPopSize)
{
//this is the amount of offspring this species is required to
// spawn. Rounded simply rounds the double up or down.
int NumToSpawn = Rounded(m_vecSpecies[spc].NumToSpawn());
bool bChosenBestYet = false;
while (NumToSpawn--)
{
//first grab the best performing genome from this species and transfer
//to the new population without mutation. This provides per species
//elitism
if (!bChosenBestYet)
{
baby = m_vecSpecies[spc].Leader();
bChosenBestYet = true;
}
else
{
//if the number of individuals in this species is only one
//then we can only perform mutation
if (m_vecSpecies[spc].NumMembers() == 1)
{
//spawn a child
baby = m_vecSpecies[spc].Spawn();
}
//if greater than one we can use the crossover operator
else
{
//spawn1
CGenome g1 = m_vecSpecies[spc].Spawn();
if (RandFloat() < CParams::dCrossoverRate)
{
//spawn2, make sure it's not the same as g1
CGenome g2 = m_vecSpecies[spc].Spawn();
//number of attempts at finding a different genome
int NumAttempts = 5;
while ( (g1.ID() == g2.ID()) && (NumAttempts--) )
{
g2 = m_vecSpecies[spc].Spawn();
}
if (g1.ID() != g2.ID())
{
baby = Crossover(g1, g2);
}
}
else
{
baby = g1;
}
}
//give the offspring its own ID
++m_iNextGenomeID;
baby.SetID(m_iNextGenomeID);
//now we have a spawned child lets mutate it! First there is the
//chance a neuron may be added
if (baby.NumNeurons() < CParams::iMaxPermittedNeurons)
{
baby.AddNeuron(CParams::dChanceAddNode,
*m_pInnovation,
CParams::iNumTrysToFindOldLink);
}
//now there's the chance a link may be added
baby.AddLink(CParams::dChanceAddLink,
CParams::dChanceAddRecurrentLink,
*m_pInnovation,
CParams::iNumTrysToFindLoopedLink,
CParams::iNumAddLinkAttempts);
//mutate the weights
baby.MutateWeights(CParams::dMutationRate,
CParams::dProbabilityWeightReplaced,
CParams::dMaxWeightPerturbation);
baby.MutateActivationResponse(CParams::dActivationMutationRate,
CParams::dMaxActivationPerturbation);
}
//sort the baby's genes by their innovation numbers
baby.SortGenes();
//add to new pop
NewPop.push_back(baby);
++NumSpawnedSoFar;
if (NumSpawnedSoFar == CParams::iPopSize)
{
NumToSpawn = 0;
}
}//end while
}//end if
}//next species
//if there is an underflow due to the rounding error and the amount
//of offspring falls short of the population size additional children
//need to be created and added to the new population. This is achieved
//simply, by using tournament selection over the entire population.
if (NumSpawnedSoFar < CParams::iPopSize)
{
//calculate amount of additional children required
int Rqd = CParams::iPopSize - NumSpawnedSoFar;
//grab them
while (Rqd--)
{
NewPop.push_back(TournamentSelection(m_iPopSize/5));
}
}
//replace the current population with the new one
m_vecGenomes = NewPop;
//create the new phenotypes
vector<CNeuralNet*> new_phenotypes;
for (int gen=0; gen<m_vecGenomes.size(); ++gen)
{
//calculate max network depth
CalculateNetDepth(m_vecGenomes[gen]);
CNeuralNet* phenotype = m_vecGenomes[gen].CreatePhenotype();
new_phenotypes.push_back(phenotype);
}
//increase generation counter
++m_iGeneration;
return new_phenotypes;
}
//--------------------------- SortAndRecord-------------------------------
//
// sorts the population into descending fitness, keeps a record of the
// best n genomes and updates any fitness statistics accordingly
//------------------------------------------------------------------------
void Cga::SortAndRecord()
{
//sort the genomes according to their unadjusted (no fitness sharing)
//fitnesses
sort(m_vecGenomes.begin(), m_vecGenomes.end());
//is the best genome this generation the best ever?
if (m_vecGenomes[0].Fitness() > m_dBestEverFitness)
{
m_dBestEverFitness = m_vecGenomes[0].Fitness();
}
//keep a record of the n best genomes
StoreBestGenomes();
}
//----------------------------- StoreBestGenomes -------------------------
//
// used to keep a record of the previous populations best genomes so that
// they can be displayed if required.
//------------------------------------------------------------------------
void Cga::StoreBestGenomes()
{
//clear old record
m_vecBestGenomes.clear();
for (int gen=0; gen<CParams::iNumBestSweepers; ++gen)
{
m_vecBestGenomes.push_back(m_vecGenomes[gen]);
}
}
//----------------- GetBestPhenotypesFromLastGeneration ------------------
//
// returns a std::vector of the n best phenotypes from the previous
// generation
//------------------------------------------------------------------------
vector<CNeuralNet*> Cga::GetBestPhenotypesFromLastGeneration()
{
vector<CNeuralNet*> brains;
for (int gen=0; gen<m_vecBestGenomes.size(); ++gen)
{
//calculate max network depth
CalculateNetDepth(m_vecBestGenomes[gen]);
brains.push_back(m_vecBestGenomes[gen].CreatePhenotype());
}
return brains;
}
//--------------------------- AdjustSpecies ------------------------------
//
// this functions simply iterates through each species and calls
// AdjustFitness for each species
//------------------------------------------------------------------------
void Cga::AdjustSpeciesFitnesses()
{
for (int sp=0; sp<m_vecSpecies.size(); ++sp)
{
m_vecSpecies[sp].AdjustFitnesses();
}
}
//------------------ SpeciateAndCalculateSpawnLevels ---------------------
//
// separates each individual into its respective species by calculating
// a compatibility score with every other member of the population and
// niching accordingly. The function then adjusts the fitness scores of
// each individual by species age and by sharing and also determines
// how many offspring each individual should spawn.
//------------------------------------------------------------------------
void Cga::SpeciateAndCalculateSpawnLevels()
{
bool bAdded = false;
//try to keep the number of species below the maximum if user has specified
//a iMaxNumberOfSpecies in params.ini.
AdjustCompatibilityThreshold();
//iterate through each genome and speciate
for (int gen=0; gen<m_vecGenomes.size(); ++gen)
{
//calculate its compatibility score with each species leader. If
//compatible add to species. If not, create a new species
for (int spc=0; spc<m_vecSpecies.size(); ++spc)
{
double compatibility = m_vecGenomes[gen].GetCompatibilityScore(m_vecSpecies[spc].Leader());
//if this individual is similar to this species add to species
if (compatibility <= CParams::dCompatibilityThreshold)
{
m_vecSpecies[spc].AddMember(m_vecGenomes[gen]);
//let the genome know which species it's in
m_vecGenomes[gen].SetSpecies(m_vecSpecies[spc].ID());
bAdded = true;
break;
}
}
if (!bAdded)
{
//we have not found a compatible species so let's create a new one
m_vecSpecies.push_back(CSpecies(m_vecGenomes[gen], m_iNextSpeciesID++));
}
bAdded = false;
}
//now all the genomes have been assigned a species the fitness scores
//need to be adjusted to take into account sharing and species age.
AdjustSpeciesFitnesses();
//calculate new adjusted total & average fitness for the population
for (int gen=0; gen<m_vecGenomes.size(); ++gen)
{
m_dTotFitAdj += m_vecGenomes[gen].GetAdjFitness();
}
m_dAvFitAdj = m_dTotFitAdj/m_vecGenomes.size();
//calculate how many offspring each member of the population
//should spawn
for (int gen=0; gen<m_vecGenomes.size(); ++gen)
{
double ToSpawn = m_vecGenomes[gen].GetAdjFitness() / m_dAvFitAdj;
m_vecGenomes[gen].SetAmountToSpawn(ToSpawn);
}
//iterate through all the species and calculate how many offspring
//each species should spawn
for (int spc=0; spc<m_vecSpecies.size(); ++spc)
{
m_vecSpecies[spc].CalculateSpawnAmount();
}
}
//--------------------- AdjustCompatibilityThreshold ---------------------
//
// this automatically adjusts the compatibility threshold in an attempt
// to keep the number of species below a maximum
//------------------------------------------------------------------------
void Cga::AdjustCompatibilityThreshold()
{
//if iMaxNumberOfSpecies < 1 then the user has effectively
//switched this feature off.
if (CParams::iMaxNumberOfSpecies < 1) return;
const double ThresholdIncrement = 0.01;
if (m_vecSpecies.size() > CParams::iMaxNumberOfSpecies)
{
CParams::dCompatibilityThreshold += ThresholdIncrement;
}
else if (m_vecSpecies.size() < 2)
{
CParams::dCompatibilityThreshold -= ThresholdIncrement;
}
return;
}
//--------------------------- TournamentSelection ------------------------
//
//------------------------------------------------------------------------
CGenome Cga::TournamentSelection(const int NumComparisons)
{
double BestFitnessSoFar = 0;
int ChosenOne = 0;
//Select NumComparisons members from the population at random testing
//against the best found so far
for (int i=0; i<NumComparisons; ++i)
{
int ThisTry = RandInt(0, m_vecGenomes.size()-1);
if (m_vecGenomes[ThisTry].Fitness() > BestFitnessSoFar)
{
ChosenOne = ThisTry;
BestFitnessSoFar = m_vecGenomes[ThisTry].Fitness();
}
}
//return the champion
return m_vecGenomes[ChosenOne];
}
//-----------------------------------Crossover----------------------------
//
//------------------------------------------------------------------------
CGenome Cga::Crossover(CGenome& mum, CGenome& dad)
{
//helps make the code clearer
enum parent_type{MUM, DAD,};
//first, calculate the genome we will using the disjoint/excess
//genes from. This is the fittest genome.
parent_type best;
//if they are of equal fitness use the shorter (because we want to keep
//the networks as small as possible)
if (mum.Fitness() == dad.Fitness())
{
//if they are of equal fitness and length just choose one at
//random
if (mum.NumGenes() == dad.NumGenes())
{
best = (parent_type)RandInt(0, 1);
}
else
{
if (mum.NumGenes() < dad.NumGenes())
{
best = MUM;
}
else
{
best = DAD;
}
}
}
else
{
if (mum.Fitness() > dad.Fitness())
{
best = MUM;
}
else
{
best = DAD;
}
}
//these vectors will hold the offspring's nodes and genes
vector<SNeuronGene> BabyNeurons;
vector<SLinkGene> BabyGenes;
//temporary vector to store all added node IDs
vector<int> vecNeurons;
//create iterators so we can step through each parents genes and set
//them to the first gene of each parent
vector<SLinkGene>::iterator curMum = mum.StartOfGenes();
vector<SLinkGene>::iterator curDad = dad.StartOfGenes();
//this will hold a copy of the gene we wish to add at each step
SLinkGene SelectedGene;
//step through each parents genes until we reach the end of both
while (!((curMum == mum.EndOfGenes()) && (curDad == dad.EndOfGenes())))
{
//the end of mum's genes have been reached
if ((curMum == mum.EndOfGenes())&&(curDad != dad.EndOfGenes()))
{
//if dad is fittest
if (best == DAD)
{
//add dads genes
SelectedGene = *curDad;
}
//move onto dad's next gene
++curDad;
}
//the end of dads's genes have been reached
else if ( (curDad == dad.EndOfGenes()) && (curMum != mum.EndOfGenes()))
{
//if mum is fittest
if (best == MUM)
{
//add mums genes
SelectedGene = *curMum;
}
//move onto mum's next gene
++curMum;
}
//if mums innovation number is less than dads
else if (curMum->InnovationID < curDad->InnovationID)
{
//if mum is fittest add gene
if (best == MUM)
{
SelectedGene = *curMum;
}
//move onto mum's next gene
++curMum;
}
//if dads innovation number is less than mums
else if (curDad->InnovationID < curMum->InnovationID)
{
//if dad is fittest add gene
if (best = DAD)
{
SelectedGene = *curDad;
}
//move onto dad's next gene
++curDad;
}
//if innovation numbers are the same
else if (curDad->InnovationID == curMum->InnovationID)
{
//grab a gene from either parent
if (RandFloat() < 0.5f)
{
SelectedGene = *curMum;
}
else
{
SelectedGene = *curDad;
}
//move onto next gene of each parent
++curMum;
++curDad;
}
//add the selected gene if not already added
if (BabyGenes.size() == 0)
{
BabyGenes.push_back(SelectedGene);
}
else
{
if (BabyGenes[BabyGenes.size()-1].InnovationID !=
SelectedGene.InnovationID)
{
BabyGenes.push_back(SelectedGene);
}
}
//Check if we already have the nodes referred to in SelectedGene.
//If not, they need to be added.
AddNeuronID(SelectedGene.FromNeuron, vecNeurons);
AddNeuronID(SelectedGene.ToNeuron, vecNeurons);
}//end while
//now create the required nodes. First sort them into order
sort(vecNeurons.begin(), vecNeurons.end());
for (int i=0; i<vecNeurons.size(); i++)
{
BabyNeurons.push_back(m_pInnovation->CreateNeuronFromID(vecNeurons[i]));
}
//finally, create the genome
CGenome babyGenome(m_iNextGenomeID++,
BabyNeurons,
BabyGenes,
mum.NumInputs(),
mum.NumOutputs());
return babyGenome;
}
//--------------------------- ResetAndKill -------------------------------
//
// This function resets some values ready for the next epoch, kills off
// all the phenotypes and any poorly performing species.
//------------------------------------------------------------------------
void Cga::ResetAndKill()
{
m_dTotFitAdj = 0;
m_dAvFitAdj = 0;
//purge the species
vector<CSpecies>::iterator curSp = m_vecSpecies.begin();
while (curSp != m_vecSpecies.end())
{
curSp->Purge();
//kill off species if not improving and if not the species which contains
//the best genome found so far
if ( (curSp->GensNoImprovement() > CParams::iNumGensAllowedNoImprovement) &&
(curSp->BestFitness() < m_dBestEverFitness) )
{
curSp = m_vecSpecies.erase(curSp);
--curSp;
}
++curSp;
}
//we can also delete the phenotypes
for (int gen=0; gen<m_vecGenomes.size(); ++gen)
{
m_vecGenomes[gen].DeletePhenotype();
}
}
//------------------------------- Split ----------------------------------
//
// this function is used to create a lookup table that is used to
// calculate the depth of the network.
//------------------------------------------------------------------------
vector<SplitDepth> Cga::Split(double low, double high, int depth)
{
static vector<SplitDepth> vecSplits;
double span = high-low;
vecSplits.push_back(SplitDepth(low + span/2, depth+1));
if (depth > 6)
{
return vecSplits;
}
else
{
Split(low, low+span/2, depth+1);
Split(low+span/2, high, depth+1);
return vecSplits;
}
}
//--------------------------- RenderSpeciesInfo --------------------------
//
// does what it says on the tin
//------------------------------------------------------------------------
void Cga::RenderSpeciesInfo(HDC &surface, RECT db)
{
if (m_vecSpecies.size() < 1) return;
int numColours = 255/m_vecSpecies.size();
double SlicePerSweeper = (double)(db.right-db.left)/(double)(CParams::iPopSize-1);
double left = db.left;
//now draw a different colored rectangle for each species
for (int spc=0; spc<m_vecSpecies.size(); ++spc)
{
//choose a brush to draw with
HBRUSH PieBrush = CreateSolidBrush(RGB(numColours*spc, 255, 255 - numColours*spc));
HBRUSH OldBrush = (HBRUSH)SelectObject(surface, PieBrush);
if (spc == m_vecSpecies.size()-1)
{
Rectangle(surface,
left,
db.top,
db.right,
db.bottom);
}
else
{
Rectangle(surface,
left,
db.top,
left+SlicePerSweeper*m_vecSpecies[spc].NumMembers(),
db.bottom);
}
left += SlicePerSweeper * m_vecSpecies[spc].NumMembers();
SelectObject(surface, OldBrush);
DeleteObject(PieBrush);
//display best performing species stats in the same color as displayed
//in the distribution bar
if ( m_vecSpecies[spc].BestFitness() == m_dBestEverFitness)
{
string s = "Best Species ID: " + itos(m_vecSpecies[spc].ID());
TextOut(surface, 5, db.top - 80, s.c_str(), s.size());
s = "Species Age: " + itos(m_vecSpecies[spc].Age());
TextOut(surface, 5, db.top - 60, s.c_str(), s.size());
s = "Gens no improvement: " + itos(m_vecSpecies[spc].GensNoImprovement());
TextOut(surface, 5, db.top - 40, s.c_str(), s.size());
s = "Threshold: " + ftos(CParams::dCompatibilityThreshold);
TextOut(surface, 5, db.top - 100, s.c_str(), s.size());
}
}
string s = "Species Distribution Bar";
TextOut(surface, 5, db.top - 20, s.c_str(), s.size());
}
//--------------------------- WriteGenome --------------------------------
//
// given an index into m_vecGenomes this function writes the structure of
// a single genome to a file
//------------------------------------------------------------------------
bool Cga::WriteGenome(const char* szFileName, const int idxGenome)
{
ofstream out(szFileName);
if (!out) return false; //error
CalculateNetDepth(m_vecGenomes[idxGenome]);
if (m_vecGenomes[idxGenome].Write(out))
{
return true;
}
return false;
}
//--------------------- SpeciesDump -------------------------------------
//
// Outputs the species info to a file
//-----------------------------------------------------------------------
bool Cga::SpeciesDump(const char* szFileName)
{
ofstream file(szFileName);
if (!file) return false; //error
file << "Best Ever Fitness is " << m_dBestEverFitness << "\n";
for (int i=0; i<m_vecSpecies.size(); ++i)
{
file << m_vecSpecies[i];
}
return true;
}