Esempio n. 1
0
def update_tree(GP_prog):
    import initGlobal as init
    import update_state as us
    anten = init.AnT()
    Sub = init.Sub()
    L = init.L()
    U = init.U()
    low = init.lowlevel()
    GP = init.GP()
    #path = us.load_temporary_path()
    us.update_all_saved_parameters(anten, Sub, L, U, GP, low)

    # calculate all of edge of substrate.
    GP_prog.childs[0].childs[0].valueofnode = []
    for i in range(3):
        GP_prog.childs[0].childs[0].valueofnode.append(
            GP_prog.childs[0].childs[0].childs[i].valueofnode)

    temp = GP_prog.childs[0].childs[0].valueofnode

    GP_prog.childs[0].valueofnode = []
    for i in range(3):
        # calculate all of the real substrate's parameters.
        if i == 0:
            temp2 = round(((temp[i] + 1) / 2) *
                          (Sub.rangeOx[1] - Sub.rangeOx[0]) + Sub.rangeOx[0],
                          4)  # Ox edge
        elif i == 1:
            temp2 = round(((temp[i] + 1) / 2) *
                          (Sub.rangeOy[1] - Sub.rangeOy[0]) + Sub.rangeOy[0],
                          4)  # Oy edge.
        else:
            temp2 = round(((temp[i] + 1) / 2) *
                          (Sub.rangeOz[1] - Sub.rangeOz[0]) + Sub.rangeOz[0],
                          4)  # Oz edge.
        GP_prog.childs[0].valueofnode.append(temp2)

    # Secondly create patterns.
    MaxX = GP_prog.childs[0].valueofnode[
        0] - Sub.decrease  ### real MaxX,Y are decreased 1mm before to create
    # any pattern unit(like L1,U1,U2,...).
    MaxY = GP_prog.childs[0].valueofnode[1] - Sub.decrease
    Zsize = GP_prog.childs[0].valueofnode[2]
    GP_prog.substrate_size = [MaxX + Sub.decrease, MaxY + Sub.decrease, Zsize]

    GP_prog.childs[1].childs[0].childs[0] = gp.updateFullBlueTree(
        GP_prog.childs[1].childs[0].childs[0], [MaxX, MaxY], 5)
    GP_prog.childs[1].childs[0].valueofnode = gp.get_val_frombluetree(
        copy.deepcopy(GP_prog.childs[1].childs[0].childs[0]))
    GP_prog.childs[1].valueofnode = GP_prog.childs[1].childs[0].valueofnode

    return GP_prog
def lowlevel_optimizer(ind, state, pop_num):
    # the inputs: - IND  individual
    # 			  - STATE
    #			  - POP_NUM the specified ID of current individual which be optimized in here.

    import initGlobal as init
    import update_state as us
    lowinit = init.lowlevel()
    ant = init.AnT()
    inGP = init.GP(
    )  # get the essential parameters of GP process from initGlobal.py file. note: this's global parameter.
    if init.Re_trainning:
        ant = init.AnT()
        Sub = init.Sub()
        L = init.L()
        U = init.U()
        lowinit = init.lowlevel()
        GP = init.GP()
        #path = us.load_temporary_path()
        us.update_all_saved_parameters(ant, Sub, L, U, GP, lowinit)
    else:
        us.update_path_low(ant, lowinit)

    anpha = lowinit.anpha
    saved_tree = [
    ]  # save all of the current tree generated by all of the directions
    for i in range(lowinit.number_direction):
        saved_tree.append([])
    state.lowlevel = True
    global_name = lowinit.tmpDir + ant.Antenna_Name + 'lowlevel_gen_'
    global_tabname = lowinit.tmpTab + ant.Antenna_Name + '_gen_'
    print('running low-level optimizer for generation ', state.gen,
          'population ', pop_num)
    chromosome, subtree_chrom, IDlist = hp.getChrom(
        ind)  # get chromosome from tree and other atributes.

    num = len(chromosome)  # number of values will be optimized.

    # create randomly the trainning data for ANN.

    y = []  # to save all of the fitness of each direction.
    for i in range(lowinit.number_direction):
        y.append([])
    state.current_low_fitness = y

    fitness = ind.fitness  # save original chromosome fitness.
    return_loss = []
    return_loss.append(ind.ReturnLoss)  # save original return loss variable.
    for i in range(lowinit.number_direction):
        return_loss.append([])

    X_training = np.zeros(
        (lowinit.number_direction,
         num))  # X_training in this case used for direct search method.

    d = X_training  # init the matrix of the directions.

    current_chromosome = np.zeros(num)

    for i in range(
            num
    ):  # save original chromosome, where this point is the start point as well as the x0 point.
        current_chromosome[i] = chromosome[i]

    for i in range(
            lowinit.number_direction):  # create the matrix of the direction.
        for ii in range(num):
            d[i][ii] = round(random.uniform(
                -1, 1), 4)  # X_training in this case is the matrix direction.
    #print(X_training)
    ########################################################################################################################
    ########################################################################################################################
    for k in range(lowinit.number_search_step):
        state.lowlevel_k = k
        # now update the x_k follow each of direction.
        for i in range(lowinit.number_direction):
            for ii in range(num):
                X_training[i][ii] = current_chromosome[ii] + anpha * d[i][ii]
                if X_training[i][ii] > 1:
                    X_training[i][ii] = 1
                if X_training[i][ii] < -1:
                    X_training[i][ii] == -1

        # generate all of the scripts.
        print('generating ', lowinit.number_direction,
              ' scripts in low lelvel optimizer in generation ', state.gen)
        '''
		# before run the next generation, all of the tab file need be deleted.
		filelist = [ f for f in os.listdir(lowinit.tmpTab) if f.endswith(".tab") ]
		for f in filelist:
			os.remove(os.path.join(lowinit.tmpTab, f))
		# be fore run the next gen, all of the hfss file in temp need be deleted.
		filelist = [ f for f in os.listdir(lowinit.tmpDir) if (f.endswith(".hfss") or f.endswith(".vbs") or f.endswith(".txt"))]
		for f in filelist: # delete all before files.
			os.remove(os.path.join(lowinit.tmpDir, f))'''
        ########################################################
        ############## insert chromosome.
        # create temporary population to save current new individual.
        #pop = []
        #for i in range(lowinit.number_direction):
        #	tree = hp.insert_chrom(ind.tree,X_training[i,:],subtree_chrom, IDlist)

        #tree_temp = hp.insert_chrom(ind.tree,X_training[2,:],subtree_chrom, IDlist)
        for i in range(lowinit.number_direction):
            tree = hp.insert_chrom(ind.tree, X_training[i, :], subtree_chrom,
                                   IDlist)
            #if i != 2:
            #	if tree == tree_temp:
            #		raise
            #pop[i].tree.childs[1].valueofnode.plot()
            [Substrate, polygons,
             centroid, poly_list, poly_list_type] = hp.get_all_para_for_hfss(
                 tree)  # get necessary parameters for genscript function.
            name = global_name + str(state.gen) + '_pop_' + str(
                state.population_num) + '_step_k' + str(k) + '_d_' + str(
                    i)  # name of directory would
            # be used to save .vbs and .hfss file.
            tabname = global_tabname + str(state.gen) + '_pop_' + str(
                state.population_num) + '_step_k' + str(k) + '_d_' + str(
                    i)  # name of directory
            # would be used to save .tab file.
            temppp.tree = tree
            temppp.nodelist = ind.nodelist
            temp, _, _ = hp.getChrom(temppp)
            print(X_training[i, :])
            print(".....")
            print(temp)
            for iiii in range(len(X_training[i, :])):
                if not (
                        X_training[i, iiii] == temp[iiii]
                ):  # this part is to test the insert and getchrom function.
                    raise
            genscript(Substrate, polygons, centroid, name + '.vbs', tabname,
                      name + '.hfss', poly_list, poly_list_type)
            f = open(name + '.txt', 'w')
            f.write(hp.tree2str(tree))
            f.close()
            saved_tree[i] = tree
            del tree
            del Substrate
            del polygons
            del centroid

        #raise ValueError("Finished testing")
        #######
        #  running all of the scripts.
        nameDir = global_name + str(state.gen) + '_pop_' + str(
            state.population_num) + '_step_k' + str(
                k) + '_d_'  # file name direction of the vbs file.
        hrun.RunPopScript(lowinit.number_direction, nameDir, 0,
                          len(init.PCnames), state)

        # getting the fitness of each
        for i in range(lowinit.number_direction):
            spec_nameDir_tab = global_tabname + str(state.gen) + '_pop_' + str(
                state.population_num) + '_step_k' + str(k) + '_d_' + str(
                    i) + '.tab'
            [m, n, p, q] = hrun.assignFitness(spec_nameDir_tab, state.gen)
            print('i ', i, '___', m)
            [y[i], return_loss[i]] = [m, n]
            if m < inGP.desired_fitness:
                shutil.copy2(
                    global_name + str(state.gen) + '_pop_' +
                    str(state.population_num) + '_step_k' + str(k) + '_d_' +
                    str(i) + '.vbs', ant.resultsDir)
                shutil.copy2(spec_nameDir_tab, ant.resultsDir)
                shutil.copy2(
                    global_name + str(state.gen) + '_pop_' +
                    str(state.population_num) + '_step_k' + str(k) + '_d_' +
                    str(i) + '.txt', ant.resultsDir)
                #hp.drawtree(pop[i].tree,ant.resultsDir + '_gen_' + str(gen) + '_pop_' + str(i))
                f = open(
                    ant.resultsDir + 'lowlevel_gen_' + str(state.gen) +
                    '_pop_' + str(state.population_num) + '_step_k' + str(k) +
                    '_d_' + str(i) + '.txt', 'w')
                #f.write(hp.tree2str(saved_tree[i]))
                #f.write('#')
                f.write('fitness: ' + str(m))
                f.write('#')
                if p:
                    f.write("_____exist best fitness")
                    if q:
                        f.write("___ that is better than overcome_desired")
                #f.write('time: ' + str((time.time() - first_time)/60))
                f.close()

        ###
        fitness_k = min(y)
        index = y.index(fitness_k)
        if fitness_k < fitness:
            for i in range(num):
                current_chromosome[i] = X_training[index][i]
            fitness = fitness_k
        else:
            anpha = anpha * lowinit.shrink  # shrink the anpha maybe because the stepsize is a little big.

    # np.savetxt('C:\\Opt_files\\lowlevel\\y.txt',y,delimiter = ',')
    # np.savetxt('C:\\Opt_files\\lowlevel\\X.txt',X_training,delimiter = ',')
    ind.fitness = fitness
    ind.tree = hp.insert_chrom(ind.tree, current_chromosome, subtree_chrom,
                               IDlist)
    state.lowlevel = False
    #del saved_tree

    return ind
def makeGP_prog(maxSub, maxPat, maxBlue, ismaxdep):
    # makeGP_prog makes a entire GP tree.
    # whre maxSub: the maximum depth of the genSub sub-tree.
    # maxPat: the maximum depth of the genPat sub-tree.
    # maxBlue: the maximum depth of the Blue sub-tree.
    # ismaxdep: specify whether GP tree will be created with maxdepth of all branch or not.
    GP_prog = gp.node()
    Sub = init.Sub()
    if init.Re_trainning:
        import update_state as us
        anten = init.AnT()
        Sub = init.Sub()
        L = init.L()
        U = init.U()
        low = init.lowlevel()
        GP = init.GP()
        #path = us.load_temporary_path()
        us.update_all_saved_parameters(anten, sub, L, U, GP, low)

    GP_prog.strname = 'GP_prog'
    GP_prog.childs = []
    GP_prog.funcORter = 'func'

    # firstly need to create the substrate tree.
    if maxSub == 1:
        # create addsub3 tree.
        gensub1 = gp.node()
        gensub1.strname = 'gensub1'
        gensub1.type = 4
        gensub1.childs = []
        gensub1.childs.append(gp.addsub3())
        gensub1.funcORter = 'func'
        GP_prog.childs.append(gensub1)
    else:  # when maxSub != 1.
        pass

    # calculate all of edge of substrate.
    GP_prog.childs[0].childs[0].valueofnode = []
    for i in range(3):
        GP_prog.childs[0].childs[0].valueofnode.append(
            GP_prog.childs[0].childs[0].childs[i].valueofnode)

    temp = GP_prog.childs[0].childs[0].valueofnode

    GP_prog.childs[0].valueofnode = []
    for i in range(3):
        # calculate all of the real substrate's parameters.
        if i == 0:
            temp2 = round(((temp[i] + 1) / 2) *
                          (Sub.rangeOx[1] - Sub.rangeOx[0]) + Sub.rangeOx[0],
                          4)  # Ox edge
        elif i == 1:
            temp2 = round(((temp[i] + 1) / 2) *
                          (Sub.rangeOy[1] - Sub.rangeOy[0]) + Sub.rangeOy[0],
                          4)  # Oy edge.
        else:
            temp2 = round(((temp[i] + 1) / 2) *
                          (Sub.rangeOz[1] - Sub.rangeOz[0]) + Sub.rangeOz[0],
                          4)  # Oz edge.
        GP_prog.childs[0].valueofnode.append(temp2)

    # Secondly create patterns.
    MaxX = GP_prog.childs[0].valueofnode[
        0] - Sub.decrease  ### real MaxX,Y are decreased 1mm before to create
    # any pattern unit(like L1,U1,U2,...).
    MaxY = GP_prog.childs[0].valueofnode[1] - Sub.decrease
    Zsize = GP_prog.childs[0].valueofnode[2]
    GP_prog.substrate_size = [MaxX + Sub.decrease, MaxY + Sub.decrease, Zsize]

    [tree, lastnode] = gp.makeBlueTree(maxBlue, ismaxdep, 0, MaxX, MaxY)
    fullbluetree = gp.genFullBlueTree(tree)

    fullbluetree = gp.updateFullBlueTree(fullbluetree, [MaxX, MaxY], 1)

    if maxPat == 1:
        # create
        genpat1 = gp.node()
        genpat1.strname = 'genpat1'
        genpat1.type = 5
        genpat1.childs = []
        bluetree1 = gp.node()
        bluetree1.strname = 'bluetree1'
        bluetree1.type = 2
        bluetree1.funcORter == 'func'
        bluetree1.childs = []
        bluetree1.childs.append(fullbluetree)
        genpat1.childs.append(bluetree1)
        genpat1.funcORter = 'func'
        GP_prog.childs.append(genpat1)
        GP_prog.childs[1].childs[0].valueofnode = gp.get_val_frombluetree(
            copy.deepcopy(fullbluetree))
        GP_prog.childs[1].valueofnode = GP_prog.childs[1].childs[0].valueofnode

    return GP_prog
Esempio n. 4
0
import GPoperators as op
import initGlobal as init
import InitPopMethods as initpop
import Helper as hp
from genscript import genscript
import matplotlib.pyplot as plt
# from testFunctionFitness import fitness
import os
import time
import shutil
import DS_lowOptimize as dslow
import ANN_lowOptimize as anlow

import helpRunning as hpr
######################################################### MAIN ####################################################33
lowlevel = init.lowlevel()
first_time = time.time()
inAnT = init.AnT(
)  # get the essential parameters of antenna from initglobal.py
mydir = inAnT.tmpTab
mydir_hfss = inAnT.tmpDir
filelist = [f for f in os.listdir(mydir) if f.endswith(".tab")]
for f in filelist:  # delete all before files.
    os.remove(os.path.join(mydir, f))

filelist = [
    f for f in os.listdir(mydir_hfss)
    if (f.endswith(".hfss") or f.endswith(".vbs") or f.endswith(".txt"))
]
for f in filelist:  # delete all before files.
    os.remove(os.path.join(mydir_hfss, f))
Esempio n. 5
0
def genscript(Substrate,polygons,centroid,tmpScriptFile,outFile,hfssFile,poly_list,poly_list_type):
	import initGlobal as init 
	anten =  init.AnT()
	sub = init.Sub()
	# this function create the vbs file.
	# input arguments:
	#			- Substrate: the list of edges of the substrate.
	#			- polygons: the list of all coordinates to help draw the patch. Got from the second output of
	#							Helper.get_all_para_for_hfss() function.

	if init.Re_trainning:
		import update_state as us 
		anten = init.AnT()
		sub = init.Sub()
		L   = init.L()
		U   = init.U()
		low = init.lowlevel()
		GP = init.GP()
		us.update_all_saved_parameters(anten, sub, L, U, GP, low)

	addition_number = sub.addition # increase the range of substrate.
	# frequency 
	c = anten.c
	fC = anten.fC
	fStart = anten.fStart
	fStop  = anten.fStop
	npoints = anten.npoints
	Lambda = (c/fC)*1000

	# radiation boundaries.
	#AirX = Nx*dAnt + Lambda/2
	#AirY = Ny*dAnt + Lambda/2
	AirZ = Lambda + Substrate[2] + 5 # 5 is the length of the coaxial cable.
	
	# solution parameters (GHz)
	

	# define some attributes of substrate.
	startX = centroid[0] - ((Substrate[0]+addition_number)/2) # the X original coordinate helps to draw the substrate.
	startY = centroid[1] - ((Substrate[1]+addition_number)/2) # the Y original coordinate helps to draw the substrate.
	length_W = Substrate[0] + addition_number # imply that it is the width_ox
	length_L = Substrate[1] + addition_number # imply that it is the length_oy
	centroidX_substrate = startX + length_W/2 # is the ox centroid coordinate of the substrate.
	centroidY_substrate = startY + length_L/2 # is the oy centroid coordinate of the substrate.
	####
	x_coaxial_cable_coordinate = centroidX_substrate + (length_W/2)/3.5
	y_coaxial_cable_coordinate = centroidY_substrate
	coaxial_check = geose.Point(x_coaxial_cable_coordinate,y_coaxial_cable_coordinate)
	checking = 0
	for i in range(len(polygons)):
		if poly_list[i].intersects(coaxial_check)[0]:
			checking = checking + 1

	if checking == 0:
		if poly_list_type[0] == 'L1' or poly_list_type[0] == 'L3' or poly_list_type[0] == 'L4' or poly_list_type[0] == 'U2' or poly_list_type[0] == 'U4':
			x_coaxial_cable_coordinate = (polygons[0][0,0] + polygons[0][2,0])/2
			y_coaxial_cable_coordinate = (polygons[0][0,1] + polygons[0][2,1])/2
		elif poly_list_type[0] == 'L2':
			x_coaxial_cable_coordinate = (polygons[0][5,0] + polygons[0][1,0])/2
			y_coaxial_cable_coordinate = (polygons[0][5,1] + polygons[0][1,1])/2
		elif poly_list_type[0] == 'U1':
			x_coaxial_cable_coordinate = (polygons[0][1,0] + polygons[0][3,0])/2
			y_coaxial_cable_coordinate = (polygons[0][1,1] + polygons[0][3,1])/2
		elif poly_list_type[0] == 'U3':
			x_coaxial_cable_coordinate = (polygons[0][7,0] + polygons[0][1,0])/2
			y_coaxial_cable_coordinate = (polygons[0][7,1] + polygons[0][1,1])/2

	'''
	#### check wheather the feed point is in range of patch.
	polygon_boundary = hp.getBoundary(polygons) # get the boundary of the patch.
	try:
		range_edges = hp.get2_suitable_edges_for_coaxial_cable(polygon_boundary,(centroidX_substrate,centroidY_substrate))
	except:
		pass

	#print(x_coaxial_cable_coordinate)
	#print(range_edges[1][1][1])
	
	# fix the coaxial point. 
	if range_edges != []:
		if len(range_edges) == 2:
			if (x_coaxial_cable_coordinate > range_edges[1][1][0]):
				# NOTE: this needs to revise because it does not include all of the case.
				#print(outFile)
				#print('__________')
				#x_coaxial_cable_coordinate = x_coaxial_cable_coordinate - (x_coaxial_cable_coordinate - range_edges[1][1][1]) - 2
				x_coaxial_cable_coordinate = (range_edges[1][1][0] - range_edges[0][1][0])/2
		else:
			if (x_coaxial_cable_coordinate > range_edges[-1][1][0]) or (x_coaxial_cable_coordinate > range_edges[-3][1][0] and x_coaxial_cable_coordinate < range_edges[-2][1][0]):
				x_coaxial_cable_coordinate = (range_edges[-1][1][0] - range_edges[-2][1][0])/2
	'''
	# open a temporary script file.
	# tmpScriptFile = 'tempPatch.vbs'
	fid = open(tmpScriptFile, 'w')

	# create a new HFSS project.
	hfss.hfssNewProject(fid)
	hfss.hfssInsertDesign(fid, 'NxN_uStrip_Patch')
	
	# Create substrate.
	hfss.hfssBox(fid, 'Substrate', [startX , startY , 0], [length_W, length_L, -Substrate[2]], 'mm')
	hfss.hfssAssignMaterial(fid,'Substrate',anten.substrate_material)
	name_all_polys = [] 
	for i in range(len(polygons)):
		# draw each polygon.
		hfss.hfssPolyline1(fid,'polygon'+str(i+1),polygons[i],'mm')
		name_all_polys.append('polygon' + str(i+1))
	if len(name_all_polys) != 1:
		hfss.hfssUnite(fid,name_all_polys)
	hfss.hfssRename(fid,'polygon1','patch') 
	hfss.hfssAssignPE(fid, 'Perf1', ['patch'], False)
	# draw a ground plane.
	hfss.hfssRectangle(fid, 'GroundPlane', 'Z', [startX,startY,-Substrate[2]], Substrate[0] + addition_number, Substrate[1]\
	 + addition_number, 'mm');
	#hfss.hfssAssignPE(fid, 'GND', ['GroundPlane']);



	# get the suitable coordinate of the coaxial cable.
	
	# draw the coaxial cable.
	hfss.hfssCircle(fid, 'Groundcir', 'Z', [x_coaxial_cable_coordinate, y_coaxial_cable_coordinate, -Substrate[2]], 1, 'mm')
	hfss.hfssSubtract(fid,['GroundPlane'],['Groundcir'])
	hfss.hfssAssignPE(fid, 'GND', ['GroundPlane'],False);

	hfss.hfssCylinder(fid, 'Cyl1', 'Z', [x_coaxial_cable_coordinate, y_coaxial_cable_coordinate,\
	 -Substrate[2]], 0.3, Substrate[2], 'mm')
	hfss.hfssAssignMaterial(fid,'Cyl1','copper')
	hfss.hfssCoaxialCable(fid, ['Cyl1_In', 'Cyl1_Er','Cyl1_Out'], 'Z', [x_coaxial_cable_coordinate, y_coaxial_cable_coordinate,\
	 -Substrate[2]-5], [0.3, 0.7, 1], 5, 'mm')
	hfss.hfssAssignMaterial(fid,'Cyl1_In','copper')
	hfss.hfssAssignMaterial(fid,'Cyl1_Er','air')
	hfss.hfssAssignMaterial(fid,'Cyl1_Out','copper')

	# feed.
	hfss.hfssCircle(fid,'feed','Z',[x_coaxial_cable_coordinate, y_coaxial_cable_coordinate, -Substrate[2]-5],0.7,'mm')
	
	hfss.hfssAssignLumpedPort(fid, 'Port1','feed', [x_coaxial_cable_coordinate, y_coaxial_cable_coordinate+0.7,\
	 -Substrate[2]-5], [x_coaxial_cable_coordinate, y_coaxial_cable_coordinate+0.3, -Substrate[2]-5], 'mm')

	# draw radiation boundaries.
	hfss.hfssBox(fid, 'AirBox', [startX - Lambda/4, startY - Lambda/4, -5 - Lambda/2 - Substrate[2]], [length_W + Lambda/2,\
	 length_L + Lambda/2, AirZ], 'mm'); 
	hfss.hfssAssignRadiation(fid, 'ABC', 'AirBox');
	hfss.hfssSetTransparency(fid, ['AirBox'], 0.95);

	############################ insert solution.
	hfss.hfssInsertSolution(fid, 'Solution1', fC/1e9)
	hfss.hfssInterpolatingSweep(fid, 'Sweep1', 'Solution1',fStart, fStop, npoints)

	# Create return loss report (new HFSS-API)
	hfss.hfssCreateReport1(fid,'ReturnLoss',1,1,'Solution1',\
	    ['Freq'],['Freq','db(S(Port1,Port1))'],'Sweep1','NULL','Sweep')
	    # Save the project to a temporary file and solve it.
	
	#hfss.hfssSolveSetup(fid, 'Solution1');
	
	#Export the S11 report to .tab file

	# solve. 
	hfss.hfssSolveSetup(fid, 'Solution1')
	#hfss.hfssSaveProject(fid, hfssFile, anten.hfss_save);
	hfss.hfssExportToFile(fid, 'ReturnLoss', outFile, 'tab')

	fid.close()
Esempio n. 6
0
import Helper as hp 
import initGlobal as init 
lowinit = init.lowlevel()

def lowlevel_optimizer(ind,state,pop_num ):
	print('running low-level optimizer for generation ',state.gen,'population ', pop_num)
	chromosome, subtree_chrom, IDlist = hp.getChrom() # get chromosome from tree and other atributes.

	num = len(chromosome) # number of values will be optimize.
	list_chrom = 
	
#								- mutaion(pop,proRed,prosubBlue,proBlue,proSubstrate,proGensub,proGenpat)
#								- update_tree_after_GP_operation(GP_prog,nodeID,typeChange) # to help two above functions.
# [email protected] - 2018
import Helper as hp
import copy
import initGlobal as init
import GP as gp
import random
inGP = init.GP()
if init.Re_trainning:
    import update_state as us
    AnT = init.AnT()
    Sub = init.Sub()
    L = init.L()
    U = init.U()
    low = init.lowlevel()
    inGP = init.GP()
    #path = us.load_temporary_path()
    us.update_all_saved_parameters(AnT, Sub, L, U, inGP, low)


def crossover(pop, state, proRed, prosubBlue, proBlue, proSubstrate, proGensub,
              proGenpat):
    # input arguments:
    #			POP - the population need be applied GP operators.
    #			PRORED - the probality whether the red node is picked to apply GP operators.
    #			PROSUBBLUE - _____________________ subblue node ______________________________.
    #			PROBLUE - ________________________ bluetree node______________________________.
    #			...............................................................................
    # Generate a child tree using crossover and previous generation of program.
def insert_chrom(or_tree, chromosome, subtree_chrom_, IDlist):
    # insert_chrom function is used to insert the red nodes into suitable tree.
    #   tree: is the tree need be inserted after the red nodes extracted.
    #   chromosome: is the list that saves all extracted values of red nodes.
    #   subtree_chrom: is the list that save all extracted red nodes.
    #   IDlist: is the list that save all ID of the extracted node.
    #       Note: The tree is used as the input of this function need be deepcopy before.
    import initGlobal as init
    Sub = init.Sub()
    if init.Re_trainning:
        import update_state as us
        AnT = init.AnT()
        #Sub = init.Sub()
        L = init.L()
        U = init.U()
        low = init.lowlevel()
        GP = init.GP()
        #path = us.load_temporary_path()
        us.update_all_saved_parameters(AnT, Sub, L, U, GP, low)

    tree = copy.deepcopy(or_tree)
    subtree_chrom = copy.deepcopy(subtree_chrom_)
    #drawtree(tree)

    length = len(chromosome)

    for i in range(length):
        subtree_chrom[i].valueofnode = chromosome[
            i]  # insert all values into subtree_chrom before insert to GP_tree(tree).

    for i in range(len(chromosome)):
        tree = replaceSubtree(tree, subtree_chrom[i], IDlist[i])
        #drawNodeIDs(tree)
    ## update tree (substrate layer).
    UpdateNodeIDs(tree, 0)
    #drawtree(tree)
    tree.childs[0].childs[0].valueofnode = []
    for i in range(len(tree.childs[0].childs[0].childs)
                   ):  # resave the sizes of substrate layer into addsub3 node.
        tree.childs[0].childs[0].valueofnode.append(
            tree.childs[0].childs[0].childs[i].valueofnode)
    temp = tree.childs[0].childs[
        0].valueofnode  # save the sizes of substrate layer into TEMP variable.

    tree.childs[0].valueofnode = []
    for i in range(3):
        # calculate all of the real substrate's parameters.
        if i == 0:
            temp2 = round(((temp[i] + 1) / 2) *
                          (Sub.rangeOx[1] - Sub.rangeOx[0]) + Sub.rangeOx[0],
                          4)  # Ox edge
        elif i == 1:
            temp2 = round(((temp[i] + 1) / 2) *
                          (Sub.rangeOy[1] - Sub.rangeOy[0]) + Sub.rangeOy[0],
                          4)  # Oy edge.
        else:
            temp2 = round(((temp[i] + 1) / 2) *
                          (Sub.rangeOz[1] - Sub.rangeOz[0]) + Sub.rangeOz[0],
                          4)  # Oz edge.
        tree.childs[0].valueofnode.append(temp2)

    # Secondly create patterns.
    MaxX = tree.childs[0].valueofnode[
        0] - Sub.decrease  ### real MaxX,Y are decreased 1mm before to create
    # any pattern unit(like L1,U1,U2,...).
    MaxY = tree.childs[0].valueofnode[1] - Sub.decrease
    Zsize = tree.childs[0].valueofnode[2]
    tree.substrate_size = [MaxX + Sub.decrease, MaxY + Sub.decrease, Zsize]
    MaxXY = [MaxX - Sub.decrease, MaxY - Sub.decrease]
    ResetSynthesischeck(tree.childs[1].childs[0].childs[0],
                        tree.childs[1].childs[0].childs[0].nodeID)
    tree.childs[1].childs[0].childs[0] = gp.updateFullBlueTree(
        tree.childs[1].childs[0].childs[0], MaxXY, 4)
    tree.childs[1].childs[0].valueofnode = gp.get_val_frombluetree(
        copy.deepcopy(tree.childs[1].childs[0].childs[0]))
    tree.childs[1].valueofnode = tree.childs[1].childs[0].valueofnode

    del subtree_chrom
    del temp
    del temp2

    return tree