From 45316286c0c373daa609a1a4793fd11a1f739d44 Mon Sep 17 00:00:00 2001 From: SimpleArt <71458112+SimpleArt@users.noreply.github.com> Date: Thu, 12 Nov 2020 17:38:10 -0500 Subject: [PATCH] Added Permutation class --- .gitignore | 2 ++ src/mutation/mutation_methods.py | 29 ++++++++++++++++++++++++----- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index bff0a0b..7b6f117 100644 --- a/.gitignore +++ b/.gitignore @@ -140,3 +140,5 @@ dmypy.json # End of https://www.toptal.com/developers/gitignore/api/python +src/database.db +src/database.db diff --git a/src/mutation/mutation_methods.py b/src/mutation/mutation_methods.py index 6ac246f..be8327c 100644 --- a/src/mutation/mutation_methods.py +++ b/src/mutation/mutation_methods.py @@ -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