forked from peter-ch/MultiNEAT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenome.cpp
More file actions
3436 lines (2843 loc) · 113 KB
/
Genome.cpp
File metadata and controls
3436 lines (2843 loc) · 113 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: Genome.cpp
// Description: Implementation of the Genome class.
///////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <fstream>
#include <queue>
#include <math.h>
#include <utility>
#include <boost/unordered_map.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include "Genome.h"
#include "Random.h"
#include "Utils.h"
#include "Parameters.h"
#include "Assert.h"
namespace NEAT
{
// forward
ActivationFunction GetRandomActivation(Parameters& a_Parameters, RNG& a_RNG);
// squared x
inline double sqr(double x)
{
return x*x;
}
// Create an empty genome
Genome::Genome()
{
m_ID = 0;
m_Fitness = 0;
m_Depth = 0;
m_LinkGenes.clear();
m_NeuronGenes.clear();
m_NumInputs=0;
m_NumOutputs=0;
m_AdjustedFitness = 0;
m_OffspringAmount = 0;
m_Evaluated = false;
m_PhenotypeBehavior = NULL;
}
// Copy constructor
Genome::Genome(const Genome& a_G)
{
m_ID = a_G.m_ID;
m_Depth = a_G.m_Depth;
m_NeuronGenes = a_G.m_NeuronGenes;
m_LinkGenes = a_G.m_LinkGenes;
m_Fitness = a_G.m_Fitness;
m_NumInputs = a_G.m_NumInputs;
m_NumOutputs = a_G.m_NumOutputs;
m_AdjustedFitness = a_G.m_AdjustedFitness;
m_OffspringAmount = a_G.m_OffspringAmount;
m_Evaluated = a_G.m_Evaluated;
m_PhenotypeBehavior = a_G.m_PhenotypeBehavior;
}
// assignment operator
Genome& Genome::operator =(const Genome& a_G)
{
// self assignment guard
if (this != &a_G)
{
m_ID = a_G.m_ID;
m_Depth = a_G.m_Depth;
m_NeuronGenes = a_G.m_NeuronGenes;
m_LinkGenes = a_G.m_LinkGenes;
m_Fitness = a_G.m_Fitness;
m_AdjustedFitness = a_G.m_AdjustedFitness;
m_NumInputs = a_G.m_NumInputs;
m_NumOutputs = a_G.m_NumOutputs;
m_OffspringAmount = a_G.m_OffspringAmount;
m_Evaluated = a_G.m_Evaluated;
m_PhenotypeBehavior = a_G.m_PhenotypeBehavior;
}
return *this;
}
Genome::Genome(unsigned int a_ID,
unsigned int a_NumInputs,
unsigned int a_NumHidden, // ignored for seed type == 0, specifies number of hidden units if seed type == 1
unsigned int a_NumOutputs,
bool a_FS_NEAT, ActivationFunction a_OutputActType,
ActivationFunction a_HiddenActType,
unsigned int a_SeedType,
const Parameters& a_Parameters)
{
ASSERT((a_NumInputs > 1) && (a_NumOutputs > 0));
RNG t_RNG;
t_RNG.TimeSeed();
m_ID = a_ID;
int t_innovnum = 1, t_nnum = 1;
// Create the input neurons.
// Warning! The last one is a bias!
// The order of the neurons is very important. It is the following: INPUTS, BIAS, OUTPUTS, HIDDEN ... (no limit)
for(unsigned int i=0; i < (a_NumInputs-1); i++)
{
m_NeuronGenes.push_back( NeuronGene(INPUT, t_nnum, 0.0) );
t_nnum++;
}
// add the bias
m_NeuronGenes.push_back( NeuronGene(BIAS, t_nnum, 0.0) );
t_nnum++;
// now the outputs
for(unsigned int i=0; i < (a_NumOutputs); i++)
{
NeuronGene t_ngene(OUTPUT, t_nnum, 1.0);
// Initialize the neuron gene's properties
t_ngene.Init( (a_Parameters.MinActivationA + a_Parameters.MaxActivationA)/2.0f,
(a_Parameters.MinActivationB + a_Parameters.MaxActivationB)/2.0f,
(a_Parameters.MinNeuronTimeConstant + a_Parameters.MaxNeuronTimeConstant)/2.0f,
(a_Parameters.MinNeuronBias + a_Parameters.MaxNeuronBias)/2.0f,
a_OutputActType );
m_NeuronGenes.push_back( t_ngene );
t_nnum++;
}
// Now add LEO
if (a_Parameters.Leo)
{
NeuronGene t_ngene(OUTPUT, t_nnum, 1.0);
// Initialize the neuron gene's properties
t_ngene.Init( (a_Parameters.MinActivationA + a_Parameters.MaxActivationA)/2.0f,
(a_Parameters.MinActivationB + a_Parameters.MaxActivationB)/2.0f,
(a_Parameters.MinNeuronTimeConstant + a_Parameters.MaxNeuronTimeConstant)/2.0f,
(a_Parameters.MinNeuronBias + a_Parameters.MaxNeuronBias)/2.0f,
UNSIGNED_STEP );
m_NeuronGenes.push_back( t_ngene );
t_nnum++;
a_NumOutputs++;
}
// add and connect hidden neurons if seed type is != 0
if ((a_SeedType != 0) && (a_NumHidden > 0))
{
for(unsigned int i=0; i < (a_NumHidden); i++)
{
NeuronGene t_ngene(HIDDEN, t_nnum, 1.0);
// Initialize the neuron gene's properties
t_ngene.Init( (a_Parameters.MinActivationA + a_Parameters.MaxActivationA)/2.0f,
(a_Parameters.MinActivationB + a_Parameters.MaxActivationB)/2.0f,
(a_Parameters.MinNeuronTimeConstant + a_Parameters.MaxNeuronTimeConstant)/2.0f,
(a_Parameters.MinNeuronBias + a_Parameters.MaxNeuronBias)/2.0f,
a_HiddenActType );
t_ngene.m_SplitY = 0.5;
m_NeuronGenes.push_back( t_ngene );
t_nnum++;
}
if (!a_FS_NEAT)
{
// The links from each input to this hidden node
for(unsigned int i=0; i < (a_NumHidden); i++)
{
for(unsigned int j= 0; j < a_NumInputs; j++)
{
// add the link
// created with zero weights. needs future random initialization. !!!!!!!!
m_LinkGenes.push_back( LinkGene(j+1, i+a_NumInputs+a_NumOutputs+1, t_innovnum, 0.0, false) );
t_innovnum++;
}
}
// The links from this hidden node to each output
for(unsigned int i=0; i < (a_NumOutputs); i++)
{
for(unsigned int j= 0; j < a_NumHidden; j++)
{
// add the link
// created with zero weights. needs future random initialization. !!!!!!!!
m_LinkGenes.push_back( LinkGene(j+a_NumInputs+a_NumOutputs+1, i+a_NumInputs+1, t_innovnum, 0.0, false) );
t_innovnum++;
}
}
// Connect the bias to the outputs as well
for(unsigned int i=0; i < (a_NumOutputs); i++)
{
// add the link
// created with zero weights. needs future random initialization. !!!!!!!!
m_LinkGenes.push_back( LinkGene(a_NumInputs, i+a_NumInputs+1, t_innovnum, 0.0, false) );
t_innovnum++;
}
}
}
else // The links connecting every input to every output - perceptron structure
{
if ((!a_FS_NEAT) && (a_SeedType == 0))
{
for(unsigned int i=0; i < (a_NumOutputs); i++)
{
for(unsigned int j= 0; j < a_NumInputs; j++)
{
// add the link
// created with zero weights. needs future random initialization. !!!!!!!!
m_LinkGenes.push_back( LinkGene(j+1, i+a_NumInputs+1, t_innovnum, 0.0, false) );
t_innovnum++;
}
}
}
else
{
// Start very minimally - connect a random input to each output
// Also connect the bias to every output
for(unsigned int i=0; i < a_NumOutputs; i++)
{
int t_inp_id = t_RNG.RandInt(1, a_NumInputs-1);
int t_bias_id = a_NumInputs;
int t_outp_id = a_NumInputs+1 + i;
// created with zero weights. needs future random initialization. !!!!!!!!
m_LinkGenes.push_back( LinkGene(t_inp_id, t_outp_id, t_innovnum, 0.0, false) );
t_innovnum++;
m_LinkGenes.push_back( LinkGene(t_bias_id, t_outp_id, t_innovnum, 0.0, false) );
t_innovnum++;
}
}
}
m_Evaluated = false;
m_NumInputs = a_NumInputs;
m_NumOutputs = a_NumOutputs;
m_Fitness = 0.0;
m_AdjustedFitness = 0.0;
m_OffspringAmount = 0.0;
m_Depth = 0;
m_PhenotypeBehavior = NULL;
}
// Alternative constructor that creates a minimum genome with a leo output and if needed a gaussian seed.
/*
Genome::Genome(unsigned int a_ID,
unsigned int a_NumInputs,
unsigned int a_NumOutputs,
bool empty,
ActivationFunction a_OutputActType,
ActivationFunction a_HiddenActType,
const Parameters& a_Parameters)
{
ASSERT((a_NumInputs > 1) && (a_NumOutputs > 0));
RNG t_RNG;
t_RNG.TimeSeed();
m_ID = a_ID;
int t_innovnum = 1, t_nnum = 1;
double weight = 0.0;
int hid = 0;
//Add the inputs
for(unsigned int i=0; i < (a_NumInputs-1); i++)
{
m_NeuronGenes.push_back( NeuronGene(INPUT, t_nnum, 0.0) );
t_nnum++;
}
// Add bias
m_NeuronGenes.push_back( NeuronGene(BIAS, t_nnum, 0.0) );
t_nnum++;
// Add Outputs
for(unsigned int i=0; i < (a_NumOutputs); i++)
{
NeuronGene t_ngene(OUTPUT, t_nnum, 1.0);
// Initialize the neuron gene's properties
t_ngene.Init( (a_Parameters.MinActivationA + a_Parameters.MaxActivationA)/2.0f,
(a_Parameters.MinActivationB + a_Parameters.MaxActivationB)/2.0f,
(a_Parameters.MinNeuronTimeConstant + a_Parameters.MaxNeuronTimeConstant)/2.0f,
(a_Parameters.MinNeuronBias + a_Parameters.MaxNeuronBias)/2.0f,
a_OutputActType );
m_NeuronGenes.push_back( t_ngene );
t_nnum++;
}
if (a_Parameters.Leo)
{
NeuronGene t_ngene(OUTPUT, t_nnum, 1.0);
t_ngene.Init( (a_Parameters.MinActivationA + a_Parameters.MaxActivationA)/2.0f,
(a_Parameters.MinActivationB + a_Parameters.MaxActivationB)/2.0f,
(a_Parameters.MinNeuronTimeConstant + a_Parameters.MaxNeuronTimeConstant)/2.0f,
(a_Parameters.MinNeuronBias + a_Parameters.MaxNeuronBias)/2.0f,
UNSIGNED_STEP);
m_NeuronGenes.push_back( t_ngene );
t_nnum++;
a_NumOutputs++;
}
if (a_Parameters.GeometrySeed)
{
hid++;
// -----------------------------------------------------------------//
// Geometry seed
NeuronGene t_ngene(HIDDEN, t_nnum, 1.0);
// Initialize the neuron gene's properties
t_ngene.Init( (a_Parameters.MinActivationA + a_Parameters.MaxActivationA)/2.0f,
(a_Parameters.MinActivationB + a_Parameters.MaxActivationB)/2.0f,
(a_Parameters.MinNeuronTimeConstant + a_Parameters.MaxNeuronTimeConstant)/2.0f,
(a_Parameters.MinNeuronBias + a_Parameters.MaxNeuronBias)/2.0f,
SIGNED_GAUSS );
t_ngene.m_SplitY = 0.5;
m_NeuronGenes.push_back( t_ngene );
t_nnum++;
// y1 and y2 coords
m_LinkGenes.push_back( LinkGene(2, a_NumInputs+a_NumOutputs + hid, t_innovnum, 1, false) );
t_innovnum++;
m_LinkGenes.push_back( LinkGene(5, a_NumInputs+a_NumOutputs + hid, t_innovnum, -1 , false) );
t_innovnum++;
m_LinkGenes.push_back( LinkGene(a_NumInputs+a_NumOutputs + hid, a_NumInputs + hid, t_innovnum, 1.0, false) );
t_innovnum++;
// connect bias to GeoSeed
m_LinkGenes.push_back( LinkGene(a_NumInputs, a_NumInputs+a_NumOutputs + hid , t_innovnum, 0.33 , false) );
t_innovnum++;
}
if (a_Parameters.LeoSeed)
{
hid++;
NeuronGene t_ngene(HIDDEN, t_nnum, 1.0);
// Initialize the neuron gene's properties
t_ngene.Init( (a_Parameters.MinActivationA + a_Parameters.MaxActivationA)/2.0f,
(a_Parameters.MinActivationB + a_Parameters.MaxActivationB)/2.0f,
(a_Parameters.MinNeuronTimeConstant + a_Parameters.MaxNeuronTimeConstant)/2.0f,
(a_Parameters.MinNeuronBias + a_Parameters.MaxNeuronBias)/2.0f,
SIGNED_GAUSS );
t_ngene.m_SplitY = 0.5;
m_NeuronGenes.push_back( t_ngene );
t_nnum++;
//connect x1 and x2 to gaussian. Obviously need to get rid oft he hardcoded values.
m_LinkGenes.push_back( LinkGene(1, a_NumInputs+a_NumOutputs + hid, t_innovnum, 1, false) );
t_innovnum++;
m_LinkGenes.push_back( LinkGene(4, a_NumInputs+a_NumOutputs + hid, t_innovnum, -1 , false) );
t_innovnum++;
//connect gaussian node
//weight = t_RNG.RandFloatClamped()*a_Parameters.MaxWeight;
m_LinkGenes.push_back( LinkGene(a_NumInputs+a_NumOutputs + hid, a_NumInputs+a_NumOutputs, t_innovnum, 1.0, false) );
t_innovnum++;
}
//Genome with only bias connected
if (empty)
{
if (a_Parameters.Leo && a_Parameters.LeoSeed) // Connect bias to LEO.
{
//weight = t_RNG.RandFloatClamped()*a_Parameters.MaxWeight;
m_LinkGenes.push_back( LinkGene(a_NumInputs, a_NumInputs+a_NumOutputs , t_innovnum, 1.0 , false) );
t_innovnum++;
}
else
{
for(unsigned int i=0; i < (a_NumOutputs); i++)
{
weight = t_RNG.RandFloatClamped()*a_Parameters.MaxWeight;
m_LinkGenes.push_back( LinkGene(a_NumInputs, a_NumInputs+i+1 , t_innovnum, weight , false) );
t_innovnum++;
}
}
}
// Or just buld a fully connected minimal genome, eh?
else
{
//connect x1 and x2 to gaussian. Obviously need to get rid oft he hardcoded values.
m_LinkGenes.push_back( LinkGene(1, a_NumInputs+1, t_innovnum, 1, false) );
t_innovnum++;
m_LinkGenes.push_back( LinkGene(4, a_NumInputs+1, t_innovnum, -1 , false) );
t_innovnum++;
}
// setup final properties
m_Evaluated = false;
m_NumInputs = a_NumInputs;
m_NumOutputs = a_NumOutputs;
m_Fitness = 0.0;
m_AdjustedFitness = 0.0;
m_OffspringAmount = 0.0;
m_Depth = 0;
m_PhenotypeBehavior = NULL;
Performance = 0.0;
Length = 0.0;
}
*/
// A little helper function to find the index of a neuron, given its ID
// returns -1 if not found
int Genome::GetNeuronIndex(unsigned int a_ID) const
{
ASSERT(a_ID > 0);
for(unsigned int i=0; i < NumNeurons(); i++)
{
if (m_NeuronGenes[i].ID() == a_ID)
{
return i;
}
}
return -1;
}
// A little helper function to find the index of a link, given its innovation ID
// returns -1 if not found
int Genome::GetLinkIndex(unsigned int a_InnovID) const
{
ASSERT(a_InnovID > 0);
ASSERT(NumLinks() > 0);
for(unsigned int i=0; i < NumLinks(); i++)
{
if (m_LinkGenes[i].InnovationID() == a_InnovID)
{
return i;
}
}
return -1;
}
// returns the max neuron ID
unsigned int Genome::GetLastNeuronID() const
{
ASSERT(NumNeurons() > 0);
unsigned int t_maxid = 0;
for(unsigned int i=0; i< NumNeurons(); i++)
{
if (m_NeuronGenes[i].ID() > t_maxid)
t_maxid = m_NeuronGenes[i].ID();
}
return t_maxid+1;
}
// returns the max innovation Id
unsigned int Genome::GetLastInnovationID() const
{
ASSERT(NumLinks() > 0);
unsigned int t_maxid = 0;
for(unsigned int i=0; i< NumLinks(); i++)
{
if (m_LinkGenes[i].InnovationID() > t_maxid)
t_maxid = m_LinkGenes[i].InnovationID();
}
return t_maxid+1;
}
// Returns true if the specified neuron ID is present in the genome
bool Genome::HasNeuronID(unsigned int a_ID) const
{
ASSERT(a_ID > 0);
ASSERT(NumNeurons() > 0);
for(unsigned int i=0; i<NumNeurons(); i++)
{
if (m_NeuronGenes[i].ID() == a_ID)
{
return true;
}
}
return false;
}
// Returns true if the specified link is present in the genome
bool Genome::HasLink(unsigned int a_n1id, unsigned int a_n2id) const
{
ASSERT((a_n1id>0)&&(a_n2id>0));
for(unsigned int i=0; i<NumLinks(); i++)
{
if ((m_LinkGenes[i].FromNeuronID() == a_n1id) && (m_LinkGenes[i].ToNeuronID() == a_n2id))
{
return true;
}
}
return false;
}
// Returns true if the specified link is present in the genome
bool Genome::HasLinkByInnovID(unsigned int id) const
{
ASSERT(id > 0);
for(unsigned int i=0; i<NumLinks(); i++)
{
if (m_LinkGenes[i].InnovationID() == id)
{
return true;
}
}
return false;
}
// This builds a fastnetwork structure out from the genome
void Genome::BuildPhenotype(NeuralNetwork& a_Net) const
{
// first clear out the network
a_Net.Clear();
a_Net.SetInputOutputDimentions(m_NumInputs, m_NumOutputs);
// Fill the net with the neurons
for(unsigned int i=0; i<NumNeurons(); i++)
{
Neuron t_n;
t_n.m_a = m_NeuronGenes[i].m_A;
t_n.m_b = m_NeuronGenes[i].m_B;
t_n.m_timeconst = m_NeuronGenes[i].m_TimeConstant;
t_n.m_bias = m_NeuronGenes[i].m_Bias;
t_n.m_activation_function_type = m_NeuronGenes[i].m_ActFunction;
t_n.m_split_y = m_NeuronGenes[i].SplitY();
t_n.m_type = m_NeuronGenes[i].Type();
a_Net.AddNeuron( t_n );
}
// Fill the net with the connections
for(unsigned int i=0; i<NumLinks(); i++)
{
Connection t_c;
t_c.m_source_neuron_idx = GetNeuronIndex( m_LinkGenes[i].FromNeuronID() );
t_c.m_target_neuron_idx = GetNeuronIndex( m_LinkGenes[i].ToNeuronID() );
t_c.m_weight = m_LinkGenes[i].GetWeight();
t_c.m_recur_flag = m_LinkGenes[i].IsRecurrent();
//////////////////////
// stupid hack
t_c.m_hebb_rate = 0.3;
t_c.m_hebb_pre_rate = 0.1;
//////////////////////
a_Net.AddConnection( t_c );
}
a_Net.Flush();
// Note however that the RTRL variables are not initialized.
// The user must manually call the InitRTRLMatrix() method to do it.
// This is because of storage issues. RTRL need not to be used every time.
}
// Builds a HyperNEAT phenotype based on the substrate
// The CPPN input dimensionality must match the largest number of
// dimensions in the substrate
// The output dimensionality is determined according to flags set in the
// substrate
// The procedure uses the [0] CPPN output for creating nodes, and if the substrate is leaky, [1] and [2] for time constants and biases
// Also assumes the CPPN uses signed activation outputs
void Genome::BuildHyperNEATPhenotype(NeuralNetwork& net, Substrate& subst)
{
// We need a substrate with at least one input and output
ASSERT(subst.m_input_coords.size() > 0);
ASSERT(subst.m_output_coords.size() > 0);
int max_dims = subst.GetMaxDims();
// Make sure the CPPN dimensionality is right
ASSERT(subst.GetMinCPPNInputs() > 0);
ASSERT(NumInputs() >= subst.GetMinCPPNInputs());
ASSERT(NumOutputs() >= subst.GetMinCPPNOutputs());
if (subst.m_leaky)
{
ASSERT(NumOutputs() >= subst.GetMinCPPNOutputs());
}
// Now we create the substrate (net)
net.SetInputOutputDimentions(static_cast<unsigned short>(subst.m_input_coords.size()),
static_cast<unsigned short>(subst.m_output_coords.size()));
// Inputs
for(unsigned int i=0; i<subst.m_input_coords.size(); i++)
{
Neuron t_n;
t_n.m_a = 1;
t_n.m_b = 0;
t_n.m_substrate_coords = subst.m_input_coords[i];
ASSERT(t_n.m_substrate_coords.size() > 0); // prevent 0D points
t_n.m_activation_function_type = NEAT::LINEAR;
t_n.m_type = NEAT::INPUT;
net.AddNeuron(t_n);
}
// Output
for(unsigned int i=0; i<subst.m_output_coords.size(); i++)
{
Neuron t_n;
t_n.m_a = 1;
t_n.m_b = 0;
t_n.m_substrate_coords = subst.m_output_coords[i];
ASSERT(t_n.m_substrate_coords.size() > 0); // prevent 0D points
t_n.m_activation_function_type = subst.m_output_nodes_activation;
t_n.m_type = NEAT::OUTPUT;
net.AddNeuron(t_n);
}
// Hidden
for(unsigned int i=0; i<subst.m_hidden_coords.size(); i++)
{
Neuron t_n;
t_n.m_a = 1;
t_n.m_b = 0;
t_n.m_substrate_coords = subst.m_hidden_coords[i];
ASSERT(t_n.m_substrate_coords.size() > 0); // prevent 0D points
t_n.m_activation_function_type = subst.m_hidden_nodes_activation;
t_n.m_type = NEAT::HIDDEN;
net.AddNeuron(t_n);
}
// Begin querying the CPPN
// Create the neural network that will represent the CPPN
NeuralNetwork t_temp_phenotype(true);
BuildPhenotype(t_temp_phenotype);
t_temp_phenotype.Flush();
// now loop over every potential connection in the substrate and take its weight
//CalculateDepth();
int dp = 8;//GetDepth();
// For leaky substrates, first loop over the neurons and set their properties
if (subst.m_leaky)
{
for(unsigned int i=net.NumInputs(); i<net.m_neurons.size(); i++)
{
// neuron specific stuff
t_temp_phenotype.Flush();
// Inputs for the generation of time consts and biases across
// the nodes in the substrate
// We input only the position of the first node and ignore the other one
std::vector<double> t_inputs;
t_inputs.resize(NumInputs());
for(unsigned int n=0; n<net.m_neurons[i].m_substrate_coords.size(); n++)
{
t_inputs[n] = net.m_neurons[i].m_substrate_coords[n];
}
if (subst.m_with_distance)
{
// compute the Eucledian distance between the point and the origin
double sum=0;
for(int n=0; n<max_dims; n++)
{
sum += sqr(t_inputs[n]);
}
sum = sqrt(sum);
t_inputs[NumInputs() - 2] = sum;
}
t_inputs[NumInputs() - 1] = 1.0; // the CPPN's bias
t_temp_phenotype.Input(t_inputs);
// activate as many times as deep
for(int d=0; d<dp; d++)
{
t_temp_phenotype.Activate();
}
double t_tc = t_temp_phenotype.Output()[NumOutputs()-2];
double t_bias = t_temp_phenotype.Output()[NumOutputs()-1];
Clamp(t_tc, -1, 1);
Clamp(t_bias, -1, 1);
// rescale the values
Scale(t_tc, -1, 1, subst.m_min_time_const, subst.m_max_time_const);
Scale(t_bias, -1, 1, -subst.m_max_weight_and_bias, subst.m_max_weight_and_bias);
net.m_neurons[i].m_timeconst = t_tc;
net.m_neurons[i].m_bias = t_bias;
}
}
// list of src_idx, dst_idx pairs of all connections to query
std::vector< std::vector<int> > t_to_query;
// There isn't custom connectiviy scheme?
if (subst.m_custom_connectivity.size() == 0)
{
// only incoming connections, so loop only the hidden and output neurons
for(unsigned int i=net.NumInputs(); i<net.m_neurons.size(); i++)
{
// loop all neurons
for(unsigned int j=0; j<net.m_neurons.size(); j++)
{
// this is connection "j" to "i"
// conditions for canceling the CPPN query
if (
( (!subst.m_allow_input_hidden_links) &&
( (net.m_neurons[j].m_type == INPUT ) && (net.m_neurons[i].m_type == HIDDEN) ))
|| ( (!subst.m_allow_input_output_links) &&
( (net.m_neurons[j].m_type == INPUT ) && (net.m_neurons[i].m_type == OUTPUT) ))
|| ( (!subst.m_allow_hidden_hidden_links) &&
( (net.m_neurons[j].m_type == HIDDEN ) && (net.m_neurons[i].m_type == HIDDEN) && (i != j)))
|| ( (!subst.m_allow_hidden_output_links) &&
( (net.m_neurons[j].m_type == HIDDEN ) && (net.m_neurons[i].m_type == OUTPUT) ))
|| ( (!subst.m_allow_output_hidden_links) &&
( (net.m_neurons[j].m_type == OUTPUT ) && (net.m_neurons[i].m_type == HIDDEN) ))
|| ( (!subst.m_allow_output_output_links) &&
( (net.m_neurons[j].m_type == OUTPUT ) && (net.m_neurons[i].m_type == OUTPUT) && (i != j)))
|| ( (!subst.m_allow_looped_hidden_links) &&
( (net.m_neurons[j].m_type == HIDDEN ) && (net.m_neurons[i].m_type == HIDDEN) && (i == j)))
|| ( (!subst.m_allow_looped_output_links) &&
( (net.m_neurons[j].m_type == OUTPUT ) && (net.m_neurons[i].m_type == OUTPUT) && (i == j)))
)
{
continue;
}
// Save potential link to query
std::vector<int> t_link;
t_link.push_back(j);
t_link.push_back(i);
t_to_query.push_back(t_link);
}
}
}
else
{
// use the custom connectivity
for(unsigned int idx=0; idx<subst.m_custom_connectivity.size(); idx++)
{
NeuronType src_type = (NeuronType) subst.m_custom_connectivity[idx][0];
int src_idx = subst.m_custom_connectivity[idx][1];
NeuronType dst_type = (NeuronType) subst.m_custom_connectivity[idx][2];
int dst_idx = subst.m_custom_connectivity[idx][3];
// determine the indices in the NN
int j; // src
int i; // dst
if ((src_type == INPUT) || (src_type == BIAS))
{
j = src_idx;
}
else
if (src_type == HIDDEN)
{
j = subst.m_input_coords.size() + subst.m_output_coords.size() + src_idx;
}
else
if (src_type == OUTPUT)
{
j = subst.m_input_coords.size() + src_idx;
}
if ((dst_type == INPUT) || (dst_type == BIAS))
{
i = dst_idx;
}
else
if (dst_type == HIDDEN)
{
i = subst.m_input_coords.size() + subst.m_output_coords.size() + dst_idx;
}
else
if (dst_type == OUTPUT)
{
i = subst.m_input_coords.size() + dst_idx;
}
// conditions for canceling the CPPN query
if (subst.m_custom_conn_obeys_flags && (
( (!subst.m_allow_input_hidden_links) &&
( (net.m_neurons[j].m_type == INPUT ) && (net.m_neurons[i].m_type == HIDDEN) ))
|| ( (!subst.m_allow_input_output_links) &&
( (net.m_neurons[j].m_type == INPUT ) && (net.m_neurons[i].m_type == OUTPUT) ))
|| ( (!subst.m_allow_hidden_hidden_links) &&
( (net.m_neurons[j].m_type == HIDDEN ) && (net.m_neurons[i].m_type == HIDDEN) && (i != j)))
|| ( (!subst.m_allow_hidden_output_links) &&
( (net.m_neurons[j].m_type == HIDDEN ) && (net.m_neurons[i].m_type == OUTPUT) ))
|| ( (!subst.m_allow_output_hidden_links) &&
( (net.m_neurons[j].m_type == OUTPUT ) && (net.m_neurons[i].m_type == HIDDEN) ))
|| ( (!subst.m_allow_output_output_links) &&
( (net.m_neurons[j].m_type == OUTPUT ) && (net.m_neurons[i].m_type == OUTPUT) && (i != j)))
|| ( (!subst.m_allow_looped_hidden_links) &&
( (net.m_neurons[j].m_type == HIDDEN ) && (net.m_neurons[i].m_type == HIDDEN) && (i == j)))
|| ( (!subst.m_allow_looped_output_links) &&
( (net.m_neurons[j].m_type == OUTPUT ) && (net.m_neurons[i].m_type == OUTPUT) && (i == j)))
)
)
{
continue;
}
// Save potential link to query
std::vector<int> t_link;
t_link.push_back(j);
t_link.push_back(i);
t_to_query.push_back(t_link);
}
}
// Query and create all links
for(unsigned int conn=0; conn<t_to_query.size(); conn++)
{
int j = t_to_query[conn][0];
int i = t_to_query[conn][1];
// Take the weight of this connection by querying the CPPN
// as many times as deep (recurrent or looped CPPNs may be very slow!!!*)
std::vector<double> t_inputs;
t_inputs.resize(NumInputs());
int from_dims = net.m_neurons[j].m_substrate_coords.size();
int to_dims = net.m_neurons[i].m_substrate_coords.size();
// input the node positions to the CPPN
// from
for(int n=0; n<from_dims; n++)
{
t_inputs[n] = net.m_neurons[j].m_substrate_coords[n];
}
// to
for(int n=0; n<to_dims; n++)
{
t_inputs[max_dims + n] = net.m_neurons[i].m_substrate_coords[n];
}
// the input is like
// x000|xx00|1 - 1D -> 2D connection
// xx00|xx00|1 - 2D -> 2D connection
// xx00|xxx0|1 - 2D -> 3D connection
// if max_dims is 4 and no distance input
if (subst.m_with_distance)
{
// compute the Eucledian distance between the two points
// differing dimensionality doesn't matter as the extra dimensions are 0s
double sum=0;
for(int n=0; n<max_dims; n++)
{
sum += sqr(t_inputs[n] - t_inputs[max_dims+n]);
}
sum = sqrt(sum);
t_inputs[NumInputs() - 2] = sum;
}
t_inputs[NumInputs() - 1] = 1.0;
// flush between each query
t_temp_phenotype.Flush();
t_temp_phenotype.Input(t_inputs);
// activate as many times as deep
for(int d=0; d<dp; d++)
{
t_temp_phenotype.Activate();
}
// the output is a weight
double t_link = 0; ;
double t_weight = 0;
if (subst.m_query_weights_only)
{
t_weight = t_temp_phenotype.Output()[0];
}
else
{
t_link = t_temp_phenotype.Output()[0];
t_weight = t_temp_phenotype.Output()[1];
}
// Clamp(t_weight, -1, 1);
if (((t_link > 0) && (!subst.m_query_weights_only)) || (subst.m_query_weights_only))
{
// now this weight will be scaled
t_weight *= subst.m_max_weight_and_bias;
// build the connection
Connection t_c;
t_c.m_source_neuron_idx = j;
t_c.m_target_neuron_idx = i;
t_c.m_weight = t_weight;
t_c.m_recur_flag = false;
net.AddConnection(t_c);
}
}
}
// Projects the weight changes of a phenotype back to the genome.
// WARNING! Using this too often in conjuction with RTRL can confuse evolution.
void Genome::DerivePhenotypicChanges(NeuralNetwork& a_Net)
{
// the a_Net and the genome must have identical topology.
// if the topology differs, no changes will be made to the genome
// Since we don't have a comparison operator yet, we are going to assume
// identical topolgy