コード例 #1
0
 def info(self, plot=True):
     eu.printParamDist(self.pop, self.paramInterval, self.gIdx)
     if plot:
         eu.printPopFitnessStats(self.pop,
                                 self.paramInterval,
                                 self.gIdx,
                                 draw_scattermatrix=True)
     bestN = 20
     print("--------------------------")
     print(f"Best {bestN} individuals:")
     eu.printIndividuals(self.toolbox.selBest(self.pop, bestN),
                         self.paramInterval)
コード例 #2
0
 def runInitial(self):
     """First round of evolution: 
     """
     ### Evaluate the initial population
     logging.info("Evaluating initial population of size %i ..." %
                  len(self.pop))
     self.gIdx = 0  # set generation index
     # evaluate
     self.pop = self.evalPopulationUsingPypet(self.traj, self.toolbox,
                                              self.pop, self.gIdx)
     if self.verbose:
         eu.printParamDist(self.pop, self.paramInterval, self.gIdx)
     self.pop = eu.saveToPypet(self.traj, self.pop, self.gIdx)
     # Only the best indviduals are selected for the population the others do not survive
     self.pop[:] = self.toolbox.selBest(self.pop, k=self.traj.popsize)
     self.initialPopulationSimulated = True
コード例 #3
0
 def info(self, plot=True, bestN=5):
     validPop = [
         p for p in self.pop if not np.any(np.isnan(p.fitness.values))
     ]
     popArray = np.array(
         [p[0:len(self.paramInterval._fields)] for p in validPop]).T
     scores = np.array(
         [validPop[i].fitness.score for i in range(len(validPop))])
     # Text output
     print("--- Info summary ---")
     print("Valid: {}".format(len(validPop)))
     print("Mean score (weighted fitness): {:.2}".format(np.mean(scores)))
     eu.printParamDist(self.pop, self.paramInterval, self.gIdx)
     print("--------------------")
     print(f"Best {bestN} individuals:")
     eu.printIndividuals(self.toolbox.selBest(self.pop, bestN),
                         self.paramInterval)
     print("--------------------")
     # Plotting
     if plot:
         eu.plotPopulation(self.pop,
                           self.paramInterval,
                           self.gIdx,
                           draw_scattermatrix=True)
コード例 #4
0
    def runEvolution(self):
        # Start evolution
        logging.info("Start of evolution")
        for self.gIdx in range(self.gIdx + 1, self.gIdx + self.traj.NGEN):
            # ------- Weed out the invalid individuals and replace them by random new indivuals -------- #
            validpop = self.getValidPopulation(self.pop)

            # add all valid individuals to the population history
            self.popHist[self.gIdx] = self.getValidPopulation(self.pop)

            # replace invalid individuals
            nanpop = self.getInvalidPopulation(self.pop)
            logging.info("Replacing {} invalid individuals.".format(
                len(nanpop)))
            newpop = self.toolbox.population(n=len(nanpop))
            newpop = self.tagPopulation(newpop)

            # self.pop = validpop + newpop

            # ------- Create the next generation by crossover and mutation -------- #
            ### Select parents using rank selection and clone them ###
            offspring = list(
                map(self.toolbox.clone,
                    self.toolbox.selRank(self.pop, self.POP_SIZE)))

            ##### cross-over ####
            for i in range(1, len(offspring), 2):
                offspring[i - 1], offspring[i] = self.toolbox.mate(
                    offspring[i - 1], offspring[i], indpb=self.CXPB)
                # del offspring[i - 1].fitness, offspring[i].fitness
                del offspring[i -
                              1].fitness.values, offspring[i].fitness.values
                del offspring[i -
                              1].fitness.wvalues, offspring[i].fitness.wvalues
                # print("Deleting ID of {} and {}".format(offspring[i - 1].id, offspring[i].id))
                del offspring[i - 1].id, offspring[i].id

            ##### Mutation ####
            # Apply adaptive mutation
            du.mutateUntilValid(offspring, self.paramInterval, self.toolbox)

            offspring = self.tagPopulation(offspring)

            # ------- Evaluate next generation -------- #

            logging.info("----------- Generation %i -----------" % self.gIdx)

            self.pop = offspring + newpop
            self.evalPopulationUsingPypet(self.traj, self.toolbox,
                                          offspring + newpop, self.gIdx)
            # ------- Select surviving population -------- #

            # select next population
            self.pop = self.toolbox.selBest(validpop + offspring + newpop,
                                            k=self.traj.popsize)

            self.best_ind = self.toolbox.selBest(self.pop, 1)[0]

            if self.verbose:
                print("----------- Generation %i -----------" % self.gIdx)
                print("Best individual is {}".format(self.best_ind))
                print("Score: {}".format(self.best_ind.fitness.score))
                print("Fitness: {}".format(self.best_ind.fitness.values))
                print("--- Population statistics ---")
                eu.printParamDist(self.pop, self.paramInterval, self.gIdx)
                eu.plotPopulation(self.pop,
                                  self.paramInterval,
                                  self.gIdx,
                                  draw_scattermatrix=True,
                                  save_plots=self.trajectoryName)

            # save all simulation data to pypet
            try:
                self.pop = eu.saveToPypet(self.traj, self.pop, self.gIdx)
            except:
                logging.warn("Error: Write to pypet failed!")

        logging.info("--- End of evolution ---")
        self.best_ind = self.toolbox.selBest(self.pop, 1)[0]
        logging.info("Best individual is %s, %s" %
                     (self.best_ind, self.best_ind.fitness.values))
        logging.info("--- End of evolution ---")

        self.traj.f_store(
        )  # We switched off automatic storing, so we need to store manually