Skip to main content

GeneticAlPy - Genetic Algorithms with Python

Project description

GeneticAlPy

Genetic Algorithms with Python

Yet another package for lightweight applications of GA in Python.

This package provides utilities for implementation of Genetic Algorithm (Holland 1962) for multivariate, multimodal optimization problems. Check out an introduction from a biological perspective in my paper, Nayak & Saha (2022)

By default, the binary representation is chosen as the genotype. The package provides roulette wheel, stochastic universal sampling and rank selection for choosing parents at each generation, uniform crossover, and bit-flip mutation. Elitist and liberal strategies may also be employed optionally.

Quickstart

Install the package with pip

pip install geneticalpy

Imports

from geneticalpy import genetical, examples
import numpy as np
import matplotlib.pyplot as plt

Define a fitness function from your cost function

cost = examples.ackley # replace this with your objective

def fitness(x): # to be maximized, by definition
    return 1/(1 + cost(x)) # this also depends loosely on your objective

Set initial GA hyperparameters

decimals   = 4
n_var      = 2
var_ranges = np.array([[-10,]*n_var,[10,]*n_var])
n_bits_segment    = len(format(int(max(var_ranges[1] - var_ranges[0])*10**decimals), 'b'))
n_bits_chromosome = n_bits_segment * n_var
offset     = -var_ranges[0]
init_popsize = 400

Initialize GA

PopGen = genetical.PopGenetics(
    fitness_func = fitness,
    n_var = n_var,
    decimal_acc = decimals,
    n_bits_chromosome = n_bits_chromosome,
)
pop_bin = PopGen.initialize_population(
    popsize = init_popsize, 
    var_ranges = var_ranges, 
    return_genotype = True,
    offset = offset,
)

Run evolution

evol_rec = PopGen.evolve(
    pop_bin, 
    n_gen    = 50, 
    n_pairs  = 800,
    elitist  = True,
    n_elites = 3,
    liberal  = False,
    n_runts  = 0,
    switch_selection = 5,
    prob_mut = 0.02, 
    prune    = True,
    pruning_cutoff = 800,
    verbose  = True,
    n_workers = 1,
)

Look at the results

print(f"Best solution is {evol_rec['fittest_individual']} with fitness {evol_rec['best_overall_fitness']}.")

plt.figure(figsize = (5,3))
gens = np.arange(len(evol_rec['best_fitness_per_generation']))+1
plt.plot(gens, evol_rec['best_fitness_per_generation'], color = 'green', label = 'Best')
plt.plot(gens, evol_rec['mean_fitness_per_generation'], color = 'blue', label = 'Mean')
plt.plot(gens, evol_rec['median_fitness_per_generation'], color = 'indigo', label = 'Median')
plt.legend()

plt.xlim(gens[0], gens[-1])
plt.xlabel('Generations')
plt.ylabel('Fitness')
plt.show()

Tutorial

Check out the notebook at tutorial/tutorial.ipynb for a lightning tutorial of GeneticAlPy!

Get in touch

Drop me an email at parth3e8@gmail.com in case of any questions or to request more functionality!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

geneticalpy-0.1.1.tar.gz (24.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

geneticalpy-0.1.1-py3-none-any.whl (23.1 kB view details)

Uploaded Python 3

File details

Details for the file geneticalpy-0.1.1.tar.gz.

File metadata

  • Download URL: geneticalpy-0.1.1.tar.gz
  • Upload date:
  • Size: 24.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for geneticalpy-0.1.1.tar.gz
Algorithm Hash digest
SHA256 b3a23ba0bd7e6b20c2c1f73fe6cde5c1acc4de197d9b839efb01cee8b6deea91
MD5 d57dffa598b9872c8a87a8417ec40bad
BLAKE2b-256 6b5c1d4e0422d42b6803b85db90aaf36764f9415118cdd4b84c738facee21a8a

See more details on using hashes here.

Provenance

The following attestation bundles were made for geneticalpy-0.1.1.tar.gz:

Publisher: python-publish.yml on par-nay/geneticalpy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file geneticalpy-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: geneticalpy-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 23.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for geneticalpy-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f63479b4cb1be41e021b65063d51107ee4e90da19a49c7b93b05ab4f085110f2
MD5 97592a26360eb36ab6db5b45aae66892
BLAKE2b-256 57da62a3c40f7b637506e3b39ec662e4647aa44d579fa734e752dbb70575b8df

See more details on using hashes here.

Provenance

The following attestation bundles were made for geneticalpy-0.1.1-py3-none-any.whl:

Publisher: python-publish.yml on par-nay/geneticalpy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page