forked from peter-ch/MultiNEAT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpecies.cpp
More file actions
977 lines (788 loc) · 31.8 KB
/
Species.cpp
File metadata and controls
977 lines (788 loc) · 31.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
///////////////////////////////////////////////////////////////////////////////////////////
// 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: Species.cpp
// Description: Implementation of the Species class.
///////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include "Genome.h"
#include "Species.h"
#include "Random.h"
#include "Population.h"
#include "Utils.h"
#include "Parameters.h"
#include "assert.h"
namespace NEAT
{
// initializes a species with a leader genome and an ID number
Species::Species(const Genome& a_Genome, int a_ID)
{
m_ID = a_ID;
m_Individuals.reserve(50);
// copy the initializing genome locally.
// it is now the representative of the species.
m_Representative = a_Genome;
m_BestGenome = a_Genome;
// add the first and only one individual
m_Individuals.push_back(a_Genome);
m_Age = 0;
m_GensNoImprovement = 0;
m_OffspringRqd = 0;
m_BestFitness = a_Genome.GetFitness();
m_BestSpecies = true;
m_WorstSpecies = false;
m_AverageFitness = 0;
// Choose a random color
RNG rng;
rng.TimeSeed();
m_R = static_cast<int>(rng.RandFloat() * 255);
m_G = static_cast<int>(rng.RandFloat() * 255);
m_B = static_cast<int>(rng.RandFloat() * 255);
}
Species& Species::operator=(const Species& a_S)
{
// self assignment guard
if (this != &a_S)
{
m_ID = a_S.m_ID;
m_Representative = a_S.m_Representative;
m_BestGenome = a_S.m_BestGenome;
m_BestSpecies = a_S.m_BestSpecies;
m_WorstSpecies = a_S.m_WorstSpecies;
m_BestFitness = a_S.m_BestFitness;
m_GensNoImprovement = a_S.m_GensNoImprovement;
m_Age = a_S.m_Age;
m_OffspringRqd = a_S.m_OffspringRqd;
m_R = a_S.m_R;
m_G = a_S.m_G;
m_B = a_S.m_B;
m_Individuals = a_S.m_Individuals;
}
return *this;
}
// adds a new member to the species and updates variables
void Species::AddIndividual(Genome& a_Genome)
{
m_Individuals.push_back( a_Genome );
}
// returns an individual randomly selected from the best N%
Genome Species::GetIndividual(Parameters& a_Parameters, RNG& a_RNG) const
{
ASSERT(m_Individuals.size() > 0);
// Make a pool of only evaluated individuals!
std::vector<Genome> t_Evaluated;
for(unsigned int i=0; i<m_Individuals.size(); i++)
{
if (m_Individuals[i].IsEvaluated())
t_Evaluated.push_back( m_Individuals[i] );
}
ASSERT(t_Evaluated.size() > 0);
if (t_Evaluated.size() == 1)
{
return (t_Evaluated[0]);
}
else if (t_Evaluated.size() == 2)
{
return (t_Evaluated[ Rounded(a_RNG.RandFloat()) ]);
}
// Warning!!!! The individuals must be sorted by best fitness for this to work
int t_chosen_one=0;
// Here might be introduced better selection scheme, but this works OK for now
if (!a_Parameters.RouletteWheelSelection)
{ //start with the last one just for comparison sake
int temp_genome;
int t_num_parents = static_cast<int>( floor((a_Parameters.SurvivalRate * (static_cast<double>(t_Evaluated.size())))+1.0));
ASSERT(t_num_parents>0);
t_chosen_one = a_RNG.RandInt(0, t_num_parents);
for (unsigned int i = 0; i < a_Parameters.TournamentSize; i++)
{
temp_genome = a_RNG.RandInt(0, t_num_parents);
if (m_Individuals[temp_genome].GetFitness() > m_Individuals[t_chosen_one].GetFitness())
{
t_chosen_one = temp_genome;
}
}
}
else
{
// roulette wheel selection
std::vector<double> t_probs;
for(unsigned int i=0; i<t_Evaluated.size(); i++)
t_probs.push_back( t_Evaluated[i].GetFitness() );
t_chosen_one = a_RNG.Roulette(t_probs);
}
return (t_Evaluated[t_chosen_one]);
}
// returns a completely random individual
Genome Species::GetRandomIndividual(RNG& a_RNG) const
{
if (m_Individuals.size() == 0) // no members yet, return representative
{
return m_Representative;
}
else
{
int t_rand_choice = 0;
t_rand_choice = a_RNG.RandInt(0, static_cast<int>(m_Individuals.size()-1));
return (m_Individuals[t_rand_choice]);
}
}
// returns the leader (the member having the best fitness)
Genome Species::GetLeader() const
{
// Don't store the leader any more
// Perform a search over the members and return the most fit member
// if empty, return representative
if (m_Individuals.size() == 0)
{
return m_Representative;
}
double t_max_fitness = -99999999;
int t_leader_idx = -1;
for(unsigned int i=0; i<m_Individuals.size(); i++)
{
double t_f = m_Individuals[i].GetFitness();
if (t_max_fitness < t_f)
{
t_max_fitness = t_f;
t_leader_idx = i;
}
}
ASSERT(t_leader_idx != -1);
return (m_Individuals[t_leader_idx]);
}
Genome Species::GetRepresentative() const
{
return m_Representative;
}
// calculates how many offspring this species should spawn
void Species::CountOffspring()
{
m_OffspringRqd = 0;
for(unsigned int i=0; i<m_Individuals.size(); i++)
{
m_OffspringRqd += m_Individuals[i].GetOffspringAmount();
}
}
// this method performs fitness sharing
// it also boosts the fitness of the young and penalizes old species
void Species::AdjustFitness(Parameters& a_Parameters)
{
ASSERT(m_Individuals.size() > 0);
// iterate through the members
for(unsigned int i=0; i<m_Individuals.size(); i++)
{
double t_fitness = m_Individuals[i].GetFitness();
// the fitness must be positive
//DBG(t_fitness);
ASSERT(t_fitness >= 0);
// this prevents the fitness to be below zero
if (t_fitness <= 0) t_fitness = 0.0001;
// update the best fitness and stagnation counter
if (t_fitness > m_BestFitness)
{
m_BestFitness = t_fitness;
m_GensNoImprovement = 0;
}
// boost the fitness up to some young age
if (m_Age < a_Parameters.YoungAgeTreshold)
{
t_fitness *= a_Parameters.YoungAgeFitnessBoost;
}
// penalty for old species
if (m_Age > a_Parameters.OldAgeTreshold)
{
t_fitness *= a_Parameters.OldAgePenalty;
}
// extreme penalty if this species is stagnating for too long time
// one exception if this is the best species found so far
if (m_GensNoImprovement > a_Parameters.SpeciesMaxStagnation)
{
// the best species is always allowed to live
if (!m_BestSpecies)
{
// when the fitness is lowered that much, the species will
// likely have 0 offspring and therefore will not survive
t_fitness *= 0.0000001;
}
}
// Compute the adjusted fitness for this member
m_Individuals[i].SetAdjFitness(t_fitness / m_Individuals.size());
}
}
// Sorts the members of this species by fitness
bool fitness_greater(Genome* ls, Genome* rs)
{
return ((ls->GetFitness()) > (rs->GetFitness()));
}
bool genome_greater(Genome ls, Genome rs)
{
return (ls.GetFitness() > rs.GetFitness());
}
void Species::SortIndividuals()
{
std::sort(m_Individuals.begin(), m_Individuals.end(), genome_greater);
}
// Removes an individual from the species by its index within the species
void Species::RemoveIndividual(unsigned int a_idx)
{
ASSERT(a_idx < m_Individuals.size());
m_Individuals.erase(m_Individuals.begin() + a_idx);
}
// New stuff
/*
SUMMARY OF THE EPOCH MECHANISM
--------------------------------------------------------------------------------------------------
- Adjust all species's fitness
- Count offspring per species
. Kill worst individuals for all species (delete them, not skip them!)
. Reproduce all species
. Kill the old parents
1. Every individual in the population is a BABY before evaluation.
2. After evaluation (i.e. lifetime), the worst individuals are killed and the others become ADULTS.
3. Reproduction mates adults and mutates offspring.
A mixture of BABIES and ADULTS emerges in each species.
New species may appear in the population during the process.
4. Then the individuals marked as ADULT are killed off.
5. What remains is a species with the new offspring (only babies)
--------------------------------------------------------------------------------------------------
*/
// Reproduce mates & mutates the individuals of the species
// It may access the global species list in the population
// because some babies may turn out to belong in another species
// that have to be created.
// Also calls Birth() for every new baby
void Species::Reproduce(Population &a_Pop, Parameters& a_Parameters, RNG& a_RNG)
{
Genome t_baby; // temp genome for reproduction
int t_offspring_count = Rounded(GetOffspringRqd());
int elite_offspring = Rounded(a_Parameters.EliteFraction * m_Individuals.size());
if (elite_offspring < 1) // can't be 0
{
elite_offspring = 1;
}
// ensure we have a champ
int elite_count = 0;
// no offspring?! yikes.. dead species!
if (t_offspring_count == 0)
{
// maybe do something else?
return;
}
//////////////////////////
// Reproduction
// Spawn t_offspring_count babies
//bool t_champ_chosen = false;
bool t_baby_exists_in_pop = false;
while(t_offspring_count--)
{
// Select the elite first..
if (elite_count < elite_offspring)
{
t_baby = m_Individuals[elite_count];
elite_count++;
}
else
{
//do // - while the baby already exists somewhere in the new population
//{
// this tells us if the baby is a result of mating
bool t_mated = false;
// There must be individuals there..
ASSERT(NumIndividuals() > 0);
// for a species of size 1 we can only mutate
// NOTE: but does it make sense since we know this is the champ?
if (NumIndividuals() == 1)
{
t_baby = GetIndividual(a_Parameters, a_RNG);
t_mated = false;
}
// else we can mate
else
{
do // keep trying to mate until a good offspring is produced
{
Genome t_mom = GetIndividual(a_Parameters, a_RNG);
// choose whether to mate at all
// Do not allow crossover when in simplifying phase
if ((a_RNG.RandFloat() < a_Parameters.CrossoverRate) && (a_Pop.GetSearchMode() != SIMPLIFYING))
{
// get the father
Genome t_dad;
bool t_interspecies = false;
// There is a probability that the father may come from another species
if ((a_RNG.RandFloat() < a_Parameters.InterspeciesCrossoverRate) && (a_Pop.m_Species.size()>1))
{
// Find different species (random one) // !!!!!!!!!!!!!!!!!
int t_diffspec = a_RNG.RandInt(0, static_cast<int>(a_Pop.m_Species.size()-1));
t_dad = a_Pop.m_Species[t_diffspec].GetIndividual(a_Parameters, a_RNG);
t_interspecies = true;
}
else
{
// Mate within species
t_dad = GetIndividual(a_Parameters, a_RNG);
// The other parent should be a different one
// number of tries to find different parent
int t_tries = 3;
if (!a_Parameters.AllowClones)
{
while(((t_mom.GetID() == t_dad.GetID()) /*|| (t_mom.CompatibilityDistance(t_dad, a_Parameters) < 0.00001)*/ ) && (t_tries--))
{
t_dad = GetIndividual(a_Parameters, a_RNG);
}
}
else
{
while(((t_mom.GetID() == t_dad.GetID()) ) && (t_tries--))
{
t_dad = GetIndividual(a_Parameters, a_RNG);
}
}
t_interspecies = false;
}
// OK we have both mom and dad so mate them
// Choose randomly one of two types of crossover
if (a_RNG.RandFloat() < a_Parameters.MultipointCrossoverRate)
{
t_baby = t_mom.Mate( t_dad, false, t_interspecies, a_RNG);
}
else
{
t_baby = t_mom.Mate( t_dad, true, t_interspecies, a_RNG);
}
t_mated = true;
}
// don't mate - reproduce the mother asexually
else
{
t_baby = t_mom;
t_mated = false;
}
} while (t_baby.HasDeadEnds() || (t_baby.NumLinks() == 0));
// in case of dead ends after crossover we will repeat crossover
// until it works
}
// Mutate the baby
if ((!t_mated) || (a_RNG.RandFloat() < a_Parameters.OverallMutationRate))
{
MutateGenome(t_baby_exists_in_pop, a_Pop, t_baby, a_Parameters, a_RNG);
}
// Check if this baby is already present somewhere in the offspring
// we don't want that
/*t_baby_exists_in_pop = false;
// Unless of course, we want
if (!a_Parameters.AllowClones)
{
for(unsigned int i=0; i<a_Pop.m_TempSpecies.size(); i++)
{
for(unsigned int j=0; j<a_Pop.m_TempSpecies[i].m_Individuals.size(); j++)
{
if (
(t_baby.CompatibilityDistance(a_Pop.m_TempSpecies[i].m_Individuals[j], a_Parameters) < 0.00001) // identical genome?
)
{
t_baby_exists_in_pop = true;
break;
}
}
}
}*/
//}
//while (t_baby_exists_in_pop); // end do
}
// Final place to test for problems
// If there is anything wrong here, we will just
// pick a random individual and leave him unchanged
if ((t_baby.NumLinks() == 0) || t_baby.HasDeadEnds())
{
t_baby = GetIndividual(a_Parameters, a_RNG);
}
// We have a new offspring now
// give the offspring a new ID
t_baby.SetID(a_Pop.GetNextGenomeID());
a_Pop.IncrementNextGenomeID();
// sort the baby's genes
t_baby.SortGenes();
// clear the baby's fitness
t_baby.SetFitness(0);
t_baby.SetAdjFitness(0);
t_baby.SetOffspringAmount(0);
t_baby.ResetEvaluated();
//////////////////////////////////
// put the baby to its species //
//////////////////////////////////
// before Reproduce() is invoked, it is assumed that a
// clone of the population exists with the name of m_TempSpecies
// we will store results there.
// after all reproduction completes, the original species will be replaced back
bool t_found = false;
std::vector<Species>::iterator t_cur_species = a_Pop.m_TempSpecies.begin();
// No species yet?
if (t_cur_species == a_Pop.m_TempSpecies.end())
{
// create the first species and place the baby there
a_Pop.m_TempSpecies.push_back( Species(t_baby, a_Pop.GetNextSpeciesID()));
a_Pop.IncrementNextSpeciesID();
}
else
{
// try to find a compatible species
Genome t_to_compare = t_cur_species->GetRepresentative();
t_found = false;
while((t_cur_species != a_Pop.m_TempSpecies.end()) && (!t_found))
{
if (t_baby.IsCompatibleWith( t_to_compare, a_Parameters))
{
// found a compatible species
t_cur_species->AddIndividual(t_baby);
t_found = true; // the search is over
}
else
{
// keep searching for a matching species
t_cur_species++;
if (t_cur_species != a_Pop.m_TempSpecies.end())
{
t_to_compare = t_cur_species->GetRepresentative();
}
}
}
// if couldn't find a match, make a new species
if (!t_found)
{
a_Pop.m_TempSpecies.push_back( Species(t_baby, a_Pop.GetNextSpeciesID()));
a_Pop.IncrementNextSpeciesID();
}
}
}
}
////////////
// Real-time code
void Species::CalculateAverageFitness()
{
double t_total_fitness = 0;
int t_num_individuals = 0;
// consider individuals that were evaluated only!
for(unsigned int i=0; i<m_Individuals.size(); i++)
{
if (m_Individuals[i].m_Evaluated)
{
t_total_fitness += m_Individuals[i].GetFitness();
t_num_individuals++;
}
}
if (t_num_individuals > 0)
m_AverageFitness = t_total_fitness / static_cast<double>(t_num_individuals);
else
m_AverageFitness = 0;
}
Genome Species::ReproduceOne(Population& a_Pop, Parameters& a_Parameters, RNG& a_RNG)
{
Genome t_baby; // for storing the result
//////////////////////////
// Reproduction
// Spawn only one baby
// this tells us if the baby is a result of mating
bool t_mated = false;
// There must be individuals there..
ASSERT(NumIndividuals() > 0);
// for a species of size 1 we can only mutate
// NOTE: but does it make sense since we know this is the champ?
if (NumIndividuals() == 1)
{
t_baby = GetIndividual(a_Parameters, a_RNG);
t_mated = false;
}
// else we can mate
else
{
Genome t_mom = GetIndividual(a_Parameters, a_RNG);
// choose whether to mate at all
// Do not allow crossover when in simplifying phase
if ((a_RNG.RandFloat() < a_Parameters.CrossoverRate) && (a_Pop.GetSearchMode() != SIMPLIFYING))
{
// get the father
Genome t_dad;
bool t_interspecies = false;
// There is a probability that the father may come from another species
if ((a_RNG.RandFloat() < a_Parameters.InterspeciesCrossoverRate) && (a_Pop.m_Species.size()>1))
{
// Find different species (random one) // !!!!!!!!!!!!!!!!!
// But the different species must have at least one evaluated individual
int t_diffspec = 0;
int t_giveup = 64;
do
{
t_diffspec = a_RNG.RandInt(0, static_cast<int>(a_Pop.m_Species.size()-1));
}
while ((a_Pop.m_Species[t_diffspec].m_AverageFitness == 0) && (t_giveup--));
if (a_Pop.m_Species[t_diffspec].m_AverageFitness == 0)
t_dad = GetIndividual(a_Parameters, a_RNG);
else
t_dad = a_Pop.m_Species[t_diffspec].GetIndividual(a_Parameters, a_RNG);
t_interspecies = true;
}
else
{
// Mate within species
t_dad = GetIndividual(a_Parameters, a_RNG);
// The other parent should be a different one
// number of tries to find different parent
int t_tries = 32;
while(((t_mom.GetID() == t_dad.GetID()) || ((!a_Parameters.AllowClones) && (t_mom.CompatibilityDistance(t_dad, a_Parameters) <= 0.00001)) ) && (t_tries--))
{
t_dad = GetIndividual(a_Parameters, a_RNG);
}
t_interspecies = false;
}
// OK we have both mom and dad so mate them
// Choose randomly one of two types of crossover
if (a_RNG.RandFloat() < a_Parameters.MultipointCrossoverRate)
{
t_baby = t_mom.Mate( t_dad, false, t_interspecies, a_RNG);
}
else
{
t_baby = t_mom.Mate( t_dad, true, t_interspecies, a_RNG);
}
t_mated = true;
}
// don't mate - reproduce the mother asexually
else
{
t_baby = t_mom;
t_mated = false;
}
}
/* if (t_baby.HasDeadEnds())
{
std::cout << "Dead ends in baby after crossover" << std::endl;
// int p;
// std::cin >> p;
}*/
// OK we have the baby, so let's mutate it.
bool t_baby_is_clone = false;
if ((!t_mated) || (a_RNG.RandFloat() < a_Parameters.OverallMutationRate))
MutateGenome(t_baby_is_clone, a_Pop, t_baby, a_Parameters, a_RNG);
// We have a new offspring now
// give the offspring a new ID
t_baby.SetID(a_Pop.GetNextGenomeID());
a_Pop.IncrementNextGenomeID();
// sort the baby's genes
t_baby.SortGenes();
// clear the baby's fitness
t_baby.SetFitness(0);
t_baby.SetAdjFitness(0);
t_baby.SetOffspringAmount(0);
t_baby.ResetEvaluated();
// debug trap
/* if (t_baby.NumLinks() == 0)
{
std::cout << "No links in baby after reproduction" << std::endl;
// int p;
// std::cin >> p;
}
if (t_baby.HasDeadEnds())
{
std::cout << "Dead ends in baby after reproduction" << std::endl;
// int p;
// std::cin >> p;
}
*/
return t_baby;
}
// Mutates a genome
void Species::MutateGenome( bool t_baby_is_clone, Population &a_Pop, Genome &t_baby, Parameters& a_Parameters, RNG& a_RNG )
{
#if 1
// NEW version:
// All mutations are mutually exclusive - can't have 2 mutations at once
// for example a weight mutation and time constants mutation
// or add link and add node and then weight mutation
// We will perform roulette wheel selection to choose the type of mutation and will mutate the baby
// This method guarantees that the baby will be mutated at least with one mutation
enum MutationTypes {ADD_NODE = 0, ADD_LINK, REMOVE_NODE, REMOVE_LINK, CHANGE_ACTIVATION_FUNCTION,
MUTATE_WEIGHTS, MUTATE_ACTIVATION_A, MUTATE_ACTIVATION_B, MUTATE_TIMECONSTS, MUTATE_BIASES
};
std::vector<int> t_muts;
std::vector<double> t_mut_probs;
// ADD_NODE;
t_mut_probs.push_back( a_Parameters.MutateAddNeuronProb );
// ADD_LINK;
t_mut_probs.push_back( a_Parameters.MutateAddLinkProb );
// REMOVE_NODE;
t_mut_probs.push_back( a_Parameters.MutateRemSimpleNeuronProb );
// REMOVE_LINK;
t_mut_probs.push_back( a_Parameters.MutateRemLinkProb );
// CHANGE_ACTIVATION_FUNCTION;
t_mut_probs.push_back( a_Parameters.MutateNeuronActivationTypeProb );
// MUTATE_WEIGHTS;
t_mut_probs.push_back( a_Parameters.MutateWeightsProb );
// MUTATE_ACTIVATION_A;
t_mut_probs.push_back( a_Parameters.MutateActivationAProb );
// MUTATE_ACTIVATION_B;
t_mut_probs.push_back( a_Parameters.MutateActivationBProb );
// MUTATE_TIMECONSTS;
t_mut_probs.push_back( a_Parameters.MutateNeuronTimeConstantsProb );
// MUTATE_BIASES;
t_mut_probs.push_back( a_Parameters.MutateNeuronBiasesProb );
// Special consideration for phased searching - do not allow certain mutations depending on the search mode
// also don't use additive mutations if we just want to get rid of the clones
if ((a_Pop.GetSearchMode() == SIMPLIFYING) || t_baby_is_clone)
{
t_mut_probs[ADD_NODE] = 0; // add node
t_mut_probs[ADD_LINK] = 0; // add link
}
if ((a_Pop.GetSearchMode() == COMPLEXIFYING) || t_baby_is_clone)
{
t_mut_probs[REMOVE_NODE] = 0; // rem node
t_mut_probs[REMOVE_LINK] = 0; // rem link
}
bool t_mutation_success = false;
// repeat until successful
while (t_mutation_success == false)
{
int ChosenMutation = a_RNG.Roulette(t_mut_probs);
// Now mutate based on the choice
switch(ChosenMutation)
{
case ADD_NODE:
t_mutation_success = t_baby.Mutate_AddNeuron(a_Pop.AccessInnovationDatabase(), a_Parameters, a_RNG);
break;
case ADD_LINK:
t_mutation_success = t_baby.Mutate_AddLink(a_Pop.AccessInnovationDatabase(), a_Parameters, a_RNG);
break;
case REMOVE_NODE:
t_mutation_success = t_baby.Mutate_RemoveSimpleNeuron(a_Pop.AccessInnovationDatabase(), a_RNG);
break;
case REMOVE_LINK:
{
// Keep doing this mutation until it is sure that the baby will not
// end up having dead ends or no links
Genome t_saved_baby = t_baby;
bool t_no_links = false, t_has_dead_ends = false;
int t_tries = 128;
do
{
t_tries--;
if (t_tries <= 0)
{
t_saved_baby = t_baby;
break; // give up
}
t_saved_baby = t_baby;
t_mutation_success = t_saved_baby.Mutate_RemoveLink(a_RNG);
t_no_links = t_has_dead_ends = false;
if (t_saved_baby.NumLinks() == 0)
t_no_links = true;
t_has_dead_ends = t_saved_baby.HasDeadEnds();
}
while(t_no_links || t_has_dead_ends);
t_baby = t_saved_baby;
// debugger trap
if (t_baby.NumLinks() == 0)
{
std::cerr << "No links in baby after mutation" << std::endl;
}
if (t_baby.HasDeadEnds())
{
std::cerr << "Dead ends in baby after mutation" << std::endl;
}
}
break;
case CHANGE_ACTIVATION_FUNCTION:
t_baby.Mutate_NeuronActivation_Type(a_Parameters, a_RNG);
t_mutation_success = true;
break;
case MUTATE_WEIGHTS:
t_baby.Mutate_LinkWeights(a_Parameters, a_RNG);
t_mutation_success = true;
break;
case MUTATE_ACTIVATION_A:
t_baby.Mutate_NeuronActivations_A(a_Parameters, a_RNG);
t_mutation_success = true;
break;
case MUTATE_ACTIVATION_B:
t_baby.Mutate_NeuronActivations_B(a_Parameters, a_RNG);
t_mutation_success = true;
break;
case MUTATE_TIMECONSTS:
t_baby.Mutate_NeuronTimeConstants(a_Parameters, a_RNG);
t_mutation_success = true;
break;
case MUTATE_BIASES:
t_baby.Mutate_NeuronBiases(a_Parameters, a_RNG);
t_mutation_success = true;
break;
default:
t_mutation_success = false;
break;
}
}
#else
// Old version of the function - added just to test various ways to do mutation
bool t_mutation_success = false;
// repeat until successful
while (t_mutation_success == false)
{
if (a_RNG.RandFloat() < a_Parameters.MutateAddNeuronProb)
t_mutation_success = t_baby.Mutate_AddNeuron(a_Pop.AccessInnovationDatabase(), a_Parameters, a_RNG);
else
if (a_RNG.RandFloat() < a_Parameters.MutateAddLinkProb)
t_mutation_success = t_baby.Mutate_AddLink(a_Pop.AccessInnovationDatabase(), a_Parameters, a_RNG);
else
{
/*if (a_RNG.RandFloat() < a_Parameters.MutateNeuronActivationTypeProb)
{
t_baby.Mutate_NeuronActivation_Type(a_Parameters, a_RNG);
t_mutation_success = true;
}*/
if (a_RNG.RandFloat() < a_Parameters.MutateWeightsProb)
{
t_baby.Mutate_LinkWeights(a_Parameters, a_RNG);
t_mutation_success = true;
break;
}
/*case MUTATE_ACTIVATION_A:
t_baby.Mutate_NeuronActivations_A(a_Parameters, a_RNG);
t_mutation_success = true;
break;
case MUTATE_ACTIVATION_B:
t_baby.Mutate_NeuronActivations_B(a_Parameters, a_RNG);
t_mutation_success = true;
break;
case MUTATE_TIMECONSTS:
t_baby.Mutate_NeuronTimeConstants(a_Parameters, a_RNG);
t_mutation_success = true;
break;
case MUTATE_BIASES:
t_baby.Mutate_NeuronBiases(a_Parameters, a_RNG);
t_mutation_success = true;
break;*/
}
}
#endif
}
} // namespace NEAT