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
import pyevolve

# 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
   # score = len(filter(lambda x: x==0, chromosome.genomeList))
   for value in chromosome:
      if value==0:
         score += 1
   
   return score

# Enable the pyevolve logging system
pyevolve.logEnable()

# 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()

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 values
def eval_func(ind):
   score = 0.0
   for x in xrange(0,len(ind)):
      if ind[x] <= 0.0: score += 0.1
   return score

# 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.nGenerations = 100

# Do the evolution
ga.evolve(10)

# Best individual
print ga.bestIndividual()

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:

# $Id: pyevolve_ex3_schaffer.py 150 2009-01-18 19:29:13Z christian.perone $
from pyevolve import G1DList, GSimpleGA, Selectors
from pyevolve import Initializators, Mutators, Consts
import math

# This is the Schaffer F6 Function, a deceptive function
def schafferF6(xlist):
   t1 = math.sin(math.sqrt(xlist[0]*xlist[0] + xlist[1]*xlist[1]));
   t2 = 1 + 0.001*(xlist[0]*xlist[0] + xlist[1]*xlist[1]);
   score = 0.5 + (t1*t1 - 0.5)/(t2*t2)
   return score

# Genome instance
genome = G1DList.G1DList(2)
genome.setParams(rangemin=-100, rangemax=100, bestRawScore=0.00, roundDecimal=2)
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.minimax = Consts.minimaxType["minimize"]
ga.setGenerations(5000)
ga.setMutationRate(0.05)
ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)

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

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

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:

# $Id: pyevolve_ex4_sigmatrunc.py 150 2009-01-18 19:29:13Z christian.perone $
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

# 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()

Example 5 - Step callback function

Filename: examples/pyevolve_ex5_callback.py

This example shows the use of the step callback function:

# $Id: pyevolve_ex5_callback.py 151 2009-01-19 01:23:22Z christian.perone $
from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
import pyevolve

# 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(chromosome):
   score = 0.0

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

# Enable the logging system
pyevolve.logEnable()

# 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, with stats dump
# frequency of 10 generations
ga.evolve()

# Best individual
print ga.bestIndividual()

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)
ga.setGenerations(80)

# Create DB Adapter and set as adapter
sqlite_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 generations
ga.evolve(freq_stats=10)

# Best individual
print ga.bestIndividual()

Example 7 - The Rastringin function

Filename: examples/pyevolve_ex7_rastringin.py

This example minimizes the deceptive function Rastringin with 20 variables:

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

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

# Genome instance
genome = G1DList.G1DList(20)
genome.setParams(rangemin=-5.2, rangemax=5.30)
genome.initializator.set(Initializators.G1DListInitializatorReal)
genome.mutator.set(Mutators.G1DListMutatorRealGaussian)

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

# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.minimax = Consts.minimaxType["minimize"]
ga.setGenerations(800)
ga.setMutationRate(0.05)

# Create DB Adapter and set as adapter
#sqlite_adapter = DBAdapters.DBSQLite(identify="rastringin")
#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

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

import pyevolve
import logging

# 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

pyevolve.logEnable()

# 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=1, 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(1000)

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

# Best individual
print ga.bestIndividual()

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)
         if chromosome[i][j]==0:
            score += 0.1
   return score

# Genome instance
genome = 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 Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.selector.set(Selectors.GRouletteWheel)
ga.setGenerations(1200)

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

# Best individual
print ga.bestIndividual()

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

# Genome instance
genome = G1DBinaryString.G1DBinaryString(60)

# 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(100)

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

# Best individual
best = ga.bestIndividual()
print best

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 Selectors
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
   return score

# Genome instance
setOfAlleles = GAllele.GAlleles()
for i in xrange(11):
   a = GAllele.GAlleleRange(0, i)
   setOfAlleles.add(a)

for i in xrange(11, 20):
   # You can even add an object to the list
   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)
genome.mutator.set(Mutators.G1DListMutatorAllele)
genome.initializator.set(Initializators.G1DListInitializatorAllele)

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

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

# Best individual
print ga.bestIndividual()

Example 12 - The Travelling Salesman Problem (TSP)

Filename: examples/pyevolve_ex12_tsp.py

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

# 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_img

from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import GAllele
from pyevolve import Mutators
from pyevolve import Initializators
from pyevolve import DBAdapters
from pyevolve import Crossovers
from pyevolve import Consts
import sys, random
from math import sqrt

PIL_SUPPORT = None

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

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 read_coords(coord_file):
   """ Read the coords from file """
   coords=[]
   for line in coord_file:
      x,y=line.strip().split(",")
      coords.append((float(x),float(y)))
   return coords

def tour_length(matrix, tour):
   """ Returns the total length of the tour """
   total=0
   num_cities=len(tour)
   for i in range(num_cities):
      j=(i+1)%num_cities
      city_i=tour[i]
      city_j=tour[j]
      total+=matrix[city_i,city_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=max(x,maxx)
      maxy=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 """
   genome.clearList()
   lst = [i for i in xrange(genome.listSize)]

   for i in xrange(genome.listSize):
      choice = random.choice(lst)
      lst.remove(choice)
      genome.append(choice)

cm = []
coords = []

def eval_func(chromosome):
   """ The evaluation function """
   global cm
   return tour_length(cm, chromosome)

def write_random(filename, cities, xmax=800, ymax=600):
   """ Write random cities/positions to a text file """
   filehandle = open(filename, "w")
   for i in xrange(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 False

def main_run():
   global cm, coords

   # write_random(filename, number of the cities, max width, max_height)
   write_random("tsp_coords.txt", 30, 600, 400)

   # load the tsp data file
   filehandle = open("tsp_coords.txt", "rw")
   coords = read_coords(filehandle)
   cm = cartesian_matrix(coords)

   # set the alleles to the cities numbers
   setOfAlleles = GAllele.GAlleles(homogeneous=True)
   lst = [ i for i in xrange(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()
   print best

   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, GSimpleGA, Selectors
from pyevolve import Initializators, Mutators, Consts, DBAdapters
import math

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

# Genome instance
genome = G1DList.G1DList(50)
genome.setParams(rangemin=-5.12, rangemax=5.13)
genome.initializator.set(Initializators.G1DListInitializatorReal)
genome.mutator.set(Mutators.G1DListMutatorRealGaussian)

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

# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.minimax = Consts.minimaxType["minimize"]
ga.setGenerations(500)
ga.setMutationRate(0.02)

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

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

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

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 ackleyF1(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

# Genome instance
genome = G1DList.G1DList(5)
genome.setParams(rangemin=-8, rangemax=8)
genome.initializator.set(Initializators.G1DListInitializatorReal)
genome.mutator.set(Mutators.G1DListMutatorRealGaussian)

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

# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.minimax = Consts.minimaxType["minimize"]
ga.setGenerations(500)
ga.setMutationRate(0.03)

# 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

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, a deception function
def rosenbrock(xlist):
   sum1 = 0
   for x in xrange(1, len(xlist)):
      sum1 += 100.0 * (xlist[x] - xlist[x-1]**2)**2 + (1 - xlist[x-1])**2

   return sum1

# Genome instance
genome = G1DList.G1DList(20)
genome.setParams(rangemin=0, rangemax=10, bestRawScore=0.0)
genome.mutator.set(Mutators.G1DListMutatorIntegerRange)

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

# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.minimax = Consts.minimaxType["minimize"]
ga.setGenerations(4000)
ga.setMutationRate(0.2)
ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)

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

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

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