Examples

All the examples can be download from the Downloads section, they are not included in the installation package.

Example 1 - Simple example

Filename: examples/pyevolve_ex1_simple.py

This is the Example #1, it is a very simple example:

from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Statistics
from pyevolve import DBAdapters

# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(genome):
   score = 0.0

   # iterate over the chromosome
   # The same as "score = len(filter(lambda x: x==0, genome))"
   for value in genome:
      if value==0:
         score += 1
   
   return score

def run_main():
   # Genome instance, 1D List of 50 elements
   genome = G1DList.G1DList(50)

   # Sets the range max and min of the 1D List
   genome.setParams(rangemin=0, rangemax=10)

   # The evaluator function (evaluation function)
   genome.evaluator.set(eval_func)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)

   # Set the Roulette Wheel selector method, the number of generations and
   # the termination criteria
   ga.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 generations
   ga.evolve(freq_stats=20)

   # Best individual
   print ga.bestIndividual()

if __name__ == "__main__":
   run_main()

Example 2 - Real numbers, Gaussian Mutator

Filename: examples/pyevolve_ex2_realgauss.py

This example uses the Initializators.G1DListInitializatorReal() initializator and the Mutators.G1DListMutatorRealGaussian() mutator:

from pyevolve import GSimpleGA
from pyevolve import G1DList
from pyevolve import Selectors
from pyevolve import Initializators, Mutators

# Find negative element
def eval_func(genome):
   score = 0.0

   for element in genome:
      if element < 0: score += 0.1

   return score

def run_main():
   # Genome instance
   genome = G1DList.G1DList(20)
   genome.setParams(rangemin=-6.0, rangemax=6.0)

   # Change the initializator to Real values
   genome.initializator.set(Initializators.G1DListInitializatorReal)

   # Change the mutator to Gaussian Mutator
   genome.mutator.set(Mutators.G1DListMutatorRealGaussian)

   # The evaluator function (objective function)
   genome.evaluator.set(eval_func)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   ga.selector.set(Selectors.GRouletteWheel)
   ga.setGenerations(100)

   # Do the evolution
   ga.evolve(freq_stats=10)

   # Best individual
   print ga.bestIndividual()

if __name__ == "__main__":
   run_main()

Example 3 - Schaffer F6 deceptive function

Filename: examples/pyevolve_ex3_schaffer.py

This examples tries to minimize the Schaffer F6 function, this function is a deceptive function, considered a GA-hard function to optimize:

from pyevolve import G1DList, GSimpleGA, Selectors
from pyevolve import Initializators, Mutators, Consts
import math

# This is the Schaffer F6 Function
# This function has been conceived by Schaffer, it's a 
# multimodal function and it's hard for GAs due to the
# large number of local minima, the global minimum is
# at x=0,y=0 and there are many local minima around it
def schafferF6(genome):
   t1 = math.sin(math.sqrt(genome[0]**2 + genome[1]**2));
   t2 = 1.0 + 0.001*(genome[0]**2 + genome[1]**2);
   score = 0.5 + (t1*t1 - 0.5)/(t2*t2)
   return score

def run_main():
   # Genome instance
   genome = G1DList.G1DList(2)
   genome.setParams(rangemin=-100.0, rangemax=100.0, bestrawscore=0.0000, rounddecimal=4)
   genome.initializator.set(Initializators.G1DListInitializatorReal)
   genome.mutator.set(Mutators.G1DListMutatorRealGaussian)

   # The evaluator function (objective function)
   genome.evaluator.set(schafferF6)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   ga.selector.set(Selectors.GRouletteWheel)

   ga.setMinimax(Consts.minimaxType["minimize"])
   ga.setGenerations(8000)
   ga.setMutationRate(0.05)
   ga.setPopulationSize(100)
   ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)

   # Do the evolution, with stats dump
   # frequency of 10 generations
   ga.evolve(freq_stats=250)

   # Best individual
   best = ga.bestIndividual()
   print best
   print "Best individual score: %.2f" % best.getRawScore()

if __name__ == "__main__":
   run_main()

Example 4 - Using Sigma truncation scaling

Filename: examples/pyevolve_ex4_sigmatrunc.py

This example shows the use of the sigma truncation scale method, it tries to minimize a function with negative results:

from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Initializators, Mutators
from pyevolve import Scaling
from pyevolve import Consts
import math

def eval_func(ind):
   score = 0.0
   var_x = ind[0]
   var_z = var_x**2+2*var_x+1*math.cos(var_x)
   return var_z

def run_main():
   # Genome instance
   genome = G1DList.G1DList(1)
   genome.setParams(rangemin=-60.0, rangemax=60.0)

   # Change the initializator to Real values
   genome.initializator.set(Initializators.G1DListInitializatorReal)

   # Change the mutator to Gaussian Mutator
   genome.mutator.set(Mutators.G1DListMutatorRealGaussian)

   # Removes the default crossover
   genome.crossover.clear()

   # The evaluator function (objective function)
   genome.evaluator.set(eval_func)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   ga.setMinimax(Consts.minimaxType["minimize"])

   pop = ga.getPopulation()
   pop.scaleMethod.set(Scaling.SigmaTruncScaling)

   ga.selector.set(Selectors.GRouletteWheel)
   ga.setGenerations(100)

   # Do the evolution
   ga.evolve(10)

   # Best individual
   print ga.bestIndividual()

if __name__ == "__main__":
   run_main()

Example 5 - Step callback function

Filename: examples/pyevolve_ex5_callback.py

This example shows the use of the step callback function:

from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors

# The step callback function, this function
# will be called every step (generation) of the GA evolution
def evolve_callback(ga_engine):
   generation = ga_engine.getCurrentGeneration()
   if generation % 100 == 0:
      print "Current generation: %d" % (generation,)
      print ga_engine.getStatistics()
   return False

# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(genome):
   score = 0.0
   # iterate over the chromosome
   for value in genome:
      if value==0: score += 0.1
   return score

def run_main():
   # Genome instance
   genome = G1DList.G1DList(200)
   genome.setParams(rangemin=0, rangemax=10)

   # The evaluator function (objective function)
   genome.evaluator.set(eval_func)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   ga.selector.set(Selectors.GRouletteWheel)
   ga.setGenerations(800)
   ga.stepCallback.set(evolve_callback)

   # Do the evolution
   ga.evolve()

   # Best individual
   print ga.bestIndividual()

if __name__ == "__main__":
   run_main()

Example 6 - The DB Adapters

Filename: examples/pyevolve_ex6_dbadapter.py

This example show the use of the DB Adapters (DBAdapters) :

from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import DBAdapters
from pyevolve import Statistics

# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
   score = 0.0

   # iterate over the chromosome
   for value in chromosome:
      if value==0:
         score += 0.5
   return score

# Genome instance
genome = G1DList.G1DList(100)
genome.setParams(rangemin=0, rangemax=10)

# The evaluator function (objective function)
genome.evaluator.set(eval_func)

# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome, 666)
ga.setGenerations(80)
ga.setMutationRate(0.2)

# Create DB Adapter and set as adapter
#sqlite_adapter = DBAdapters.DBSQLite(identify="ex6", resetDB=True)
#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 generations
ga.evolve(freq_stats=10)

# Best individual
#print ga.bestIndividual()

Example 7 - The Rastrigin function

Filename: examples/pyevolve_ex7_rastrigin.py

This example minimizes the deceptive function Rastrigin with 20 variables:

from pyevolve import GSimpleGA
from pyevolve import G1DList
from pyevolve import Mutators, Initializators
from pyevolve import Selectors
from pyevolve import Consts
import math

# This is the Rastrigin Function, a deception function
def rastrigin(genome):
   n = len(genome)
   total = 0
   for i in xrange(n):
      total += genome[i]**2 - 10*math.cos(2*math.pi*genome[i])
   return (10*n) + total

def run_main():
   # Genome instance
   genome = G1DList.G1DList(20)
   genome.setParams(rangemin=-5.2, rangemax=5.30, bestrawscore=0.00, rounddecimal=2)
   genome.initializator.set(Initializators.G1DListInitializatorReal)
   genome.mutator.set(Mutators.G1DListMutatorRealGaussian)

   genome.evaluator.set(rastrigin)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)
   ga.setMinimax(Consts.minimaxType["minimize"])
   ga.setGenerations(3000)
   ga.setCrossoverRate(0.8)
   ga.setPopulationSize(100)
   ga.setMutationRate(0.06)

   ga.evolve(freq_stats=50)

   best = ga.bestIndividual()
   print best

if __name__ == "__main__":
   run_main()

Example 8 - The Gaussian Integer Mutator

Filename: examples/pyevolve_ex8_gauss_int.py

This example shows the use of the Gaussian Integer Mutator (Mutators.G1DListMutatorIntegerGaussian):

from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Mutators

# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
   score = 0.0

   # iterate over the chromosome
   for value in chromosome:
      if value==0:
         score += 0.1
   return score


def run_main():
   # Genome instance
   genome = 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 defaults
   genome.setParams(rangemin=0, rangemax=10, gauss_mu=4, gauss_sigma=6)
   genome.mutator.set(Mutators.G1DListMutatorIntegerGaussian)

   # The evaluator function (objective function)
   genome.evaluator.set(eval_func)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   #ga.selector.set(Selectors.GRouletteWheel)
   ga.setGenerations(800)

   # Do the evolution, with stats dump
   # frequency of 10 generations
   ga.evolve(freq_stats=150)

   # Best individual
   print ga.bestIndividual()


if __name__ == "__main__":
   run_main()

Example 9 - The 2D List genome

Filename: examples/pyevolve_ex9_g2dlist.py

This example shows the use of the 2d list genome (G2DList.G2DList):

from pyevolve import G2DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Crossovers
from pyevolve import Mutators

# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
   score = 0.0

   # iterate over the chromosome
   for i in xrange(chromosome.getHeight()):
      for j in xrange(chromosome.getWidth()):
         # You can use the chromosome.getItem(i, j) too
         if chromosome[i][j]==0:
            score += 0.1
   return score

def run_main():
   # Genome instance
   genome = G2DList.G2DList(8, 5)
   genome.setParams(rangemin=0, rangemax=100)

   # The evaluator function (objective function)
   genome.evaluator.set(eval_func)
   genome.crossover.set(Crossovers.G2DListCrossoverSingleHPoint)
   genome.mutator.set(Mutators.G2DListMutatorIntegerRange)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   ga.setGenerations(800)

   # Do the evolution, with stats dump
   # frequency of 10 generations
   ga.evolve(freq_stats=100)

   # Best individual
   print ga.bestIndividual()


if __name__ == "__main__":
   run_main()

Example 10 - The 1D Binary String

Filename: examples/pyevolve_ex10_g1dbinstr.py

This example shows the use of the 1D Binary String genome:

from pyevolve import G1DBinaryString
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Mutators

# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
   score = 0.0

   # iterate over the chromosome
   for value in chromosome:
      if value == 0:
         score += 0.1
      
   return score

def run_main():
   # Genome instance
   genome = G1DBinaryString.G1DBinaryString(50)

   # The evaluator function (objective function)
   genome.evaluator.set(eval_func)
   genome.mutator.set(Mutators.G1DBinaryStringMutatorFlip)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   ga.selector.set(Selectors.GTournamentSelector)
   ga.setGenerations(70)

   # Do the evolution, with stats dump
   # frequency of 10 generations
   ga.evolve(freq_stats=20)

   # Best individual
   print ga.bestIndividual()

if __name__ == "__main__":
   run_main()
   

Example 11 - The use of alleles

Filename: examples/pyevolve_ex11_allele.py

This example shows the use of alleles:

from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Mutators
from pyevolve import Initializators
from pyevolve import GAllele

# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
   score = 0.0

   # iterate over the chromosome
   for value in chromosome:
      if value == 0:
         score += 0.5

   # Remember from the allele set defined above
   # this value 'a' is possible at this position
   if chromosome[18] == 'a':
      score += 1.0

   # Remember from the allele set defined above
   # this value 'xxx' is possible at this position
   if chromosome[12] == 'xxx':
      score += 1.0

   return score

def run_main():
   # Genome instance
   setOfAlleles = GAllele.GAlleles()

   # From 0 to 10 we can have only some
   # defined ranges of integers
   for i in xrange(11):
      a = GAllele.GAlleleRange(0, i)
      setOfAlleles.add(a)

   # From 11 to 19 we can have a set
   # of elements
   for i in xrange(11, 20):
      # You can even add objects instead of strings or 
      # primitive values
      a = 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)

   # This mutator and initializator will take care of
   # initializing valid individuals based on the allele set
   # that we have defined before
   genome.mutator.set(Mutators.G1DListMutatorAllele)
   genome.initializator.set(Initializators.G1DListInitializatorAllele)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   ga.setGenerations(40)

   # Do the evolution, with stats dump
   # frequency of 10 generations
   ga.evolve(freq_stats=5)

   # Best individual
   print ga.bestIndividual()


if __name__ == "__main__":
   run_main()

Example 12 - The Travelling Salesman Problem (TSP)

Filename: examples/pyevolve_ex12_tsp.py

This example shows the use of Pyevolve to solve the TSP:

from pyevolve import G1DList, GAllele
from pyevolve import GSimpleGA
from pyevolve import Mutators
from pyevolve import Crossovers
from pyevolve import Consts

import sys, random
random.seed(1024)
from math import sqrt

PIL_SUPPORT = None

try:
   from PIL import Image, ImageDraw, ImageFont
   PIL_SUPPORT = True
except:
   PIL_SUPPORT = False


cm     = []
coords = []
CITIES = 100
WIDTH   = 1024
HEIGHT  = 768
LAST_SCORE = -1

def cartesian_matrix(coords):
   """ A distance matrix """
   matrix={}
   for i,(x1,y1) in enumerate(coords):
      for j,(x2,y2) in enumerate(coords):
         dx, dy = x1-x2, y1-y2
         dist=sqrt(dx*dx + dy*dy)
         matrix[i,j] = dist
   return matrix

def tour_length(matrix, tour):
   """ Returns the total length of the tour """
   total = 0
   t = tour.getInternalList()
   for i in range(CITIES):
      j      = (i+1)%CITIES
      total += matrix[t[i], t[j]]
   return total

def write_tour_to_img(coords, tour, img_file):
   """ The function to plot the graph """
   padding=20
   coords=[(x+padding,y+padding) for (x,y) in coords]
   maxx,maxy=0,0
   for x,y in coords:
      maxx, maxy = max(x,maxx), max(y,maxy)
   maxx+=padding
   maxy+=padding
   img=Image.new("RGB",(int(maxx),int(maxy)),color=(255,255,255))
   font=ImageFont.load_default()
   d=ImageDraw.Draw(img);
   num_cities=len(tour)
   for i in range(num_cities):
      j=(i+1)%num_cities
      city_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))

   for x,y in coords:
      x,y=int(x),int(y)
      d.ellipse((x-5,y-5,x+5,y+5),outline=(0,0,0),fill=(196,196,196))
   del d
   img.save(img_file, "PNG")
   print "The plot was saved into the %s file." % (img_file,)

def G1DListTSPInitializator(genome, **args):
   """ The initializator for the TSP """
   lst = [i for i in xrange(genome.getListSize())]
   random.shuffle(lst)
   genome.setInternalList(lst)

# 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):
   global LAST_SCORE
   if ga_engine.getCurrentGeneration() % 100 == 0:
      best = ga_engine.bestIndividual()
      if LAST_SCORE != best.getRawScore():
         write_tour_to_img( coords, best, "tspimg/tsp_result_%d.png" % ga_engine.getCurrentGeneration())
         LAST_SCORE = best.getRawScore()
   return False

def main_run():
   global cm, coords, WIDTH, HEIGHT

   coords = [(random.randint(0, WIDTH), random.randint(0, HEIGHT))
                 for i in xrange(CITIES)]
   cm     = cartesian_matrix(coords)
   genome = G1DList.G1DList(len(coords))

   genome.evaluator.set(lambda chromosome: tour_length(cm, chromosome))
   genome.crossover.set(Crossovers.G1DListCrossoverEdge)
   genome.initializator.set(G1DListTSPInitializator)

   # 3662.69
   ga = GSimpleGA.GSimpleGA(genome)
   ga.setGenerations(200000)
   ga.setMinimax(Consts.minimaxType["minimize"])
   ga.setCrossoverRate(1.0)
   ga.setMutationRate(0.02)
   ga.setPopulationSize(80)

   # This is to make a video
   ga.stepCallback.set(evolve_callback)
   # 21666.49
   import psyco
   psyco.full()

   ga.evolve(freq_stats=500)
   best = ga.bestIndividual()

   if PIL_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:

_images/ex_12_tsp_result.png

To plot this image, you will need the Python Imaging Library (PIL).

See also

Python Imaging Library (PIL)
The Python Imaging Library (PIL) adds image processing capabilities to your Python interpreter. This library supports many file formats, and provides powerful image processing and graphics capabilities.

Example 13 - The sphere function

Filename: examples/pyevolve_ex13_sphere.py

This is the GA to solve the sphere function:

from pyevolve import G1DList
from pyevolve import Mutators, Initializators
from pyevolve import GSimpleGA, Consts

# This is the Sphere Function
def sphere(xlist):
   total = 0
   for i in xlist:
      total += i**2
   return total

def run_main():
   genome = G1DList.G1DList(140)
   genome.setParams(rangemin=-5.12, rangemax=5.13)
   genome.initializator.set(Initializators.G1DListInitializatorReal)
   genome.mutator.set(Mutators.G1DListMutatorRealGaussian)
   genome.evaluator.set(sphere)

   ga = GSimpleGA.GSimpleGA(genome, seed=666)
   ga.setMinimax(Consts.minimaxType["minimize"])
   ga.setGenerations(1500)
   ga.setMutationRate(0.01)
   ga.evolve(freq_stats=500)

   best = ga.bestIndividual()

if __name__ == "__main__":
   run_main()
   

Example 14 - The Ackley function

Filename: examples/pyevolve_ex14_ackley.py

This example minimizes the Ackley F1 function, a deceptive function:

from pyevolve import G1DList, GSimpleGA, Selectors
from pyevolve import Initializators, Mutators, Consts, DBAdapters
import math

# This is the Rastringin Function, a deception function
def ackley(xlist):
   sum1 = 0
   score = 0
   n = len(xlist)
   for i in xrange(n):
      sum1 += xlist[i]*xlist[i]
   t1 = math.exp(-0.2*(math.sqrt((1.0/5.0)*sum1)))

   sum1 = 0
   for i in xrange(n):
      sum1 += math.cos(2.0*math.pi*xlist[i]);
   t2 = math.exp((1.0/5.0)*sum1);
   score = 20 + math.exp(1) - 20 * t1 - t2;

   return score


def run_main():
   # Genome instance
   genome = G1DList.G1DList(5)
   genome.setParams(rangemin=-8, rangemax=8,  bestrawscore=0.00, rounddecimal=2)
   genome.initializator.set(Initializators.G1DListInitializatorReal)
   genome.mutator.set(Mutators.G1DListMutatorRealGaussian)

   # The evaluator function (objective function)
   genome.evaluator.set(ackley)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   ga.setMinimax(Consts.minimaxType["minimize"])
   ga.setGenerations(1000)
   ga.setMutationRate(0.04)
   ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)

   # Create DB Adapter and set as adapter
   # sqlite_adapter = DBAdapters.DBSQLite(identify="ackley")
   # ga.setDBAdapter(sqlite_adapter)

   # Do the evolution, with stats dump
   # frequency of 10 generations
   ga.evolve(freq_stats=50)

   # Best individual
   best = ga.bestIndividual()
   print "\nBest individual score: %.2f" % (best.getRawScore(),)
   print best

if __name__ == "__main__":
   run_main()

Example 15 - The Rosenbrock function

Filename: examples/pyevolve_ex15_rosenbrock.py

This example minimizes the Rosenbrock function, another deceptive function:

from pyevolve import G1DList, GSimpleGA, Selectors, Statistics
from pyevolve import Initializators, Mutators, Consts, DBAdapters

# This is the Rosenbrock Function
def rosenbrock(xlist):
   sum_var = 0
   for x in xrange(1, len(xlist)):
      sum_var += 100.0 * (xlist[x] - xlist[x-1]**2)**2 + (1 - xlist[x-1])**2
   return sum_var

def run_main():
   # Genome instance
   genome = G1DList.G1DList(15)
   genome.setParams(rangemin=-1, rangemax=1.1)
   genome.initializator.set(Initializators.G1DListInitializatorReal)
   genome.mutator.set(Mutators.G1DListMutatorRealRange)

   # The evaluator function (objective function)
   genome.evaluator.set(rosenbrock)

   # Genetic Algorithm Instance
   ga = GSimpleGA.GSimpleGA(genome)
   ga.setMinimax(Consts.minimaxType["minimize"])
   ga.selector.set(Selectors.GRouletteWheel)
   ga.setGenerations(4000)
   ga.setCrossoverRate(0.9)
   ga.setPopulationSize(100)
   ga.setMutationRate(0.03)

   ga.evolve(freq_stats=500)

   # Best individual
   best = ga.bestIndividual()
   print "\nBest individual score: %.2f" % (best.score,)
   print best


if __name__ == "__main__":
    run_main()

Example 16 - The 2D Binary String

Filename: examples/pyevolve_ex16_g2dbinstr.py

This example shows the use of the 2D Binary String genome:

from pyevolve import G2DBinaryString
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Crossovers
from pyevolve import Mutators

# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
   score = 0.0

   # iterate over the chromosome
   for i in xrange(chromosome.getHeight()):
      for j in xrange(chromosome.getWidth()):
         # You can use the chromosome.getItem(i, j)
         if chromosome[i][j]==0:
            score += 0.1
   return score

# Genome instance
genome = G2DBinaryString.G2DBinaryString(8, 5)

# The evaluator function (objective function)
genome.evaluator.set(eval_func)
genome.crossover.set(Crossovers.G2DBinaryStringXSingleHPoint)
genome.mutator.set(Mutators.G2DBinaryStringMutatorSwap)

# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.setGenerations(200)

# Do the evolution, with stats dump
# frequency of 10 generations
ga.evolve(freq_stats=10)

# Best individual
print ga.bestIndividual()

Example 17 - The Tree genome example

Filename: examples/pyevolve_ex17_gtree.py

This example shows the use of the Tree genome:

from pyevolve import GSimpleGA
from pyevolve import GTree
from pyevolve import Crossovers
from pyevolve import Mutators
import time
import random

def eval_func(chromosome):
   score = 0.0
   # If you want to add score values based
   # in the height of the Tree, the extra
   # code is commented.

   #height = chromosome.getHeight()

   for node in chromosome:
      score += (100 - node.getData())*0.1

   #if height <= chromosome.getParam("max_depth"):
   #   score += (score*0.8)

   return score

def run_main():
   genome = GTree.GTree()
   root = GTree.GTreeNode(2)
   genome.setRoot(root)
   genome.processNodes()

   genome.setParams(max_depth=3, max_siblings=2, method="grow")
   genome.evaluator.set(eval_func)
   genome.crossover.set(Crossovers.GTreeCrossoverSinglePointStrict)

   ga = GSimpleGA.GSimpleGA(genome)
   ga.setGenerations(100)
   ga.setMutationRate(0.05)
   
   ga.evolve(freq_stats=10)
   print ga.bestIndividual()

if __name__ == "__main__":
   run_main()

  

Example 18 - The Genetic Programming example

Filename: examples/pyevolve_ex18_gp.py

This example shows the use of the GTreeGP genome (for Genetic Programming):

from pyevolve import Util
from pyevolve import GTree
from pyevolve import GSimpleGA
from pyevolve import Consts
import math

rmse_accum = Util.ErrorAccumulator()

def gp_add(a, b): return a+b
def gp_sub(a, b): return a-b
def gp_mul(a, b): return a*b
def gp_sqrt(a):   return math.sqrt(abs(a))
   
def eval_func(chromosome):
   global rmse_accum
   rmse_accum.reset()
   code_comp = chromosome.getCompiledCode()
   
   for a in xrange(0, 5):
      for b in xrange(0, 5):
         evaluated     = eval(code_comp)
         target        = math.sqrt((a*a)+(b*b))
         rmse_accum   += (target, evaluated)

   return rmse_accum.getRMSE()

def main_run():
   genome = GTree.GTreeGP()
   genome.setParams(max_depth=4, method="ramped")
   genome.evaluator += eval_func

   ga = GSimpleGA.GSimpleGA(genome)
   ga.setParams(gp_terminals       = ['a', 'b'],
                gp_function_prefix = "gp")

   ga.setMinimax(Consts.minimaxType["minimize"])
   ga.setGenerations(50)
   ga.setCrossoverRate(1.0)
   ga.setMutationRate(0.25)
   ga.setPopulationSize(800)
   
   ga(freq_stats=10)
   best = ga.bestIndividual()
   print best

if __name__ == "__main__":
   main_run()

Example 21 - The n-queens problem (64x64 chess board)

Filename: examples/pyevolve_ex21_nqueens.py

This example shows the use of GA to solve the n-queens problem for a chess board of size 64x64:

from pyevolve import G1DList
from pyevolve import Mutators, Crossovers
from pyevolve import Consts, GSimpleGA
from pyevolve import DBAdapters
from random import shuffle

# The "n" in n-queens
BOARD_SIZE = 64

# The n-queens fitness function
def queens_eval(genome):
   collisions = 0
   for i in xrange(0, BOARD_SIZE):
      if i not in genome: return 0
   for i in xrange(0, BOARD_SIZE):
      col = False
      for j in xrange(0, BOARD_SIZE):
         if (i != j) and (abs(i-j) == abs(genome[j]-genome[i])):
            col = True
      if col == True: collisions +=1
   return BOARD_SIZE-collisions

def queens_init(genome, **args):
   genome.genomeList = range(0, BOARD_SIZE)
   shuffle(genome.genomeList)

def run_main():
   genome = G1DList.G1DList(BOARD_SIZE)
   genome.setParams(bestrawscore=BOARD_SIZE, rounddecimal=2)
   genome.initializator.set(queens_init)
   genome.mutator.set(Mutators.G1DListMutatorSwap)
   genome.crossover.set(Crossovers.G1DListCrossoverCutCrossfill)
   genome.evaluator.set(queens_eval)

   ga = GSimpleGA.GSimpleGA(genome)
   ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)
   ga.setMinimax(Consts.minimaxType["maximize"])
   
   ga.setPopulationSize(100)
   ga.setGenerations(250)
   ga.setMutationRate(0.02)
   ga.setCrossoverRate(1.0)

   #sqlite_adapter = DBAdapters.DBSQLite(identify="queens")
   #ga.setDBAdapter(sqlite_adapter)

   vpython_adapter = DBAdapters.DBVPythonGraph(identify="queens", frequency=1)
   ga.setDBAdapter(vpython_adapter)
   
   ga.evolve(freq_stats=10)

   best = ga.bestIndividual()
   print best
   print "Best individual score: %.2f\n" % (best.getRawScore(),)

if __name__ == "__main__":
   run_main()
  

Example 22 - The Infinite Monkey Theorem

Filename: examples/pyevolve_ex22_monkey.py

This example was a kindly contribution by Jelle Feringa, it shows the Infinite Monkey Theorem:

#===============================================================================
# Pyevolve version of the Infinite Monkey Theorem
# See: http://en.wikipedia.org/wiki/Infinite_monkey_theorem
# By Jelle Feringa
#===============================================================================

from pyevolve import G1DList
from pyevolve import GSimpleGA, Consts
from pyevolve import Selectors
from pyevolve import Initializators, Mutators, Crossovers
import math

sentence = """
'Just living is not enough,' said the butterfly,
'one must have sunshine, freedom, and a little flower.'
"""
numeric_sentence = map(ord, sentence)

def evolve_callback(ga_engine):
   generation = ga_engine.getCurrentGeneration()
   if generation%50==0:
      indiv = ga_engine.bestIndividual()
      print ''.join(map(chr,indiv))
   return False

def run_main():
   genome = G1DList.G1DList(len(sentence))
   genome.setParams(rangemin=min(numeric_sentence),
                    rangemax=max(numeric_sentence),
                    bestrawscore=0.00,
                    gauss_mu=1, gauss_sigma=4)

   genome.initializator.set(Initializators.G1DListInitializatorInteger)
   genome.mutator.set(Mutators.G1DListMutatorIntegerGaussian)
   genome.evaluator.set(lambda genome: sum(
                           [abs(a-b) for a, b in zip(genome, numeric_sentence)]
                        ))

   ga = GSimpleGA.GSimpleGA(genome)
   #ga.stepCallback.set(evolve_callback)
   ga.setMinimax(Consts.minimaxType["minimize"])
   ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)
   ga.setPopulationSize(60)
   ga.setMutationRate(0.02)
   ga.setCrossoverRate(0.9)
   ga.setGenerations(5000)
   ga.evolve(freq_stats=100)

   best = ga.bestIndividual()
   print "Best individual score: %.2f" % (best.score,)
   print ''.join(map(chr, best))

if __name__ == "__main__":
   run_main()