def evolve(pc,popsize,rankfunction,maxgen=500,mutationrate=0.1,breedingrate=0.4,pexp=0.7,pnew=0.05,previouswinner=0): def selectindex(): return int(log(random())/log(pexp)) population=[makerandomtree(pc) for i in range(popsize)] if previouswinner!=0: population.pop() population.append(previouswinner) for i in range(maxgen): scores=rankfunction(population) print scores[0][0] if scores[0][0]==0: break newpop=[scores[0][1],scores[1][1]] while len(newpop)<popsize: if random()>pnew: newpop.append(mutate(crossover(scores[selectindex()][1],scores[selectindex()][1],probswap=breedingrate),pc,probchange=mutationrate)) else: newpop.append(makerandomtree(pc)) population=newpop scores[0][1].display() return scores[0][1]
def mutate(t,pc,probchange=0.1): if random()<probchange: return makerandomtree(pc) else: result=deepcopy(t) if isinstance(t,node): result.children=[mutate(c,pc,probchange) for c in t.children] return result