frompyevolveimportG1DListfrompyevolveimportGSimpleGAfrompyevolveimportSelectorsfrompyevolveimportStatisticsfrompyevolveimportDBAdaptersimportpyevolve# This function is the evaluation function, we want# to give high score to more zero'ed chromosomesdefeval_func(chromosome):score=0.0# iterate over the chromosome# score = len(filter(lambda x: x==0, chromosome.genomeList))forvalueinchromosome:ifvalue==0:score+=1returnscore# Enable the pyevolve logging systempyevolve.logEnable()# Genome instance, 1D List of 50 elementsgenome=G1DList.G1DList(50)# Sets the range max and min of the 1D Listgenome.setParams(rangemin=0,rangemax=10)# The evaluator function (evaluation function)genome.evaluator.set(eval_func)# Genetic Algorithm Instancega=GSimpleGA.GSimpleGA(genome)# Set the Roulette Wheel selector method, the number of generations and# the termination criteriaga.selector.set(Selectors.GRouletteWheel)ga.setGenerations(500)ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria)# Sets the DB Adapter, the resetDB flag will make the Adapter recreate# the database and erase all data every run, you should use this flag# just in the first time, after the pyevolve.db was created, you can# omit it.sqlite_adapter=DBAdapters.DBSQLite(identify="ex1",resetDB=True)ga.setDBAdapter(sqlite_adapter)# Do the evolution, with stats dump# frequency of 20 generationsga.evolve(freq_stats=20)# Best individualprintga.bestIndividual()

# $Id: pyevolve_ex5_callback.py 151 2009-01-19 01:23:22Z christian.perone $frompyevolveimportG1DListfrompyevolveimportGSimpleGAfrompyevolveimportSelectorsimportpyevolve# The step callback function, this function# will be called every step (generation) of the GA evolutiondefevolve_callback(ga_engine):generation=ga_engine.getCurrentGeneration()ifgeneration%100==0:print"Current generation: %d"%(generation,)printga_engine.getStatistics()returnFalse# This function is the evaluation function, we want# to give high score to more zero'ed chromosomesdefeval_func(chromosome):score=0.0# iterate over the chromosomeforvalueinchromosome:ifvalue==0:score+=0.1returnscore# Enable the logging systempyevolve.logEnable()# Genome instancegenome=G1DList.G1DList(200)genome.setParams(rangemin=0,rangemax=10)# The evaluator function (objective function)genome.evaluator.set(eval_func)# Genetic Algorithm Instancega=GSimpleGA.GSimpleGA(genome)ga.selector.set(Selectors.GRouletteWheel)ga.setGenerations(800)ga.stepCallback.set(evolve_callback)# Do the evolution, with stats dump# frequency of 10 generationsga.evolve()# Best individualprintga.bestIndividual()

frompyevolveimportG1DListfrompyevolveimportGSimpleGAfrompyevolveimportSelectorsfrompyevolveimportDBAdaptersfrompyevolveimportStatistics# This function is the evaluation function, we want# to give high score to more zero'ed chromosomesdefeval_func(chromosome):score=0.0# iterate over the chromosomeforvalueinchromosome:ifvalue==0:score+=0.5returnscore# Genome instancegenome=G1DList.G1DList(100)genome.setParams(rangemin=0,rangemax=10)# The evaluator function (objective function)genome.evaluator.set(eval_func)# Genetic Algorithm Instancega=GSimpleGA.GSimpleGA(genome)ga.setGenerations(80)# Create DB Adapter and set as adaptersqlite_adapter=DBAdapters.DBSQLite(identify="ex6")ga.setDBAdapter(sqlite_adapter)# Using CSV Adapter#csvfile_adapter = DBAdapters.DBFileCSV()#ga.setDBAdapter(csvfile_adapter)# Using the URL Post Adapter# urlpost_adapter = DBAdapters.DBURLPost(url="http://whatismyip.oceanus.ro/server_variables.php", post=False)# ga.setDBAdapter(urlpost_adapter)# Do the evolution, with stats dump# frequency of 10 generationsga.evolve(freq_stats=10)# Best individualprintga.bestIndividual()

frompyevolveimportG1DListfrompyevolveimportGSimpleGAfrompyevolveimportSelectorsfrompyevolveimportMutatorsimportpyevolveimportlogging# This function is the evaluation function, we want# to give high score to more zero'ed chromosomesdefeval_func(chromosome):score=0.0# iterate over the chromosomeforvalueinchromosome:ifvalue==0:score+=0.1returnscorepyevolve.logEnable()# Genome instancegenome=G1DList.G1DList(40)# The gauss_mu and gauss_sigma is used to the Gaussian Mutator, but# if you don't specify, the mutator will use the defaultsgenome.setParams(rangemin=0,rangemax=10,gauss_mu=1,gauss_sigma=6)genome.mutator.set(Mutators.G1DListMutatorIntegerGaussian)# The evaluator function (objective function)genome.evaluator.set(eval_func)# Genetic Algorithm Instancega=GSimpleGA.GSimpleGA(genome)ga.selector.set(Selectors.GRouletteWheel)ga.setGenerations(1000)# Do the evolution, with stats dump# frequency of 10 generationsga.evolve(freq_stats=150)# Best individualprintga.bestIndividual()

frompyevolveimportG2DListfrompyevolveimportGSimpleGAfrompyevolveimportSelectorsfrompyevolveimportCrossoversfrompyevolveimportMutators# This function is the evaluation function, we want# to give high score to more zero'ed chromosomesdefeval_func(chromosome):score=0.0# iterate over the chromosomeforiinxrange(chromosome.getHeight()):forjinxrange(chromosome.getWidth()):# You can use the chromosome.getItem(i, j)ifchromosome[i][j]==0:score+=0.1returnscore# Genome instancegenome=G2DList.G2DList(8,5)genome.setParams(rangemin=0,rangemax=10)# The evaluator function (objective function)genome.evaluator.set(eval_func)genome.crossover.set(Crossovers.G2DListCrossoverSingleHPoint)genome.mutator.set(Mutators.G2DListMutatorIntegerGaussian)# Genetic Algorithm Instancega=GSimpleGA.GSimpleGA(genome)ga.selector.set(Selectors.GRouletteWheel)ga.setGenerations(1200)# Do the evolution, with stats dump# frequency of 10 generationsga.evolve(freq_stats=100)# Best individualprintga.bestIndividual()

frompyevolveimportG1DBinaryStringfrompyevolveimportGSimpleGAfrompyevolveimportSelectorsfrompyevolveimportMutators# This function is the evaluation function, we want# to give high score to more zero'ed chromosomesdefeval_func(chromosome):score=0.0# iterate over the chromosomeforvalueinchromosome:ifvalue==0:score+=0.1returnscore# Genome instancegenome=G1DBinaryString.G1DBinaryString(60)# The evaluator function (objective function)genome.evaluator.set(eval_func)genome.mutator.set(Mutators.G1DBinaryStringMutatorFlip)# Genetic Algorithm Instancega=GSimpleGA.GSimpleGA(genome)ga.selector.set(Selectors.GTournamentSelector)ga.setGenerations(100)# Do the evolution, with stats dump# frequency of 10 generationsga.evolve(freq_stats=10)# Best individualbest=ga.bestIndividual()printbest

frompyevolveimportG1DListfrompyevolveimportGSimpleGAfrompyevolveimportSelectorsfrompyevolveimportMutatorsfrompyevolveimportInitializatorsfrompyevolveimportGAllele# This function is the evaluation function, we want# to give high score to more zero'ed chromosomesdefeval_func(chromosome):score=0.0# iterate over the chromosomeforvalueinchromosome:ifvalue==0:score+=0.5returnscore# Genome instancesetOfAlleles=GAllele.GAlleles()foriinxrange(11):a=GAllele.GAlleleRange(0,i)setOfAlleles.add(a)foriinxrange(11,20):# You can even add an object to the lista=GAllele.GAlleleList(['a','b','xxx',666,0])setOfAlleles.add(a)genome=G1DList.G1DList(20)genome.setParams(allele=setOfAlleles)# The evaluator function (objective function)genome.evaluator.set(eval_func)genome.mutator.set(Mutators.G1DListMutatorAllele)genome.initializator.set(Initializators.G1DListInitializatorAllele)# Genetic Algorithm Instancega=GSimpleGA.GSimpleGA(genome)ga.selector.set(Selectors.GRouletteWheel)ga.setGenerations(500)# Do the evolution, with stats dump# frequency of 10 generationsga.evolve(freq_stats=50)# Best individualprintga.bestIndividual()

# The follow TSP routines was get from the above site, I'm too lazy to reinvent a new pretty wheel:# http://www.psychicorigami.com/2007/04/17/tackling-the-travelling-salesman-problem-part-one/# Routines:# - cartesian_matrix# - read_coords# - tour_length# - write_tour_to_imgfrompyevolveimportG1DListfrompyevolveimportGSimpleGAfrompyevolveimportGAllelefrompyevolveimportMutatorsfrompyevolveimportInitializatorsfrompyevolveimportDBAdaptersfrompyevolveimportCrossoversfrompyevolveimportConstsimportsys,randomfrommathimportsqrtPIL_SUPPORT=Nonetry:fromPILimportImage,ImageDraw,ImageFontPIL_SUPPORT=Trueexcept:PIL_SUPPORT=Falsedefcartesian_matrix(coords):""" A distance matrix """matrix={}fori,(x1,y1)inenumerate(coords):forj,(x2,y2)inenumerate(coords):dx,dy=x1-x2,y1-y2dist=sqrt(dx*dx+dy*dy)matrix[i,j]=distreturnmatrixdefread_coords(coord_file):""" Read the coords from file """coords=[]forlineincoord_file:x,y=line.strip().split(",")coords.append((float(x),float(y)))returncoordsdeftour_length(matrix,tour):""" Returns the total length of the tour """total=0num_cities=len(tour)foriinrange(num_cities):j=(i+1)%num_citiescity_i=tour[i]city_j=tour[j]total+=matrix[city_i,city_j]returntotaldefwrite_tour_to_img(coords,tour,img_file):""" The function to plot the graph """padding=20coords=[(x+padding,y+padding)for(x,y)incoords]maxx,maxy=0,0forx,yincoords:maxx=max(x,maxx)maxy=max(y,maxy)maxx+=paddingmaxy+=paddingimg=Image.new("RGB",(int(maxx),int(maxy)),color=(255,255,255))font=ImageFont.load_default()d=ImageDraw.Draw(img);num_cities=len(tour)foriinrange(num_cities):j=(i+1)%num_citiescity_i=tour[i]city_j=tour[j]x1,y1=coords[city_i]x2,y2=coords[city_j]d.line((int(x1),int(y1),int(x2),int(y2)),fill=(0,0,0))d.text((int(x1)+7,int(y1)-5),str(i),font=font,fill=(32,32,32))forx,yincoords:x,y=int(x),int(y)d.ellipse((x-5,y-5,x+5,y+5),outline=(0,0,0),fill=(196,196,196))deldimg.save(img_file,"PNG")print"The plot was saved into the %s file."%(img_file,)defG1DListTSPInitializator(genome,**args):""" The initializator for the TSP """genome.clearList()lst=[iforiinxrange(genome.listSize)]foriinxrange(genome.listSize):choice=random.choice(lst)lst.remove(choice)genome.append(choice)cm=[]coords=[]defeval_func(chromosome):""" The evaluation function """globalcmreturntour_length(cm,chromosome)defwrite_random(filename,cities,xmax=800,ymax=600):""" Write random cities/positions to a text file """filehandle=open(filename,"w")foriinxrange(cities):x=random.randint(0,xmax)y=random.randint(0,ymax)filehandle.write("%d,%d\n"%(x,y))filehandle.close()# This is to make a video of best individuals along the evolution# Use mencoder to create a video with the file list list.txt# mencoder mf://@list.txt -mf w=400:h=200:fps=3:type=png -ovc lavc# -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o output.avi## def evolve_callback(ga_engine):# if ga_engine.currentGeneration % 10 == 0:# best = ga_engine.bestIndividual()# write_tour_to_img( coords, best, "tsp_result_%d.png" % (ga_engine.currentGeneration,))# return Falsedefmain_run():globalcm,coords# write_random(filename, number of the cities, max width, max_height)write_random("tsp_coords.txt",30,600,400)# load the tsp data filefilehandle=open("tsp_coords.txt","rw")coords=read_coords(filehandle)cm=cartesian_matrix(coords)# set the alleles to the cities numberssetOfAlleles=GAllele.GAlleles(homogeneous=True)lst=[iforiinxrange(len(coords))]a=GAllele.GAlleleList(lst)setOfAlleles.add(a)genome=G1DList.G1DList(len(coords))genome.setParams(allele=setOfAlleles)genome.evaluator.set(eval_func)genome.mutator.set(Mutators.G1DListMutatorSwap)genome.crossover.set(Crossovers.G1DListCrossoverOX)genome.initializator.set(G1DListTSPInitializator)ga=GSimpleGA.GSimpleGA(genome)ga.setGenerations(1000)ga.setMinimax(Consts.minimaxType["minimize"])ga.setCrossoverRate(1.0)ga.setMutationRate(0.03)ga.setPopulationSize(80)#sqlite_adapter = DBAdapters.DBSQLite(identify="tsp", commit_freq=1000, frequency=500)#ga.setDBAdapter(sqlite_adapter)# This is to make a video# ga.stepCallback.set(evolve_callback)ga.evolve(freq_stats=100)best=ga.bestIndividual()printbestifPIL_SUPPORT:write_tour_to_img(coords,best,"tsp_result.png")else:print"No PIL detected, cannot plot the graph !"if__name__=="__main__":main_run()

This example will plot a file called tsp_result.png in the same
directory of the execution, this image will be the best result of the
TSP, it looks like: