Comments updated

This commit is contained in:
SimpleArt
2020-11-20 19:06:55 -05:00
parent 68b10c3fde
commit 73461f7915
10 changed files with 159 additions and 52 deletions

View File

@ -2,18 +2,18 @@ import random
from math import ceil
def loop_selections(selection_method):
"""Runs the selection method until enough chromosomes are mutated."""
def helper(ga):
# Loop until enough mutations occur
for n in range(ceil(len(ga.population)*ga.chromosome_mutation_rate)):
selection_method(ga)
return helper
def loop_mutations(mutation_method):
"""Runs the mutation method until enough genes are mutated."""
def helper(ga, old_chromosome):
chromosome = ga.make_chromosome(list(old_chromosome))
# Loops until enough mutations occur
for n in range(ceil(len(chromosome)*ga.gene_mutation_rate)):
mutation_method(ga, chromosome)
@ -23,6 +23,7 @@ def loop_mutations(mutation_method):
class Mutation_Methods:
# Private method decorators, see above.
def __loop_selections(selection_method):
return loop_selections(selection_method)
def __loop_mutations(mutation_method):
@ -32,10 +33,9 @@ class Mutation_Methods:
class Population:
"""Methods for selecting chromosomes to mutate"""
@loop_selections
def random_selection(ga):
"""Selects random chromosomes"""
"""Selects random chromosomes."""
index = random.randint(0, len(ga.population)-1)
ga.population[index] = ga.mutation_individual_impl(ga, ga.population[index])
@ -43,7 +43,7 @@ class Mutation_Methods:
@loop_selections
def random_selection_then_cross(ga):
"""Selects random chromosomes and self-crosses with parent"""
"""Selects random chromosomes and self-crosses with parent."""
index = random.randint(0, len(ga.population)-1)
chromosome = ga.population[index]
@ -51,12 +51,11 @@ class Mutation_Methods:
class Individual:
"""Methods for mutating a single chromosome"""
"""Methods for mutating a single chromosome."""
@loop_mutations
def individual_genes(ga, chromosome):
"""Mutates a random gene in the chromosome and resets the fitness."""
"""Mutates a random gene in the chromosome."""
index = random.randint(0, len(chromosome)-1)
# Using the chromosome_impl
@ -72,15 +71,15 @@ class Mutation_Methods:
raise Exception("Did not specify any initialization constraints.")
class Permutation:
"""Methods for mutating a chromosome
by changing the order of the genes."""
class Permutation:
"""Methods for mutating a chromosome
by changing the order of the genes."""
@loop_mutations
def swap_genes(ga, chromosome):
"""Mutates a random gene in the chromosome and resets the fitness."""
@loop_mutations
def swap_genes(ga, chromosome):
"""Swaps two random genes in the chromosome."""
index_one = random.randint(0, len(chromosome)-1)
index_two = random.randint(0, len(chromosome)-1)
index_one = random.randint(0, len(chromosome)-1)
index_two = random.randint(0, len(chromosome)-1)
chromosome[index_one], chromosome[index_two] = chromosome[index_two], chromosome[index_one]
chromosome[index_one], chromosome[index_two] = chromosome[index_two], chromosome[index_one]