geatpy模板sga_new_code_templet添加约束

描述

之前实现了geatpy模板sga_new_code_templet的简单应用,现在通过惩罚函数,实现添加约束,求解一个简单的线性规划问题,最后用Lingo验证一下。
Lingo模型:

model:

max=2*x1+3*x2;
x1+2*x2<=8;
4*x1<=16;
4*x2<=12;

end

Lingo结果:

   Global optimal solution found.
   Objective value:                              14.00000
   Total solver iterations:                             2


                       Variable           Value        Reduced Cost
                             X1        4.000000            0.000000
                             X2        2.000000            0.000000

                            Row    Slack or Surplus      Dual Price
                              1        14.00000            1.000000
                              2        0.000000            1.500000
                              3        0.000000           0.1250000
                              4        4.000000            0.000000


使用geatpy模板求解

代码(aimfuc)

import numpy as np


def aimfuc(Phen, LegV):
	x1 = Phen[:, [0]]
	x2 = Phen[:, [1]]
	f = 2 * x1 + 3 * x2
	idx1 = np.where(x1 + 2 * x2 > 8)[0] #约束惩罚
	idx2 = np.where(4 * x1 > 16)[0]
	idx3 = np.where(4 * x2 > 12)[0]
	f[idx1] = 0 #惩罚函数
	f[idx2] = 0
	f[idx3] = 0
	return [f, LegV]

代码(main)

import numpy as np
import geatpy as ga

AIM_M = __import__('aimfuc')
x1 = [0, 100] #预置变量范围
x2 = [0, 100]
b1 = [1, 1] #变量是否包含边界
b2 = [1, 1]
codes = [0, 0] #标准二进制编码
precisions = [6, 6] #精度
scales = [0, 0] #算数刻度
ranges = np.vstack([x1, x2]).T
borders = np.vstack([b1, b2]).T

fieldd = ga.crtfld(ranges, borders, precisions, codes, scales)
problem = 'I' #整数问题
maxormin = -1 #求最大值
MAXGEN = 100
NIND = 50
SUBPOP = 1
GGAP = 0.65
pm = 0.05
selectStyle = 'sus'
recombinStyle = 'xovdp'
drawing = 1

[pop_trace, var_trcae, times] = ga.sga_new_code_templet(AIM_M, 'aimfuc', None, None, fieldd, problem=problem,
                                                        maxormin=maxormin,
                                                        MAXGEN=MAXGEN, NIND=NIND, SUBPOP=SUBPOP, GGAP=GGAP,
                                                        selectStyle=selectStyle,
                                                        recombinStyle=recombinStyle, recopt=None, pm=pm,
                                                        distribute=True,
                                                        drawing=drawing)

结果

最优的目标函数值为:14.0
最优的控制变量值为:
4.0
2.0
有效进化代数:100
最优的一代是第 22 代
时间已过 0.8224434852600098 秒

1

猜你喜欢

转载自blog.csdn.net/weixin_40775077/article/details/84705644