diff --git a/algorithms/genetic_algorithm.py b/algorithms/genetic_algorithm.py index 6e94f0a0df0e468b72674a6f7b2b1fb51bdc7b4b..c9aa63d6bf5cf54470bd8f5ebdbc99d68c6e168e 100644 --- a/algorithms/genetic_algorithm.py +++ b/algorithms/genetic_algorithm.py @@ -47,7 +47,7 @@ class Chromosome: class GeneticAlgorithm(BaseAlgorithm): - """ Finds nulls by running a genetic algorithm on all possible + """ Finds nulls by running a genetic algorithm on all possible discrete values. """ @@ -69,6 +69,7 @@ class GeneticAlgorithm(BaseAlgorithm): self.gen_to_repeat = options.gen_to_repeat self.time_limit = options.time_limit self.stop_after_score = options.stop_after_score + self.max_time_limit = 20 * 1000 self.generations = 0 self.chromosomes = [] @@ -95,7 +96,11 @@ class GeneticAlgorithm(BaseAlgorithm): self.organize_sample() solve_function = getattr(self, "solve_" + self.stop_criterion) solve_function() - return (self.make_weights(self.chromosomes[0]), self.chromosomes[0].get_score(), self.generations) + return ( + self.make_weights(self.chromosomes[0]), + self.chromosomes[0].get_score(), + self.generations + ) def solve_time(self): start_time = time_ns() @@ -104,7 +109,7 @@ class GeneticAlgorithm(BaseAlgorithm): def solve_target(self): start_time = time_ns() - while (time_ns() - start_time) // 10**6 <= 10 * 1000: + while (time_ns() - start_time) // 10**6 <= self.max_time_limit: self.step() def solve_iter(self): @@ -115,6 +120,7 @@ class GeneticAlgorithm(BaseAlgorithm): self.create_children() self.mutate_sample() self.organize_sample() + self.generations += 1 def create_children(self): """Using the better half of the population, creates children overwriting the bottom half by doing crossovers. @@ -137,8 +143,6 @@ class GeneticAlgorithm(BaseAlgorithm): ) if len(self.buckets[bucket_opp]) > 0 else choice(self.chromosomes) self.crossover_bucket(p1, p2, child, child + 1) - self.generations += 1 - def organize_sample(self): """Reorganizes the sample by updating pattern for all chromosomes and sorting them by their scores. Optionally, if use_buckets is True, allocates each chromosome to its respective bucket."""