A Quick Example of Genetic Evolution in JavaScript: Let’s Make a Baby.

Kieran Maher
· 5 min read

“The process of mutation is the only known source of the new materials of genetic variability, and hence of evolution.” — Dobzhansky, 1957.

Genetic Evolution algorithms are truly fascinating to me. The ability to program virtual DNA is just a phenomenal feat of computer science. The ability to write, in code, Darwin’s theory of evolution and to actually see a Survival of the Fittest model in action is just astounding.

I’ve never really touched on genetic algorithms before and decided it was time I started. And what better place to start than the actual, start, right? In this tutorial I will create a ‘stick’, and that stick wants to reach a ‘circle’. Infer from that what you will, but I write family friendly tutorials and it will stay that way.

I am taking incredibly heavy influence from The Coding Train: Coding Challenge #29 as the inspiration for this. Link to it here. He was inspired by Smart Rockets, so while I am not making anything new or original, I hope for it to serve as an example of a genetic evolution algorithm. I am utilising the P5.JS library, that I would summarise as a visual JavaScript library.

Before I can create any kind of genetic algorithm, I first need to set up the actual setting. First I create a very simple HTML page.

I have two libraries for P5. Main handles the drawing to the screen, instantiation of variables, etc. A stick is the line that will be evolving, a population is a collection of sticks, and dna is what I would consider the core of the genetic algorithm. Let’s take a look at the code for Stick:

So a stick has some basic features. It must be able to move, so it has a movement ‘engine’ (for want of a better term) in the velocity, acceleration and position variables. At the moment all movement is controlled by the mysterious DNA function. Before we get to DNA, let’s take a look at population:

Population really isn’t that interesting. It creates 25 sticks, which I believe is sufficient for a population, and then moves them on the screen. Breaking no barriers with this function! DNA:

At this point, DNA does basically nothing. One stick gets one DNA, and one DNA has a set of 200 genes, which is the length of a lifespan for my little stick. Don’t worry, more will be added in due course. The Main file:

So Main is doing a fair few things here. Firstly, we need to create a new generation of sticks, which is an instantiation of population, and then we create our circle, which the sticks will aim for later down the line. Then we are drawing everything to the screen, with the added ability to kill and create a new generation, every time their life cycle ends.

So if we run this as it currently stands, we get this:

The confused little sticks

Now at this point, it isn’t actually a genetic algorithm, at all. Instead, it is a set of sticks moving at randomly selected vectors, with a dot drawn on the screen. So let’s add the genetic part.

So we want the stick that makes it the furthest, the closest to the circle, to be the stick that passes its genes on to its children. This is basically survival of the fittest: whoever survives the longest, is the one to pass on their genes.

So we can begin to implement this by giving each stick a new variable: fitness.

var fitness = 0

Fitness will be calculated by the current position of the stick, relative to the position of the circle (target). We can implement this as a function, to calculateFitness on each stick.

this.calculateFitness = function() {var distance = dist(this.pos.x, this.pos.y, target.x, target.y)this.fitness = 1 / distance}

Now, we have sticks that have a fitness rating — i.e. they have better genes, because they survived longer. So now we need a way to be able to reproduce those sticks with top tier genes. Enter, the pool:

So, this pool is relatively straight forward in concept. We have already figured above that the most successful genes are the ones that are the closest to the circle. The closer the stick is, then the more times it’s genome will be entered to the pool, and the more likely it is to reproduce. A stick that made it 5% of the way will have a 5% chance to reproduce, whereas a stick that made it 70% of the way, has a 70% chance to reproduce. I hope I explained that well enough. More successful stick = better chance to be reborn as part of a new stick.

The above is two new functions. Selection is, as the name would imply, selecting the parent genes from the gene pool. These genes are then combined to form a new DNA in crossover, which in turn is then assigned to the new stick! That’s pretty much it, since we want to keep this relatively simple and rudimentary.

Pretty cool, our sticks are now able to take the best of the predecessors abilities, and use them to find the circle! If we now look at it in action:

The still confused but slightly smarter sticks.

After several dozen iterations, it begins to look like they have been dying off, as only a few lines are visible. But that’s not the case: the lighter the stick, means multiple sticks are following the exact same path. This is to be expected, since we have a relatively limited pool of genes.

The very smart, alpha sticks.

The longer it is left running, the more there will appear only one stick on the screen. This stick represents the optimal stick! The chosen stick. Here they are, the culmination of our genetic algorithm:

Genius stick(s)!

So that’s a genetic evolution algorithm, written completely in the browser! It’s not a perfect example of genetic evolution, sure, but it is a fine example of it at work. Our little stick can now go on to get the circle and what follows next, is not a topic for today.

As mentioned at the beginning this is heavily influenced by The Coding Train. Link to their repo.

My Full Code.

Data Driven Investor

from confusion to clarity, not insanity

Kieran Maher

Written by

Software Developer & Analyst. General technology enthusiast.

Data Driven Investor

from confusion to clarity, not insanity

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade