classEA: def__init__(self, placer, X=None,fit=0): self.placer = placer if X isNone: self.x = np.random.randint(self.placer.lb, self.placer.ub + 1, self.placer.dim) else: self.x = X self.fit = fit defeval(self,bestfit): self.fit = self.placer._evaluate(self.x)
设计EA类,用于存储单个个体的所有信息。
1 2 3 4 5 6 7 8 9
n = 10 EAs = [] comp = [0for _ inrange(bbo_placer.dim)] for _ inrange(n): ea = EA(placer=bbo_placer) ea.eval(comp) EAs.append(ea) EA_run(n,EAs,args.max_iteration)
defEA_run(n,EAs,max_iteration): p1 = 1/15 p2 = 1 for _ inrange(max_iteration): max_fit = max([i.fit for i in EAs]) total_fit = max_fit * 1.001 * n - sum([i.fit for i in EAs]) prob = [(max_fit * 1.001 - i.fit) / total_fit for i in EAs] print(prob)
if random.random() < p2: EA_p3 = Deepcopy(EA_p1) for i inrange(EA_p3.placer.dim): if random.random() < 0.5: EA_p3.x[i]=EA_p2.x[i] EA_p3.eval(EAs[0].x) EAs.append(EA_p3) prob.append(0)
for i inrange(EA_p1.placer.dim): if random.random() < p1: EA_p1.x[i] = np.random.randint(EA_p1.placer.lb, EA_p1.placer.ub+1)[0] if random.random() < p1: EA_p2.x[i] = np.random.randint(EA_p1.placer.lb, EA_p1.placer.ub+1)[0] EA_p1.eval(EAs[0].x) EAs.append(EA_p1) prob.append(0) EA_p2.eval(EAs[0].x) EAs.append(EA_p2) prob.append(0)
defeval(self,bestfit): self.fit = self.placer._evaluate(self.x) print(self.fit) sum=0 kg=1 for i inrange(len(self.x)): if self.x[i]==bestfit[i]: sum+=1 else: kg=0 if kg==1: return self.fit+=sum*5e3
for __ inrange(1): EA_p1.Deepcopy(random.choices(EA1)[0]) EA_p2.Deepcopy(random.choices(EA3)[0]) if random.random() < p2: EA_p3.Deepcopy(EA_p1) for i inrange(EA_p3.placer.dim): if random.random() < 0.5: EA_p3.x[i]=EA_p2.x[i] EA_p3.eval() EA1.append(EA_p3) EA_p1.Deepcopy(random.choices(EA2)[0]) EA_p2.Deepcopy(random.choices(EA4)[0]) if random.random() < p2: EA_p3.Deepcopy(EA_p1) for i inrange(EA_p3.placer.dim): if random.random() < 0.5: EA_p3.x[i]=EA_p2.x[i] EA_p3.eval() EA2.append(EA_p3) EA_p1.Deepcopy(random.choices(EA3)[0]) EA_p2.Deepcopy(random.choices(EA2)[0]) if random.random() < p2: EA_p3.Deepcopy(EA_p1) for i inrange(EA_p3.placer.dim): if random.random() < 0.5: EA_p3.x[i]=EA_p2.x[i] EA_p3.eval() EA3.append(EA_p3) EA_p1.Deepcopy(random.choices(EA4)[0]) EA_p2.Deepcopy(random.choices(EA1)[0]) if random.random() < p2: EA_p3.Deepcopy(EA_p1) for i inrange(EA_p3.placer.dim): if random.random() < 0.5: EA_p3.x[i]=EA_p2.x[i] EA_p3.eval() EA4.append(EA_p3)
for i in EA1: print("EA1",i.fit,"-->",i.x) for i in EA2: print("EA2",i.fit,"-->",i.x) for i in EA3: print("EA3",i.fit,"-->",i.x) for i in EA4: print("EA4",i.fit,"-->",i.x)