1. 程式人生 > >geatpy模板sga_new_code_templet新增約束

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