def test(): WORLD = World(fitness=fitness) WORLD.population = IntListPopulation(length=10) rho = 2 PARENTS = select_fittest(WORLD, rho=rho) assert len(PARENTS) == rho assert PARENTS[0].gene[0] == 0 assert PARENTS[1].gene[0] == 0
def ea(SIGMA=SIGMA): # initialize world = World(fitness=fitness) world.population = IntListPopulation(length=MU, gene_size=GENE_SIZE) # iterate over generations for generation_count in range(MAX_GENERATIONS): # log this generation's population to stdout print("%s: %s" % (generation_count, world.population)) # if we reached a sufficiently good solution, stop if min(world.scores) < MIN_FITNESS: break # select rho fittest individuals as parents parents = select(world=world, rho=RHO) # generate children by crossing over the parents children_original = [] while len(children_original) < LAMBDA: children_original += crossover(population=parents) # mutate children children = [mutate(individual=individual, mu=0, sigma=SIGMA) for individual in children_original] # self-adapt mutation strenght using Rechenberg's success rule SIGMA = rechenberg(children_original=children_original, children_mutated=children, fitness=world.fitness, a=A_RECHENBERG, sigma=SIGMA) if MODE == '+': # extend population with children world.population += Population.from_individuals( individuals=children) elif MODE == ',': # replace population with children world.population = Population.from_individuals( individuals=children) # select fittest mu individuals for next generation world.population = select(rho=MU, world=world) # log best individual print("Best individual is %s with a score of %s." % (select(world=world, rho=1)[0], min(world.scores)))