This project implements a Genetic Algorithm (GA) from scratch in Python, designed to find the maximum point of a given mathematical function (defaulting to a quadratic function). The code is modular, highly configurable, and automatically generates both detailed execution logs and graphical representations of the population's evolution.
By default, the algorithm searches for the maximum of a quadratic function on a defined interval. To achieve this, it uses binary encoding for chromosomes and applies classic genetic operators across multiple generations.
- Configurability: The
config.pyfile can be edited to simulate the evolution of populations under varied parameters. - Binary Encoding: Transforms real-valued numbers into binary strings with high precision (configurable).
- Roulette Wheel Selection: Includes a Fitness Scaling implementation to correctly handle negative fitness values.
- Single-point Crossover: Exchanges genetic material between selected pairs of individuals.
- Uniform Mutation: Flips bits (
0to1and vice versa) based on a defined probability. - Elitism: Guarantees that the absolute best individual (the Elite) passes into the next generation completely unaltered.
- Logging System: Automatically saves detailed metrics of each generation into a text file (
evolution.txt). - Graphical Visualization: Generates a plot (
evolution_plot.png) at the end of the execution to visualize algorithm convergence (Max Fitness vs. Average Fitness).
main.py- The entry point of the application. It manages the main generational loop and handles file writing/plotting.config.py- The configuration file containing all the algorithm's hyperparameters (population size, probabilities, precision, etc.).ga/- The core package containing the genetic logic:individual.py- Defines the Individual class, encoding/decoding methods, and fitness calculation.genetic_algorithm.py- The main steps of the GA (selection, crossover, mutation, parent replacement).operators.py- The mathematical logic behind the genetic operators.population_generator.py- Handles the generation of the initial random population.
utils/- Package for optional utility functions:logger.py- Dedicated functions for formatting and displaying population information (probabilities, intervals, mutations).plotter.py- Functions for generating and saving performance charts using Matplotlib.
data/- Directory designated for storing charts and the text file containing data of one simulation.
This project requires Python 3.x. The external libraries required are:
numpy(for random number generation and vectorized operations)matplotlib(for generating evolution plots)
You can install the requirements using pip:
pip install numpy matplotlib