forked from peter-ch/MultiNEAT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulation.cpp
More file actions
1321 lines (1051 loc) · 39.8 KB
/
Population.cpp
File metadata and controls
1321 lines (1051 loc) · 39.8 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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///////////////////////////////////////////////////////////////////////////////////////////
// MultiNEAT - Python/C++ NeuroEvolution of Augmenting Topologies Library
//
// Copyright (C) 2012 Peter Chervenski
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see < http://www.gnu.org/licenses/ >.
//
// Contact info:
//
// Peter Chervenski < spookey@abv.bg >
// Shane Ryan < shane.mcdonald.ryan@gmail.com >
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// File: Population.cpp
// Description: Implementation of the Population class.
///////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <fstream>
#include "Genome.h"
#include "Species.h"
#include "Random.h"
#include "Parameters.h"
#include "PhenotypeBehavior.h"
#include "Population.h"
#include "Utils.h"
#include "Assert.h"
namespace NEAT
{
// The constructor
Population::Population(const Genome& a_Seed, const Parameters& a_Parameters,
bool a_RandomizeWeights, double a_RandomizationRange, int a_RNG_seed)
{
m_RNG.Seed(a_RNG_seed);
m_BestFitnessEver = 0.0;
m_Parameters = a_Parameters;
m_Generation = 0;
m_NumEvaluations = 0;
m_NextGenomeID = m_Parameters.PopulationSize;
m_NextSpeciesID = 1;
m_GensSinceBestFitnessLastChanged = 0;
m_GensSinceMPCLastChanged = 0;
// Spawn the population
for(unsigned int i=0; i<m_Parameters.PopulationSize; i++)
{
Genome t_clone = a_Seed;
t_clone.SetID(i);
m_Genomes.push_back( t_clone );
}
// Now now initialize each genome's weights
for(unsigned int i=0; i<m_Genomes.size(); i++)
{
if (a_RandomizeWeights)
m_Genomes[i].Randomize_LinkWeights(a_RandomizationRange, m_RNG);
//m_Genomes[i].CalculateDepth();
}
// Speciate
Speciate();
// set these phased search variables now since used in MutateGenome
if (m_Parameters.PhasedSearching)
{
m_SearchMode = COMPLEXIFYING;
}
else
{
m_SearchMode = BLENDED;
}
// initial mutation
/*for (unsigned int i = 0; i < m_Species.size(); i++)
{
for (unsigned int j = 0; j < m_Species[i].m_Individuals.size(); j++)
{
m_Species[i].MutateGenome( true, *this, m_Species[i].m_Individuals[j], m_Parameters, m_RNG );
}
}
Speciate();*/
// Initialize the innovation database
m_InnovationDatabase.Init(a_Seed);
m_BestGenome = m_Species[0].GetLeader();
Sort();
// Set up the rest of the phased search variables
CalculateMPC();
m_BaseMPC = m_CurrentMPC;
m_OldMPC = m_BaseMPC;
m_InnovationDatabase.m_Innovations.reserve(50000);
}
Population::Population(const char *a_FileName)
{
m_BestFitnessEver = 0.0;
m_Generation = 0;
m_NumEvaluations = 0;
m_NextSpeciesID = 1;
m_GensSinceBestFitnessLastChanged = 0;
m_GensSinceMPCLastChanged = 0;
std::ifstream t_DataFile(a_FileName);
if (!t_DataFile.is_open())
throw std::exception();
std::string t_str;
// Load the parameters
m_Parameters.Load(t_DataFile);
// Load the innovation database
m_InnovationDatabase.Init(t_DataFile);
// Load all genomes
for(unsigned int i=0; i<m_Parameters.PopulationSize; i++)
{
Genome t_genome(t_DataFile);
m_Genomes.push_back( t_genome );
}
t_DataFile.close();
m_NextGenomeID = 0;
for(unsigned int i=0; i<m_Genomes.size(); i++)
{
if (m_Genomes[i].GetID() > m_NextGenomeID)
{
m_NextGenomeID = m_Genomes[i].GetID();
}
}
m_NextGenomeID++;
// Initialize
Speciate();
m_BestGenome = m_Species[0].GetLeader();
Sort();
// Set up the phased search variables
CalculateMPC();
m_BaseMPC = m_CurrentMPC;
m_OldMPC = m_BaseMPC;
if (m_Parameters.PhasedSearching)
{
m_SearchMode = COMPLEXIFYING;
}
else
{
m_SearchMode = BLENDED;
}
}
// Save a whole population to a file
void Population::Save(const char* a_FileName)
{
FILE* t_file = fopen(a_FileName, "w");
// Save the parameters
m_Parameters.Save(t_file);
// Save the innovation database
m_InnovationDatabase.Save(t_file);
// Save each genome
for(unsigned i=0; i<m_Species.size(); i++)
{
for(unsigned j=0; j<m_Species[i].m_Individuals.size(); j++)
{
m_Species[i].m_Individuals[j].Save(t_file);
}
}
// bye
fclose(t_file);
}
// Calculates the current mean population complexity
void Population::CalculateMPC()
{
m_CurrentMPC = 0;
for(unsigned int i=0; i<m_Genomes.size(); i++)
{
m_CurrentMPC += AccessGenomeByIndex(i).NumLinks();
}
m_CurrentMPC /= m_Genomes.size();
}
// Separates the population into species
// also adjusts the compatibility treshold if this feature is enabled
void Population::Speciate()
{
// iterate through the genome list and speciate
// at least 1 genome must be present
ASSERT(m_Genomes.size() > 0);
// first clear out the species
m_Species.clear();
bool t_added = false;
// NOTE: we are comparing the new generation's genomes to the representatives from the previous generation!
// Any new species that is created is assigned a representative from the new generation.
for(unsigned int i=0; i<m_Genomes.size(); i++)
{
t_added = false;
// iterate through each species and check if compatible. If compatible, then add to the species.
// if not compatible, create a new species.
for(unsigned int j=0; j<m_Species.size(); j++)
{
Genome tmp = m_Species[j].GetRepresentative();
if (m_Genomes[i].IsCompatibleWith( tmp, m_Parameters ))
{
// Compatible, add to species
m_Species[j].AddIndividual( m_Genomes[i] );
t_added = true;
break;
}
}
if (!t_added)
{
// didn't find compatible species, create new species
m_Species.push_back( Species(m_Genomes[i], m_NextSpeciesID));
m_NextSpeciesID++;
}
}
// Remove all empty species (cleanup routine for every case..)
std::vector<Species>::iterator t_cs = m_Species.begin();
while(t_cs != m_Species.end())
{
if (t_cs->NumIndividuals() == 0)
{
// remove the dead species
t_cs = m_Species.erase( t_cs );
if (t_cs != m_Species.begin()) // in case the first species are dead
t_cs--;
}
t_cs++;
}
/*
//////////////////
// extensive test DEBUG
// ////
// check to see if compatible enough individuals are in different species
// for each species
for(int i=0; i<m_Species.size(); i++)
{
for(int j=0; j<m_Species.size(); j++)
{
// do not check individuals in the same species
if (i != j)
{
// now for each individual in species [i]
// compare it to all individuals in species [j]
// report if there is a distance smaller that CompatTreshold
for(int sp1=0; sp1<m_Species[i].m_Members.size(); sp1++)
{
for(int sp2=0; sp2<m_Species[j].m_Members.size(); sp2++)
{
double t_dist = m_Species[i].m_Members[sp1]->CompatibilityDistance( *(m_Species[j].m_Members[sp2]) );
if (t_dist <= GlobalParameters.CompatTreshold)
{
const string tMessage = "Compatible individuals in different species!";
m_MessageQueue.push(tMessage);
}
}
}
}
}
}
*/
}
// Adjust the fitness of all species
void Population::AdjustFitness()
{
ASSERT(m_Genomes.size() > 0);
ASSERT(m_Species.size() > 0);
for(unsigned int i=0; i<m_Species.size(); i++)
{
m_Species[i].AdjustFitness(m_Parameters);
}
}
// Calculates how many offspring each genome should have
void Population::CountOffspring()
{
ASSERT(m_Genomes.size() > 0);
ASSERT(m_Genomes.size() == m_Parameters.PopulationSize);
double t_total_adjusted_fitness = 0;
double t_average_adjusted_fitness = 0;
Genome t_t;
// get the total adjusted fitness for all individuals
for(unsigned int i=0; i<m_Species.size(); i++)
{
for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
{
t_total_adjusted_fitness += m_Species[i].m_Individuals[j].GetAdjFitness();
}
}
// must be above 0
ASSERT(t_total_adjusted_fitness > 0);
t_average_adjusted_fitness = t_total_adjusted_fitness / static_cast<double>(m_Parameters.PopulationSize);
// Calculate how much offspring each individual should have
for(unsigned int i=0; i<m_Species.size(); i++)
{
for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
{
m_Species[i].m_Individuals[j].SetOffspringAmount( m_Species[i].m_Individuals[j].GetAdjFitness() / t_average_adjusted_fitness);
}
}
// Now count how many offpring each species should have
for(unsigned int i=0; i<m_Species.size(); i++)
{
m_Species[i].CountOffspring();
}
}
// This little tool function helps ordering the genomes by fitness
bool species_greater(Species ls, Species rs)
{
return ((ls.GetBestFitness()) > (rs.GetBestFitness()));
}
void Population::Sort()
{
ASSERT(m_Species.size() > 0);
// Step through each species and sort its members by fitness
for(unsigned int i=0; i<m_Species.size(); i++)
{
ASSERT(m_Species[i].NumIndividuals() > 0);
m_Species[i].SortIndividuals();
}
// Now sort the species by fitness (best first)
std::sort(m_Species.begin(), m_Species.end(), species_greater);
}
// Updates the species
void Population::UpdateSpecies()
{
// search for the current best species ID if not at generation #0
int t_oldbestid = -1, t_newbestid = -1;
int t_oldbestidx = -1;
if (m_Generation > 0)
{
for(unsigned int i=0; i<m_Species.size(); i++)
{
if (m_Species[i].IsBestSpecies())
{
t_oldbestid = m_Species[i].ID();
t_oldbestidx = i;
}
}
ASSERT(t_oldbestid != -1);
ASSERT(t_oldbestidx != -1);
}
for(unsigned int i=0; i<m_Species.size(); i++)
{
m_Species[i].SetBestSpecies(false);
}
bool t_marked = false; // new best species marked?
for(unsigned int i=0; i<m_Species.size(); i++)
{
// Reset the species and update its age
m_Species[i].IncreaseAge();
m_Species[i].IncreaseGensNoImprovement();
m_Species[i].SetOffspringRqd(0);
// Mark the best species so it is guaranteed to survive
// Only one species will be marked - in case several species
// have equally best fitness
if ((m_Species[i].GetBestFitness() >= m_BestFitnessEver) && (!t_marked))
{
m_Species[i].SetBestSpecies(true);
t_marked = true;
t_newbestid = m_Species[i].ID();
}
}
// This prevents the previous best species from sudden death
// If the best species happened to be another one, reset the old
// species age so it still will have a chance of survival and improvement
// if it grows old and stagnates again, it is no longer the best one
// so it will die off anyway.
if ((t_oldbestid != t_newbestid) && (t_oldbestid != -1))
{
m_Species[t_oldbestidx].ResetAge();
}
}
// the epoch method - the heart of the GA
void Population::Epoch()
{
// So, all genomes are evaluated..
for(unsigned int i=0; i<m_Species.size(); i++)
{
for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
{
m_Species[i].m_Individuals[j].SetEvaluated();
}
}
// Sort each species's members by fitness and the species by fitness
Sort();
// Update species stagnation info & stuff
UpdateSpecies();
///////////////////
// Preparation
///////////////////
// Adjust the species's fitness
AdjustFitness();
// Count the offspring of each individual and species
CountOffspring();
// Incrementing the global stagnation counter, we can check later for global stagnation
m_GensSinceBestFitnessLastChanged++;
// Find and save the best genome and fitness
for(unsigned int i=0; i<m_Species.size(); i++)
{
// Update best genome info
m_Species[i].m_BestGenome = m_Species[i].GetLeader();
for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
{
// Make sure all are evaluated as we don't run in realtime
m_Species[i].m_Individuals[j].SetEvaluated();
const double t_Fitness = m_Species[i].m_Individuals[j].GetFitness();
if (m_BestFitnessEver < t_Fitness)
{
// Reset the stagnation counter only if the fitness jump is greater or equal to the delta.
if (fabs(t_Fitness - m_BestFitnessEver) >= m_Parameters.StagnationDelta)
{
m_GensSinceBestFitnessLastChanged = 0;
}
m_BestFitnessEver = t_Fitness;
m_BestGenomeEver = m_Species[i].m_Individuals[j];
}
}
}
// Find and save the current best genome
double t_bestf = std::numeric_limits<double>::min();
for(unsigned int i=0; i<m_Species.size(); i++)
{
for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
{
if (m_Species[i].m_Individuals[j].GetFitness() > t_bestf)
{
t_bestf = m_Species[i].m_Individuals[j].GetFitness();
m_BestGenome = m_Species[i].m_Individuals[j];
}
}
}
// adjust the compatibility threshold
if (m_Parameters.DynamicCompatibility == true)
{
if ((m_Generation % m_Parameters.CompatTreshChangeInterval_Generations) == 0)
{
if (m_Species.size() > m_Parameters.MaxSpecies)
{
m_Parameters.CompatTreshold += m_Parameters.CompatTresholdModifier;
}
else if (m_Species.size() < m_Parameters.MinSpecies)
{
m_Parameters.CompatTreshold -= m_Parameters.CompatTresholdModifier;
}
}
if (m_Parameters.CompatTreshold < m_Parameters.MinCompatTreshold) m_Parameters.CompatTreshold = m_Parameters.MinCompatTreshold;
}
// A special case for global stagnation.
// Delta coding - if there is a global stagnation
// for dropoff age + 10 generations, focus the search on the top 2 species,
// in case there are more than 2, of course
if (m_Parameters.DeltaCoding)
{
if (m_GensSinceBestFitnessLastChanged > (m_Parameters.SpeciesMaxStagnation + 10))
{
// make the top 2 reproduce by 50% individuals
// and the rest - no offspring
if (m_Species.size() > 2)
{
// The first two will reproduce
m_Species[0].SetOffspringRqd( m_Parameters.PopulationSize/2 );
m_Species[1].SetOffspringRqd( m_Parameters.PopulationSize/2 );
// The rest will not
for (unsigned int i=2; i<m_Species.size(); i++)
{
m_Species[i].SetOffspringRqd( 0 );
}
// Now reset the stagnation counter and species age
m_Species[0].ResetAge();
m_Species[1].ResetAge();
m_GensSinceBestFitnessLastChanged = 0;
}
}
}
//////////////////////////////////
// Phased searching core logic
//////////////////////////////////
// Update the current MPC
CalculateMPC();
if (m_Parameters.PhasedSearching)
{
// Keep track of complexity when in simplifying phase
if (m_SearchMode == SIMPLIFYING)
{
// The MPC has lowered?
if (m_CurrentMPC < m_OldMPC)
{
// reset that
m_GensSinceMPCLastChanged = 0;
m_OldMPC = m_CurrentMPC;
}
else
{
m_GensSinceMPCLastChanged++;
}
}
// At complexifying phase?
if (m_SearchMode == COMPLEXIFYING)
{
// Need to begin simplification?
if (m_CurrentMPC > (m_BaseMPC + m_Parameters.SimplifyingPhaseMPCTreshold))
{
// Do this only if the whole population is stagnating
if (m_GensSinceBestFitnessLastChanged > m_Parameters.SimplifyingPhaseStagnationTreshold)
{
// Change the current search mode
m_SearchMode = SIMPLIFYING;
// Reset variables for simplifying mode
m_GensSinceMPCLastChanged = 0;
m_OldMPC = std::numeric_limits<double>::max(); // Really big one
// reset the age of species
for(unsigned int i=0; i<m_Species.size(); i++)
{
m_Species[i].ResetAge();
}
}
}
}
else if (m_SearchMode == SIMPLIFYING)
// At simplifying phase?
{
// The MPC reached its floor level?
if (m_GensSinceMPCLastChanged > m_Parameters.ComplexityFloorGenerations)
{
// Re-enter complexifying phase
m_SearchMode = COMPLEXIFYING;
// Set the base MPC with the current MPC
m_BaseMPC = m_CurrentMPC;
// reset the age of species
for(unsigned int i=0; i<m_Species.size(); i++)
{
m_Species[i].ResetAge();
}
}
}
}
/////////////////////////////
// Reproduction
/////////////////////////////
// Kill all bad performing individuals
// Todo: this baby/adult/killworst scheme is complicated and basically sucks,
// I should remove it completely.
// for(unsigned int i=0; i<m_Species.size(); i++) m_Species[i].KillWorst(m_Parameters);
// Perform reproduction for each species
m_TempSpecies.clear();
m_TempSpecies = m_Species;
for(unsigned int i=0; i<m_TempSpecies.size(); i++)
{
m_TempSpecies[i].Clear();
}
for(unsigned int i=0; i<m_Species.size(); i++)
{
m_Species[i].Reproduce(*this, m_Parameters, m_RNG);
}
m_Species = m_TempSpecies;
// Now we kill off the old parents
// Todo: this baby/adult scheme is complicated and basically sucks,
// I should remove it completely.
// for(unsigned int i=0; i<m_Species.size(); i++) m_Species[i].KillOldParents();
// Here we kill off any empty species too
// Remove all empty species (cleanup routine for every case..)
for(unsigned int i=0; i<m_Species.size(); i++)
{
if (m_Species[i].m_Individuals.size() == 0)
{
m_Species.erase(m_Species.begin() + i);
i--;
}
}
// Now reassign the representatives for each species
for(unsigned int i=0; i<m_Species.size(); i++)
{
m_Species[i].SetRepresentative( m_Species[i].m_Individuals[0] );
}
// If the total amount of genomes reproduced is less than the population size,
// due to some floating point rounding error,
// we will add some bonus clones of the first species's leader to it
unsigned int t_total_genomes = 0;
for(unsigned int i=0; i<m_Species.size(); i++)
t_total_genomes += static_cast<unsigned int>(m_Species[i].m_Individuals.size());
if (t_total_genomes < m_Parameters.PopulationSize)
{
int t_nts = m_Parameters.PopulationSize - t_total_genomes;
while(t_nts--)
{
ASSERT(m_Species.size() > 0);
Genome t_tg = m_Species[0].m_Individuals[0];
m_Species[0].AddIndividual(t_tg);
}
}
// Increase generation number
m_Generation++;
// At this point we may also empty our innovation database
// This is the place where we control whether we want to
// keep innovation numbers forever or not.
if (!m_Parameters.InnovationsForever)
{
m_InnovationDatabase.Flush();
}
}
Genome g_dummy; // empty genome
Genome& Population::AccessGenomeByIndex(unsigned int const a_idx)
{
ASSERT(a_idx < m_Genomes.size());
unsigned int t_counter = 0;
for (unsigned int i = 0; i < m_Species.size(); i++)
{
for (unsigned int j = 0; j < m_Species[i].m_Individuals.size(); j++)
{
if (t_counter == a_idx)// reached the index?
{
return m_Species[i].m_Individuals[j];
}
t_counter++;
}
}
// not found?! return dummy
return g_dummy;
}
/////////////////////////////////
// Realtime code
// Decides which species should have offspring. Returns the index of the species
unsigned int Population::ChooseParentSpecies()
{
ASSERT(m_Species.size() > 0);
double t_total_fitness = 0;
double t_marble=0, t_spin=0; // roulette wheel variables
unsigned int t_curspecies = 0;
// sum the average estimated fitness for the roulette
for(unsigned int i=0; i<m_Species.size(); i++)
{
t_total_fitness += m_Species[i].m_AverageFitness;
}
do
{
t_marble = m_RNG.RandFloat() * t_total_fitness;
t_spin = m_Species[t_curspecies].m_AverageFitness;
t_curspecies = 0;
while(t_spin < t_marble)
{
t_curspecies++;
t_spin += m_Species[t_curspecies].m_AverageFitness;
}
}
while(m_Species[t_curspecies].m_AverageFitness == 0); // prevent species with no evaluated members to be chosen
return t_curspecies;
}
// Takes a genome and assigns it to a different species (where it belongs)
void Population::ReassignSpecies(unsigned int a_genome_idx)
{
ASSERT(a_genome_idx < m_Genomes.size());
// first remember where is this genome exactly
unsigned int t_species_idx = 0, t_genome_rel_idx = 0;
unsigned int t_counter = 0;
// to keep the genome
Genome t_genome;
// search for it
bool t_f = false;
t_species_idx = 0;
for(unsigned int i=0; i<m_Species.size(); i++)
{
t_genome_rel_idx = 0;
for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
{
if (t_counter == a_genome_idx)
{
// get the genome and break
t_genome = m_Species[i].m_Individuals[j];
t_f = true;
break;
}
t_counter++;
t_genome_rel_idx++;
}
if (!t_f)
{
t_species_idx++;
}
else
{
break;
}
}
// Remove it from its species
m_Species[t_species_idx].RemoveIndividual(t_genome_rel_idx);
// If the species becomes empty, remove the species as well
if (m_Species[t_species_idx].m_Individuals.size() == 0)
{
m_Species.erase(m_Species.begin() + t_species_idx);
}
// Find a new species for this genome
bool t_found = false;
std::vector<Species>::iterator t_cur_species = m_Species.begin();
// No species yet?
if (t_cur_species == m_Species.end())
{
// create the first species and place the baby there
m_Species.push_back( Species(t_genome, GetNextSpeciesID()));
IncrementNextSpeciesID();
}
else
{
// try to find a compatible species
Genome t_to_compare = t_cur_species->GetRepresentative();
t_found = false;
while((t_cur_species != m_Species.end()) && (!t_found))
{
if (t_genome.IsCompatibleWith( t_to_compare, m_Parameters ))
{
// found a compatible species
t_cur_species->AddIndividual(t_genome);
t_found = true; // the search is over
}
else
{
// keep searching for a matching species
t_cur_species++;
if (t_cur_species != m_Species.end())
{
t_to_compare = t_cur_species->GetRepresentative();
}
}
}
// if couldn't find a match, make a new species
if (!t_found)
{
m_Species.push_back( Species(t_genome, GetNextSpeciesID()));
IncrementNextSpeciesID();
}
}
}
// Main realtime loop. We assume that the whole population was evaluated once before calling this.
// Returns a pointer to the baby in the population. It will be the only individual that was not evaluated.
// Set the m_Evaluated flag of the baby to true after evaluation!
Genome* Population::Tick(Genome& a_deleted_genome)
{
// Make sure all individuals are evaluated
/*for(unsigned int i=0; i<m_Species.size(); i++)
for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
ASSERT(m_Species[i].m_Individuals[j].m_Evaluated);*/
m_NumEvaluations++;
// Find and save the best genome and fitness
for(unsigned int i=0; i<m_Species.size(); i++)
{
m_Species[i].IncreaseGensNoImprovement();
for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
{
if (m_Species[i].m_Individuals[j].GetFitness() <= 0.0)
{
m_Species[i].m_Individuals[j].SetFitness(0.00001);
}
const double t_Fitness = m_Species[i].m_Individuals[j].GetFitness();
if (t_Fitness > m_BestFitnessEver)
{
// Reset the stagnation counter only if the fitness jump is greater or equal to the delta.
if (fabs(t_Fitness - m_BestFitnessEver) >= m_Parameters.StagnationDelta)
{
m_GensSinceBestFitnessLastChanged = 0;
}
m_BestFitnessEver = t_Fitness;
m_BestGenomeEver = m_Species[i].m_Individuals[j];
}
}
}
double t_f = std::numeric_limits<double>::min();
for(unsigned int i=0; i<m_Species.size(); i++)
{
for(unsigned int j=0; j<m_Species[i].m_Individuals.size(); j++)
{
if (m_Species[i].m_Individuals[j].GetFitness() > t_f)
{
t_f = m_Species[i].m_Individuals[j].GetFitness();
m_BestGenome = m_Species[i].m_Individuals[j];
}
if (m_Species[i].m_Individuals[j].GetFitness() >= m_Species[i].GetBestFitness())
{
m_Species[i].m_BestFitness = m_Species[i].m_Individuals[j].GetFitness();
m_Species[i].m_GensNoImprovement = 0;
}
}
}
// adjust the compatibility treshold
bool t_changed = false;
if (m_Parameters.DynamicCompatibility == true)
{
if ((m_NumEvaluations % m_Parameters.CompatTreshChangeInterval_Evaluations) == 0)
{
if (m_Species.size() > m_Parameters.MaxSpecies)
{
m_Parameters.CompatTreshold += m_Parameters.CompatTresholdModifier;
t_changed = true;
}
else if (m_Species.size() < m_Parameters.MinSpecies)
{
m_Parameters.CompatTreshold -= m_Parameters.CompatTresholdModifier;
t_changed = true;
}
if (m_Parameters.CompatTreshold < m_Parameters.MinCompatTreshold) m_Parameters.CompatTreshold = m_Parameters.MinCompatTreshold;
}
}