def WriteInitialPopulation2DB(popsize,root_node,mintreesize,maxtreesize,buildmethod,dbname,tablename): """ Function: WriteInitialPopulation2DB ==================================== create a new population of randomly generated trees and write them to a database @param popsize: size of the population @param root_node: specify the root node and its arity (nb of children). e.g. (0,2,'root') @param mintreesize: min tree depth (at the moment only 2 working) @param maxtreesize: max tree depth (At least 2) @param buildmethod: which Koza method is used to build the trees (either 'AddHalfNode' or 'AddFullNode' or 'AddGrowNodeMin' respectively for Half, Full, or Ramped Half-n-Half) @param dbname: path to database e.g. r'D:\3d_work\pythongp\pySTGP_0.51\src\pop_db' @param tablename: name of the database table """ con = sqlite.connect(dbname) con.execute("create table %s(o_id INTEGER PRIMARY KEY,tree TEXT,\ tree_mapping TEXT, treedepth INTEGER, evaluated INTEGER, fitness FLOAT)"%tablename) trees=[] i=0 while i <popsize: # create a tree individual method = getattr(buildtree.buildTree(),buildmethod) my_tree = method(root_node,0,mintreesize,maxtreesize) if my_tree not in trees: # my_tree = method(root_node,0,mintreesize,maxtreesize) trees.append(my_tree) # create its tree mapping my_tree_indices=crossutil.GetIndicesMappingFromTree(my_tree) # get depth of the tree depth=crossutil.GetDepthFromIndicesMapping(my_tree_indices) # get fitness of the tree resultfitness=settings.FitnessFunction(my_tree) #myfitness=evalfitness.EvalTreeForAllInputSets(my_tree,xrange(settings.nb_eval)) #myfitness=evalfitness.EvalTreeForOneListInputSet(my_tree) #print myfitness #resultfitness=evalfitness.FinalFitness(myfitness) #resultfitness=evalfitness.FinalFitness2(myfitness) #resultfitness=evalfitness.FinalFitness4(myfitness) #print resultfitness con.execute("insert into %s(o_id,tree,tree_mapping,treedepth,evaluated,fitness) values (NULL,?,?,?,?,?)"%tablename,(buffer(marshal.dumps(my_tree,-1)),buffer(marshal.dumps(my_tree_indices,-1)),depth,1,resultfitness)) i=i+1 con.commit() con.close()
#final_output= sum([(math.fabs(settings.ideal_results[x][y]-intermediate_outputs[2][x][y]),math.fabs(settings.ideal_results[x][y]-intermediate_outputs[1][x][y])) [intermediate_outputs[0][x][y]] for x in xrange(len(intermediate_outputs[1])) for y in xrange(len(intermediate_outputs[1][x]))]) #for i in xrange( len(result)): # for j in xrange( len(result[i])): # print result[i][j] return final_output if __name__ == '__main__': #for i in xrange(2000): #a=buildtree.buildTree().AddFullNode((0,3,'root'),0,2,8) #a=buildtree.buildTree().AddFullNode((0,3,'root'),0,8) a=buildtree.buildTree().AddFullNode((0,2,'root'),0,8) #print a #print i #print r #print FinalFitness_tutorial9(EvalTreeForOneListInputSet_tutorial9(a)) #t1 = timeit.Timer('evalfitness.EvalTreeForOneListInputSet_tutorial9(a)' , 'from __main__ import a ;import evalfitness') t2 = timeit.Timer('evalfitness.FinalFitness_tutorial9(evalfitness.EvalTreeForOneListInputSet_tutorial9(a))' , 'from __main__ import a ;import evalfitness') #print t1.timeit(100) print t2.timeit(1000) #print FinalFitness_tutorial8(EvalTreeForOneListInputSet_tutorial8(a)) #print FinalFitness3(EvalTreeForAllInputSets(a,xrange(20))) #print FinalFitness4(EvalTreeForOneListInputSet(a))
second_p_cross = Koza1PointCrossover(maxdepth, cp2_copy_parent1, cp2_copy_parent2, cp2_copy_p1_map, cp2_copy_p2_map, cp2_copy_p1_depth, cp2_copy_p2_depth) if second_p_cross[0] == [1, 1, 1, 1]: break return second_p_cross if __name__ == '__main__': # testing 1-point crossover capability # by generating 2 offsprings for i in xrange(10000): a = buildtree.buildTree().AddHalfNode((0, 2, 'root'), 0, 3, 7) b = buildtree.buildTree().AddHalfNode((0, 2, 'root'), 0, 3, 7) a_map = crossutil.GetIndicesMappingFromTree(a) b_map = crossutil.GetIndicesMappingFromTree(b) a_depth = crossutil.GetDepthFromIndicesMapping(a_map) b_depth = crossutil.GetDepthFromIndicesMapping(b_map) #r=Koza1PointCrossover(10,a,b,a_map,b_map,a_depth,b_depth) #print r #r2=Koza2PointsCrossover(10,a,b,a_map,b_map,a_depth,b_depth) #print r2 #print a #print b r2 = Koza1PointCrossover(15, a, b, a_map, b_map, a_depth, b_depth) #if r2[1][1][0]!=(2, 2, 'adf1'): print r2 #if r2[0][0]==1 and r2[0][1]==1:
def Mutate(maxdepth, parent, p1_map, p1_depth): """ Function: Mutate ================= create a mutated individual from a parent tree using Koza styled mutation @param maxdepth: maximum depth of the mutated offspring @param parent: parent tree e.g. a=buildtree.buildTree().AddHalfNode((0,2,'root'),0,2,7) @param p1_map: parent tree index mapping e.g a_map=crossutil.get_indices_mapping_from_tree(a) @param p1_depth: parent tree depth e.g. a_depth=crossutil.get_depth_from_indices_mapping(a_map) @return: a tuple containing two elements. - The first one is a boolean indicating if the mutated tree is identical to the parent (if identical, returns True) - The second one is the mutated tree """ # get a random depth for parent1 if p1_depth >= 1: p1_mutation_depth = 1 else: p1_mutation_depth = random.randint(1, p1_depth - 1) # get a random depth in p2 such that the resulting # offspring lenght is <= offspring maxdepth mychoice1=crossutil.UnpackIndicesFromList(\ crossutil.GetPackedListIndicesAtDepth(p1_map,p1_mutation_depth)) p1_point = random.choice(mychoice1) parent1_clone = copy.deepcopy(parent) exec("fragment_p1=parent1_clone%s" % crossutil.IndexLstToIndexStr2(p1_point)) # first we need to extract the top node of each subtree if isinstance(fragment_p1, list): firstnode_p1 = fragment_p1[0] if isinstance(fragment_p1, tuple): firstnode_p1 = fragment_p1 # get the parent node of each sub tree (context of each parent) subtree1_parent_s = crossutil.IndexLstToIndexStr2(p1_point) # if the first node is not an ADF, the string version of the # index of the subtree is just the index of upper node in the tree if firstnode_p1[0] != 2: subtree1_parent_s = subtree1_parent_s[:-3] # get the subtree using the index we just obtained exec("subtree1_parent=parent1_clone%s" % subtree1_parent_s) # get the flat list of permitted nodes for the parent tree # for that first get the list of permitted branch nodes... context_p1 = settings.treeRules[subtree1_parent[0][2]] context = copy.deepcopy(context_p1) # and extend to it the list of permitted leaf nodes context[p1_point[-1] - 1][0].extend(context[p1_point[-1] - 1][1]) if len(context[p1_point[-1] - 1][0]) > 1 and firstnode_p1[0] == 2: context[p1_point[-1] - 1][0].remove(firstnode_p1) # get the context from grammar rules for each parent # min_mutation_depth for the subtree has to be extracted by looking when is the next child with a terminal min_mutation_depth = 1 #print context[p1_point[-1]-1][0] flag = random.choice(context[p1_point[-1] - 1][0]) if not settings.treeRules[subtree1_parent[0][2]][p1_point[-1] - 1][1]: min_mutation_depth = 2 #print flag mutant_fragment=buildtree.buildTree().AddHalfNode(\ random.choice(context[p1_point[-1]-1][0]) ,p1_mutation_depth,p1_mutation_depth+min_mutation_depth,maxdepth) # make sure that the mutant fragment is different from the previous fragment if len(mutant_fragment) == 1 and isinstance(mutant_fragment[0], tuple): mutant_fragment = mutant_fragment[0] exec("parent1_clone%s=mutant_fragment" % crossutil.IndexLstToIndexStr2(p1_point)) identical = False if mutant_fragment == fragment_p1: identical = True # no branch nor leaf compatible from fragment to parent nodes return (identical, parent1_clone)