Skip to main content
Yanked

This release has been yanked by its maintainers, and will be ignored by installers, except when explicitly specified.

SPGA: Simple and Personalizable Genetic Algorithm

PyPI version Python versions License: MIT

Overview

SPGA is a lightweight Python framework for building customizable genetic algorithms. Designed for education and production, it offers:

  • Full control over genetic operations
  • Clean generational workflow
  • Built-in progress visualization
  • Minimal dependencies (NumPy + Matplotlib)
  • Pre-built genetic operators
pip install spga

Quickstart

import math
import random
import numpy as np
from spga import (
    genetic_algorithm,
    Solution,
    create_genetic_operations,
    tournament_selection,
    mean_crossover,
    uniform_mutation
)

# 1. Problem configuration
SEARCH_SPACE = (0, 12.55)  # Search space boundaries
POPULATION_SIZE = 100
NUM_ITERATIONS = 100

def population_generator(**kwargs):

    return [Solution(
        solution=[random.uniform(*SEARCH_SPACE)],
        fitness=None
    ) for _ in range(kwargs['population_size'])]

def evaluate_fitness(individual, **kwargs):

    x = individual.solution[0]
    if x > SEARCH_SPACE[1] or x < SEARCH_SPACE[0]:
        return 0
    return math.sin(x) * (x ** 2)

# 4. Algorithm configuration
ga_args = {
    'population_size': POPULATION_SIZE,
    'num_iterations': NUM_ITERATIONS,
    'optimization': 'max',  # Optimization direction
    'tournament_size': 3,  # Number of individuals in tournament
    'mutation_probability': 0.15,  # Probability of mutation
    'crossover_probability': 0.8,    # Probability of crossover (disabled here)
    'max_its_with_enhancing': 20  # Max iterations without improvement
}

# Configure genetic operations pipeline
genetic_operations = create_genetic_operations(
    selection_func=tournament_selection,
    crossover_func=mean_crossover,
    mutation_func=uniform_mutation,
    elitism=True
)

# 5. Algorithm execution
result = genetic_algorithm(
    population_generator=population_generator,
    evaluate_fitness=evaluate_fitness,
    genetic_operations=genetic_operations,
    args=ga_args,
    verbose=True,
    plot=True
)
# 6. Results output
print("\n--- FINAL RESULTS ---")
print(f"Best solution found: x = {result.best_solution[0]:.4f}")
print(f"Function value: f(x) = {result.best_fitness:.4f}")

Custom Genetic Operators

Custom Selection Operator

from spga import BaseOperator

def custom_tournament(population, **kargs):
    optimization = kargs['optimization']
    tournament_size = kargs.get('tournament_size', 3)
    new_population = []
    for i in range(len(population)):
        tournament = random.sample(population, tournament_size)
        if optimization == 'max':
            best = max(tournament, key=lambda x: x.fitness)
        else:
            best = min(tournament, key=lambda x: x.fitness)
        new_population.append(best)
    return new_population

Custom Crossover Operator

def custom_uniform_crossover(parent1, parent2, **kargs):
    child1,child2 = [],[]
    for i in range(len(parent1.solution)):
        if random.random() < 0.5:
            child1.append(parent1.solution[i])
            child2.append(parent2.solution[i])
        else:
            child1.append(parent2.solution[i])
            child2.append(parent1.solution[i])
    return Solution(solution=child1, fitness=None),Solution(solution=child2, fitness=None)

Custom Selection Operator

def custom_constant_mutation(individual, **kargs):
    for i in range(len(individual.solution)):
        index = random.randint(0, len(individual.solution)-1)
        fact = 1.0
        if random.random() < 0.5:
            fact = -1.0
        individual.solution[index] = individual.solution[index] + fact * 0.01
    return individual

Key Features

Progress Tracking

result = genetic_algorithm(..., plot=True)  # Auto-generates fitness plot

Progress Tracking

args = {
    'population_size': 50,
    'num_iterations': 200,
    'optimization': 'min',
    'early_stop': True,  # Stop if solution is good enough
    'log_scale': True    # Plot fitness in log scale
}

Documentation

Contributing

Contributions welcome! Please submit:

  • Bug reports via issues

  • Feature requests via issues

Metadata

Release files for SPGA 0.1.3

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

Source distribution (sdist)

Source distribution for SPGA 0.1.3
File Size Uploaded Provenance Actions
spga-0.1.3.tar.gz 8.8 kB Without provenance Details for spga-0.1.3.tar.gz

Built distribution (wheel)

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

Total release size: 18.4 kB

Release files / spga-0.1.3.tar.gz

Download URL spga-0.1.3.tar.gz
Size 8.8 kB
Tags Source
SHA-256 checksum
How to use checksums
3b99895374a664b210328d48a15e7e5d08d939a3aa75d5b4b8c50d24adf7b135
BLAKE2b-256 checksum
How to use checksums
38abf5c2c3118b744d74e9e49d4248a805fdc50d11f9bd35662b9627f2799717
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.12

Release files / SPGA-0.1.3-py3-none-any.whl

Download URL SPGA-0.1.3-py3-none-any.whl
Size 9.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bd0ed007c7cb1589c89c2e510f852cf29a61d41f0836da6350d5ac604cb0033a
BLAKE2b-256 checksum
How to use checksums
c5b6b9737911b55d4228bd25a12c8fb127a51720c96dd71193ce3b7d3f53f3e5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.12

Security for SPGA 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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