序列二次规划(SQP)是解决约束优化问题中较好的一种算法,其流程为
在实现算法的过程中,使用了scipy.optimize模块:
scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)
[source]
minimize f(x) subject to
g_i(x) >= 0, i = 1,...,m
h_j(x) = 0, j = 1,...,p
import sympy,numpy
from numpy import *
from scipy.optimize import fsolve, minimize
def SQP(x,w,v):
x0=numpy.array([1,1])
w0=5;v0=2
W=numpy.array([[2+2*w0,0],[0,2]])
x = x0
w,v=w0,v0
for i in range(30):
f = x[0]**2+(x[1]-4)**2
f_d = numpy.array([2*x[0],2*x[1]-8])
g = x[1] - (x[0]-4)**2
g_d = numpy.array([-2*(x[0]-4),1])
h = 2*x[0]-x[1]-1
h_d = numpy.array([2,-1])
#res = SQP(numpy.array([[1.0],[-3.0]]))
#********求lambda最小值************
Q = lambda d: 0.5 * (numpy.dot(numpy.dot(d.T, W), d)) + numpy.dot(f_d.T, d)
cons = ({'type': 'ineq', 'fun': lambda x: x[1] - (x[0]-4)**2+numpy.dot(g_d.T, x)},
{'type': 'eq', 'fun': lambda x:2*x[0]-x[1]-1+numpy.dot(h_d.T, x)})
bnds = ((0, None), (0, None))
res = minimize(Q, (0, 0), method='SLSQP', bounds=bnds, constraints=cons)
print res['x']
#********end************
x = x+numpy.array(res['x'])
A=[[g_d[0],h_d[0]],[g_d[1],h_d[1]]] #线性方程组求解
A = numpy.array(A)
Q_d = numpy.dot(W, res['x'])
b=Q_d
b = numpy.array(b)
solu = numpy.linalg.solve(A, b)
w=solu[0]
v=solu[1]
print "d=%s,x=%s"%(res['x'],x)