Skip to content

Mutation raises OverflowError with numpy.uint8 genes #379

Closed

Description

@omadson

Version: PyGAD 3.8.0 (same code on master). Checked on NumPy 2.5.4 (Python 3.14) and NumPy 1.24.4 (Python 3.9).

While testing PyGAD 3.8.0 with randomly generated GA configurations (random gene types, operators and parameters), run() often failed with OverflowError: Python integer -1 out of bounds for uint8. It happens with gene_type=numpy.uint8 (or another NumPy integer type) and the default mutation settings.

mutation_change_gene_dtype_and_round() (pygad/helper/misc.py L421-L434) adds the random offset to the gene and casts the result without checking the limits of the type. A uint8 gene at 0 with an offset of -1 becomes -1, and an int8 gene at 127 with +1 becomes 128. NumPy 1.24 wraps the value instead of raising, so 0 becomes 255.

The initial population already clamps to the type limits (_initial_population_integer_bounds()).

Reproduction

import numpy
import pygad

def fitness_func(ga_instance, solution, solution_idx):
    return float(numpy.sum(solution))

ga_instance = pygad.GA(
    num_generations=30,
    num_parents_mating=4,
    fitness_func=fitness_func,
    sol_per_pop=10,
    num_genes=6,
    gene_type=numpy.uint8,
    init_range_low=0,
    init_range_high=3,
    random_seed=0
)
ga_instance.run()  # fails for 12 of the seeds 0 to 19

# The failing call in isolation: gene value 0, random offsets -1 and 0.
ga_instance.mutation_change_gene_dtype_and_round(
    numpy.array([-1, 0], dtype=object), 0, numpy.uint8(0), False
)

NumPy 2.5.4: both calls raise OverflowError: Python integer -1 out of bounds for uint8.
NumPy 1.24.4: run() finishes after a DeprecationWarning, and the second call returns array([255, 0], dtype=uint8).

Proposed fix

Clamp the mutated value to the limits of its NumPy integer type before the cast. Python int, floats and object genes, and values already in range, stay unchanged. I can send a pull request with tests.

Activity

  1. added a commit that references this issue on Oct 11, 2026
    d12725f
  2. self-assigned this
    on Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions