-
Notifications
You must be signed in to change notification settings - Fork 1
/
bundle.js
5636 lines (4434 loc) · 191 KB
/
bundle.js
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
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var neatjs = require('neatjs');
// var neatGenome = neatjs.loadLibraryFile('neatjs', 'neatGenome');
var weightRange = 2;
var connectionProportion = 1;
var ins = 2;
var outs = 1;
//clear out genome IDs and innovation IDs
neatjs.neatGenome.Help.resetGenomeID();
// NeatGenome.Help.resetInnovationID();
var ng = neatjs.neatGenome.Help.CreateGenomeByInnovation(ins,
outs, {connectionProportion: connectionProportion, connectionWeightRange: weightRange});
//console.log( ng );
},{"neatjs":8}],2:[function(require,module,exports){
/**
* Module dependencies.
*/
var NeatGenome = require('../genome/neatGenome.js');
//pull in variables from cppnjs
var cppnjs = require('cppnjs');
var utilities = cppnjs.utilities;
/**
* Expose `iec objects`.
*/
module.exports = GenericIEC;
//seeds are required -- and are expected to be the correct neatGenome types
function GenericIEC(np, seeds, iecOptions)
{
var self = this;
self.options = iecOptions || {};
self.np = np;
//we keep track of new nodes and connections for the session
self.newNodes = {};
self.newConnections = {};
//we can send in a seed genome -- to create generic objects when necessary
self.seeds = seeds;
for(var s=0; s < seeds.length; s++)
{
var seed = seeds[s];
for(var c =0; c < seed.connections.length; c++)
{
var sConn = seed.connections[c];
var cid = '(' + sConn.sourceID + ',' + sConn.targetID + ')';
self.newConnections[cid] = sConn;
}
}
self.cloneSeed = function(){
var seedIx = utilities.next(self.seeds.length);
var seedCopy = NeatGenome.Copy(self.seeds[seedIx]);
if(self.options.seedMutationCount)
{
for(var i=0; i < self.options.seedMutationCount; i++)
seedCopy.mutate(self.newNodes, self.newConnections, self.np);
}
return seedCopy;
};
self.markParentConnections = function(parents){
for(var s=0; s < parents.length; s++)
{
var parent = parents[s];
for(var c =0; c < parent.connections.length; c++)
{
var sConn = parent.connections[c];
var cid = '(' + sConn.sourceID + ',' + sConn.targetID + ')';
self.newConnections[cid] = sConn;
}
}
};
//this function handles creating a genotype from sent in parents.
//it's pretty simple -- however many parents you have, select a random number of them, and attempt to mate them
self.createNextGenome = function(parents)
{
self.markParentConnections(parents);
//IF we have 0 parents, we create a genome with the default configurations
var ng;
var initialMutationCount = self.options.initialMutationCount || 0,
postXOMutationCount = self.options.postMutationCount || 0;
var responsibleParents = [];
switch(parents.length)
{
case 0:
//parents are empty -- start from scratch!
ng = self.cloneSeed();
for(var m=0; m < initialMutationCount; m++)
ng.mutate(self.newNodes, self.newConnections, self.np);
//no responsible parents
break;
case 1:
//we have one parent
//asexual reproduction
ng = parents[0].createOffspringAsexual(self.newNodes, self.newConnections, self.np);
//parent at index 0 responsible
responsibleParents.push(0);
for(var m=0; m < postXOMutationCount; m++)
ng.mutate(self.newNodes, self.newConnections, self.np);
break;
default:
//greater than 1 individual as a possible parent
//at least 1 parent, and at most self.activeParents.count # of parents
var parentCount = 1 + utilities.next(parents.length);
if(parentCount == 1)
{
//select a single parent for offspring
var rIx = utilities.next(parents.length);
ng = parents[rIx].createOffspringAsexual(self.newNodes, self.newConnections, self.np);
//1 responsible parent at index 0
responsibleParents.push(rIx);
break;
}
//we expect active parents to be small, so we grab parentCount number of parents from a small array of parents
var parentIxs = utilities.RouletteWheel.selectXFromSmallObject(parentCount, parents);
var p1 = parents[parentIxs[0]], p2;
//if I have 3 parents, go in order composing the objects
responsibleParents.push(parentIxs[0]);
//p1 mates with p2 to create o1, o1 mates with p3, to make o2 -- p1,p2,p3 are all combined now inside of o2
for(var i=1; i < parentIxs.length; i++)
{
p2 = parents[parentIxs[i]];
ng = p1.createOffspringSexual(p2, self.np);
p1 = ng;
responsibleParents.push(parentIxs[i]);
}
for(var m=0; m < postXOMutationCount; m++)
ng.mutate(self.newNodes, self.newConnections, self.np);
break;
}
//we have our genome, let's send it back
//the reason we don't end it inisde the switch loop is that later, we might be interested in saving this genome from some other purpose
return {offspring: ng, parents: responsibleParents};
};
};
},{"../genome/neatGenome.js":6,"cppnjs":14}],3:[function(require,module,exports){
//here we have everything for NSGA-II mutliobjective search and neatjs
/**
* Module dependencies.
*/
var NeatGenome = require('../genome/neatGenome.js');
var Novelty = require('./novelty.js');
//pull in variables from cppnjs
var cppnjs = require('cppnjs');
var utilities = cppnjs.utilities;
/**
* Expose `MultiobjectiveSearch`.
*/
module.exports = MultiobjectiveSearch;
//information to rank each genome
MultiobjectiveSearch.RankInfo = function()
{
var self = this;
//when iterating, we count how many genomes dominate other genomes
self.dominationCount = 0;
//who does this genome dominate
self.dominates = [];
//what is this genome's rank (i.e. what pareto front is it on)
self.rank = 0;
//has this genome been ranked
self.ranked = false;
};
MultiobjectiveSearch.RankInfo.prototype.reset = function(){
var self = this;
self.rank = 0;
self.ranked = false;
self.dominationCount = 0;
self.dominates = [];
};
MultiobjectiveSearch.Help = {};
MultiobjectiveSearch.Help.SortPopulation = function(pop)
{
//sort genomes by fitness / age -- as genomes are often sorted
pop.sort(function(x,y){
var fitnessDelta = y.fitness - x.fitness;
if (fitnessDelta < 0.0)
return -1;
else if (fitnessDelta > 0.0)
return 1;
var ageDelta = x.age - y.age;
// Convert result to an int.
if (ageDelta < 0)
return -1;
else if (ageDelta > 0)
return 1;
return 0;
});
};
//class to assign multiobjective fitness to individuals (fitness based on what pareto front they are on)
MultiobjectiveSearch.multiobjectiveUtilities = function(np)
{
var self = this;
self.np = np;
self.population = [];
self.populationIDs = {};
self.ranks = [];
self.nov = new Novelty(10.0);
self.doNovelty = false;
self.generation = 0;
self.localCompetition = false;
self.measureNovelty = function()
{
var count = self.population.length;
self.nov.initialize(self.population);
//reset locality and competition for each genome
for(var i=0; i < count; i++)
{
var genome = self.population[i];
genome.locality=0.0;
genome.competition=0.0;
//we measure all objectives locally -- just to make it simpler
for(var o=0; o < genome.objectives.length; o++)
genome.localObjectivesCompetition[o] = 0.0;
}
var ng;
var max = 0.0, min = 100000000000.0;
for (var i = 0; i< count; i++)
{
ng = self.population[i];
var fit = self.nov.measureNovelty(ng);
//reset our fitness value to be local, yeah boyee
//the first objective is fitness which is replaced with local fitness -- how many did you beat around you
// # won / total number of neighbors = % competitive
ng.objectives[0] = ng.competition / ng.nearestNeighbors;
ng.objectives[ng.objectives.length - 2] = fit + 0.01;
//the last local measure is the genome novelty measure
var localGenomeNovelty = ng.localObjectivesCompetition[ng.objectives.length-1];
//genomic novelty is measured locally as well
console.log("Genomic Novelty: " + ng.objectives[ng.objectives.length - 1] + " After: " + localGenomeNovelty / ng.nearestNeighbors);
//this makes genomic novelty into a local measure
ng.objectives[ng.objectives.length - 1] = localGenomeNovelty / ng.nearestNeighbors;
if(fit>max) max=fit;
if(fit<min) min=fit;
}
console.log("nov min: "+ min + " max:" + max);
};
//if genome x dominates y, increment y's dominated count, add y to x's dominated list
self.updateDomination = function( x, y, r1, r2)
{
if(self.dominates(x,y)) {
r1.dominates.push(r2);
r2.dominationCount++;
}
};
//function to check whether genome x dominates genome y, usually defined as being no worse on all
//objectives, and better at at least one
self.dominates = function( x, y) {
var better=false;
var objx = x.objectives, objy = y.objectives;
var sz = objx.length;
//if x is ever worse than y, it cannot dominate y
//also check if x is better on at least one
for(var i=0;i<sz-1;i++) {
if(objx[i]<objy[i]) return false;
if(objx[i]>objy[i]) better=true;
}
//genomic novelty check, disabled for now
//threshold set to 0 -- Paul since genome is local
var thresh=0.0;
if((objx[sz-1]+thresh)<(objy[sz-1])) return false;
if((objx[sz-1]>(objy[sz-1]+thresh))) better=true;
return better;
};
//distance function between two lists of objectives, used to see if two individuals are unique
self.distance = function(x, y) {
var delta=0.0;
var len = x.length;
for(var i=0;i<len;i++) {
var d=x[i]-y[i];
delta+=d*d;
}
return delta;
};
//Todo: Print to file
self.printDistribution = function()
{
var filename="dist"+ self.generation+".txt";
var content="";
console.log("Print to file disabled for now, todo: write in save to file!");
// XmlDocument archiveout = new XmlDocument();
// XmlPopulationWriter.WriteGenomeList(archiveout, population);
// archiveout.Save(filename);
};
//currently not used, calculates genomic novelty objective for protecting innovation
//uses a rough characterization of topology, i.e. number of connections in the genome
self.calculateGenomicNovelty = function() {
var sum=0.0;
var max_conn = 0;
var xx, yy;
for(var g=0; g < self.population.length; g++) {
xx = self.population[g];
var minDist=10000000.0;
var difference=0.0;
var delta=0.0;
//double array
var distances= [];
if(xx.connections.length > max_conn)
max_conn = xx.connections.length;
//int ccount=xx.ConnectionGeneList.Count;
for(var g2=0; g2 < self.population.length; g2++) {
yy = self.population[g2];
if(g==g2)
continue;
//measure genomic compatability using neatparams
var d = xx.compat(yy, np);
//if(d<minDist)
// minDist=d;
distances.push(d);
}
//ascending order
//want the closest individuals
distances.Sort(function(a,b) {return a-b;});
//grab the 10 closest distances
var sz=Math.min(distances.length,10);
var diversity = 0.0;
for(var i=0;i<sz;i++)
diversity+=distances[i];
xx.objectives[xx.objectives.length-1] = diversity;
sum += diversity;
}
console.log("Diversity: " + sum/population.length + " " + max_conn);
};
//add an existing population from hypersharpNEAT to the multiobjective population maintained in
//this class, step taken before evaluating multiobjective population through the rank function
self.addPopulation = function(genomes)
{
for(var i=0;i< genomes.length;i++)
{
var blacklist=false;
//TODO: I'm not sure this is correct, since genomes coming in aren't measured locally yet
//so in some sense, we're comparing local measures to global measures and seeing how far
//if they are accidentally close, this could be bad news
// for(var j=0;j<self.population.length; j++)
// {
// if(self.distance(genomes[i].behavior.objectives, self.population[j].objectives) < 0.01)
// blacklist=true; //reject a genome if it is very similar to existing genomes in pop
// }
//no duplicates please
if(self.populationIDs[genomes[i].gid])
blacklist = true;
//TODO: Test if copies are needed, or not?
if(!blacklist) {
//add genome if it is unique
//we might not need to make copies
//this will make a copy of the behavior
// var copy = new neatGenome.NeatGenome.Copy(genomes[i], genomes[i].gid);
// self.population.push(copy);
//push directly into population, don't use copy -- should test if this is a good idea?
self.population.push(genomes[i]);
self.populationIDs[genomes[i].gid] = genomes[i];
}
}
};
self.rankGenomes = function()
{
var size = self.population.length;
self.calculateGenomicNovelty();
if(self.doNovelty) {
self.measureNovelty();
}
//reset rank information
for(var i=0;i<size;i++) {
if(self.ranks.length<i+1)
self.ranks.push(new MultiobjectiveSearch.RankInfo());
else
self.ranks[i].reset();
}
//calculate domination by testing each genome against every other genome
for(var i=0;i<size;i++) {
for(var j=0;j<size;j++) {
self.updateDomination(self.population[i], self.population[j],self.ranks[i],self.ranks[j]);
}
}
//successively peel off non-dominated fronts (e.g. those genomes no longer dominated by any in
//the remaining population)
var front = [];
var ranked_count=0;
var current_rank=1;
while(ranked_count < size) {
//search for non-dominated front
for(var i=0;i<size;i++)
{
//continue if already ranked
if(self.ranks[i].ranked) continue;
//if not dominated, add to front
if(self.ranks[i].dominationCount==0) {
front.push(i);
self.ranks[i].ranked=true;
self.ranks[i].rank = current_rank;
}
}
var front_size = front.length;
console.log("Front " + current_rank + " size: " + front_size);
//now take all the non-dominated individuals, see who they dominated, and decrease
//those genomes' domination counts, because we are removing this front from consideration
//to find the next front of individuals non-dominated by the remaining individuals in
//the population
for(var i=0;i<front_size;i++) {
var r = self.ranks[front[i]];
for (var dominated in r.dominates) {
dominated.dominationCount--;
}
}
ranked_count+=front_size;
front = [];
current_rank++;
}
//we save the last objective for potential use as genomic novelty objective
var last_obj = self.population[0].objectives.length-1;
//fitness = popsize-rank (better way might be maxranks+1-rank), but doesn't matter
//because speciation is not used and tournament selection is employed
for(var i=0;i<size;i++) {
self.population[i].fitness = (size+1)-self.ranks[i].rank;//+population[i].objectives[last_obj]/100000.0;
}
//sorting based on fitness
MultiobjectiveSearch.Help.SortPopulation(self.population);
self.generation++;
if(self.generation%250==0)
self.printDistribution();
};
//when we merge populations together, often the population will overflow, and we need to cut
//it down. to do so, we just remove the last x individuals, which will be in the less significant
//pareto fronts
self.truncatePopulation = function(size)
{
var toRemove = self.population.length - size;
console.log("population size before: " + self.population.length);
console.log("removing " + toRemove);
//remove the tail after sorting
if(toRemove > 0)
self.population.splice(size, toRemove);
//changes to population, make sure to update our lookup
self.populationIDs = NeatGenome.Help.CreateGIDLookup(self.population);
console.log("population size after: " + self.population.length);
return self.population;
};
};
function MultiobjectiveSearch(seedGenomes, genomeEvaluationFunctions, neatParameters, searchParameters)
{
var self=this;
//functions for evaluating genomes in a population
self.genomeEvaluationFunctions = genomeEvaluationFunctions;
self.generation = 0;
self.np = neatParameters;
self.searchParameters = searchParameters;
//for now, we just set seed genomes as population
//in reality, we should use seed genomes as seeds into population determined by search parameters
//i.e. 5 seed genomes -> 50 population size
//TODO: Turn seed genomes into full first population
self.population = seedGenomes;
//create genome lookup once we have population
self.populationIDs = NeatGenome.Help.CreateGIDLookup(seedGenomes);
//see end of multiobjective search declaration for initailization code
self.multiobjective= new MultiobjectiveSearch.multiobjectiveUtilities(neatParameters);
self.np.compatibilityThreshold = 100000000.0; //disable speciation w/ multiobjective
self.initializePopulation = function()
{
// The GenomeFactories normally won't bother to ensure that like connections have the same ID
// throughout the population (because it's not very easy to do in most cases). Therefore just
// run this routine to search for like connections and ensure they have the same ID.
// Note. This could also be done periodically as part of the search, remember though that like
// connections occuring within a generation are already fixed - using a more efficient scheme.
self.matchConnectionIDs();
// Evaluate the whole population.
self.evaluatePopulation();
//TODO: Add in some concept of speciation for NSGA algorithm -- other than genomic novelty?
//We don't do speciation for NSGA-II algorithm
// Now we have fitness scores and no speciated population we can calculate fitness stats for the
// population as a whole -- and save best genomes
//recall that speciation is NOT part of NSGA-II
self.updateFitnessStats();
};
self.matchConnectionIDs = function()
{
var connectionIdTable = {};
var genomeBound = self.population.length;
for(var genomeIdx=0; genomeIdx<genomeBound; genomeIdx++)
{
var genome = self.population[genomeIdx];
//loop through all the connections for this genome
var connectionGeneBound = genome.connections.length;
for(var connectionGeneIdx=0; connectionGeneIdx<connectionGeneBound; connectionGeneIdx++)
{
var connectionGene = genome.connections[connectionGeneIdx];
var ces = connectionGene.sourceID + "," + connectionGene.targetID;
var existingID = connectionIdTable[ces];
if(existingID==null)
{ // No connection withthe same end-points has been registered yet, so
// add it to the table.
connectionIdTable[ces] = connectionGene.gid;
}
else
{ // This connection is already registered. Give our latest connection
// the same innovation ID as the one in the table.
connectionGene.gid = existingID;
}
}
// The connection genes in this genome may now be out of order. Therefore we must ensure
// they are sorted before we continue.
genome.connections.sort(function(a,b){
return a.gid - b.gid;
});
}
};
self.incrementAges = function()
{
//would normally increment species age as well, but doesn't happen in multiobjective
for(var i=0; i < self.population.length; i++)
{
var ng = self.population[i];
ng.age++;
}
};
self.updateFitnessStats = function()
{
self.bestFitness = Number.MIN_VALUE;
self.bestGenome = null;
self.totalNeuronCount = 0;
self.totalConnectionCount = 0;
self.totalFitness = 0;
self.avgComplexity = 0;
self.meanFitness =0;
//go through the genomes, find the best genome and the most fit
for(var i=0; i < self.population.length; i++)
{
var ng = self.population[i];
if(ng.realFitness > self.bestFitness)
{
self.bestFitness = ng.realFitness;
self.bestGenome = ng;
}
self.totalNeuronCount += ng.nodes.length;
self.totalConnectionCount += ng.connections.length;
self.totalFitness += ng.realFitness;
}
self.avgComplexity = (self.totalNeuronCount + self.totalConnectionCount)/self.population.length;
self.meanFitness = self.totalFitness/self.population.length;
};
self.tournamentSelect = function(genomes)
{
var bestFound= 0.0;
var bestGenome=null;
var bound = genomes.length;
//grab the best of 4 by default, can be more attempts than that
for(var i=0;i<self.np.tournamentSize;i++) {
var next= genomes[utilities.next(bound)];
if (next.fitness > bestFound) {
bestFound=next.fitness;
bestGenome=next;
}
}
return bestGenome;
};
self.evaluatePopulation= function()
{
//for each genome, we need to check if we should evaluate the individual, and then evaluate the individual
//default everyone is evaluated
var shouldEvaluate = self.genomeEvaluationFunctions.shouldEvaluateGenome || function(){return true;};
var defaultFitness = self.genomeEvaluationFunctions.defaultFitness || 0.0001;
if(!self.genomeEvaluationFunctions.evaluateGenome)
throw new Error("No evaluation function defined, how are you supposed to run evolution?");
var evaluateGenome = self.genomeEvaluationFunctions.evaluateGenome;
for(var i=0; i < self.population.length; i++)
{
var ng = self.population[i];
var fit = defaultFitness;
if(shouldEvaluate(ng))
{
fit = evaluateGenome(ng, self.np);
}
ng.fitness = fit;
ng.realFitness = fit;
}
};
self.performOneGeneration = function()
{
//No speciation in multiobjective
//therefore no species to check for removal
//----- Stage 1. Create offspring / cull old genomes / add offspring to population.
var regenerate = false;
self.multiobjective.addPopulation(self.population);
self.multiobjective.rankGenomes();
//cut the population down to the desired size
self.multiobjective.truncatePopulation(self.population.length);
//no speciation necessary
//here we can decide if we want to save to WIN
self.updateFitnessStats();
if(!regenerate)
{
self.createOffSpring();
//we need to trim population to the elite count, then replace
//however, this doesn't affect the multiobjective population -- just the population held in search at the time
MultiobjectiveSearch.Help.SortPopulation(self.population);
var eliteCount = Math.floor(self.np.elitismProportion*self.population.length);
//remove everything but the most elite!
self.population.splice(eliteCount, self.population.length - eliteCount);
// Add offspring to the population.
var genomeBound = self.offspringList.length;
for(var genomeIdx=0; genomeIdx<genomeBound; genomeIdx++)
self.population.push(self.offspringList[genomeIdx]);
}
//----- Stage 2. Evaluate genomes / Update stats.
self.evaluatePopulation();
self.updateFitnessStats();
self.incrementAges();
self.generation++;
};
self.createOffSpring = function()
{
self.offspringList = [];
// Create a new lists so that we can track which connections/neurons have been added during this routine.
self.newConnectionTable = [];
self.newNodeTable = [];
//now create chunk of offspring asexually
self.createMultipleOffSpring_Asexual();
//then the rest sexually
self.createMultipleOffSpring_Sexual();
};
self.createMultipleOffSpring_Asexual = function()
{
//function for testing if offspring is valid
var validOffspring = self.genomeEvaluationFunctions.isValidOffspring || function() {return true;};
var attemptValid = self.genomeEvaluationFunctions.validOffspringAttempts || 5;
var eliteCount = Math.floor(self.np.elitismProportion*self.population.length);
//how many asexual offspring? Well, the proportion of asexual * total number of desired new individuals
var offspringCount = Math.max(1, Math.round((self.population.length - eliteCount)*self.np.pOffspringAsexual));
// Add offspring to a seperate genomeList. We will add the offspring later to prevent corruption of the enumeration loop.
for(var i=0; i<offspringCount; i++)
{
var parent=null;
//tournament select in multiobjective search
parent = self.tournamentSelect(self.population);
var offspring = parent.createOffspringAsexual(self.newNodeTable, self.newConnectionTable, self.np);
var testCount = 0, maxTests = attemptValid;
//if we have a valid genotype test function, it should be used for generating this individual!
while (!validOffspring(offspring, self.np) && testCount++ < maxTests)
offspring = parent.createOffspringAsexual(self.newNodeTable, self.newConnectionTable, self.np);
//we have a valid offspring, send it away!
self.offspringList.push(offspring);
}
};
self.createMultipleOffSpring_Sexual = function()
{
//function for testing if offspring is valid
var validOffspring = self.genomeEvaluationFunctions.isValidOffspring || function() {return true;};
var attemptValid = self.genomeEvaluationFunctions.validOffspringAttempts || 5;
var oneMember=false;
var twoMembers=false;
if(self.population.length == 1)
{
// We can't perform sexual reproduction. To give the species a fair chance we call the asexual routine instead.
// This keeps the proportions of genomes per species steady.
oneMember = true;
}
else if(self.population.length==2)
twoMembers = true;
// Determine how many sexual offspring to create.
var eliteCount = Math.floor(self.np.elitismProportion*self.population.length);
//how many sexual offspring? Well, the proportion of sexual * total number of desired new individuals
var matingCount = Math.round((self.population.length - eliteCount)*self.np.pOffspringSexual);
for(var i=0; i<matingCount; i++)
{
var parent1;
var parent2=null;
var offspring;
if(utilities.nextDouble() < self.np.pInterspeciesMating)
{ // Inter-species mating!
//System.Diagnostics.Debug.WriteLine("Inter-species mating!");
if(oneMember)
parent1 = self.population[0];
else {
//tournament select in multiobjective search
parent1 = self.tournamentSelect(self.population);
}
// Select the 2nd parent from the whole popualtion (there is a chance that this will be an genome
// from this species, but that's OK).
var j=0;
do
{
parent2 = self.tournamentSelect(self.population);
}
while(parent1==parent2 && j++ < 4); // Slightly wasteful but not too bad. Limited by j.
}
else
{ // Mating within the current species.
//System.Diagnostics.Debug.WriteLine("Mating within the current species.");
if(oneMember)
{ // Use asexual reproduction instead.
offspring = self.population[0].createOffspringAsexual(self.newNodeTable, self.newConnectionTable, self.np);
var testCount = 0; var maxTests = attemptValid;
//if we have an assess function, it should be used for generating this individual!
while (!validOffspring(offspring) && testCount++ < maxTests)
offspring = self.population[0].createOffspringAsexual(self.newNodeTable, self.newConnectionTable, self.np);
self.offspringList.push(offspring);
continue;
}
if(twoMembers)
{
offspring = self.population[0].createOffspringSexual(self.population[1], self.np);
var testCount = 0; var maxTests = attemptValid;
//if we have an assess function, it should be used for generating this individual!
while (!validOffspring(offspring) && testCount++ < maxTests)
offspring = self.population[0].createOffspringSexual(self.population[1], self.np);
self.offspringList.push(offspring);
continue;
}
parent1 = self.tournamentSelect(self.population);
var j=0;
do
{
parent2 = self.tournamentSelect(self.population);
}
while(parent1==parent2 && j++ < 4); // Slightly wasteful but not too bad. Limited by j.
}
if(parent1 != parent2)
{
offspring = parent1.createOffspringSexual(parent2, self.np);
var testCount = 0; var maxTests = attemptValid;
//if we have an assess function, it should be used for generating this individual!
while (!validOffspring(offspring) && testCount++ < maxTests)
offspring = parent1.createOffspringSexual(parent2, self.np);
self.offspringList.push(offspring);
}
else
{ // No mating pair could be found. Fallback to asexual reproduction to keep the population size constant.
offspring = parent1.createOffspringAsexual(self.newNodeTable, self.newConnectionTable,self.np);
var testCount = 0; var maxTests = attemptValid;
//if we have an assess function, it should be used for generating this individual!
while (!validOffspring(offspring) && testCount++ < maxTests)
offspring = parent1.createOffspringAsexual(self.newNodeTable, self.newConnectionTable,self.np);
self.offspringList.push(offspring);
}
}
};
//finishing initalizatgion of object
self.initializePopulation();
}
},{"../genome/neatGenome.js":6,"./novelty.js":4,"cppnjs":14}],4:[function(require,module,exports){
/**
* Module dependencies.
*/
var NeatGenome = require('../genome/neatGenome.js');
var utilities = require('cppnjs').utilities;
/**
* Expose `NeatNode`.
*/
module.exports = Novelty;
/**
* Initialize a new NeatNode.
*
* @param {Number} threshold
* @api public
*/
function Novelty(threshold)
{
var self = this;
self.nearestNeighbors = 20;
self.initialized = false;
self.archiveThreshold = threshold;
self.measureAgainst = [];
self.archive = [];
self.pendingAddition = [];
self.maxDistSeen = Number.MIN_VALUE;
}
Novelty.Behavior = function()
{
var self =this;
self.behaviorList = null;
self.objectives = null;