Skip to content

About

An agent-based simulation of predator-prey eye evolution, using perceptrons and a genetic algorithm.

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Repository files navigation

Eye-Evolution

An agent-based simulation of predator-prey eye evolution, using perceptrons and a genetic algorithm.

What this is

Green prey and red predators move around a square world. Each creature has four eyes. An eye is a ray (a straight line of sight) that reports what it hits and how far away it is. A small neural network (a set of connected artificial neurons, or perceptrons, that turns inputs into outputs) reads the eyes and decides how to move. Prey score points for staying alive and eating yellow food. Predators score points for catching prey.

At the end of each generation, the best scorers are picked to breed. Their children inherit a mix of their parents' network weights and eye positions, with small random changes. Over many generations you can watch where the eyes end up on each kind of creature.

What you can learn from it

  • Biology: natural selection. Creatures with higher fitness are more likely to be picked as parents, so useful traits spread.
  • Biology: predator-prey co-evolution. Each side's fitness depends on the other, so they evolve against each other.
  • Biology: genotype and phenotype. The gene is a list of numbers (network weights and eye angles); the behaviour you see on screen is what those numbers produce.
  • Biology: variation from crossover and mutation, the two ways a child's gene differs from its parents'.
  • Computer Science: neural networks, genetic algorithms, and ray casting (finding where a line first hits a shape).
  • Statistics: the analytics overlay reports means, bests and standard deviations for each generation, and every run writes them to a CSV file you can graph.

Run it

On your own computer

You will need:

  • A C++17 compiler: Xcode Command Line Tools on macOS, build-essential on Ubuntu, or Visual Studio with the C++ workload on Windows.

  • CMake 3.16 or newer.

  • Git.

  • On Ubuntu or Debian, the graphics libraries SFML needs:

    sudo apt install cmake build-essential libgl-dev libx11-dev libxrandr-dev libfreetype-dev libudev-dev

The build has not been tested on a particular operating system for this guide.

  1. Download the code:

    git clone https://github.com/godofecht/Eye-Evolution.git
    cd Eye-Evolution
  2. Configure and build. CMake downloads SFML 2.6.2 (a library for windows and 2D graphics) and TinyML (the neural network library) for you, so the first build takes a few minutes.

    cmake -B build -DCMAKE_BUILD_TYPE=Release
    cmake --build build --target EyeEvolution --parallel
  3. Run it:

    ./build/bin/EyeEvolution

    On Windows with Visual Studio, the program may be in build\bin\Release\.

A 600 by 600 window called "Eye Evolution" opens. You should see green prey, red predators, yellow food, and white lines for the eyes. The counter in the top-left shows the generation number.

Controls

Key Does
Space fast-forward on or off (stops drawing so generations run quickly)
A show or hide the analytics overlay
H run 50 generations without drawing, then carry on
R reset to generation 1

Each generation also prints a summary line in the terminal. The program writes the same numbers to evolution_log.csv in the folder you started it from.

How it works

  1. Perception. Each creature casts one ray from each of its four eyes. For each eye, the network gets two numbers: how close the hit is, and what was hit.
  2. Decision. The network has 8 inputs, two hidden layers of 8 and 6 neurons, and 2 outputs.
  3. Action. The two outputs move the creature forward and turn it.
  4. Fitness. Prey gain a little for every step alive, more for seeing things, 300 for eating food, and lose 500 if caught. Predators gain 500 for a catch, a little for seeing things and for being close to prey, and lose a little every step.
  5. Selection. A generation ends after 2,000 steps or when every prey is caught. Creatures are ranked and parents are chosen by roulette wheel selection (the chance of being picked is in proportion to fitness). The best creature of each kind is copied unchanged.
  6. Reproduction. Two parents make two children by single-point crossover (cut both genes at one point and swap the tails), on both the weights and the eye positions. Each number then has a 15% chance of a random nudge.
File or folder What is in it
src/main.cpp the window, the keys and the analytics overlay
src/Environment.cpp one generation: movement, fitness, food, the genetic algorithm and the graphs
include/Environment.h world size, number of eyes, prey, predators and generation length
src/Prey.cpp, src/Predator.cpp each creature's network, eyes and movement
include/Gene.h the gene, crossover and mutation
include/FitnessTables.h ranking and roulette wheel selection
include/RayCast.h ray and circle intersection
include/GenerationStats.h the per-generation statistics
CMakeLists.txt the build

Ideas to try

  1. In include/Environment.h, change NUM_EYES from 4 to 2 or 6 and see whether the eyes spread out in a different way.
  2. In include/Gene.h, change mutationRate and mutationStrength in mutate. Does a higher rate help or hurt? Use evolution_log.csv to compare runs.
  3. In src/Environment.cpp, change the fitness rewards: make food worth more, or remove the reward for seeing things. Watch how the behaviour changes.
  4. Plot evolution_log.csv in a spreadsheet or Python. Compare avg_prey_eye_spread with avg_predator_eye_spread over time. Real prey often have eyes on the sides of the head and real predators often have forward-facing eyes; check whether that appears here.
  5. In src/Prey.cpp, change buildTopology to give prey a bigger brain and see if they get better at escaping.

Technical details

Eye inputs (raycasts) --> ML::Model (TinyML NN) --> Movement vector (forward + rotate)
        ^                                                  |
        |                                                  v
        +-------------- Environment (SFML loop) <----------+
                                |
                                | end of generation
                                v
                     Genetic algorithm (crossover)
  • Each creature's brain is an ML::Model from TinyML that maps eye inputs to movement outputs.
  • Eye placement around the body is encoded in the genome alongside the network weights.
  • Creatures cast rays to detect predators, prey and food.
  • Prey must balance escaping predators with collecting food to maximise fitness.
  • If you have tinyML cloned as a sibling directory (../tinyml-repo/), CMake uses it directly instead of fetching it from GitHub. You can also set -DTINYML_DIR=/path/to/tinyml-repo.
  • The EyeEvolution/ folder and EyeEvolution.sln are an older Visual Studio version of the project. The CMake build uses src/ and include/ only.

Roadmap

  • Cross-platform CMake build system
  • TinyML integration for neural networks
  • Data logging across generations (evolution_log.csv, on-screen fitness graph)
  • Configurable simulation parameters via config file or CLI flags
  • Save/load evolved populations to disk
  • Multiple environment topologies (walls, obstacles)

See the open issues for proposed features and known issues.

Project status

There is no automated build. The CMake build fetches TinyML from its main branch, so a change there can break this build. The repository also holds old Visual Studio build output (.vs/, Debug/, EyeEvolution/x64/), which makes it about 116 MB to download.

Issues License

Licence

You can use, copy, change and share this code for any purpose, as long as you keep the copyright notice and do not use the author's name to promote your version. See LICENSE (BSD 3-Clause).

Credits

  • Written by Abhishek Shivakumar. Citation details are in CITATION.cff.
  • TinyML, a C++ machine learning library by the same author.
  • SFML, the Simple and Fast Multimedia Library.
  • The old README was based on Best-README-Template.

About

An agent-based simulation of predator-prey eye evolution, using perceptrons and a genetic algorithm.

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Contributors

Languages