Watching a Genetic Algorithm in a Predator–Prey Ecosystem: Understanding Selection, Crossover and Mutation Through Genome Stripes
Check how a genetic algorithm's selection, crossover and mutation work using a simulation of herbivores and carnivores. Lining up every animal's bit string lets you see the population shift toward a body color that matches the background, and why adaptation stops at a 0% mutation rate. Also covers results compared across 10 random seeds and the pitfalls of encoding genes as plain binary.
Contents
Most explanations of genetic algorithms (GAs) say something like: “Select individuals with high fitness, cross them over, and occasionally introduce a mutation. Repeat, and you find a good solution.” That really is the whole procedure, so it is not hard to memorize. What is hard to grasp is why something that just flips random bits keeps heading in a better direction as it repeats. Even a chart of a traveling salesman route getting shorter generation by generation does not show you what is going on inside.
So I built the Genetic Algorithm Simulator, which lays out the genome of every member of the population on screen so you can watch it change as the generations pass. The setting is a predator–prey relationship between herbivores and carnivores. Instead of a fitness formula, only the animals that avoid being eaten and build up enough energy get to have offspring. In this article I go through the parts of a genetic algorithm one by one and explain what you can see on the simulator’s screen and what changes when you move the controls.
The parts of a genetic algorithm
The genetic algorithm is a search and optimization method that John Holland laid out in his 1975 book Adaptation in Natural and Artificial Systems. It does not reproduce biological evolution as it is; it borrows only the part of the mechanism where “good things survive and change little by little” and uses it for computation. The textbook form looks like this:
1. Create N random individuals (bit strings)
2. Compute each individual's fitness
3. Choose parents so that fitter individuals are more likely to be picked (selection)
4. Make offspring by splicing two parents' bit strings at a cut point (crossover)
5. Flip the offspring's bits with a low probability (mutation)
6. Replace the population with the offspring and go back to 2
Each part has its own role.
| Part | Role | What happens without it |
|---|---|---|
| Encoding | Represents candidate solutions as bit strings or something else easy to manipulate | Crossover and mutation cannot be defined |
| Fitness and selection | Better candidates leave more descendants | It becomes plain random search |
| Crossover | Combines good parts found by different individuals into one | Combinations of good parts are hard to try |
| Mutation | Produces values not yet present in the population | The search cannot leave the combinations remaining in the population |
Selection works to “increase the good ones among what already exists,” and mutation works to “create what does not exist yet.” The two pull against each other. If selection is too strong, the population soon fills up with near-identical individuals; if mutation is too strong, good individuals are found but their qualities are not passed on to their offspring. You can see this balance clearly later when you move the mutation rate control.
The rules of the simulator’s world
The simulator contains ground where grass grows, herbivores (circles) that eat the grass, and carnivores (triangles) that hunt the herbivores. Every animal has energy, which drains just from moving. Herbivores eat grass and carnivores catch herbivores to replenish it. An animal starves when its energy reaches 0, and it also dies when it reaches the end of its lifespan.
Each gene is 8 bits, so a herbivore’s genome is 48 bits (6 genes) and a carnivore’s is 32 bits (4 genes). The 8 bits are read as an integer from 0 to 255 and mapped onto each gene’s range. For example, herbivore speed ranges from 0.5 to 2.0, so 00000000 means 0.5 and 11111111 means 2.0.
| Gene | Effect | Cost |
|---|---|---|
| Speed | Escape or catch up | The energy needed to maintain the body grows with the square of the speed |
| Vision | Notice grass, enemies and prey farther away | Slightly worse energy efficiency |
| Body color (herbivores) | The closer it is to the background brightness, the shorter the distance at which carnivores notice the animal (down to 30% of their vision) | None |
| Timidity (herbivores) | Flee while the enemy is still far away | Cannot eat grass while fleeing |
| Flocking (herbivores) | Move toward peers. Prey in a group are harder to target | Competition for nearby grass |
| Lurking (carnivores) | Save energy by not roaming when no prey is in sight | Fewer encounters with prey |
| Breeding threshold | Give birth when energy exceeds this value | Low: less energy passed to offspring. High: longer wait before breeding |
I gave every gene except body color a cost to rule out the answer “just max everything out.” A genetic algorithm gets interesting when you make it solve a problem of finding the point where benefits and costs balance.
When an animal gives birth, it performs one-point crossover with a nearby animal of the same species, and then each bit of the offspring is flipped with some probability. This differs from the textbook procedure in two ways:
- There is no fitness formula. Parents are not chosen by scoring speed or body color; animals whose energy exceeds their breeding threshold give birth on their own. Animals that are easy to spot or waste energy get eaten or starve before they reproduce. That is the selection.
- Generations do not turn over all at once. Parents and offspring live at the same time, and an offspring’s generation number is its parent’s plus 1. The “up to generation N” figure on screen is the number of the lineage that has gone through the most generations at that moment.
The numbers and rules here form a simple model meant to make the behavior of a genetic algorithm easy to see. They do not reproduce the ecology of real animals. I tuned constants such as the resting time after a kill so that both herbivores and carnivores survive for a long time.
Running it
When you open the simulator, it is set up with random seed 1, 120 herbivores, 14 carnivores and the background on “Dark forest.” The initial genomes are random, so the brightness of the circles varies widely.

At this point, “Population genomes” shows a mottled pattern of dark and light cells in every gene. Each row is one animal’s genome and each cell is one bit, with dark meaning 1 and light meaning 0. The strip on top shows the share of animals that have a 1 in that bit, and every column is a middling shade.
I pressed “▶ Play,” set the speed to ×40, let it run for about 12,000 steps and paused. The highest herbivore generation was around 70. The same view had changed like this:
A column with a vertical stripe is one where almost the entire population has the same value for that bit; in other words, it has converged. Here is some of what you can read from it:
- In the herbivores’ flocking gene, the left (higher) 4 bits became 0 in almost everyone. The average is 0.03, so the tendency to stick close to peers has been almost entirely discarded. In this model, the cost of competing for grass outweighed the protection a group offers.
- In timidity, the most significant bit became 1 in 90% of the animals, so those that flee early when they see an enemy survived.
- In vision, the top 2 bits are also 0 in nearly everyone, and the average fell to 0.18. Seeing nearby enemies seems to be enough to decide when to flee, and the energy cost of seeing far was not worth it.
- In body color, the most significant bit became 0 in 90% of the animals, meaning most are dark, with values below 0.5. The average is 0.33, close to the background brightness of 0.3.
- Carnivores number only a few to about 50, so their stripes line up faster than the herbivores’. With so few animals, a small number of lineages easily spreads through the whole population.
Notice also that the columns line up from the left end (the higher bits) first. The most significant of the 8 bits decides half the value, so an animal that gets it wrong pays dearly. The lower bits make little difference either way, so they tend to stay mottled without converging.
In the population chart, you can see waves: carnivores increase a little after herbivores increase, and carnivores decrease when herbivores decrease. This resembles the oscillation of predator and prey populations known in ecology as the Lotka–Volterra equations.
Checking crossover and mutation in a single genome
Press “Pick a newborn” and the genome of the animal born most recently appears. Besides the bit string and the value of each gene, it shows where the crossover happened when it inherited from its parents and which bits mutated.
One-point crossover puts a single cut somewhere in the genome and takes the part before it from one parent and the part after it from the other. The cut position is chosen at random each time. At the default mutation rate of 1%, a newborn 48-bit herbivore has just under 0.5 bits flipped on average. If you pick several, you will find that almost all have no mutation or just one flipped bit.
Crossover and mutation fit in this short piece of code, and the simulator does the same thing:
// One-point crossover: inherit the part before the cut from parent a, the rest from parent b
function crossover(a, b) {
const cut = 1 + Math.floor(Math.random() * (a.length - 1));
return a.map((bit, i) => (i < cut ? bit : b[i]));
}
// Mutation: flip each bit with probability rate
function mutate(genome, rate) {
return genome.map((bit) => (Math.random() < rate ? bit ^ 1 : bit));
}
Change the background and body color follows
At the 12,000-step mark, I moved “Background brightness” close to the right end (bright sand) and kept it running. The dark animals suddenly stood out, and the distance at which carnivores could spot them grew. Now the minority with a light body color had the better chance of survival.
After the background changed, the average body color climbed from around 0.3 to around 0.7 over several thousand steps. In the population genomes, the column for the most significant body color bit switches from light to dark. Some readers may be reminded of the peppered moth, whose dark form became more common as industrial soot blackened tree trunks. The change in this simulator, however, comes from the simple rule that contrast with the background decides how easily an animal is spotted; it does not reproduce the actual moth research.
What changes when you move the controls
What you see on screen might be chance, so I ran the same calculation code as the simulator in Node.js and compared 10 runs with seeds 1 through 10. Each run advanced 12,000 steps with a background of 0.3, then switched the background to 0.85, and I recorded the number of steps until the average body color exceeded 0.6 and the average body color 20,000 steps after the switch. “Bring in immigrants on extinction” stayed on, as in the defaults.
| Condition | Steps until exceeding 0.6 (median) | Runs that exceeded 0.6 | Body color average after 20,000 steps | Gene spread before the background change |
|---|---|---|---|---|
| Defaults (1% mutation, crossover on) | About 7,300 steps | 10 of 10 | 0.75–0.84 | 0.14 |
| 0% mutation | ― | 1 of 10 | 0.17–0.81 | 0.08 |
| 8% mutation | About 2,400 steps | 10 of 10 | 0.60–0.80 | 0.23 |
| No crossover (1% mutation) | About 5,900 steps | 10 of 10 | 0.80–0.88 | 0.13 |
The spread column is the average of the standard deviations (computed on 0–1 values) of each of the herbivores’ 6 genes.
0% mutation: adaptation stalls
Without mutation, in 9 of 10 runs the average body color was still below 0.4 even after 20,000 steps. During the 12,000 steps before the background changed, selection had done its work and the bits that make a light body color had disappeared from the population. Crossover only rearranges bits that already exist, so it cannot create a 1 that no individual has. The small spread of 0.08 shows that the population has lost its diversity.
In the one run that did adapt, seed 2, herbivores and carnivores went extinct a combined 12 times along the way, and each time animals with random genomes were brought in. The newcomers carried bits the population no longer had. Taking mutation away makes it very clear that its role is to “produce values not yet present in the population.”
8% mutation: quick to catch up, but never settles
At an 8% mutation rate, the time to exceed 0.6 shrank to about a third of the default. The spread is large, and some light animals are mixed in even before the background changes, so they can multiply right away. On the other hand, the body color average after 20,000 steps was 0.6–0.8, struggling to reach the background’s 0.85. Even when an offspring is born from parents that match the background, the bits of its body color get scrambled almost every time. On screen, too, you can see the stripes that had lined up quickly fall apart.
The mutation rate is a trade-off between how quickly the population follows a change and how well it keeps an answer it has found. When genetic algorithms are used for real optimization, the standard advice is to start with a mutation rate of about 1 divided by the length of the bit string, and this balance is the reason. For 48 bits, that is about 2%.
No crossover: not slower in this model
What surprised me was that turning crossover off did not slow adaptation; if anything, it was slightly faster. I can think of two reasons.
The first is that the crossover partner is “whoever happens to be nearby,” not a good individual. Right after the background changes, the minority with a light body color crosses over with the dark animals around them, and depending on where the cut falls, it may take the body color gene from the partner. Crossover dilutes the rare variants that matter.
The second is that this task can be solved with a single gene, body color. Crossover shines when you need to combine good parts in different places, such as a good speed found by one individual and a good vision found by another. If all you need is to match one gene to the background, mutation and selection are enough.
Crossover is the signature operation of genetic algorithms, but for some problems it does not help. Toggle crossover on and off in the simulator and compare how the vertical stripes form in the population genomes, and the difference becomes visible.
Pitfalls of encoding genes in binary
The higher bits have more influence on the value because the genes use plain binary numbers directly. This representation has a quirk.
In 8 bits, 127 is 01111111 and 128 is 10000000. The values differ by only 1, yet all 8 bits are flipped. For an animal with a body color near 0.49 to move to 0.51, a single-bit mutation is not enough; many bits have to change at once. Conversely, flipping just the most significant bit makes the value jump by 0.5. This kind of step is called a Hamming cliff.
A common remedy is Gray code, in which adjacent integers differ by only one bit. In Gray code, 127 and 128 are also one bit apart. This simulator deliberately uses plain binary so that the mapping between bit strings and values is easy to follow by eye. When you display a single genome and compare the value bars with the bit patterns, you should get a real feel for how much the higher bits weigh.
How this differs from real optimization
In that it “does not write fitness as a formula,” this simulator is a little different from how genetic algorithms are used in practice. Real optimization uses them when the thing to evaluate can be computed as a number: the total distance of a delivery route, the weight of a part, the performance of an antenna. On ST5, a set of small satellites NASA launched in 2006, an antenna designed by an evolutionary algorithm flew, with a twisted shape no human would have come up with.
On the other hand, a situation where the evaluation criteria keep changing along with the environment is hard to express with a fitness formula. Change the background midway and body color follows; when herbivores get faster, the carnivores’ speed is affected too. Changes like these are visible because this is an ecosystem model; running the textbook procedure as is will not produce them.
Start by playing it with the default settings and watch the vertical stripes form in the population genomes. Then set the mutation rate to 0% and change the background, or turn crossover off, and you can check the differences described in this article on your own screen. With the same seed, the same actions reproduce the same results.