Added Permutation class

This commit is contained in:
SimpleArt
2020-11-12 17:38:10 -05:00
parent aab353b825
commit 45316286c0
2 changed files with 26 additions and 5 deletions

2
.gitignore vendored
View File

@ -140,3 +140,5 @@ dmypy.json
# End of https://www.toptal.com/developers/gitignore/api/python
src/database.db
src/database.db

View File

@ -53,20 +53,17 @@ class Mutation_Methods:
def individual_genes(ga, old_chromosome):
"""Mutates a random gene in the chromosome and resets the fitness."""
chromosome = ga.make_chromosome(old_chromosome.get_gene_list())
mutation_count = 0
# Loops until enough mutations occur
while mutation_count < chromosome.size()*ga.gene_mutation_rate:
mutation_count += 1
for n in range(int(chromosome.size()*ga.gene_mutation_rate)):
index = random.randint(0, chromosome.size()-1)
# Using the chromosome_impl
if ga.chromosome_impl != None:
index = random.randint(0, chromosome.size()-1)
chromosome.set_gene(ga.make_gene(ga.chromosome_impl()[index]), index)
# Using the gene_impl
elif ga.gene_impl != None:
index = random.randint(0, chromosome.size()-1)
chromosome.set_gene(ga.make_gene(ga.gene_impl()), index)
# Exit because no gene creation method specified
@ -75,3 +72,25 @@ class Mutation_Methods:
break
return chromosome
class Permutation:
"""Methods for mutating a chromosome
by changing the order of the genes."""
def swap_genes(ga, old_chromosome):
"""Mutates a random gene in the chromosome and resets the fitness."""
chromosome = ga.make_chromosome(old_chromosome.get_gene_list())
# Loops until enough mutations occur
for n in range(int(chromosome.size()*ga.gene_mutation_rate)):
index_one = random.randint(0, chromosome.size()-1)
index_two = random.randint(0, chromosome.size()-1)
gene_one = chromosome.get_gene(index_one)
gene_two = chromosome.get_gene(index_two)
chromosome.set_gene(gene_one, index_two)
chromosome.set_gene(gene_two, index_one)
return chromosome