def ga_opt(self, max_=False): if not max_: ga = GA(func=self.func, n_dim=len(self.lb), size_pop=50, max_iter=int(self.repeaT), lb=self.lb, ub=self.ub, constraint_eq=self.eq_ls, constraint_ueq=self.ueq_ls, precision=1e-5) self.best_x, self.best_y = ga.run() elif max_: ga = GA(func=-self.func, n_dim=len(self.lb), size_pop=50, max_iter=int(self.repeaT), lb=self.lb, ub=self.ub, constraint_eq=self.eq_ls, constraint_ueq=self.ueq_ls, precision=1e-5) self.best_x, self.best_y = ga.run() self.best_y = -self.best_y
def fit_ga(self, y0, E, I, R, n): self.parameter = [E, I, R, y0] self.y0 = y0 if n == 4: ga = GA(func=self.loss_function_ga, n_dim=4, size_pop=50, max_iter=300, lb=[0, 0, 0, 0], ub=[1, 1, 1, 1]) elif n == 2: ga = GA(func=self.loss_function_ga_2, n_dim=2, size_pop=50, max_iter=300, lb=[0, 0], ub=[1, 1]) # 遗传算法求解 best_x, best_y = ga.run() if n == 4: alpha, beta1, beta2, gamma2 = best_x[0], best_x[1], best_x[ 2], best_x[3] return alpha, beta1, beta2, gamma2 elif n == 2: alpha, gamma2 = best_x[0], best_x[1] return alpha, gamma2
def trainab(model_name, dataset_name, iter_num): # init T,R,SP T = getSGGRes(model_name, dataset_name, "train", tasktype) R = getGT(model_name, dataset_name, "train", tasktype) SP, N = getPfromR(R, dataset_name) print("T info: ", len(T), len(T[0]), T[0][0]) print("R info: ", len(R), len(R[0]), R[0][0]) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") dd = 1e23 # start iteration for i in range(iter_num): ga = GA(func=fitness, n_dim=2, size_pop=10, max_iter=50, \ lb=[0.0, 0.0], ub=[dd, dd], precision=1e-7) #ga = GA(func=fitness, n_dim=2, size_pop=10, max_iter=4, \ # lb=[0.0, 0.0], ub=[dd, dd], precision=1e-7) ga.to(device=device) #GPU best_x, best_y = ga.run() # best_x={alpha,beta},best_y=Q-R alpha, beta = best_x print('iteration ', i, ': best alpha and beta: ', alpha, beta) print('best_y:', best_y) if best_y == 0: print('best {alpha,beta}:', best_x, 'best_y', best_y) end_cnt = fitness(best_x) print("detect if zeros: ", end_cnt) if end_cnt == 0: break else: R = ReSet(alpha, beta) SP, _ = getPfromR(R, dataset_name) return best_x
def fit2(self): # ga_beta = GA(func=self.loss_function2_beta, n_dim=2, size_pop=50, max_iter=1000, lb=[0, 0], ub=[1, 1], precision=1e-7) # ga_gamma = GA(func=self.loss_function2_gamma, n_dim=2, size_pop=50, max_iter=1000, lb=[0, 0], ub=[1, 1], precision=1e-7) # best_x_beta, best_y = ga_beta.run() # best_x_gamma, best_y = ga_gamma.run() ga = GA(func=self.loss_function2, n_dim=2, size_pop=50, max_iter=3000, lb=[0, 0], ub=[1, 1], precision=1e-7) best_x, best_y = ga.run() # self.__beta = best_x_beta[0] # self.__gamma = best_x_gamma[1] self.__beta = best_x[0] self.__gamma = best_x[1] print('best_x:', best_x)
def reg_time(args): #假设TEST_TIME为100 #总运行次数小于T1(比如200)时,运行次数就是运行次数 #总运行次数大于T1(比如200)时,计算运行次数乘以TEST_TIME/实际运行次数与T2的调和平均数 #这里T1代表了实际最大运算次数,T2代表了计算结果的最大重算次数 kind, f, p_min = args print(".", end="") res_ary = [1e+500] if kind == "de": de = DE(func=f, n_dim=DIM, lb=LB, ub=UB, max_iter=ITER // 2, size_pop=POP) time_de = 0 while res_ary[-1] > p_min + MIN_PRECISION: if len(res_ary) > STOP_ITER_TIME and res_ary[ -STOP_ITER_TIME] - res_ary[-1] < CALC_PRECISION: return (False, time_de - STOP_ITER_TIME) _, temp_de = de.run() res_ary.append(temp_de[0]) time_de += 1 return (True, time_de) if kind == "ga": ga = GA(func=f, n_dim=DIM, lb=LB, ub=UB, max_iter=ITER, size_pop=POP, precision=1e-200) time_ga = 0 while res_ary[-1] > p_min + MIN_PRECISION: if len(res_ary) > STOP_ITER_TIME and res_ary[ -STOP_ITER_TIME] - res_ary[-1] < CALC_PRECISION: return (False, time_ga - STOP_ITER_TIME) _, temp_ga = ga.run() res_ary.append(temp_ga[0]) time_ga += 1 return (True, time_ga) if kind == "pso": pso = PSO(func=f, dim=DIM, pop=POP, max_iter=ITER, lb=LB, ub=UB) time_pso = 0 while res_ary[-1] > p_min + MIN_PRECISION: if len(res_ary) > STOP_ITER_TIME and res_ary[ -STOP_ITER_TIME] - res_ary[-1] < CALC_PRECISION: return (False, time_pso - STOP_ITER_TIME) pso.run() res_ary.append(pso.gbest_y) time_pso += 1 return (True, time_pso)
def trainabGA(model_name,dataset_name,iter_num): # init T,R,SP T = getSGGRes(model_name,dataset_name,"train",tasktype) R = getGT(model_name,dataset_name,"train",tasktype) SP,N = getPfromR(R,dataset_name) print("T info: ",len(T),len(T[0]),T[0][0]) print("R info: ",len(R),len(R[0]),R[0][0]) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # start iteration low = [0.0,0.0] high = [1e6,1e6] for i in range(iter_num): #ga = GA(func=fitness, n_dim=2, size_pop=4, max_iter=10, \ # lb=[0.0, 0.0], ub=[1.0, 1.0], precision=1e-7) #ga = GA(func=fitness, n_dim=2, size_pop=6, max_iter=50, \ # lb=low, ub=high, precision=1e-7) #ga = GA(func=fitness, n_dim=2, size_pop=50, max_iter=50, \ # lb=low, ub=high, precision=1e-7) ga = GA(func=fitnessNDCG, n_dim=2, size_pop=100, max_iter=100, \ lb=low, ub=high, precision=1e-7) ga.register(operator_name='selection', operator=selection_tournament, tourn_size=3).\ register(operator_name='ranking', operator=ranking.ranking). \ register(operator_name='crossover', operator=crossover.crossover_2point). \ register(operator_name='mutation', operator=mutation.mutation) ga.to(device=device) #GPU start_time = time.time() best_x, best_y = ga.run()# best_x={alpha,beta},best_y=Q-R print("run time: ",time.time() - start_time) alpha, beta = best_x print('iteration ',i,': best alpha and beta: ', alpha,beta) print('best_y:', best_y) print("sum_ndcg: ",-best_y-0.5*(alpha**2+beta**2)) if best_y==0: print('best {alpha,beta}:',best_x,'best_y',best_y) end_cnt = fitnessNDCG(best_x) print("detect if zeros: ",end_cnt) if end_cnt==0: break else: #R = ReSet(alpha,beta) R = addsmallNDCG(alpha,beta,R) SP,_ = getPfromR(R,dataset_name) cnt_now=fitness(best_x) print(i," iter :", cnt_now) return best_x
class EvolutionarySearch: def __init__(self, env, pop_size=100, genotype_size=61, lb=-1, ub=1, max_iter=100, init=None): self.env = env global E E = env #The evolutionary search object self.ga = GA(func=EvaluateGenome, n_dim=genotype_size, size_pop=pop_size, max_iter=max_iter, lb=lb, ub=ub, precision=1e-7) if init is not None: self.ga.Chrom = init def calc_genotype(self, pheno_dict): genotype_length = 0 for key in pheno_dict: genotype_length += len(pheno_dict[key]) return genotype_length def run(self, increments=10): total_its = self.ga.max_iter // increments for i in range(total_its): best_x, best_y = self.ga.run(max_iter=increments) gen = (i + 1) * increments print(f'Generation: {gen}') print('best_x:', best_x, '\n', 'best_y:', best_y) # %% Plot the result Y_history = pd.DataFrame(self.ga.all_history_Y) fig, ax = plt.subplots(2, 1) ax[0].plot(Y_history.index, Y_history.values, '.', color='red') Y_history.min(axis=1).cummin().plot(kind='line') plt.show() fig.savefig('./evo_run.pdf') Y_history.to_pickle("Run_history.pkl") return best_x
def GAmethod(max_iter=50, size_pop=500): lb = lb ub = ub ga = GA(func=calculEffFunc, n_dim=5, size_pop=size_pop, max_iter=max_iter, lb=lb, ub=ub, precision=1e-7, prob_mut=prob_mut) #只求解最小值 best_x, best_y = ga.run() Y_history = ga.all_history_Y return best_x, best_y, Y_history, ga.generation_best_Y
def findWay(tryNum): # 找从起点移动tryNum步距终点最近的路径 lBoundary = [] # 存自变量下界 uBoundary = [] # 存自变量上界 precisions = [] # 存自变量精度 for i in range(tryNum): # 0,1,2,3代表四个方向,从0到3,精度为1 lBoundary.append(0) uBoundary.append(3) precisions.append(1) ga = GA(func=demo_func, n_dim=tryNum, size_pop=150, max_iter=1000, lb=lBoundary, ub=uBoundary, precision=precisions) return ga.run()
def GA_CAV_included_best_UE(control_portion): constraint_ueq = [ lambda x: sum(x) - 5 * control_portion, ] # ga = SA(func=CAV_UE, x0=[0]*15, n_dim=15, size_pop=50, max_iter=200, lb=[0]*15, ub=[5]*15, precision=1e-7, constraint_eq=constraint_eq) # ga = PSO(func=CAV_UE, n_dim=15, size_pop=50, max_iter=200, lb=[0]*15, ub=[5]*15, precision=1e-7, constraint_eq=constraint_eq) set_run_mode(CAV_UE, 'multiprocessing') ga = GA(func=CAV_UE, n_dim=2, size_pop=50, max_iter=800, lb=[0] * 2, ub=[5 * control_portion] * 2, precision=1e-5, constraint_ueq=constraint_ueq) best_x, best_y = ga.run() print('best_x:', best_x, '\n', 'best_y:', best_y) return best_y
def GAmethod(max_iter=50): start_time = datetime.now() ga = GA(func=finallFunction, n_dim=5, size_pop=size_pop, max_iter=max_iter, lb=lb, ub=ub, prob_mut=prob_mut) #只求解最小值 end_time = datetime.now() print('Itreation numbers is {}, weight is '.format(max_iter) + str(weight) + ' using time is {}'.format((end_time - start_time).total_seconds())) best_x, best_y = ga.run() Y_history = ga.all_history_Y tm = time.localtime(time.time()) tm_str = '{}-{}-{} {}:{}:{} '.format(tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]) with open(r'GArecordHistory_Y.txt', 'a') as f: for yh in ga.all_history_Y: f.write(str(yh)[1:-1] + '\n\n') with open(r'GAbestPredictCircuit.txt', 'a') as f: f.write(tm_str + 'GA algorithm iteration number is {} best Predict Circuit is '. format(max_iter) + str(bestPredictCircuit)[1:-1] + ' using time is {}'.format((end_time - start_time).total_seconds()) + '\n') with open(r'GAbestStructure.txt', 'a') as f: f.write( tm_str + 'GA algorithm iteration number is {}, weight is {} best Structure is ' .format(max_iter, weight) + str(best_x)[1:-1] + ' ' + 'Best result is ' + str(bestPredictCircuit[0] - bestPredictCircuit[1] + bestPredictCircuit[2] - bestPredictCircuit[3]) + '\n') return best_x, best_y, Y_history, ga
def _calT(): def obj_func(p): x1, x2 = p return np.abs(r[kx, ky, 1] - x1 - x2 + r[kx - 1, ky, 0]) if r[kx, ky + 1, 1] == NaN: constraint_ueq = [lambda x: np.abs(r[kx, ky, 1] - x[0]) - 0.1] ga = GA(func=obj_func, n_dim=2, size_pop=popsize, max_iter=maxiter, lb=[0, -r[kx - 1, ky + 1, 2]], ub=[r[kx, ky + 1, 2] + prec, r[kx - 1, ky + 1, 2] + prec], precision=[prec, prec], constraint_ueq=constraint_ueq) else: constraint_ueq = [ lambda x: np.abs(r[kx, ky, 0] - x[0]) - 0.1, lambda x: np.abs(r[kx - 1, ky, 1] - x[1]) - 0.1, ] constraint_eq = [ lambda x: r[kx, ky + 1, 2]**2 - r[kx, ky + 1, 1]**2 - x[0]**2 ] ga = GA(func=obj_func, n_dim=2, size_pop=popsize, max_iter=maxiter, lb=[0, -r[kx - 1, ky + 1, 2]], ub=[r[kx, ky + 1, 2] + prec, r[kx - 1, ky + 1, 2] + prec], precision=[prec, prec], constraint_eq=constraint_eq, constraint_ueq=constraint_ueq) best_x, _ = ga.run() r[kx, ky + 1, 0] = best_x[0] r[kx - 1, ky + 1, 1] = best_x[1] return
x1, x2 = p x = np.square(x1) + np.square(x2) return 0.5 + (np.square(np.sin(x)) - 0.5) / np.square(1 + 0.001 * x) your_class = YourClass() set_run_mode(your_class.obj_func2, 'vectorization') set_run_mode(your_class.obj_func3, 'parallel') ga1 = GA(func=your_class.obj_func1, n_dim=2, size_pop=10, max_iter=5, lb=[-1, -1], ub=[1, 1], precision=1e-7) ga2 = GA(func=your_class.obj_func2, n_dim=2, size_pop=10, max_iter=5, lb=[-1, -1], ub=[1, 1], precision=1e-7) ga3 = GA(func=your_class.obj_func3, n_dim=2, size_pop=10, max_iter=5, lb=[-1, -1], ub=[1, 1], precision=1e-7) start_time = datetime.datetime.now() best_x, best_y = ga1.run() print('common mode, time costs: ', (datetime.datetime.now() - start_time).total_seconds()) start_time = datetime.datetime.now() best_x, best_y = ga2.run() print('vector mode, time costs: ', (datetime.datetime.now() - start_time).total_seconds()) start_time = datetime.datetime.now() best_x, best_y = ga3.run() print('parallel mode, time costs: ', (datetime.datetime.now() - start_time).total_seconds()) # %% set_run_mode(your_class.obj_func4_2, 'cached') ga4_1 = GA(func=your_class.obj_func4_1, n_dim=2, size_pop=6, max_iter=10, lb=[-2, -2], ub=[2, 2], precision=1) ga4_2 = GA(func=your_class.obj_func4_2, n_dim=2, size_pop=6, max_iter=10, lb=[-2, -2], ub=[2, 2], precision=1)
ga = GA(func=func, n_dim=2, size_pop=50, max_iter=1, precision=1e-5,lb=[-3.5,4.1], ub=[12.1,5.8]) b1=np.array([-3.5,4.1]) b2=np.array([12.1,5.8]) ga1 = GA(func=func, n_dim=2, size_pop=50, max_iter=1, precision=1e-5,lb=[-3.5,4.1], ub=[12.1,5.8]) fk1=[] fk2=[] fk3=[] fk4=[] coll_t1=[] coll_t2=[] for i in range(60): best_x, best_y = ga.run(1) best_11, best_12 = ga1.run(1) print(best_y) print(best_12) t1=ga.X t2=ga.Y if i<11: coll_t1.append(t1) coll_t2.append(t2) else: best_model=prn.train_LM(t2.T,t1.T,best_model,verbose=False,k_max=10,E_stop=1e-8) if i==10: t1=np.array(coll_t1).reshape(-1,2).T t2=np.array(coll_t2).reshape(-1,1).T np.savetxt('t1',t1)
# 计算预测结果 def f_fun(x, a, b, c, d): return a * x**3 + b * x**2 + c * x + d # 计算loss def obj_fun(p): a, b, c, d = p # 计算残差 loss loss = np.square(f_fun(x_true, a, b, c, d) - y_true).sum() return loss # 使用 scikit-opt 做最优化 ga = GA(func=obj_fun, n_dim=4, size_pop=100, max_iter=500, lb=[-2] * 4, ub=[2] * 4) best_params, loss = ga.run() print('best_x:', best_params, '\n', 'best_y:', loss) # 画出拟合效果图 # 得到预测值 y_predict = f_fun(x_true, *best_params) fig, ax = plt.subplots() ax.plot(x_true, y_true, 'o') ax.plot(x_true, y_predict, '-') plt.show()
def P_min(f): other_mins = [] de = DE(func=f, n_dim=DIM, lb=LB, ub=UB, max_iter=ITER // 2, size_pop=POP) ga = GA(func=f, n_dim=DIM, lb=LB, ub=UB, max_iter=ITER, size_pop=POP, precision=1e-200) pso = PSO(func=f, dim=DIM, pop=POP, max_iter=ITER, lb=LB, ub=UB) _, e_de = de.run() e_de = e_de[0] _, e_ga = ga.run() e_ga = e_ga[0] pso.run() e_pso = pso.gbest_y time_de, time_ga, time_pso = 0, 0, 0 cnt = 0 while True: de_x, temp_de = de.run() temp_de = temp_de[0] time_de = time_de + 1 if e_de - temp_de < CALC_PRECISION else 0 e_de = temp_de ga_x, temp_ga = ga.run() temp_ga = temp_ga[0] time_ga = time_ga + 1 if e_ga - temp_ga < CALC_PRECISION else 0 e_ga = temp_ga pso.run() time_pso = time_pso + 1 if e_pso - pso.gbest_y < CALC_PRECISION else 0 e_pso = pso.gbest_y res = sorted([[e_de, time_de, de_x], [e_ga, time_ga, ga_x], [e_pso, time_pso, pso.gbest_x]], key=lambda x: x[0]) if res[1][0] - res[0][0] < CALC_PRECISION and res[0][ 1] > STOP_ITER_TIME: return (res[0][0], res[0][2]) if res[0][1] > STOP_ITER_TIME and res[1][1] > STOP_ITER_TIME and res[ 2][1] > STOP_ITER_TIME: other_mins.append((res[0][0], res[0][2])) if len(other_mins) == 10: return min(other_mins, key=lambda x: x[0]) res = [] de = DE(func=f, n_dim=DIM, lb=LB, ub=UB, max_iter=ITER // 2, size_pop=POP) ga = GA(func=f, n_dim=DIM, lb=LB, ub=UB, max_iter=ITER, size_pop=POP, precision=1e-200) pso = PSO(func=f, dim=DIM, pop=POP, max_iter=ITER, lb=LB, ub=UB) de_x, e_de = de.run() e_de = e_de[0] ga_x, e_ga = ga.run() e_ga = e_ga[0] pso.run() e_pso = pso.gbest_y time_de, time_ga, time_pso = 0, 0, 0
costly_function() x1, x2 = p x = np.square(x1) + np.square(x2) return 0.5 + (np.square(np.sin(x)) - 0.5) / np.square(1 + 0.001 * x) for mode in ('common', 'multithreading', 'multiprocessing'): set_run_mode(obj_func, mode) ga = GA(func=obj_func, n_dim=2, size_pop=10, max_iter=5, lb=[-1, -1], ub=[1, 1], precision=1e-7) start_time = datetime.datetime.now() best_x, best_y = ga.run() print( 'on {task_type} task,use {mode} mode, costs {time_costs}s'.format( task_type=task_type, mode=mode, time_costs=(datetime.datetime.now() - start_time).total_seconds())) # to use the vectorization mode, the function itself should support the mode. mode = 'vectorization' def obj_func2(p): costly_function() x1, x2 = p[:, 0], p[:, 1] x = np.square(x1) + np.square(x2) return 0.5 + (np.square(np.sin(x)) - 0.5) / np.square(1 + 0.001 * x)
lambda x: np.sum(x[:, 0]), lambda x: np.sum(x[:, -1]) - 1, lambda x: np.sum(x[-1, :]), ] constraint_ueq = [ lambda x: np.sum(x, axis=1) - 1, lambda x: np.sum(x, axis=0) - 1, ] # # demo_func = lambda x: -(x[0] * 4000 + x[1]* 3000)##目标函数是求最小值 # #约束条件小于等于0是满足 # constraint_ueq=[ # lambda x:2*x[0]+x[1]-10, # lambda x:x[0]+x[1]-8, # lambda x:x[1]-7, # # lambda x:-x[0], # # lambda x:-x[1], # ] ga = GA(func=demo_func, n_dim=(10, 10), constraint_ueq=constraint_ueq, max_iter=500, lb=[0] * 100, ub=[1] * 100, precision=[1] * 100) res = ga.run() # print('best_x:', best_x, '\n', 'best_y:', best_y) print(res)
lb = [-10] * n_dim ub = [10] * n_dim # lb = [0] * n_dim # ub = [10] * n_dim # %% sko GA optimizer np.random.seed(SEED) skoga = GA(func=lambda x: -func(x)[0] if func == ode_loss_func else -func(x), n_dim=n_dim, size_pop=n_pop, max_iter=n_iter, prob_mut=0.05, lb=lb, ub=ub, precision=1e-5) sko_best_x, sko_best_y = skoga.run() Y_history = pd.DataFrame(skoga.all_history_Y) # %% Self defined GA optimizer np.random.seed(SEED) ga_opt = GAOPT( func=func, n_dim=n_dim, n_iter=n_iter, n_pop=n_pop, pcr=0.9, pm=0.01, lb=lb, ub=ub, precision=1e-5, sel="Tournament",
def gaRun(): # 调用遗传算法库得到解 ga = GA(func=demo_func, n_dim=clickNum, size_pop=size_pop, max_iter=max_iter, lb=[0]*clickNum, ub=[pNum-1]*clickNum, precision=[1]*clickNum) return ga.run()
from sko.GA import GA demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2 ga = GA(func=demo_func, n_dim=3, max_iter=500, lb=[-1, -10, -5], ub=[2, 10, 2]) best_x, best_y = ga.run() print('best_x:', best_x, '\n', 'best_y:', best_y) import pandas as pd import matplotlib.pyplot as plt Y_history = ga.all_history_Y Y_history = pd.DataFrame(Y_history) fig, ax = plt.subplots(3, 1) ax[0].plot(Y_history.index, Y_history.values, '.', color='red') plt_mean = Y_history.mean(axis=1) plt_max = Y_history.min(axis=1) ax[1].plot(plt_mean.index, plt_mean, label='mean') ax[1].plot(plt_max.index, plt_max, label='min') ax[1].set_title('mean and all Y of every generation') ax[1].legend() ax[2].plot(plt_max.index, plt_max.cummin()) ax[2].set_title('best fitness of every generation') plt.show()
def _calE(): # ============== def obj_func1(p): x1, = p assert r[zeroP[0] + border, zeroP[1] - border, 0] != NaN, "obj_func1 is NaN" assert r[zeroP[0] + border + 1, zeroP[1] - border, 1] != NaN, "obj_func1 is NaN" assert r[zeroP[0] + border, zeroP[1] - border - 1, 1] != NaN, "obj_func1 is NaN" return np.abs(r[zeroP[0] + border, zeroP[1] - border, 0] - r[zeroP[0] + border + 1, zeroP[1] - border, 1] - x1 + r[zeroP[0] + border, zeroP[1] - border - 1, 1]) def obj_func2(p): x1, x2, x3 = p assert r[zeroP[0] + border, zeroP[1] - border, 1] != NaN, "obj_func2 is NaN" return np.abs(-r[zeroP[0] + border, zeroP[1] - border, 1] + x1 + x2 - x3) constraint_eq1 = [ lambda x: r[zeroP[0] + border, zeroP[1] - border - 1, 2]**2 - r[ zeroP[0] + border, zeroP[1] - border - 1, 1]**2 - x[0]**2, lambda x: r[zeroP[0] + border + 1, zeroP[1] - border - 1, 2]**2 - r[zeroP[0] + border + 1, zeroP[1] - border - 1, 0]**2 - x[1]**2, lambda x: r[zeroP[0] + border + 1, zeroP[1] - border, 2]**2 - r[ zeroP[0] + border + 1, zeroP[1] - border, 1]**2 - x[2]**2 ] ga = GA(func=obj_func1, n_dim=1, size_pop=popsize, max_iter=maxiter, lb=0, ub=r[zeroP[0] + border + 1, zeroP[1] - border - 1, 2] + prec, precision=prec) best_x, _ = ga.run() r[zeroP[0] + border + 1, zeroP[1] - border - 1, 0] = best_x[0] ga = GA(func=obj_func2, n_dim=3, size_pop=popsize, max_iter=maxiter, lb=[0, -r[zeroP[0] + border + 1, zeroP[1] - border - 1, 2], 0], ub=[ r[zeroP[0] + border, zeroP[1] - border - 1, 2] + prec, r[zeroP[0] + border + 1, zeroP[1] - border - 1, 2] + prec, r[zeroP[0] + border + 1, zeroP[1] - border, 2] + prec ], precision=[prec, prec, prec], constraint_eq=constraint_eq1) best_x, _ = ga.run() r[zeroP[0] + border, zeroP[1] - border - 1, 0] = best_x[0] r[zeroP[0] + border + 1, zeroP[1] - border - 1, 1] = best_x[1] r[zeroP[0] + border + 1, zeroP[1] - border, 0] = best_x[2] # ============== def obj_func3(p): x1, = p assert r[zeroP[0] + border, zeroP[1] + border, 1] != NaN, "obj_func3 is NaN" assert r[zeroP[0] + border, zeroP[1] + border + 1, 0] != NaN, "obj_func3 is NaN" assert r[zeroP[0] + border + 1, zeroP[1] + border, 0] != NaN, "obj_func3 is NaN" return np.abs(r[zeroP[0] + border, zeroP[1] + border, 1] + r[zeroP[0] + border, zeroP[1] + border + 1, 0] - x1 - r[zeroP[0] + border + 1, zeroP[1] + border, 0]) def obj_func4(p): x1, x2, x3 = p assert r[zeroP[0] + border, zeroP[1] + border, 0] != NaN, "obj_func4 is NaN" return np.abs(r[zeroP[0] + border, zeroP[1] + border, 0] + x1 - x2 - x3) constraint_eq2 = [ lambda x: r[zeroP[0] + border + 1, zeroP[1] + border, 2]**2 - r[ zeroP[0] + border + 1, zeroP[1] + border, 0]**2 - x[0]**2, lambda x: r[zeroP[0] + border + 1, zeroP[1] + border + 1, 2]**2 - r[zeroP[0] + border + 1, zeroP[1] + border + 1, 1]**2 - x[1]**2, lambda x: r[zeroP[0] + border, zeroP[1] + border + 1, 2]**2 - r[ zeroP[0] + border, zeroP[1] + border + 1, 0]**2 - x[2]**2 ] ga = GA(func=obj_func3, n_dim=1, size_pop=popsize, max_iter=maxiter, lb=-r[zeroP[0] + border + 1, zeroP[1] + border + 1, 2], ub=r[zeroP[0] + border + 1, zeroP[1] + border + 1, 2] + prec, precision=prec) best_x, _ = ga.run() r[zeroP[0] + border + 1, zeroP[1] + border + 1, 1] = best_x[0] ga = GA(func=obj_func4, n_dim=3, size_pop=popsize, max_iter=maxiter, lb=[ -r[zeroP[0] + border + 1, zeroP[1] + border, 2], 0, -r[zeroP[0] + border, zeroP[1] + border + 1, 2] ], ub=[ r[zeroP[0] + border + 1, zeroP[1] + border, 2] + prec, r[zeroP[0] + border + 1, zeroP[1] + border + 1, 2] + prec, r[zeroP[0] + border, zeroP[1] + border + 1, 2] + prec ], precision=[prec, prec, prec], constraint_eq=constraint_eq2) best_x, _ = ga.run() r[zeroP[0] + border + 1, zeroP[1] + border, 1] = best_x[0] r[zeroP[0] + border + 1, zeroP[1] + border + 1, 0] = best_x[1] r[zeroP[0] + border, zeroP[1] + border + 1, 1] = best_x[2] # ============== def obj_func5(p): x1, = p assert r[zeroP[0] - border, zeroP[1] + border, 0] != NaN, "obj_func5 is NaN" assert r[zeroP[0] - border - 1, zeroP[1] + border, 1] != NaN, "obj_func5 is NaN" assert r[zeroP[0] - border, zeroP[1] + border + 1, 1] != NaN, "obj_func5 is NaN" return np.abs(-r[zeroP[0] - border, zeroP[1] + border, 0] + r[zeroP[0] - border - 1, zeroP[1] + border, 1] + x1 - r[zeroP[0] - border, zeroP[1] + border + 1, 1]) def obj_func6(p): x1, x2, x3 = p assert r[zeroP[0] - border, zeroP[1] + border, 1] != NaN, "obj_func6 is NaN" return np.abs(r[zeroP[0] - border, zeroP[1] + border, 1] - x1 - x2 + x3) constraint_eq3 = [ lambda x: r[zeroP[0] - border, zeroP[1] + border + 1, 2]**2 - r[ zeroP[0] - border, zeroP[1] + border + 1, 1]**2 - x[0]**2, lambda x: r[zeroP[0] - border - 1, zeroP[1] + border + 1, 2]**2 - r[zeroP[0] - border - 1, zeroP[1] + border + 1, 0]**2 - x[1]**2, lambda x: r[zeroP[0] - border - 1, zeroP[1] + border, 2]**2 - r[ zeroP[0] - border - 1, zeroP[1] + border, 1]**2 - x[2]**2 ] ga = GA(func=obj_func5, n_dim=1, size_pop=popsize, max_iter=maxiter, lb=0, ub=r[zeroP[0] + border - 1, zeroP[1] + border + 1, 2] + prec, precision=prec) best_x, _ = ga.run() r[zeroP[0] - border - 1, zeroP[1] + border + 1, 0] = best_x[0] ga = GA(func=obj_func6, n_dim=3, size_pop=popsize, max_iter=maxiter, lb=[0, -r[zeroP[0] - border - 1, zeroP[1] + border + 1, 2], 0], ub=[ r[zeroP[0] - border, zeroP[1] + border + 1, 2] + prec, r[zeroP[0] - border - 1, zeroP[1] + border + 1, 2] + prec, r[zeroP[0] - border - 1, zeroP[1] + border, 2] + prec ], precision=[prec, prec, prec], constraint_eq=constraint_eq3) best_x, _ = ga.run() r[zeroP[0] - border, zeroP[1] + border + 1, 0] = best_x[0] r[zeroP[0] - border - 1, zeroP[1] + border + 1, 1] = best_x[1] r[zeroP[0] - border - 1, zeroP[1] + border, 0] = best_x[2] # ============== def obj_func7(p): x1, = p assert r[zeroP[0] - border, zeroP[1] - border, 1] != NaN, "obj_func7 1 is NaN" assert r[zeroP[0] - border, zeroP[1] - border - 1, 0] != NaN, "obj_func7 2 is NaN" assert r[zeroP[0] - border - 1, zeroP[1] - border, 0] != NaN, "obj_func7 3 is NaN" return np.abs(-r[zeroP[0] - border, zeroP[1] - border, 1] - r[zeroP[0] - border, zeroP[1] - border - 1, 0] + x1 + r[zeroP[0] - border - 1, zeroP[1] - border, 0]) def obj_func8(p): x1, x2, x3 = p assert r[zeroP[0] - border, zeroP[1] - border, 0] != NaN, "obj_func8 is NaN" return np.abs(-r[zeroP[0] - border, zeroP[1] - border, 0] - x1 + x2 + x3) constraint_eq4 = [ lambda x: r[zeroP[0] - border - 1, zeroP[1] - border, 2]**2 - r[ zeroP[0] - border - 1, zeroP[1] - border, 0]**2 - x[0]**2, lambda x: r[zeroP[0] - border - 1, zeroP[1] - border - 1, 2]**2 - r[zeroP[0] - border - 1, zeroP[1] - border - 1, 1]**2 - x[1]**2, lambda x: r[zeroP[0] - border, zeroP[1] - border - 1, 2]**2 - r[ zeroP[0] - border, zeroP[1] - border - 1, 0]**2 - x[2]**2 ] ga = GA(func=obj_func7, n_dim=1, size_pop=popsize, max_iter=maxiter, lb=-r[zeroP[0] - border - 1, zeroP[1] - border - 1, 2], ub=r[zeroP[0] - border - 1, zeroP[1] - border - 1, 2] + prec, precision=prec) best_x, _ = ga.run() r[zeroP[0] - border - 1, zeroP[1] - border - 1, 1] = best_x[0] ga = GA(func=obj_func8, n_dim=3, size_pop=popsize, max_iter=maxiter, lb=[ -r[zeroP[0] - border - 1, zeroP[1] - border, 2], 0, -r[zeroP[0] - border, zeroP[1] - border - 1, 2] ], ub=[ r[zeroP[0] - border - 1, zeroP[1] - border, 2] + prec, r[zeroP[0] - border - 1, zeroP[1] - border - 1, 2] + prec, r[zeroP[0] - border, zeroP[1] - border - 1, 2] + prec ], precision=[prec, prec, prec], constraint_eq=constraint_eq4) best_x, _ = ga.run() r[zeroP[0] - border - 1, zeroP[1] - border, 1] = best_x[0] r[zeroP[0] - border - 1, zeroP[1] - border - 1, 0] = best_x[1] r[zeroP[0] - border, zeroP[1] - border - 1, 1] = best_x[2] return