Example #1
0
class GeneticOptimization(OptimizationStep):
    "Genetic optimization step."
    def __init__(self, no_vars, mins, maxes, comm, stop_flag, seed=False,
            allele=False, size=200, generations=100):
        super(GeneticOptimization, self).__init__(no_vars, mins, maxes, comm,
            stop_flag)
        self.seed = seed
        self.allele = allele
        self.size = size
        self.timer = Timer()
        self.generations = generations
        self.prepare()

    def __prepare_genome(self):
        u"Initialize genome with constraints."
        if self.allele:  # Built-in allele version.
            self.genome = AlleleG1DList(self.no_vars, constr_min=self.mins,
                constr_max=self.maxes)
        else:  # Custom, ported genetic operators.
            self.genome = CustomG1DList(self.no_vars)
            self.genome.setParams(min_constr=self.mins, max_constr=self.maxes)
        self.genome.evaluator.set(GeneticObjective(self.comm))

    def __prepare_engine(self):
        u"Prepare the GA engine."
        # Set GA engine parameters.
        self.ga = CustomGSimpleGA(self.genome, self.seed)
        self.ga.setPopulationSize(self.size)
        self.ga.setGenerations(self.generations)
        self.ga.setParams(stop_file=self.stop_flag)
        self.ga.setParams(timer=self.timer)

    def prepare(self):
        self.__prepare_genome()
        self.__prepare_engine()

    def run(self):
        u"Fire the Genetic Algorithm Engine."
        printf("Starting GA: %d generations of %d individuals" % (
            self.generations, self.size))
        self.timer.start()
        self.ga.evolve()
        self.__post_run()
        # Return the best parameters found.
        return list(self.ga.bestIndividual().getInternalList())

    def __post_run(self):
        stats_step_callback(self.ga)  # Display final statistics.
        # Evolution is stoped.
        run_time = self.timer.stop()
        print "GA finished in %g s." % run_time