def advance_generation(self): self.mark_oldno() self.sort() self.update_no() for dude in self: k, l = self.imap[dude.oldno] self.map[k, l] = dude.no self.update_imap() Population.advance_generation(self)
def __init__(self,species,popsize,objfunc,paramspace): Population.__init__(self,species,popsize,objfunc,paramspace) self.sa_improverate=0. self.sa_toleraterate=0. self.ga_improverate=0. self.sa_bestcontributions=0 self.ga_bestcontributions=0 self.sa_beststeps=[] self.ga_beststeps=[]
def __init__(self, species, popsize, objfunc, paramspace): Population.__init__(self, species, popsize, objfunc, paramspace) self.sa_improverate = 0. self.sa_toleraterate = 0. self.ga_improverate = 0. self.sa_bestcontributions = 0 self.ga_bestcontributions = 0 self.sa_beststeps = [] self.ga_beststeps = []
def advance_generation(self): self.mark_oldno() self.sort() self.update_no() for dude in self: k,l=self.imap[dude.oldno] self.map[k,l]=dude.no self.update_imap() Population.advance_generation(self)
def __init__(self, species, popsize, objfunc, paramspace): Population.__init__(self, species, popsize, objfunc, paramspace) self.sa_improved = 0 self.sa_tolerated = 0 self.sa_events = 0 self.sa_improverate = 0.0 self.sa_toleraterate = 0.0 self.ga_improved = 0 self.ga_events = 0 self.ga_improverate = 0.0
def __init__(self, species, popsize, objfunc, paramspace): Population.__init__(self, species, popsize, objfunc, paramspace) self.sa_improved = 0 self.sa_tolerated = 0 self.sa_events = 0 self.sa_improverate = 0. self.sa_toleraterate = 0. self.ga_improved = 0 self.ga_events = 0 self.ga_improverate = 0.
def __init__(self,species,popsize,objfunc,paramspace,toposhape,nh_degree): Population.__init__(self,species,popsize,objfunc,paramspace) PSO_Topo_standard2D.__init__(self,toposhape,nh_degree) if not self.is_of_size(self.psize): raise ValueError("The topology shape does not fit the population size.") self.alpha=0.7298 self.psi=2.9922 self.attractor_boost=1.0 for dude in self: dude.swarm=self # making individuals conscious of the general population
def __init__(self, species, popsize, objfunc, paramspace, toposhape, nh_degree): Population.__init__(self, species, popsize, objfunc, paramspace) PSO_Topo_standard2D.__init__(self, toposhape, nh_degree) if not self.is_of_size(self.psize): raise ValueError( "The topology shape does not fit the population size.") self.alpha = 0.7298 self.psi = 2.9922 self.attractor_boost = 1.0 for dude in self: dude.swarm = self # making individuals conscious of the general population
return x*x searchspace=(('p1',0.,360.), ('p2',0.,360.), ('p3',0.,360.), ('p4',0.,360.), ('p5',0.,360.), ('p6',0.,360.), ('p7',0.,360.), ('p8',0.,360.)) mu=1 # size of parent population of (mu,lambda)-ES la=5 # size of offspring population of (mu,lambda)-ES G=160 # number of generations dim=len(searchspace) parents=Population(necklace,mu,dummyfunc,searchspace) offspring=Population(necklace,la,dummyfunc,searchspace) plotpath=join(getcwd(),'plots') #------------------------------------------------------------------------------- #--- part 2: random starting point for search ---------------------------------- #--- and more initialisation --------------------------------------------------- #------------------------------------------------------------------------------- npr.seed(11) # seeding numpy's random number generator so we get reproducibly the same random numbers startpoint=360*npr.rand(dim) # point in search space where initial population is placed parents.set_every_DNA(startpoint) parents.eval_all() print 'fitness of initial population: ' print [dude.score for dude in parents]
searchspace2=(('p1',-20.,+40.), ('p2',-20.,+20.)) searchspace3=(('p1',-20.,+40.), ('p2',-20.,+20.), ('p3',-20.,+20.)) searchspace5=(('p1',-20.,+40.), ('p2',-20.,+20.), ('p3',-20.,+20.), ('p4',-20.,+20.), ('p5',-20.,+20.)) N=10 p2a=Population(Individual,N,parabolic,searchspace2) p3a=Population(Individual,N,parabolic,searchspace3) p5a=Population(Individual,N,parabolic,searchspace5) P=p2a+p3a+p5a npr.seed(1) x0,y0=-12,5 for dude in P: dude.DNA[:2]=x0,y0 #p5a.print_stuff() startDNA2=p2a[0].get_copy_of_DNA() startDNA3=p3a[0].get_copy_of_DNA() startDNA5=p5a[0].get_copy_of_DNA() # now mutate by adding a vector of well-defined length D=4 into a random direction D=0.3 #*40 # multiplication with 40 for getting a similar result with uCS=False nn=5000
join(self.plotpath, 'FMsynth_solution_' + runlabel + '.png')) plt.close() def set_bad_score(self): self.score = 9999. # search space boundaries: searchspace = (('amp 1', -6.4, +6.35), ('omega 1', -6.4, +6.35), ('amp 2', -6.4, +6.35), ('omega 2', -6.4, +6.35), ('amp 3', -6.4, +6.35), ('omega 3', -6.4, +6.35)) dim = len(searchspace) # search space dimension ps = 80 p = Population(FMsynthC, ps, dummyfunc, searchspace) rec = Recorder(p) ea = CMAES(p, 40, rec) # instanciate the algorithm from library ea.maxeval = 1e6 def gcb(eaobj): if eaobj.F0.gg % 10 == 0: # every 10th generation b = eaobj.F0[0] b.plot_FMsynth_solution() print 'gcb: generation: {} score: {} DNA: {}'.format( eaobj.F0.gg, b.score, b.DNA) rec.save_status() ea.generation_callbacks.append(gcb)
from peabox_recorder import Recorder from peabox_plotting import ancestryplot #------------------------------------------------------------------------------- #--- part 1: Ingredients ------------------------------------------------------- #------------------------------------------------------------------------------- dim=10 f11=tfp(11,dim) # Weierstrass function in 10 dimensions searchspace=simple_searchspace(10,-3.,1.) ps=40 # population size G=40 # number of generations to go through parents=Population(Individual,ps,f11,searchspace); parents.objname='CEC05 f11' offspring=Population(Individual,ps,f11,searchspace); offspring.objname='CEC05 f11' rec=Recorder(parents) # creating this Recorder instance to collect survey data on parent population #------------------------------------------------------------------------------- #--- part 2: initialisation ---------------------------------------------------- #------------------------------------------------------------------------------- seed(1) # seeding numpy's random number generator so we get reproducibly the same random numbers parents.new_random_genes() parents.eval_all() parents.sort() parents.update_no() rec.save_status()
def parabolic(x): return np.sum(x*x) searchspace=(('p1',-1.,+1.), ('p2',-1.,+1.), ('p3',-1.,+1.), ('p4',-1.,+1.), ('p5',-1.,+1.), ('p6',-1.,+1.), ('p7',-1.,+1.), ('p8',-1.,+1.)) mu=4 # size of parent population of (mu,lambda)-ES la=12 # size of offspring population of (mu,lambda)-ES dim=len(searchspace) parents=Population(Individual,mu,parabolic,searchspace) offspring=Population(Individual,la,parabolic,searchspace) #------------------------------------------------------------------------------- #--- part 2: random starting point for search ---------------------------------- #--- and more initialisation --------------------------------------------------- #------------------------------------------------------------------------------- npr.seed(1) # seeding numpy's random number generator so we get reproducibly the same random numbers startpoint=2*npr.rand(dim)-1 # point in search space where initial population is placed parents.set_every_DNA(startpoint) parents.eval_all() print 'fitness of initial population: ' print [dude.score for dude in parents] print 'or also via get_scores():'
self.score = 100000. def dummyfunc(x): return x * x searchspace = (('p1', 0., 360.), ('p2', 0., 360.), ('p3', 0., 360.), ('p4', 0., 360.), ('p5', 0., 360.), ('p6', 0., 360.), ('p7', 0., 360.), ('p8', 0., 360.)) mu = 1 # size of parent population of (mu,lambda)-ES la = 5 # size of offspring population of (mu,lambda)-ES G = 160 # number of generations dim = len(searchspace) parents = Population(necklace, mu, dummyfunc, searchspace) offspring = Population(necklace, la, dummyfunc, searchspace) plotpath = join(getcwd(), 'plots') #------------------------------------------------------------------------------- #--- part 2: random starting point for search ---------------------------------- #--- and more initialisation --------------------------------------------------- #------------------------------------------------------------------------------- npr.seed( 11 ) # seeding numpy's random number generator so we get reproducibly the same random numbers startpoint = 360 * npr.rand( dim) # point in search space where initial population is placed parents.set_every_DNA(startpoint) parents.eval_all()
import numpy.random as npr #from numpy import array, arange, asfarray, pi, cos, zeros, where, linspace #import matplotlib as mpl #import matplotlib.pyplot as plt from peabox_individual import Individual from peabox_population import Population def parabolic(x): return np.sum(x*x) searchspace=(('length',12.,14.), ('wall_thickness',0.1,1.4), ('radius',20.,40.)) N=5 p=Population(Individual,N,parabolic,searchspace) npr.seed(3) p.new_random_genes() p.eval_all() for dude in p: dude.score=np.round(dude.score,2) sc=p.get_scores() print "the population's scores: ",sc # should give the list [ 1.22 1.32 0.53 0.17 1.81] dude0,dude1,dude2,dude3,dude4=p print 'dude0<dude1 yields ',dude0<dude1,' and dude0.isbetter(dude1) yields ',dude0.isbetter(dude1) print 'dude0<dude2 yields ',dude0<dude2,' and dude0.isbetter(dude2) yields ',dude0.isbetter(dude2) print 'p.whatisfit and dude0.whatisfit are: ',p.whatisfit,dude0.whatisfit p.determine_whatisfit('max') print "now how does it look like after the spell 'p.determine_whatisfit('max')'?"
parentb=np.sum(where(self.thresh<r2,1,0)) return parenta,parentb searchspace=(('p1',-5.,+5.), ('p2',-5.,+5.), ('p3',-5.,+5.), ('p4',-5.,+5.), ('p5',-5.,+5.), ('p6',-5.,+5.), ('p7',-5.,+5.), ('p8',-5.,+5.)) ps=40 # population size G=41 # number of generations to go through dim=len(searchspace) parents=Population(Individual,ps,rastrigin,searchspace) offspring=Population(Individual,ps,rastrigin,searchspace) rw=RouletteWheel(dim) #------------------------------------------------------------------------------- #--- part 2: random starting point for search ---------------------------------- #--- and more initialisation --------------------------------------------------- #------------------------------------------------------------------------------- npr.seed(3) # seed differently or comment out if you want to see an algorithm's average performance over several runs parents.new_random_genes() parents.eval_all() parents.sort() print 'initial population:\nbest score = ',parents[0].score
the wave functions are calculated as it doesn't rely on the formula, but refers directly to the results stored in self.target and self.trial. """ # search space boundaries: searchspace=(('amp 1', -6.4, +6.35), ('omega 1', -6.4, +6.35), ('amp 2', -6.4, +6.35), ('omega 2', -6.4, +6.35), ('amp 3', -6.4, +6.35), ('omega 3', -6.4, +6.35)) ps=4 # population size dim=len(searchspace) # search space dimension pC=Population(FMsynthC,ps,dummyfunc,searchspace) pC.set_ncase(1) pC.new_random_genes() pC.eval_all() print 'DNAs of pC:' print pC.get_DNAs() pC.print_stuff(slim=True) for dude in pC: dude.plot_FMsynth_solution() # and the modified version pD=Population(FMsynthC,ps,dummyfunc,searchspace) pD.set_ncase(2) for dude in pD: dude.w[1]=4.7
from peabox_testfuncs import CEC05_test_function_producer as tfp from peabox_helpers import parentselect_exp as pse from peabox_helpers import simple_searchspace #------------------------------------------------------------------------------- #--- part 1: Ingredients ------------------------------------------------------- #------------------------------------------------------------------------------- dim=10 f11=tfp(11,dim) # Weierstrass function in 10 dimensions searchspace=simple_searchspace(10,-3.,1.) ps=40 # population size G=80 # number of generations to go through parents=Population(Individual,ps,f11,searchspace) offspring=Population(Individual,ps,f11,searchspace) #------------------------------------------------------------------------------- #--- part 2: initialisation ---------------------------------------------------- #------------------------------------------------------------------------------- seed(1) # seeding numpy's random number generator so we get reproducibly the same random numbers parents.new_random_genes() parents.eval_all() parents.sort() parents.update_no() sa_T=parents[-1].score-parents[0].score # starting temperature saga_ratio=0.5 # fraction of offspring created by SA and not GA sa_mstep=0.02 # mutation step size parameter sa_mprob=0.6 # mutation probability
self.fmwave( [DNA[0],DNA[2],DNA[4]] , [DNA[1],DNA[3],DNA[5]] ) return np.sum((self.trial-self.target)**2) # search space boundaries: searchspace=(('amp 1', -6.4, +6.35), ('omega 1', -6.4, +6.35), ('amp 2', -6.4, +6.35), ('omega 2', -6.4, +6.35), ('amp 3', -6.4, +6.35), ('omega 3', -6.4, +6.35)) ps=4 # population size dim=len(searchspace) # search space dimension # now let's create a population to test version A of the objective function implementation pA=Population(Individual,ps,FMsynthA,searchspace) pA.new_random_genes() pA.eval_all() print 'DNAs of pA:' print pA.get_DNAs() pA.print_stuff(slim=True) # and here the objective function version B and another population to test it problem_instance=FMsynthB() objfuncB=problem_instance.call pB=Population(Individual,ps,objfuncB,searchspace) pB.copy_otherpop(pA) pB.eval_all() print 'DNAs of pB:' print pB.get_DNAs() pB.print_stuff(slim=True)
from tkframe import TKEA_win import matplotlib.pyplot as plt #plt.ion() def dummyfunc(x): return np.sum(x) ndim=8 ps=80 problem = 'gf_kragtraeger' EA_type = 'CMAES' if problem == 'FMsynth': space=simple_searchspace(ndim, -6.4, +6.35) p0=Population(FMsynth,ps,dummyfunc,space) p1=Population(FMsynth,ps,dummyfunc,space) rec=Recorder(p0) elif problem == 'necklace': space=simple_searchspace(ndim, 0., 360.) p0=Population(necklace,ps,dummyfunc,space) p1=Population(necklace,ps,dummyfunc,space) rec=Recorder(p0) elif problem == 'hilly': space=simple_searchspace(ndim, 0., 360.) p0=Population(hilly,ps,dummyfunc,space) p1=Population(hilly,ps,dummyfunc,space) rec=Recorder(p0)
#from numpy import array, arange, asfarray, pi, cos, zeros, where, linspace #import matplotlib as mpl #import matplotlib.pyplot as plt from peabox_individual import Individual from peabox_population import Population def parabolic(x): return np.sum(x * x) searchspace = (('length', 12., 14.), ('wall_thickness', 0.1, 1.4), ('radius', 20., 40.)) N = 5 p = Population(Individual, N, parabolic, searchspace) npr.seed(3) p.new_random_genes() p.eval_all() for dude in p: dude.score = np.round(dude.score, 2) sc = p.get_scores() print "the population's scores: ", sc # should give the list [ 1.22 1.32 0.53 0.17 1.81] dude0, dude1, dude2, dude3, dude4 = p print 'dude0<dude1 yields ', dude0 < dude1, ' and dude0.isbetter(dude1) yields ', dude0.isbetter( dude1) print 'dude0<dude2 yields ', dude0 < dude2, ' and dude0.isbetter(dude2) yields ', dude0.isbetter( dude2) print 'p.whatisfit and dude0.whatisfit are: ', p.whatisfit, dude0.whatisfit
join(self.plotpath, 'FMsynth_solution_' + runlabel + '.png')) plt.close() def set_bad_score(self): self.score = 9999. # search space boundaries: searchspace = (('amp 1', -6.4, +6.35), ('omega 1', -6.4, +6.35), ('amp 2', -6.4, +6.35), ('omega 2', -6.4, +6.35), ('amp 3', -6.4, +6.35), ('omega 3', -6.4, +6.35)) dim = len(searchspace) # search space dimension ps = 80 parents = Population(FMsynthC, ps, dummyfunc, searchspace) offspring = Population(FMsynthC, ps, dummyfunc, searchspace) rec = Recorder(parents) ea = ComboB(parents, offspring) # instanciate the algorithm from library def gcb(eaobj): if eaobj.F0.gg % 10 == 0: # every 10th generation b = eaobj.F0[0] b.plot_FMsynth_solution() print 'gcb: generation: {} score: {} DNA: {}'.format( eaobj.F0.gg, b.score, b.DNA) rec.save_status() ea.generation_callbacks.append(gcb)
from peabox_population import Population #------------------------------------------------------------------------------- #--- part 1: setup ------------------------------------------------------------- #------------------------------------------------------------------------------- def parabolic(x): # the test function to be minimised return np.sum(x * x) dim = 8 # search space dimension searchspace = [('parameter' + str(i + 1), -1., +1.) for i in range(dim)] mu = 4 # size of parent population of (mu,lambda)-ES la = 12 # size of offspring population of (mu,lambda)-ES parents = Population(Individual, mu, parabolic, searchspace) offspring = Population(Individual, la, parabolic, searchspace) P = 1. # probability that a gene gets modified by the mutation operator mstep = 0.01 # mutation step size parameter parents.new_random_genes() parents.sort() #------------------------------------------------------------------------------- #--- part 2: the loop for (mu,la)-ES ------------------------------------------- #------------------------------------------------------------------------------- for g in range(50): # generation loop for dude in offspring: parentchoice = npr.randint( mu ) # all among the mu best of the old generation have an equal chance to reproduce dude.copy_DNA_of(parents[parentchoice])
def call(self, DNA): self.fmwave([DNA[0], DNA[2], DNA[4]], [DNA[1], DNA[3], DNA[5]]) return np.sum((self.trial - self.target)**2) # search space boundaries: searchspace = (('amp 1', -6.4, +6.35), ('omega 1', -6.4, +6.35), ('amp 2', -6.4, +6.35), ('omega 2', -6.4, +6.35), ('amp 3', -6.4, +6.35), ('omega 3', -6.4, +6.35)) ps = 4 # population size dim = len(searchspace) # search space dimension # now let's create a population to test version A of the objective function implementation pA = Population(Individual, ps, FMsynthA, searchspace) pA.new_random_genes() pA.eval_all() print 'DNAs of pA:' print pA.get_DNAs() pA.print_stuff(slim=True) # and here the objective function version B and another population to test it problem_instance = FMsynthB() objfuncB = problem_instance.call pB = Population(Individual, ps, objfuncB, searchspace) pB.copy_otherpop(pA) pB.eval_all() print 'DNAs of pB:' print pB.get_DNAs() pB.print_stuff(slim=True)
b.evaluate() assert b.score == oldscore # just being a little paranoid b.plot_FMsynth_solution() print 'gcb: score: {} DNA: {}'.format(b.score, b.DNA) print 'gcb: target[:5]: ', b.target[:5] # search space boundaries: searchspace = (('amp 1', -6.4, +6.35), ('omega 1', -6.4, +6.35), ('amp 2', -6.4, +6.35), ('omega 2', -6.4, +6.35), ('amp 3', -6.4, +6.35), ('omega 3', -6.4, +6.35)) dim = len(searchspace) # search space dimension ps_ref = 20 dset = Population(FMsynthC, 40, dummyfunc, searchspace) rset = Population(FMsynthC, ps_ref, dummyfunc, searchspace) rec = Recorder(rset) def gcb2(eaobj): rec.save_status() ea = ScatterSearch(dset, rset, nref=ps_ref, b1=10) ea.refset_update_style = 'Herrera' ea.generation_callbacks.append(gcb1) ea.generation_callbacks.append(gcb2) ea.complete_algo(10)
import numpy as np import numpy.random as npr from numpy import amax, linspace from peabox_individual import Individual from peabox_population import Population def parabolic(x): return np.sum(x*x) searchspace=(('p1',-20.,+20.), ('p2',-20.,+20.), ('p3',-20.,+20.), ('p4',-20.,+20.), ('p5',-20.,+20.)) N=5 p=Population(Individual,N,parabolic,searchspace) npr.seed(3) p.new_random_genes() p.eval_all() p.sort() p.update_no() w = amax(p[0].widths) # largest width of the search space ms=linspace(0.05*w,0.5*w,N) # a range of mutation step sizes for dude in p: dude.mutate(1,ms[dude.no]) # applying individual mutation step sizes print "dude {} has score {:.4f} and gets mutated with step size {:.4f}".format(dude.no,dude.score,ms[dude.no])
from peabox_testfuncs import CEC05_test_function_producer as tfp from peabox_helpers import parentselect_exp as pse from peabox_helpers import simple_searchspace #------------------------------------------------------------------------------- #--- part 1: Ingredients ------------------------------------------------------- #------------------------------------------------------------------------------- dim = 10 f11 = tfp(11, dim) # Weierstrass function in 10 dimensions searchspace = simple_searchspace(10, -3., 1.) ps = 40 # population size G = 80 # number of generations to go through parents = Population(Individual, ps, f11, searchspace) offspring = Population(Individual, ps, f11, searchspace) #------------------------------------------------------------------------------- #--- part 2: initialisation ---------------------------------------------------- #------------------------------------------------------------------------------- seed( 1 ) # seeding numpy's random number generator so we get reproducibly the same random numbers parents.new_random_genes() parents.eval_all() parents.sort() parents.update_no() sa_T = parents[-1].score - parents[0].score # starting temperature saga_ratio = 0.5 # fraction of offspring created by SA and not GA
def choose_parents(self): r1, r2 = npr.rand(2) parenta = np.sum(where(self.thresh < r1, 1, 0)) parentb = np.sum(where(self.thresh < r2, 1, 0)) return parenta, parentb searchspace = (('p1', -5., +5.), ('p2', -5., +5.), ('p3', -5., +5.), ('p4', -5., +5.), ('p5', -5., +5.), ('p6', -5., +5.), ('p7', -5., +5.), ('p8', -5., +5.)) ps = 40 # population size G = 41 # number of generations to go through dim = len(searchspace) parents = Population(Individual, ps, rastrigin, searchspace) offspring = Population(Individual, ps, rastrigin, searchspace) rw = RouletteWheel(dim) #------------------------------------------------------------------------------- #--- part 2: random starting point for search ---------------------------------- #--- and more initialisation --------------------------------------------------- #------------------------------------------------------------------------------- npr.seed( 3 ) # seed differently or comment out if you want to see an algorithm's average performance over several runs parents.new_random_genes() parents.eval_all() parents.sort() print 'initial population:\nbest score = ', parents[0].score
# ('p2',-20.,+20.)) # #searchspace3=(('p1',-20.,+20.), # ('p2',-20.,+20.), # ('p3',-20.,+20.)) searchspace5=(('p1',-20.,+20.), ('p2',-20.,+20.), ('p3',-20.,+20.), ('p4',-20.,+20.), ('p5',-20.,+20.)) N=6 #p2a=Population(Individual,N,parabolic,searchspace2) #p3a=Population(Individual,N,parabolic,searchspace3) p5a=Population(Individual,N,parabolic,searchspace5) p5b=Population(Individual,N,parabolic,searchspace5) npr.seed(1) p5a.marker_genes() p5b.marker_genes(offset=10) print 'printing results of get_DNAs()' print p5a.get_DNAs() print p5b.get_DNAs() print '\n' print 'using p.print_stuff() and p.print_stuff(slim_True)' p5a.print_stuff(slim=True) print '\n\nHere comes p5a' p5a.print_stuff() print '\nHere comes p5b'
# ------------------------------------------------------------------------------- # --- part 1: setup ------------------------------------------------------------- # ------------------------------------------------------------------------------- def parabolic(x): # the test function to be minimised return np.sum(x * x) dim = 8 # search space dimension searchspace = [("parameter" + str(i + 1), -1.0, +1.0) for i in range(dim)] mu = 4 # size of parent population of (mu,lambda)-ES la = 12 # size of offspring population of (mu,lambda)-ES parents = Population(Individual, mu, parabolic, searchspace) offspring = Population(Individual, la, parabolic, searchspace) P = 1.0 # probability that a gene gets modified by the mutation operator mstep = 0.01 # mutation step size parameter parents.new_random_genes() parents.sort() # ------------------------------------------------------------------------------- # --- part 2: the loop for (mu,la)-ES ------------------------------------------- # ------------------------------------------------------------------------------- for g in range(50): # generation loop for dude in offspring: parentchoice = npr.randint(mu) # all among the mu best of the old generation have an equal chance to reproduce dude.copy_DNA_of(parents[parentchoice]) dude.mutate( P, mstep