Genetic algorithm, Hello World
Javascript ES6
2018
Step 1 Create a population. Here 30 particles whith a constant accélération
Step 2 Give some “DNA”. In this example DNA is an array of 200 random directions (normalized random 2D vector) that will be read sequentially each frame
Step 3 Evaluate/crossover/mutate the population.
My fitness function evaluate the distance of the ‘robot’ from the target, if he ‘crash’ too far, his dna should be eliminated (fitness = 0) but i always keep 10% of the previous generation wathever the fitness, in order to keep some diversity.
this.calcFitness = function() { var dx = obstacles[0].x - this.pos.x; // obstacles[0] is the target var dy = obstacles[0].y - this.pos.y; var d = Math.sqrt(dx*dx + dy*dy); this.fitness = Math.min(1,TARGET_SIZE / d); if(this.isBroken) // has crashed (screen border or obstacle) { if(d > WIDTH2) // too far ! { this.fitness = 0; } } }
this.crossover = function(other) { var result = []; var limit = Math.floor(Math.random() * this.genes.length); for(var i = 0 ; i < this.genes.length ; i++) { if(i <limit) { result[i] = this.genes[i]; }else{ result[i] = other.genes[i]; } } return new DNA(result); }
this.mutation = function() { const POW = 1; for(var i = 0 ; i < this.genes.length ; i++) { if(Math.random() < GENE_MUTATION_CHANCE) { this.genes[i] = new Vector2D(POW * getRandomFloat(-1,1), POW * getRandomFloat(-1,1)); } } }
Step 4 Add some graphics and obstacles and have fun :)
Step 5 [TODO] Add some interactivity (sliders), include time in the calcFitness function