You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Mutation raises OverflowError with numpy.uint8 genes #379
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.
importnumpyimportpygaddeffitness_func(ga_instance, solution, solution_idx):
returnfloat(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
Clip mutated values to NumPy integer limits
Use consistent 64-bit storage for Python int genes
Prepare PyGAD 3.8.1