Created
September 5, 2016 08:37
-
-
Save MatthiasKrijgsman/6d407e21fe62d98617c7629bcef9e29b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Population; | |
Population = function(size, mutationRate, eliminationRate){ | |
this.size = size; | |
this.mutationRate = mutationRate; | |
this.eliminationRate = eliminationRate; | |
this.pool = [] | |
for(var x = 0; x < size; x++){ | |
// Set Custom DNA Options | |
this.pool.push(new DNA(-1, 1, 8)); | |
} | |
this.currentGen = 0; | |
}; | |
Population.prototype.calcFitness = function(){ | |
this.averageFitness = 0; | |
for(var x = 0; x < this.size; x++){ | |
//Edit this if you don't want to calculate each fitness individual | |
this.pool[x].getFitness(); | |
this.averageFitness += this.pool[x].fitness; | |
} | |
this.averageFitness /= this.pool.length; | |
}; | |
Population.prototype.naturalSelection = function(){ | |
this.matingPool = []; | |
var maxFitness = 0; | |
var minFitness = 0; | |
//Sort population to Fitness value | |
this.pool.sort(function(a, b){ | |
if(a.fitness > b.fitness){ | |
return -1; | |
}else{ | |
return 1; | |
} | |
}); | |
//Elimination | |
for(var x = 0; x < Math.floor(this.pool.length * this.eliminationRate); x++){ | |
this.pool.pop(); | |
} | |
maxFitness = this.pool[0].fitness; | |
//Creating Mating Pool | |
this.pool.map(function(x,y){ | |
var n = Math.floor((x.fitness/maxFitness) * 100); | |
for(var z = 0; z < n; z++){ | |
this.matingPool.push(y); | |
} | |
},this); | |
}; | |
Population.prototype.crossover = function(){ | |
var n = this.size - this.pool.length; | |
for(var x = 0; x < n; x++){ | |
var P1 = this.matingPool[Math.floor(Math.random() * this.matingPool.length)]; | |
var P2 = this.matingPool[Math.floor(Math.random() * this.matingPool.length)]; | |
this.pool.push(this.pool[P1].partner(this.pool[P2], this.mutationRate)); | |
} | |
}; | |
Population.prototype.evaluate = function(){ | |
this.currentGen++; | |
this.highestFitness = this.pool[0].fitness; | |
console.log("Current Generation:",this.currentGen); | |
console.log("Highest Fitness:",this.highestFitness); | |
console.log("Average Fitness:",this.averageFitness); | |
}; | |
Population.prototype.nextGeneration = function(){ | |
this.calcFitness(); | |
this.naturalSelection(); | |
this.crossover(); | |
this.evaluate(); | |
}; | |
Population.prototype.setTargetFitness = function(x){ | |
this.targetFitess = x; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment