Example #1
0
def crossoverAndMutation(problem, individuals):

    # Format a population data structure usable by DEAP's package
    dIndividuals = deap_format(problem, individuals)

    # Crossover
    for ind1, ind2 in zip(dIndividuals[::2], dIndividuals[1::2]):
        if random.random() <= 0.9:  #crossover rate
            tools.cxUniform(ind1, ind2, indpb=1.0 / len(problem.decisions))

    # Mutation
    for ind in dIndividuals:
        tools.mutPolynomialBounded(ind,
                                   eta=1.0,
                                   low=[dec.low for dec in problem.decisions],
                                   up=[dec.up for dec in problem.decisions],
                                   indpb=0.1)
        del ind.fitness.values

    # Update beginning population data structure
    for individual, dIndividual in zip(individuals, dIndividuals):
        for i in range(len(individual.decisionValues)):
            individual.decisionValues[i] = dIndividual[i]
            individual.fitness = None

    return individuals, 0
Example #2
0
def mateNN(ind1, ind2):
    gen = ind1.gen
    genotype(ind1)
    genotype(ind2)
    tools.cxUniform(ind1, ind2, params["xoi"])
    phenotype(ind1)
    phenotype(ind2)
    ind1.gen = gen
    ind2.gen = gen
    return (ind1, ind2)
def cx(ind1, ind2):
    new_wealth = ((ind1.wealth + ind2.wealth) /
                  2 if use_inheritance else initial_wealth)
    parents = (ind1.id, ind2.id)
    tools.cxUniform(ind1, ind2, 0.5)  # tools.cxTwoPoint
    ind1.wealth = ind2.wealth = new_wealth
    ind1.connections_ids = []
    ind2.connections_ids = []
    ind1.parents = ind2.parents = parents
    return ind1, ind2
Example #4
0
def cxTwo_Uniform(ind1, ind2):
    x = tools.cxTwoPoint(ind1, ind2)
    y = tools.cxUniform(ind1, ind2, indpb=0.9)
    if sum(max(x)) > sum(max(y)):
        return x
    else:
        return y
Example #5
0
    def cxUniform(self, ind1, ind2, indpb):
        for _ in range(100):
            c1, c2 = tools.cxUniform(ind1, ind2, indpb)
            if self.check_constraint(c1) and self.check_constraint(c2):
                break

        return (c1, c2)
Example #6
0
 def crossover(self, individual_1, individual_2, probability):
     if self.method == 'Uniform':
         return tools.cxUniform(individual_1,
                                individual_2,
                                probability)
     elif self.method == 'TwoPoint':
         return tools.cxESTwoPoint(individual_1,
                                   individual_2)
Example #7
0
def crossover_weights(ind1, ind2, force):
    #ind1.check()
    #ind2.check()

    child1, child2 = tools.cxUniform(ind1.weights, ind2.weights, indpb=0.5)

    ind1.weights[:] = fix_weights(child1, force)
    ind2.weights[:] = fix_weights(child2, force)

    #ind1.check()
    #ind2.check()

    return ind1, ind2
Example #8
0
def crossoverAndMutation(problem, individuals):

    # Format a population data structure usable by DEAP's package
    dIndividuals = deap_format(problem, individuals)
    
    # Crossover
    for ind1, ind2 in zip(dIndividuals[::2], dIndividuals[1::2]):
        if random.random() <= 0.9: #crossover rate
            tools.cxUniform(ind1, ind2, indpb=1.0/len(problem.decisions))
            

    # Mutation
    for ind in dIndividuals:
        tools.mutPolynomialBounded(ind, eta = 1.0, low=[dec.low for dec in problem.decisions], up=[dec.up for dec in problem.decisions], indpb=0.1 )
        del ind.fitness.values
         
    # Update beginning population data structure
    for individual,dIndividual in zip(individuals, dIndividuals):
        for i in range(len(individual.decisionValues)):
            individual.decisionValues[i] = dIndividual[i]
            individual.fitness = None

    return individuals,0
Example #9
0
def main():
    # 杂交函数测试
    ind1 = [1, 1, 1, 1, 1]
    ind2 = [0, 0, 0, 0, 0]
    print(ind1, ind2)
    """交换从任意位置开始并且到结尾的一段基因"""
    n1, n2 = tools.cxOnePoint(ind1, ind2)
    print(n1, n2)
    """交换连续的一段长度随机,位置随机的基因"""
    n3, n4 = tools.cxTwoPoint(ind1, ind2)
    print(n3, n4)
    """进行min(len(ind1), len(ind2))次杂交,每轮交换前产生一个随机数a,若a小于indpb则交换该轮次位置的两个基因,否则不执行交换"""
    n5, n6 = tools.cxUniform(ind1, ind2, indpb=0.5)
    print(n5, n6)
Example #10
0
def customXover(ind1, ind2):

    g_01, g_02 = tools.cxUniform([ind1[0]], [ind2[0]], CXPROB)
    g1, g2 = tools.cxTwoPoint(ind1[1:], ind2[1:])

    ind1[0] = g_01[0]
    ind2[0] = g_02[0]

    for i in range(1, len(ind1)):
        ind1[i] = g1[i - 1]
    for i in range(1, len(ind2)):
        ind2[i] = g2[i - 1]

    return ind1, ind2
Example #11
0
def crossover_centroid(ind1, ind2):
    ind1.check()
    ind2.check()

    child1, child2 = tools.cxUniform(ind1.centroid.flatten(),
                                     ind2.centroid.flatten(),
                                     indpb=0.5)

    ind1.centroid[:, :] = child1.reshape((ind1.NC, ind1.ND))
    ind2.centroid[:, :] = child2.reshape((ind2.NC, ind2.ND))

    ind1.check()
    ind2.check()

    return ind1, ind2
Example #12
0
 def _mate(ind1, ind2, low, up, blend_prob=0.5):
     # a mixture of blend and 2 point crossover
     if random.random() < blend_prob:
         ind1, ind2 = tools.cxBlend(ind1, ind2, alpha=0.5)
         size = min(len(ind1), len(ind2))
         for i, u, l in zip(range(size), up, low):
             ind1[i] = math.floor(ind1[i])
             ind2[i] = math.ceil(ind2[i])
             if ind1[i] > u:
                 ind1[i] = u
             elif ind1[i] < l:
                 ind1[i] = l
             if ind2[i] > u:
                 ind2[i] = u
             elif ind2[i] < l:
                 ind2[i] = l
         return ind1, ind2
     else:
         return tools.cxUniform(ind1, ind2, indpb=0.5)
Example #13
0
 def my_crossover(self,LL,UU,ind1, ind2):
     t=self.t
     typeOfInput=len(t)
     ind11 = []
     ind22 = []
     for i in range(typeOfInput):
         if t[i] =='float':
             ind1var1,ind2var1=tools.cxSimulatedBinaryBounded([ind1[i]], [ind2[i]], low=LL[i], up=UU[i], eta=20.0)
             ind11.append(ind1var1[0])
             ind22.append(ind2var1[0])
         elif t[i]=='int':
             ind1var2,ind2var2=tools.cxUniform([ind1[i]], [ind2[i]],indpb=0.9)
             ind11.append(ind1var2[0])
             ind22.append(ind2var2[0])
         elif t[i]=='bool':
             toss = random.random()
             if toss > 0.5:
                 ind1var3,ind2var3=ind2[i], ind1[i]
                 ind11.append(ind1var3)
                 ind22.append(ind2var3)
     return ind11,ind22
Example #14
0
def crossover_weights(ind1, ind2, force):
    #ind1.check()
    #ind2.check()

    child1, child2 = tools.cxUniform(ind1.weights.flatten(),
                                     ind2.weights.flatten(),
                                     indpb=0.5)

    ind1.weights[:, :] = child1.reshape((ind1.NC, ind1.ND))
    ind2.weights[:, :] = child2.reshape((ind2.NC, ind2.ND))

    NC, ND = ind1.weights.shape

    for i in range(NC):
        ind1.weights[i, :] = fix_weights(ind1.weights[i, :], force)
        ind2.weights[i, :] = fix_weights(ind2.weights[i, :], force)

    #ind1.check()
    #ind2.check()

    return ind1, ind2
Example #15
0
##Mutation
mutant = toolbox.clone(ind1)
#ind2 = tools.mutGaussian(mutant, mu=0.0, sigma=0.2, indpb=0.2)
ind2, = tools.mutUniformInt(mutant, low=0, up=1, indpb=0.5)
del mutant.fitness.values
ind2
ind1
ind2.fitness.values = evalKnapsack(ind2)

ind2.fitness.values
ind1.fitness.values

##CROSSOVER
child1, child2 = [toolbox.clone(ind) for ind in (ind1, ind2)]
tools.cxUniform(child1, child2, 0.5)
#tools.cxSimulatedBinary(child1, child2,0.5)

#tools.cxPartialyMatched(child1, child2)
del child1.fitness.values
del child2.fitness.values

selected = tools.selNSGA2([child1, child2], nd="standard")
print(child1 in selected)  # True

for g in range(NGEN):
    # Select and clone the next generation individuals
    offspring = map(toolbox.clone, toolbox.select(pop, len(pop)))

    # Apply crossover and mutation on the offspring
 def uniform_crossover(ind1, ind2, ind_pb):
     tools.cxUniform(ind1, ind2, ind_pb)  # params: ind1, ind2, ind_pb
Example #17
0
    def customXover(self, ind1, ind2, indpb):
        """
        Parameters
        ----------
        ind1 : Deap invidual parent 1
        ind2 : Deap invidual parent 2
        indpb : float
            Defined the probability that a semantically equal slices of genetic code are recombined 

        Returns
        -------
        ind1 : Deap invidual
        ind2 : Deap invidual
            Recombined Individuals
        
        Semantically equal slice are recombined together with indpb probability. If the slice is a single attribute cxUniform is used,
        CxTwoPoint deap crossover is used in the other case. 

        """
        #Q
        g_q1, g_q2 = tools.cxUniform([ind1[0]], [ind2[0]], indpb=indpb)
        #GED
        g_ged1, g_ged2 = tools.cxTwoPoint(ind1[1:7], ind2[1:7])
        #Tau
        g_tau1, g_tau2 = tools.cxUniform([ind1[7]], [ind2[7]], indpb=indpb)
        #Test weight comp card
        #g_eta1,g_eta2 = tools.cxUniform([ind1[8]], [ind2[8]], indpb = indpb)
        ####################

        #Set if crossovered
        ind1[0] = g_q1[0]
        ind2[0] = g_q2[0]
        #two point crossover individuals are always modified. We edit this slice of genetic code only if condition is valid
        if random.random() < indpb:
            for i, (g1, g2) in enumerate(zip(g_ged1, g_ged2), start=1):
                ind1[i] = g1
                ind2[i] = g2
            # for i in range(1,7):
            #     ind2[i]=g2
        #
        ind1[7] = g_tau1[0]
        ind2[7] = g_tau2[0]
        #Test weight comp card
        # ind1[8]=g_eta1[0]
        # ind2[8]=g_eta2[0]
        #############à

        if self._problemName == 'GREC':

            g_add1, g_add2 = tools.cxTwoPoint(ind1[8:13], ind2[8:13])
            #Weight eta
            #g_add1, g_add2 =  tools.cxTwoPoint(ind1[9:14], ind2[9:14])
            ################
            #Same for ged attributes
            if random.random() < indpb:
                for i, (g1, g2) in enumerate(zip(g_add1, g_add2), start=8):
                    #Weight eta
                    #for i,(g1,g2) in enumerate(zip(g_add1,g_add2),start = 9):
                    ###########
                    ind1[i] = g1
                    ind2[i] = g2

        return ind1, ind2
def main(epsilon, delta):
	global lambda_values
	global population_size
	global population
	global population_obj_func_vals
	global iterations

	outputs = []

	for lambda_index in range(1, number_of_lambdas+1):
		_lambda = float(lambda_index-1)/(number_of_lambdas-1)

		improved_solutions = []							#improved solutions for a particular lambda
		v_lambda = float('Inf')

		for i in range(1 , population_size+1):
			sample = [[0,0] for x in range(number_of_assets)]
			Q = random.sample([x for x in range(1, number_of_assets+1)],10)

			for asset in Q:
				sample[asset-1] = [1, myRandom(0,1)]
			
			population[i-1] = list(sample)

		for ind,S in enumerate(population):
			[population_obj_func_vals[ind], v_lambda, improved] = evaluate(S, _lambda, 0, v_lambda, False, improved_solutions, UPDATE_H)

		for itr in range(iterations):
			#binary tournament for selecting parents S_star and S_double_star
			chosen = []
			for i in xrange(2):
				aspirants = tools.selRandom(population, 40)
				for i,aspirant in enumerate(aspirants):
					h = []
					f_aspirant = 0
					v = float('Inf')
					imp = False
					[f_aspirant, v, imp] = evaluate(aspirant, _lambda, 0, v, False, h, DONT_UPDATE_H)
					aspirants[i] = [aspirant, f_aspirant]
					
				chosen.append(min(aspirants, key=lambda x: x[1])[0])
			
			S_star = list(chosen[0])
			S_double_star = list(chosen[1])
			
			#Uniform crossover to find child C
			C = []
			[C1, C2] = tools.cxUniform(S_star, S_double_star, ind_prob)
			f1 = f2 = 0
			v = float('Inf')
			imp = False
			h = []
			[f1, v, imp] = evaluate(C1, _lambda, 0, v, False, h, DONT_UPDATE_H)
			[f2, v, imp] = evaluate(C2, _lambda, 0, v, False, h, DONT_UPDATE_H)

			if f1<f2:
				C = C1
			else:
				C = C2

			#find assets in parents but not in child
			A_star = []
			for i in range(number_of_assets):
				if S_star[i][0]==1 and S_double_star[i][0]==0 and C[i][0]==0:
					A_star.append([i+1, S_star[i][1]])
				elif S_star[i][0]==0 and S_double_star[i][0]==1 and C[i][0]==0:
					A_star.append([i+1, S_double_star[i][1]])

			#Mutation
			mutation_index = random.randint(0, number_of_assets-1)
			while C[mutation_index][0]==0:
				mutation_index = random.randint(0, number_of_assets-1)
			m = random.randint(0,1)

			if m == 0:
				# C_i = 0.9*(epsilon + C[mutation_index][1]) - epsilon
				C_i = 0.9*(epsilon[mutation_index] + C[mutation_index][1]) - epsilon[mutation_index]
			else:
				# C_i = 1.1*(epsilon + C[mutation_index][1]) - epsilon
				C_i = 1.1*(epsilon[mutation_index] + C[mutation_index][1]) - epsilon[mutation_index]

			if C_i<0:
				C[mutation_index][0] = 0
				C[mutation_index][1] = 0

			#check if child contains more or less than K assets and fix it
			total_assets_in_child = 0
			child_copy = list(C)
			sorted_child_copy = sorted(child_copy, key=itemgetter(1))
			
			for item in sorted_child_copy:
				if item[0]==1:
					total_assets_in_child += 1
			if total_assets_in_child > K:
				for item in sorted_child_copy[:-K]:
					# C.index(item) = [0,0]
					C[C.index(item)] = [0,0]
			elif total_assets_in_child < K:
				while total_assets_in_child < K:
					if len(A_star) > 0:
						random_index = random.randint(0,len(A_star)-1)
						random_element = A_star.pop(random_index)
						C[random_element[0]-1] = [1, random_element[1]]
					else:
						random_index = random.randint(0,30)
						while C[random_index][0]==1:
							random_index = random.randint(0,30)
						C[random_index] = [1, 0]
					total_assets_in_child += 1
					
			#change the population by adding child to it
			obj_func_val_child = 0
			[obj_func_val_child, v_lambda, improved] = evaluate(C, _lambda, 0, v_lambda, False, improved_solutions, UPDATE_H)
			
			if improved:
				population[population_obj_func_vals.index(max(population_obj_func_vals))] = C
		
		print lambda_index

		outputs.append(evaluate(improved_solutions[-1], _lambda, 0, float('Inf'), False, None, FINAL_SAMPLE))

		H.append(improved_solutions)

	np_out_matrix = np.matrix(outputs)
	np_out_matrix = np_out_matrix.T
	outputs = np_out_matrix.tolist()

	f = open("out5.csv", "w")
	writer = csv.writer(f)
	for row in outputs:
		writer.writerow(tuple(row))
	f.close()
Example #19
0
def cxUniform(ind1, ind2, indpb):
    c1, c2 = tools.cxUniform(ind1, ind2, indpb)
    return (c1, c2)
Example #20
0
def crossoverAndMutation(problem, individuals):

    from copy import copy
    new_individuals = individuals

    if CULLING is True:
        count = 0
        new_crop = []

        # Format a population data structure usable by DEAP's package
        dIndividuals = deap_format(problem, individuals)

        while True:
            count += 1
            if count > 10 or len(dIndividuals) == 1 or len(new_crop) == len(individuals):
                break

            # Crossover
            for ind1, ind2 in zip(dIndividuals[::2], dIndividuals[1::2]):
                if random.random() <= 0.9: #crossover rate
                    tools.cxUniform(ind1, ind2, indpb=1.0/len(problem.decisions))

            # Mutation
            for ind in dIndividuals:
                temp = []
                tools.mutPolynomialBounded(ind, eta = 1.0, low=[dec.low for dec in problem.decisions], up=[dec.up for dec in problem.decisions], indpb=0.1 )
                del ind.fitness.values
                temp = problem.evaluate(ind)
                if temp[0] > jmoo_properties.CULLING_PD and temp[1] < jmoo_properties.CULLING_PF:
                    import numpy as np
                    test = np.array(ind).tolist()
                    # print "IND: ", ind
                    # print "TEST: ", test
                    if len(new_crop) != len(individuals):
                        new_crop = helper_list(new_crop, test)
                    # print ">> ", problem.evaluate(ind)



        print "NEW CROP: ", len(new_crop)
        for x in new_crop:
            if x in dIndividuals:
                dIndividuals.remove(x)
            else:
                dIndividuals.remove(random.choice(dIndividuals))
            for _ in xrange(1):
                print ">> ", problem.evaluate(x), x
        dIndividuals.extend(new_crop)
        print "Length : ", len(dIndividuals)

        # Update beginning population data structure
        for individual,dIndividual in zip(individuals, dIndividuals):
            for i in range(len(individual.decisionValues)):
                individual.decisionValues[i] = dIndividual[i]
                individual.fitness = None

        return individuals, len(individuals) * (count - 1)

    else:
        # Format a population data structure usable by DEAP's package
        dIndividuals = deap_format(problem, individuals)
        new_dIndividuals = []
        # print "Number of Individuals: ", len(dIndividuals)

        # Crossover
        for ind1, ind2 in zip(dIndividuals[::2], dIndividuals[1::2]):
            if random.random() <= 1: #crossover rate
                # print ".",
                ind1, ind2 = tools.cxUniform(ind1, ind2, indpb=1.0/len(problem.decisions))
                new_dIndividuals.append(ind1)
                new_dIndividuals.append(ind2)
            else:
                new_dIndividuals.append(ind1)
                new_dIndividuals.append(ind2)



        # Mutation
        for ind in new_dIndividuals:
            # print "+",
            tools.mutPolynomialBounded(ind, eta = 1.0, low=[dec.low for dec in problem.decisions], up=[dec.up for dec in problem.decisions], indpb=0.1 )
            del ind.fitness.values

        # Update beginning population data structure
        for individual, dIndividual in zip(new_individuals, new_dIndividuals):
            for i in range(len(individual.decisionValues)):
                individual.decisionValues[i] = dIndividual[i]
                individual.fitness = None


        return new_individuals,0
def main(epsilon, delta):
	global lambda_values
	global population_size
	global population
	global population_obj_func_vals
	global iterations

	outputs = []

	for lambda_index in range(1, number_of_lambdas+1):
		_lambda = float(lambda_index-1)/(number_of_lambdas-1)

		improved_solutions = []							#improved solutions for a particular lambda
		v_lambda = float('Inf')

		for i in range(1 , population_size+1):
			sample = [[0,0] for x in range(number_of_assets)]
			Q = random.sample([x for x in range(1, number_of_assets+1)],10)

			for asset in Q:
				sample[asset-1] = [1, myRandom(0,1)]
			
			population[i-1] = list(sample)

		for ind,S in enumerate(population):
			[population_obj_func_vals[ind], v_lambda, improved] = evaluate(S, _lambda, 0, v_lambda, False, improved_solutions, UPDATE_H)

		for itr in range(iterations):
			#binary tournament for selecting parents S_star and S_double_star
			chosen = []
			for i in xrange(2):
				aspirants = tools.selRandom(population, 40)
				for i,aspirant in enumerate(aspirants):
					h = []
					f_aspirant = 0
					v = float('Inf')
					imp = False
					[f_aspirant, v, imp] = evaluate(aspirant, _lambda, 0, v, False, h, DONT_UPDATE_H)
					aspirants[i] = [aspirant, f_aspirant]
					
				chosen.append(min(aspirants, key=lambda x: x[1])[0])
			
			S_star = list(chosen[0])
			S_double_star = list(chosen[1])
			
			#Uniform crossover to find child C
			C = []
			[C1, C2] = tools.cxUniform(S_star, S_double_star, ind_prob)
			f1 = f2 = 0
			v = float('Inf')
			imp = False
			h = []
			[f1, v, imp] = evaluate(C1, _lambda, 0, v, False, h, DONT_UPDATE_H)
			[f2, v, imp] = evaluate(C2, _lambda, 0, v, False, h, DONT_UPDATE_H)

			if f1<f2:
				C = C1
			else:
				C = C2

			#find assets in parents but not in child
			A_star = []
			for i in range(number_of_assets):
				if S_star[i][0]==1 and S_double_star[i][0]==0 and C[i][0]==0:
					A_star.append([i+1, S_star[i][1]])
				elif S_star[i][0]==0 and S_double_star[i][0]==1 and C[i][0]==0:
					A_star.append([i+1, S_double_star[i][1]])

			#Mutation
			mutation_index = random.randint(0, number_of_assets-1)
			while C[mutation_index][0]==0:
				mutation_index = random.randint(0, number_of_assets-1)
			m = random.randint(0,1)

			if m == 0:
				# C_i = 0.9*(epsilon + C[mutation_index][1]) - epsilon
				C_i = 0.9*(epsilon[mutation_index] + C[mutation_index][1]) - epsilon[mutation_index]
			else:
				# C_i = 1.1*(epsilon + C[mutation_index][1]) - epsilon
				C_i = 1.1*(epsilon[mutation_index] + C[mutation_index][1]) - epsilon[mutation_index]

			if C_i<0:
				C[mutation_index][0] = 0
				C[mutation_index][1] = 0

			#check if child contains more or less than K assets and fix it
			total_assets_in_child = 0
			child_copy = list(C)
			sorted_child_copy = sorted(child_copy, key=itemgetter(1))
			
			for item in sorted_child_copy:
				if item[0]==1:
					total_assets_in_child += 1
			if total_assets_in_child > K:
				for item in sorted_child_copy[:-K]:
					# C.index(item) = [0,0]
					C[C.index(item)] = [0,0]
			elif total_assets_in_child < K:
				while total_assets_in_child < K:
					if len(A_star) > 0:
						random_index = random.randint(0,len(A_star)-1)
						random_element = A_star.pop(random_index)
						C[random_element[0]-1] = [1, random_element[1]]
					else:
						random_index = random.randint(0,30)
						while C[random_index][0]==1:
							random_index = random.randint(0,30)
						C[random_index] = [1, 0]
					total_assets_in_child += 1
					
			#change the population by adding child to it
			obj_func_val_child = 0
			[obj_func_val_child, v_lambda, improved] = evaluate(C, _lambda, 0, v_lambda, False, improved_solutions, UPDATE_H)
			
			if improved:
				population[population_obj_func_vals.index(max(population_obj_func_vals))] = C
		
		print lambda_index

		outputs.append(evaluate(improved_solutions[-1], _lambda, 0, float('Inf'), False, None, FINAL_SAMPLE))

		H.append(improved_solutions)

	np_out_matrix = np.matrix(outputs)
	np_out_matrix = np_out_matrix.T
	outputs = np_out_matrix.tolist()

	f = open("out2.csv", "w")
	writer = csv.writer(f)
	for row in outputs:
		writer.writerow(tuple(row))
	f.close()
Example #22
0
    def cxUniform(self, ind1, ind2, indpb):
        for _ in range(100):
            c1, c2 = tools.cxUniform(ind1, ind2, indpb)

        return (c1, c2)
    img = (np.expand_dims(image_copy, 0))

    predictions = model.predict(img)
    print(np.argmax(predictions))
    print(test_labels[0])
    # Select the next generation individuals
    offspring = tools.selRoulette(pop, len(pop))
    # Clone the selected individuals
    offspring = list(map(toolbox.clone, offspring))

    # Apply crossover and mutation on the offspring
    for child1, child2 in zip(offspring[::2], offspring[1::2]):
        if np.random.random() < CXPB:
            fitness_child1 = child1.fitness.values[0]
            fitness_child2 = child2.fitness.values[0]
            tools.cxUniform(child1, child2, fitness_child1 / (fitness_child1 + fitness_child2))
            del child1.fitness.values
            del child2.fitness.values

    for mutant in offspring:
        if np.random.random() < MUTPB:
            operators.mutate(mutant, 0.5, DELTA)
            del mutant.fitness.values

    # Evaluate the individuals with an invalid fitness
    invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
    fitnesses = map(toolbox.evaluate, invalid_ind)
    for ind, fit in zip(invalid_ind, fitnesses):
        ind.fitness.values = fit

    pop[:] = offspring
    def crossover(self, individualA, individualB, pb):

        tools.cxUniform(individualA, individualB, pb)
Example #25
0
	def cxGIMME_Order(self, ind1, ind2):

		# configs
		config1 = ind1[0]
		config2 = ind2[0]

		newConfig1 = []
		newConfig2 = []

		l1 = len(config1)
		l2 = len(config2)

		if (l1 > l2):
			maxLenConfig = config1
			maxLen = l1
			minLenConfig = config2
			minLen = l2
		else:
			maxLenConfig = config2
			maxLen = l2
			minLenConfig = config1
			minLen = l1

		cxpoints = [] 
		
		clist1 = []
		clist2 = []

		remainder1 = []
		remainder2 = []
		for i in range(minLen):
			parent1 = minLenConfig[i]
			parent2 = maxLenConfig[i]

			cxpoint = random.randint(0,len(minLenConfig[i]))
			cxpoints.append(cxpoint) 

			clist1.extend(parent1)
			clist2.extend(parent2)

			remainder1.extend(parent1[cxpoint:])
			remainder2.extend(parent2[cxpoint:])


		d1 = {k:v for v,k in enumerate(clist1)}
		d2 = {k:v for v,k in enumerate(clist2)}

		remainder1.sort(key=d2.get)
		remainder2.sort(key=d1.get)

		for i in range(minLen):
			parent1 = minLenConfig[i]
			parent2 = maxLenConfig[i]

			cxpoint = cxpoints[i] 

			#C1 Implementation
			# maintain left part
			child1, child2 = parent1[:cxpoint], parent2[:cxpoint]


			# reorder right part
			missingLen1 = len(parent1) - len(child1)
			child1.extend(remainder1[:missingLen1])
			remainder1 = remainder1[missingLen1:]

			missingLen2 = len(parent2) - len(child2)
			child2.extend(remainder2[:missingLen2])
			remainder2 = remainder2[missingLen2:]

			newConfig1.append(child1)
			newConfig2.append(child2)


		#the inds become children
		ind1[0] = newConfig1
		ind2[0] = newConfig2

		# breakpoint()

		# profiles are crossed with one point (no need for that when profiles are 1D)
		# breakpoint()
		# if self.interactionsProfileTemplate.dimensionality > 1:
		for i in range(minLen):
			prof1 = ind1[1][i].flattened()
			prof2 = ind2[1][i].flattened()

			newProfiles = tools.cxUniform(prof1, prof2, 0.5)
			# newProfiles = tools.cxOnePoint(prof1, prof2)
			
			#the inds become children
			ind1[1][i] = self.interactionsProfileTemplate.unflattened(newProfiles[0])
			ind2[1][i] = self.interactionsProfileTemplate.unflattened(newProfiles[1])

			# breakpoint()

		del ind1.fitness.values
		del ind2.fitness.values

		return (ind1, ind2)
Example #26
0
    # SELECT WINNERS
    winners = toolbox.clone(winners)
    for w in winners:
        del w.fitness.values
        mutant = toolbox.clone(w)
        mutant = tools.mutGaussian(mutant, mu=0.0, sigma=0.1, indpb=0.2)
        pop_new.append(mutant[0])

    # SELECT RANDOM AND CROSSOVER
    rand = toolbox.clone(rand)
    for r in rand:
        del r.fitness.values
    rand1 = rand[:int((POP_SIZE * 0.5) / 2)]
    rand2 = rand[int((POP_SIZE * 0.5) / 2):]
    for r1, r2 in zip(rand1, rand2):
        child1, child2 = tools.cxUniform(r1, r2, 0.25)

        pop_new.append(child1)
        pop_new.append(child2)

    for n in new:
        pop_new.append(n)

    for p in pop_new:
        if not p.fitness.values:
            p.fitness.values = evaluate(p, fin_list)

    pop[:] = pop_new
    HoF.update(pop)

    del pop_new
def crossover_main(ind1, ind2, indpb, column_names, heating_unit_names_share,
                   cooling_unit_names_share, column_names_buildings_heating,
                   column_names_buildings_cooling, district_heating_network,
                   district_cooling_network):
    # create dict of individual with his/her name
    ind1_with_name_dict = dict(zip(column_names, ind1))
    ind2_with_name_dict = dict(zip(column_names, ind2))

    if district_heating_network:

        # MUTATE BUILDINGS CONNECTED
        buildings_heating_ind1 = [
            ind1_with_name_dict[column]
            for column in column_names_buildings_heating
        ]
        buildings_heating_ind2 = [
            ind2_with_name_dict[column]
            for column in column_names_buildings_heating
        ]
        # apply crossover
        buildings_heating_ind1, buildings_heating_ind2 = tools.cxUniform(
            buildings_heating_ind1, buildings_heating_ind2, indpb)
        # take back to the individual
        for column, cross_over_value in zip(column_names_buildings_heating,
                                            buildings_heating_ind1):
            ind1_with_name_dict[column] = cross_over_value
        for column, cross_over_value in zip(column_names_buildings_heating,
                                            buildings_heating_ind2):
            ind2_with_name_dict[column] = cross_over_value

        # MUTATE SUPPLY SYSTEM UNITS SHARE
        heating_units_share_ind1 = [
            ind1_with_name_dict[column] for column in heating_unit_names_share
        ]
        heating_units_share_ind2 = [
            ind2_with_name_dict[column] for column in heating_unit_names_share
        ]
        # apply crossover
        heating_units_share_ind1, heating_units_share_ind2 = tools.cxUniform(
            heating_units_share_ind1, heating_units_share_ind2, indpb)
        # takeback to the individual
        for column, cross_over_value in zip(heating_unit_names_share,
                                            heating_units_share_ind1):
            ind1_with_name_dict[column] = cross_over_value
        for column, cross_over_value in zip(heating_unit_names_share,
                                            heating_units_share_ind2):
            ind2_with_name_dict[column] = cross_over_value

    if district_cooling_network:

        # CROSSOVER BUILDINGS CONNECTED
        buildings_cooling_ind1 = [
            ind1_with_name_dict[column]
            for column in column_names_buildings_cooling
        ]
        buildings_cooling_ind2 = [
            ind2_with_name_dict[column]
            for column in column_names_buildings_cooling
        ]
        # apply crossover
        buildings_cooling_ind1, buildings_cooling_ind2 = tools.cxUniform(
            buildings_cooling_ind1, buildings_cooling_ind2, indpb)
        # take back to teh individual
        for column, cross_over_value in zip(column_names_buildings_cooling,
                                            buildings_cooling_ind1):
            ind1_with_name_dict[column] = cross_over_value
        for column, cross_over_value in zip(column_names_buildings_cooling,
                                            buildings_cooling_ind2):
            ind2_with_name_dict[column] = cross_over_value

        # CROSSOVER SUPPLY SYSTEM UNITS SHARE
        cooling_units_share_ind1 = [
            ind1_with_name_dict[column] for column in cooling_unit_names_share
        ]
        cooling_units_share_ind2 = [
            ind2_with_name_dict[column] for column in cooling_unit_names_share
        ]
        # apply crossover
        cooling_units_share_ind1, cooling_units_share_ind2 = tools.cxUniform(
            cooling_units_share_ind1, cooling_units_share_ind2, indpb)
        # takeback to teh individual
        for column, cross_over_value in zip(cooling_unit_names_share,
                                            cooling_units_share_ind1):
            ind1_with_name_dict[column] = cross_over_value
        for column, cross_over_value in zip(cooling_unit_names_share,
                                            cooling_units_share_ind2):
            ind2_with_name_dict[column] = cross_over_value

    # now validate individual
    # now validate individual
    ind1_with_name_dict = validation_main(ind1_with_name_dict,
                                          column_names_buildings_heating,
                                          column_names_buildings_cooling,
                                          district_heating_network,
                                          district_cooling_network)

    ind2_with_name_dict = validation_main(ind2_with_name_dict,
                                          column_names_buildings_heating,
                                          column_names_buildings_cooling,
                                          district_heating_network,
                                          district_cooling_network)

    # now pass all the values mutated to the original individual
    for i, column in enumerate(column_names):
        ind1[i] = ind1_with_name_dict[column]

    for i, column in enumerate(column_names):
        ind2[i] = ind2_with_name_dict[column]

    return ind1, ind2