Skip to main content

PyGenAlgo: A simple and powerful toolkit for genetic algorithms.

Logo

DOI

linting: pylint Supports Python 3.10 License: GPL v3 PyPI version PyPI downloads

Pylint score: 9.85 / 10

This repository implements a genetic algorithm toolbox in Python3 programming language, using only Numpy and Joblib as additional libraries. The toolbox offers the following implementations (as engines):

  • A StandardGA class, where the whole population of chromosomes is replaced by a new one at the end of each iteration (or epoch).
  • An IslandModelGA class offers a new genetic operator (MigrationOperator), which allows for periodic migration of the best individuals among the (co-evolving) different island populations. The island populations are coevolving in parallel using separate CPUs.
  • A brand new MultiObjectiveGA class is added that allows the user to solve more complex multiobjective optimization problems. The major difference in the new class is that the fitness function is expected to return a tuple with all the objective function values, e.g. (fx1, fx2, ..., fxn) rather a single function value fx. Note, that if the problem has additional constraints to satisfy, as is usually the case, they should be summed in one 'penalty' variable and included in the tuple before any other objective value i.e. (sum_penalty, fx1, fx2, ..., fxn). This way, when the chromosomes are sorted those that minimize all constraints (sum_penalty == 0) will be placed higher in the rank.

For computationally expensive fitness functions the StandardGA and MultiObjectiveGA classes provide the option of parallel evaluation (of the individual chromosomes), by setting in the method run(..., parallel=True). However, for fast fitness functions this will actually cause the algorithm to execute slower (due to the time required to open and close the parallel pool). So the default setting here is "parallel=False". Regarding the IslandModelGA this is running in parallel mode by definition.

NEWS: The latest release includes three additional selection operators: (i) ExponentialRank, (ii) ParetoFrontSelector and (iii) ParetoTournamentSelector. The last two are used exclusively with the 'MultiObjectiveGA' engine using pareto- front selection techniques. Note that both of these classes provide a base for the development of possible new selection methodologies for multi-objective problems. Examples that use the new techniques have also been added to demonstrate their use. In addition, the IslandModelGA engine has been enhanced and with three new three 'IslandOperators'. This new approach allows the use a different set of genetic operators for each island (i.e. subpopulation), thus allowing them to evolve in completely different ways. Finally, the HalfUniformCrossover (HUX), PrefixOrderCrossover (POX) and WholeArithmeticCrossover (WAX) have also been added, to provide alternative recombination options.

The current implementation provides (out of the box) a wide variety of genetic operators, including:

NOTE(1): Meta operators call randomly other compatible operators (selection/crossover/mutation/migration) from a predefined set, with equal probability.

NOTE(2): Crossover operators marked by '*' support variable length chromosomes (VLC). By definition all mutation operators support VLC too, because they operate on a single chromosome at a time.

NOTE(3): Island operators are intended to work only with the IslandModelGA. They are designed to hold a list of other operators (one for each island) and call its specific function according to the island that they belong. This way in the IslandModelGA all the subpopulations can evolve independently using a completely different set of operators.

Operators

Incorporating additional genetic operators is easily facilitated by inheriting from the base classes:

and implementing the basic interface as described therein. In the examples that follow I show how one can use this code to run a GA for (single/multi-) optimization problems (maximization or minimization) with and without constraints. The project is ongoing so new things might come along the way.

Installation

There are two options to install the software.

The easiest way is to download it from PyPI. Simply run the following command on a terminal:

pip install pygenalgo

Alternatively one can clone directly the latest version using git as follows:

git clone https://github.com/vrettasm/PyGeneticAlgorithms.git

After the download of the code (or the git clone), one can use the following commands:

cd PyGeneticAlgorithms
pip install .

This will install the latest PyGenAlgo version in the package management system.

Required packages

The recommended version is Python 3.10 (and above). To simplify the required packages just use:

pip install -r requirements.txt

Fitness function

The most important thing the user has to do is to define the fitness function. A template for single objective function is provided here in addition to the examples below. The cost_function decorator is used to indicate whether the function will be maximized (default), or minimized. The second output parameter ("solution_found") is optional; only in the cases where we can evaluate if a termination condition is satisfied.

from pygenalgo.genome.chromosome import Chromosome
from pygenalgo.utils.utilities import cost_function


# Fitness function <template>.
@cost_function(minimize=True)
def fitness_func(individual: Chromosome):
    """
    This is how a fitness function should look like. The whole
    evaluation should be implemented (or wrapped around) this
    function.
    
    :param individual: Individual chromosome to be evaluated.
    
    :return: the function value evaluated at the individual.
    """

    # Extract gene values from the chromosome.
    x = individual.values()
    
    # ... CODE TO IMPLEMENT ...

    # Compute the function value.
    f_value = ...

    # Condition for termination.
    # We set it to True / False.
    solution_found = ...

    # Return the solution.
    return f_value, solution_found
# _end_def_

Once the fitness function is defined correctly the next steps are straightforward as described in the examples. Note that for multi-objective problems, using the MultiObjectiveGA engine, the fitness_func is expected to return a tuple: $(penalty, f_1, f_2, ..., f_n)$, grouping all the penalties together, and each objective function separately.

Examples

Some optimization examples on how to use these algorithms:

Problem Variables Objectives Constraints Optima
Sphere M (=5) 1 no single
Rastrigin M (=5) 1 no single
Rosenbrock M (=2) 1 1 single
Knapsack 0/1 M (=50) 1 yes single
Binh & Korn M (=2) 2 2 Pareto
Sphere (parallel) M (=10) 1 no single
Easom (parallel) M (=2) 1 no single
Traveling Salesman M (=10) 1 yes single
N-Queens M (=8) 1 yes single
OneMax M (=50) 1 no single
Zakharov M (=8) 1 no single
Shubert 2 1 no multiple
Gaussian Mixture 2 1 no multiple
Multi-Depot VRP M 1 yes multiple
MOO: Binh & Korn M (=2) 2 2 Pareto
MOO: Tanaka M (=2) 2 2 Pareto
MOO: Osyczka & Kundu 6 2 6 Pareto
MOO: DTLZ3 N 3 no Pareto

Constraint optimization problems can be easily addressed using the Penalty Method.

References and Documentation

This work is described in:

You can find the latest documentation here.

Contact

For any questions/comments (regarding this code) please contact me at: vrettasm@gmail.com

Metadata

Release files for pygenalgo 2.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pygenalgo 2.3.0
File Size Uploaded
pygenalgo-2.3.0.tar.gz 91.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pygenalgo 2.3.0
File Interpreter ABI Platform
pygenalgo-2.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 208.2 kB

Release files / pygenalgo-2.3.0.tar.gz

Download URL pygenalgo-2.3.0.tar.gz
Size 91.8 kB
Tags Source
SHA-256 checksum
How to use checksums
82612346ac3d942e516f2406d5ba72d7eb8a83c62d4df61fb199e45941553c0e
BLAKE2b-256 checksum
How to use checksums
88dc556f054a70088a3e5132b554eee05519487bfaae8164315642e1c695fd13
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.20

Release files / pygenalgo-2.3.0-py3-none-any.whl

Download URL pygenalgo-2.3.0-py3-none-any.whl
Size 116.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
92c8b767174e27393d6cd5568acd874fd9c81e2069e575116c3a56d0a03b4265
BLAKE2b-256 checksum
How to use checksums
1e52738d052764eb5b6cd64333672f0608c955738b8fcc1a9116f0e2c5c57111
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.20

Release history Release notifications | RSS feed

2.4.1

2 release files

2.4.0

2 release files

This release

2.3.0 This release

2 release files

2.2.1

2 release files

2.2.0

2 release files

2.1.0

2 release files

2.0.1

2 release files

1.9.1

2 release files

1.9.0

2 release files

1.8.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page