Skip to main content

Una librería flexible para implementar algoritmos genéticos

Project description

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

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

SPGA-0.1.1.tar.gz (8.4 kB view details)

Uploaded Source

Built Distribution

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

SPGA-0.1.1-py3-none-any.whl (9.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: SPGA-0.1.1.tar.gz
  • Upload date:
  • Size: 8.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.12

File hashes

Hashes for SPGA-0.1.1.tar.gz
Algorithm Hash digest
SHA256 640e84eadc80ca09abdc9b0219ce9fc21518ebacbb7cf63a6f79aaa40a003d7b
MD5 072f50186e95e44f0cda9dce831e2476
BLAKE2b-256 db5cfbe0736a33ea2eb8e285376d1ac369fa33f1728006c01544775953365e3b

See more details on using hashes here.

File details

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

File metadata

  • Download URL: SPGA-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 9.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.12

File hashes

Hashes for SPGA-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 97512629a95a181a3d73ebde4254fddd7113785bcfd190c11118d69479de88a2
MD5 bfef9f4722b2755de16b13ce20001ba9
BLAKE2b-256 054ee82dcb575f7d3fd9000cd55210286cccc6ea1becb2500def56b42696cfdb

See more details on using hashes here.

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