Skip to content

Swap genes when the random mutation finds no free value - #373

Open
tachsin wants to merge 1 commit into
ahmedfgad:masterfrom
tachsin:fix-permutation-random-mutation
Open

tachsin wants to merge 1 commit into
ahmedfgad:masterfrom
tachsin:fix-permutation-random-mutation

Conversation

@tachsin

@tachsin tachsin commented Sep 28, 2026

Copy link
Copy Markdown

Fixes #372.

With allow_duplicate_genes=False and a gene space of num_genes values (the permutation setup of pygad.benchmarks.tsp), every value of the space is used, so select_unique_value() kept the gene's value and the random mutation never changed a solution.

This adds swap_gene_by_space() to the Mutation class. In the 4 mutations by space (mutation_by_space, mutation_probs_by_space, adaptive_mutation_by_space, adaptive_mutation_probs_by_space), when the picked value equals the gene's value and duplicates aren't allowed, the gene swaps values with another gene, picked at random among those whose value is in its space and whose space holds its value. The swap keeps the genes unique, so the duplicate resolution isn't needed. Genes with a gene_constraint aren't swapped, and nothing changes when duplicates are allowed or a free value exists.

On examples/benchmarks/example_tsp.py's settings with 12 cities on a circle (200 generations, seeds 0 to 2), the best tours go from lengths 11.7, 12.5 and 9.6 to the optimum, 6.2.

Tests: 3 tests in tests/test_crossover_mutation.py mutate 100 permutations of 8 (with mutation_num_genes, with mutation_probability=1.0, and with a nested gene space) and check that each one changes and stays a permutation. They fail on master and pass with this change.

pytest tests (without test_kerasga.py and test_torchga.py, which need TensorFlow and PyTorch): 874 passed, 1 skipped. The only failure is test_submodule_versions.py::test_changed_submodule_is_version_bumped[utils], since pygad/utils changed; I left the version bump to you for the release.

With allow_duplicate_genes=False and a gene space of num_genes values, as
for permutations, every value of the space is used, so a mutated gene
kept its value and the mutation never changed a solution. In the 4
mutations by space, swap the gene with another gene whose value is in
its space and whose space holds its value instead.

Fixes ahmedfgad#372

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

With allow_duplicate_genes=False, the random mutation never changes a permutation

1 participant