def train(modelName, dim, maxIter): """训练""" # logger.info("{}-GAMain-train-{}".format('*'*25, '*'*25)) problem = MyProblem(modelName) NIND = dim # 种群规模 Encoding = 'RI' # 实整数编码 Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) population = ea.Population(Encoding, Field, NIND) myAlgorithm = ea.soea_SEGA_templet(problem, population) myAlgorithm.MAXGEN = maxIter # 最大进化代数 myAlgorithm.drawing = 1 [population, obj_trace, var_trace] = myAlgorithm.run() population.save(printHandler=logger.info) # 输出结果 best_gen = np.argmin(problem.maxormins * obj_trace[:, 1]) # 记录最优种群个体是在哪一代 best_ObjV = obj_trace[best_gen, 1] logger.info('最优的目标函数值为:%s' % (best_ObjV)) logger.info('最优的控制变量值为:') for i in range(var_trace.shape[1]): logger.info(var_trace[best_gen, i]) logger.info('有效进化代数:%s' % (obj_trace.shape[0])) logger.info('最优的一代是第 %s 代' % (best_gen + 1)) logger.info('评价次数:%s' % (myAlgorithm.evalsNum)) logger.info('时间已过 %s 秒' % (myAlgorithm.passTime))
def main(aim, n, Dim, phase): start = time.perf_counter() """===============================实例化问题对象===========================""" PoolType = 'Thread' problem = MyProblem_multiprocess(aim, n, Dim, phase, PoolType) # 生成问题对象 """=================================种群设置===============================""" Encoding = 'RI' # 编码方式 NIND = 300 # 种群规模 Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # 创建区域描述器 population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) """===============================算法参数设置=============================""" myAlgorithm = ea.soea_SEGA_templet(problem, population) # 实例化一个算法模板对象 # myAlgorithm.mutOper.Pm = 1 # 修改变异算子的变异概率(原模板中breeder GA变异算子的Pm定义为1 / Dim) # myAlgorithm.recOper.XOVR = 0.9 # 修改交叉算子的交叉概率 myAlgorithm.MAXGEN = 15 # 最大进化代数 myAlgorithm.trappedValue = 1e-6 # “进化停滞”判断阈值 myAlgorithm.maxTrappedCount = 10 # 进化停滞计数器最大上限值,如果连续maxTrappedCount代被判定进化陷入停滞,则终止进化 myAlgorithm.drawing = 2 # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画) """==========================调用算法模板进行种群进化=======================""" [population, obj_trace, var_trace] = myAlgorithm.run() # 执行算法模板 population.save() # 把最后一代种群的信息保存到文件中 # 输出结果 best_gen = np.argmin(problem.maxormins * obj_trace[:, 1]) # 记录最优种群个体是在哪一代 best_ObjV = obj_trace[best_gen, 1] print('最优的目标函数值为:%.8smm' % (best_ObjV)) if phase == None: phase = [0] + [i * 10 for i in var_trace[best_gen, :]] # 第一次算出的所有相位值 res = aim.bias_n_li_fast(phase) find_index = np.where(max(res[n + 1:, 0]) == res[ n + 1:, 0])[0][0] + 1 # 第一次最大偏心值的索引位置(此处res内的n+1和最后面的+1表示:不考虑第一级,整体向后偏移一位) else: phase = phase + [i * 10 for i in var_trace[best_gen, :]] # 所有相位值(后续几级相位值有更新) res = aim.bias_n_li_fast(phase) find_index = np.where(max(res[n:, 0]) == res[n:, 0])[0][0] # 每次的最大偏心值的索引位置 print('所在位置及相位偏斜角为:第%s级零件末端; %.8s°' % (find_index + 1 + n, res[find_index + n, 1])) if n == 0: for i in range(len(phase)): print('第%s级相位、偏心值及相位偏斜角为:%s°; %.8smm; %.8s°' % (i + 1, phase[i], res[i, 0], res[i, 1])) else: for i in range(var_trace.shape[1]): print('第%s级相位、偏心值及相位偏斜角为:%s°; %.8smm; %.8s°' % (i + (n + 1), phase[i + n], res[i + n, 0], res[i + n, 1])) print('有效进化代数:%s' % (obj_trace.shape[0])) print('最优的一代是第 %s 代' % (best_gen + 1)) print('评价次数:%s' % (myAlgorithm.evalsNum)) # print('时间已过 %s 分 %.8s 秒' % (int(myAlgorithm.passTime // 60), myAlgorithm.passTime % 60)) n = n + int( (find_index + 1)) # 计算累计固定好的级数(此处find_index类型为int64,改为int类型防止后面报错!) end = time.perf_counter() print(f'时间已过 {int((end - start) // 60)} 分 {(end - start) % 60:.8f} 秒') return myAlgorithm, obj_trace, var_trace, best_gen, best_ObjV, phase, res, n
def opti_function(nind, maxgen, X_train, Y_train, n_fidelity, fullname_temp, feature, wlcb, fre_E, d_x, bounds): gol.set_map("feature", feature) gol.set_map("wlcb", wlcb) gol.set_map("fre_E", fre_E) gol.set_map("d_x", d_x) gol.set_map("bounds", bounds) # from function_nonlinmodel import variable_model variable_model(X_train, Y_train, n_fidelity, fullname_temp) # 实例化问题对象 problem = MyProblem() # 生成问题对象 # 种群设置 Encoding = 'BG' # 编码方式 NIND = nind # 种群规模 Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # 创建区域描述器 population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) # 算法参数设置 myAlgorithm = ea.soea_SEGA_templet(problem, population) # 实例化一个算法模板对象 myAlgorithm.MAXGEN = maxgen # 最大进化代数 myAlgorithm.drawing = 0 # 不画图 # 调用算法模板进行种群进化 [population, obj_trace, var_trace] = myAlgorithm.run() # 执行算法模板 population.save() # 把最后一代种群的信息保存到文件中 # 输出结果 best_gen = np.argmin(problem.maxormins * obj_trace[:, 1]) # 记录最优种群个体是在哪一代 best_ObjV = obj_trace[best_gen, 1] '''# 遗传算法画图 try: plt.close("Ga 1") plt.ion() plt.figure("Ga 1") plt.plot(obj_trace[:, 0], lw=3, label='Average objective function value') plt.plot(obj_trace[:, 1], lw=3, label='Optimal objective function value') # plt.grid(True) plt.legend(loc=0) # 图例位置自动 plt.xlabel('Number of Generation') plt.ylabel('Value') plt.title('objective function value') plt.draw() except: plt.ion() plt.figure("Ga 1") plt.plot(obj_trace[:, 0], lw=3, label='Average objective function value') plt.plot(obj_trace[:, 1], lw=3, label='Optimal objective function value') # plt.grid(True) plt.legend(loc=0) # 图例位置自动 # plt.axis('tight') plt.xlabel('Number of Generation') plt.ylabel('Value') plt.title('objective function value') plt.draw()''' return var_trace[best_gen, :].reshape(1, -1), best_ObjV
def geatpy_optimizer(func, Dim, lb, ub, n_group, n_iter, pco, pm, seed): """ 定义优化问题 """ # 随机数种子设置 np.random.seed(seed=seed) """===============================实例化问题对象===========================""" problem = MyProblem(func, Dim, lb, ub, n_group) # 生成问题对象 """=================================种群设置==============================""" Encoding = 'BG' # 编码方式 NIND = n_group # 种群规模 Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # 创建区域描述器 population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) """===============================算法参数设置=============================""" myAlgorithm = ea.soea_SEGA_templet(problem, population) # 实例化一个算法模板对象 myAlgorithm.MAXGEN = n_iter # 最大进化代数 myAlgorithm.recOper.XOVR = pco # 设置交叉概率 myAlgorithm.mutOper.Pm = pm # 设置变异概率 myAlgorithm.logTras = 1 # 设置每隔多少代记录日志,若设置成0则表示不记录日志 myAlgorithm.verbose = True # 设置是否打印输出日志信息 myAlgorithm.drawing = 0 # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画) """==========================调用算法模板进行种群进化========================""" [BestIndi, population] = myAlgorithm.run() # 执行算法模板,得到最优个体以及最后一代种群 # 保留前5个最优的解 # top_five_index = np.argsort(population.ObjV * problem.maxormins, axis=0)[:5] # top_five_pop = population[top_five_index] BestIndi.save() # 把最优个体的信息保存到文件中 """=================================输出结果==============================""" print('评价次数:%s' % myAlgorithm.evalsNum) print('时间已过 %s 秒' % myAlgorithm.passTime) if BestIndi.sizes != 0: print('最优的目标函数值为:%s' % BestIndi.ObjV[0][0]) print('最优的控制变量值为:') for i in range(BestIndi.Phen.shape[1]): print(BestIndi.Phen[0, i]) else: print('没找到可行解。') return myAlgorithm, population
def geat_method(dist, NIND=500, Encoding='P', MAXGEN=300, XOVR=0.2, Pm=0.5): '''NIND:种群规模 Encoding:编码方式 MAXGEN:最大进化代数 XOVR:交叉算子 Pm:变异算子''' problem = MyProblem(dist) # 生成问题对象 """=================================种群设置=================================""" Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # 创建区域描述器 population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) """===============================算法参数设置===============================""" myAlgorithm = ea.soea_SEGA_templet(problem, population) # 实例化一个算法模板对象 myAlgorithm.MAXGEN = MAXGEN # 最大进化代数 myAlgorithm.recOper = ea.Xovox(XOVR=XOVR) # 设置交叉算子 myAlgorithm.mutOper = ea.Mutinv(Pm=Pm) # 设置变异算子 myAlgorithm.drawing = 1 # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制过程动画) """==========================调用算法模板进行种群进化==========================""" [population, obj_trace, var_trace] = myAlgorithm.run() # 执行算法模板,得到最后一代种群以及进化记录器 population.save() # 把最后一代种群的信息保存到文件中 # 输出结果 best_gen = np.argmin(obj_trace[:, 1]) # 记录最优种群是在哪一代 best_ObjV = np.min(obj_trace[:, 1]) print('最短路程为:%s' % (best_ObjV)) print('最佳路线为:') best_journey, edges = problem.decode(var_trace[best_gen, :]) print(best_journey) for i in range(len(best_journey)): print(int(best_journey[i]), end=' ') print() print('有效进化代数:%s' % (obj_trace.shape[0])) print('最优的一代是第 %s 代' % (best_gen + 1)) print('评价次数:%s' % (myAlgorithm.evalsNum)) print('时间已过 %s 秒' % (myAlgorithm.passTime)) info = ["Geat Method", str(MAXGEN) + " times", str(int(best_ObjV)) + " Km"] return best_journey, info, myAlgorithm.passTime
import numpy as np """==================================实例化问题对象================================""" problemName = 'Rastrigrin' # 问题名称 fileName = problemName # 这里因为目标函数写在与之同名的文件里,所以文件名也是问题名称 MyProblem = getattr(__import__(fileName), problemName) # 获得自定义问题类 problem = MyProblem(30) # 生成问题对象 """==================================种群设置================================""" Encoding = 'RI' # 编码方式 NIND = 100 # 种群规模 precisions = [50] * problem.Dim # 编码精度(适用于二进制/格雷编码) Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders, precisions) # 创建区域描述器 population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) """==================================算法参数设置================================""" myAlgorithm = ea.soea_SEGA_templet(problem, population) # 实例化一个算法模板对象 myAlgorithm.MAXGEN = 1000 # 最大进化代数 myAlgorithm.drawing = 1 # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制过程动画) """=======================调用算法模板进行种群进化==============================""" [population, obj_trace, var_trace] = myAlgorithm.run() # 执行算法模板,得到最后一代种群以及进化记录器 population.save() # 把最后一代种群的信息保存到文件中 # 输出结果 best_gen = np.argmin(obj_trace[:, 1]) # 记录最优种群是在哪一代 best_ObjV = np.min(obj_trace[:, 1]) print('最优的目标函数值为:%s' % (best_ObjV)) print('最优的控制变量值为:') for i in range(var_trace.shape[1]): print(var_trace[best_gen, i]) print('有效进化代数:%s' % (obj_trace.shape[0])) print('最优的一代是第 %s 代' % (best_gen + 1))
x1 = Vars[i, 0] x2 = Vars[i, 1] CV.append(np.array([(x1 - 0.5)**2 - 0.25, (x2 - 1)**2 - 1])) return np.vstack(f), np.vstack(CV) # 返回目标函数值矩阵和违反约束程度矩阵 problem = ea.Problem( name='soea quick start demo', M=1, # 目标维数 maxormins=[1], # 目标最小最大化标记列表,1:最小化该目标;-1:最大化该目标 Dim=5, # 决策变量维数 varTypes=[0, 0, 1, 1, 1], # 决策变量的类型列表,0:实数;1:整数 lb=[-1, 1, 2, 1, 0], # 决策变量下界 ub=[1, 4, 5, 2, 1], # 决策变量上界 evalVars=evalVars) # 构建算法 algorithm = ea.soea_SEGA_templet( problem, ea.Population(Encoding='RI', NIND=20), MAXGEN=50, # 最大进化代数。 logTras=1, # 表示每隔多少代记录一次日志信息,0表示不记录。 trappedValue=1e-6, # 单目标优化陷入停滞的判断阈值。 maxTrappedCount=10) # 进化停滞计数器最大上限值。 # 求解 res = ea.optimize(algorithm, verbose=True, drawing=1, outputMsg=True, drawLog=False, saveFlag=True) print(res)
def optimize(datasetX, datasetY, featureNamesAfterCombination, featureOptimizationParams, datasetParams, forecastModelParams): featureNamesAfterOptimization = [] featureOptimizationProcess = None isPerformOptimization = featureOptimizationParams[ "isPerformOptimization"] if isPerformOptimization: dim = len(featureNamesAfterCombination) problem = FeatureOptimizationProblem(datasetX, datasetY, featureNamesAfterCombination, datasetParams, forecastModelParams) encoding = 'RI' popNum = 10 field = ea.crtfld(encoding, problem.varTypes, problem.ranges, problem.borders) pop = ea.Population(encoding, field, popNum) if dim < 7: # 维度不高时采用穷举 Phen = [] for i in range(1, pow(2, dim)): numStr = MathNormalUtils.toBinaryWithFixedLength(i, dim) numArray = list(map(int, numStr)) Phen.append(numArray) # 受维数灾影响 随机优化5个特征组合 resultlist = random.sample(range(len(Phen)), 3) Phen = np.array(Phen) # Phen = Phen[resultlist, :] pop.Phen = Phen problem.aimFunc(pop) objTrace, varTrace = pop.ObjV, pop.Phen objTrace = NumpyUtils.hStackByCutHead(objTrace, objTrace) else: algorithm = ea.soea_SEGA_templet(problem, pop) # 算法最大进化代数 algorithm.MAXGEN = 10 # 0表示不绘图;1表示绘图;2表示动态绘图 algorithm.drawing = 1 [pop, objTrace, varTrace] = algorithm.run() featureOptimizationProcess = { "objTrace": objTrace, "varTrace": varTrace } bestGen = np.argmin(problem.maxormins * objTrace[:, 1]) bestVar = varTrace[bestGen, :] bestVar = [int(x) for x in bestVar] bestVar = np.array(bestVar) featureCombinationParams = { "isPerformCombination": True, "featureFlags": bestVar } featureCombination = FeatureCombination( datasetX, datasetY, featureNamesAfterCombination, featureCombinationParams) datasetAfterOptimizationX, datasetAfterOptimizationY, featureNamesAfterOptimization = featureCombination.getDatasetAfterCombination( ) else: datasetAfterOptimizationX = datasetX datasetAfterOptimizationY = datasetY featureNamesAfterOptimization = featureNamesAfterCombination dataset = Dataset(datasetAfterOptimizationX, datasetAfterOptimizationY, datasetParams) forecastTemplate = ForecastTemplate(dataset, forecastModelParams) loss = forecastTemplate.getObjective() if (datasetAfterOptimizationX is None) or (datasetAfterOptimizationY is None): raise Exception("特征优化中全部特征未被选取,请检查参数!") return datasetAfterOptimizationX, datasetAfterOptimizationY, featureNamesAfterOptimization, featureOptimizationProcess
def each_brake(each_wait_list, L, W, brake_num, wait_list_num): wait_list = each_wait_list """===============================实例化问题对象===========================""" problem = MyProblem(wait_list, L, W) # 生成问题对象 """=================================种群设置===============================""" Encoding = 'P' # 编码方式 NIND = 6000 #4000,6000 种群规模 # ranges还是原来的,Field会在最后一行加上1 Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # 创建区域描述器 population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) """===============================算法参数设置=============================""" myAlgorithm = ea.soea_SEGA_templet(problem, population) # 实例化一个算法模板对象,单目标模板 # myAlgorithm=ea.moea_NSGA2_templet(problem, population) #多目模板 myAlgorithm.MAXGEN = 3 # 13 # 最大进化代数 # myAlgorithm.recOper = ea.Xovox(XOVR=0.8) # 设置交叉算子 __init__(self, XOVR=0.7, Half=False) # myAlgorithm.mutOper = ea.Mutinv(Pm=0.2) # 设置变异算子 myAlgorithm.logTras = 1 # 设置每多少代记录日志,若设置成0则表示不记录日志 myAlgorithm.verbose = False # 设置是否打印输出日志信息 myAlgorithm.drawing = 0 # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画) """==========================调用算法模板进行种群进化=======================""" [population, obj_trace, var_trace] = myAlgorithm.run() # 执行算法模板 # population.save() # 把最后一代种群的信息保存到文件中 # 输出结果 best_gen = np.argmin(problem.maxormins * obj_trace[:, 1]) # 记录最优种群个体是在哪一代 best_ObjV = obj_trace[best_gen, 1] # print('最优的目标函数值为:%s' % (best_ObjV)) # print('最优的控制变量值为:') for i in range(var_trace.shape[1]): # (MAXGEN,Dim),进化的总代数和决策变量的维度 print(var_trace[best_gen, i]) best_sort_sequence = [int(each) for each in var_trace[best_gen]] # (4000, 12) #best_brake_seq={i:wait_list[i] for i in best_sort_sequence} best_brake_seq = wait_list[best_sort_sequence] #闸次原始顺序 brake_boat = quick_sort_brake(best_brake_seq, L, W) # #将快速入闸的顺序,对应到最优选择的顺序 # brake_boat={best_sort_sequence[k]:v for k,v in brake_boat.items()} # # #将最优选择的顺序,对应到最原始的队列中的序号 # brake_boat={wait_list_num[k]:v for k,v in brake_boat.items()} # N_e = len(brake_boat) # plot_example(X, Y, li_e, wi_e, N_e,brake_num=brake_num) best_use_rate = plot_save(brake_boat, brake_num) print('plot finished') # print('有效进化代数:%s' % (obj_trace.shape[0])) # print('最优的一代是第 %s 代' % (best_gen + 1)) # print('评价次数:%s' % (myAlgorithm.evalsNum)) # print('时间已过 %s 秒' % (myAlgorithm.passTime)) return { 'brake_boat': brake_boat, 'best_sort_sequence': best_sort_sequence, 'best_use_rate': best_use_rate }
def each_brake(each_wait_list,L,W): def get_sqare_rate(in_brake_sort, L,W): brake_boat=quick_sort_brake(in_brake_sort, L, W) s=0 for k,v in brake_boat.items(): s=s+v[1][0]*v[1][1] sqare_rate=s/(L*W) return sqare_rate,brake_boat wait_list=each_wait_list """===============================实例化问题对象===========================""" problem = MyProblem(wait_list, L, W) # 生成问题对象 """=================================种群设置===============================""" Encoding = 'P' # 编码方式 NIND = 6000 # 种群规模 # ranges还是原来的,Field会在最后一行加上1 Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # 创建区域描述器 population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) """===============================算法参数设置=============================""" myAlgorithm = ea.soea_SEGA_templet(problem, population) # 实例化一个算法模板对象,单目标模板 # myAlgorithm=ea.moea_NSGA2_templet(problem, population) #多目模板 myAlgorithm.MAXGEN = 15 # 13 # 最大进化代数 # myAlgorithm.recOper = ea.Xovox(XOVR=0.8) # 设置交叉算子 __init__(self, XOVR=0.7, Half=False) # myAlgorithm.mutOper = ea.Mutinv(Pm=0.2) # 设置变异算子 myAlgorithm.logTras = 1 # 设置每多少代记录日志,若设置成0则表示不记录日志 myAlgorithm.verbose = True # 设置是否打印输出日志信息 myAlgorithm.drawing = 1 # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画) """==========================调用算法模板进行种群进化=======================""" [population, obj_trace, var_trace] = myAlgorithm.run() # 执行算法模板 population.save() # 把最后一代种群的信息保存到文件中 # 输出结果 best_gen = np.argmin(problem.maxormins * obj_trace[:, 1]) # 记录最优种群个体是在哪一代 best_ObjV = obj_trace[best_gen, 1] print('最优的目标函数值为:%s' % (best_ObjV)) print('最优的控制变量值为:') for i in range(var_trace.shape[1]): # (MAXGEN,Dim),进化的总代数和决策变量的维度 print(var_trace[best_gen, i]) best_sort_sequence = [int(each) for each in var_trace[best_gen]] # (4000, 12) #best_brake_seq={i:wait_list[i] for i in best_sort_sequence} # best_brake_seq = wait_list[best_sort_sequence] # all_brake_boat = {} # in_brake_sort = best_brake_seq # sqare_rate,brake_boat=get_sqare_rate(in_brake_sort, L,W) # brake_num=list(brake_boat.keys()) # brake_boat={best_sort_sequence[k]:v for k,v in brake_boat.items()} # all_brake_boat[0]= {'brake_boat':brake_boat,'best_use_rate':sqare_rate} # print('一闸最优解:组合={} \n 面积利用率={}'.format(brake_boat,sqare_rate)) # # each2=np.delete(best_sort_sequence,brake_num,axis=0) # in_brake_sort2=np.delete(in_brake_sort,brake_num,axis=0) # if len(in_brake_sort2)>0: # sqare_rate2,brake_boat2=get_sqare_rate(in_brake_sort2, L,W) # brake_num2=list(brake_boat2.keys()) # #sqare_rate=sqare_rate+sqare_rate2 # brake_boat2={each2[k]:v for k,v in brake_boat2.items()} # all_brake_boat[1] = {'brake_boat':brake_boat2,'best_use_rate':sqare_rate2} # print('二闸最优解:组合={} \n 面积利用率={}'.format(brake_boat2,sqare_rate2)) # # each3=np.delete(each2,brake_num2,axis=0) # in_brake_sort3=np.delete(in_brake_sort2,brake_num2,axis=0) # if len(in_brake_sort3)>0: # sqare_rate3,brake_boat3=get_sqare_rate(in_brake_sort3, L,W) # brake_num3=list(brake_boat3.keys()) # # brake_boat3={each3[k]:v for k,v in brake_boat3.items()} # all_brake_boat[2] = {'brake_boat':brake_boat3,'best_use_rate':sqare_rate3}#brake_boat3 # print('三闸最优解:组合={} \n 面积利用率={}'.format(brake_boat3,sqare_rate3)) # #sqare_rate=sqare_rate+sqare_rate3 # print('all_brake_boat00',all_brake_boat) best_brake_seq = wait_list[best_sort_sequence] all_brake_boat = {} all_brake_times = 0 in_brake_sort = best_brake_seq while True: if len(in_brake_sort) > 0 and all_brake_times < 3: sqare_rate, brake_boat = get_sqare_rate(in_brake_sort, L, W) # 将闸室序号,映射到原始信号 brake_num = list(brake_boat.keys()) # 更新in_brake_sort ##each2=np.delete(each,brake_num,axis=0) in_brake_sort = np.delete(in_brake_sort, brake_num, axis=0) brake_boat = {best_sort_sequence[k]: v for k, v in brake_boat.items()} best_sort_sequence = np.delete(best_sort_sequence, brake_num, axis=0) all_brake_boat[all_brake_times] = {'brake_boat': brake_boat, 'best_use_rate': sqare_rate} print('第{}闸最优解:组合={} \n 面积利用率={}'.format(all_brake_times, brake_boat, sqare_rate)) #绘制并保存图形 plot_save(brake_boat, all_brake_times) all_brake_times = all_brake_times + 1 else: break print(' all_brake_boat11', all_brake_boat) #brake_boat = quick_sort_brake(best_brake_seq, L, W) ##将快速入闸的顺序,对应到最优选择的顺序 #brake_boat={best_sort_sequence[k]:v for k,v in brake_boat.items()} ##将最优选择的顺序,对应到最原始的队列中的序号 #brake_boat={wait_list_num[k]:v for k,v in brake_boat.items()} print('有效进化代数:%s' % (obj_trace.shape[0])) print('最优的一代是第 %s 代' % (best_gen + 1)) print('评价次数:%s' % (myAlgorithm.evalsNum)) print('时间已过 %s 秒' % (myAlgorithm.passTime)) return all_brake_boat
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np from MyProblem import MyProblem # 导入自定义问题接口 import geatpy as ea # import geatpy """ 该案例展示了一个带约束的单目标旅行商问题的求解。问题的定义详见MyProblem.py。 """ if __name__ == '__main__': # 实例化问题对象 problem = MyProblem() # 构建算法 algorithm = ea.soea_SEGA_templet( problem, ea.Population(Encoding='P', NIND=50), MAXGEN=200, # 最大进化代数 logTras=1) # 表示每隔多少代记录一次日志信息,0表示不记录。 algorithm.mutOper.Pm = 0.5 # 变异概率 # 求解 res = ea.optimize(algorithm, verbose=True, drawing=1, outputMsg=True, drawLog=False, saveFlag=True) # 绘制路线图 if res['success']: print('最短路程为:%s' % res['ObjV'][0][0]) print('最佳路线为:') best_journey = np.hstack([0, res['Vars'][0, :], 0])