【二次规划】扩展单纯形法,Python求解约束优化问题

二次规划问题描述如下,通过扩展的单纯形法解决:

$$
        \mathop {min} \limits_{x}\left( x_1-1 \right) ^2+\left( x_2-2.5 \right) ^2
        $$
        $$
        s.t.\,\,\begin{cases}
            x_1-2x_2+1\ge 0\\
            -x_1-2x_2+6\ge 0\\
            -x_1-2x_2+2\ge 0\\
            x_1\ge 0\\
            x_2\ge 0\\
        \end{cases}
        $$

转换为二次规划的标准形式如下:
        $$\mathop {min} \limits_{x}\,\,f\left( x \right) =\frac{1}{2}x^THx+c^Tx
        $$
        $$
        s.t.\,\,\begin{cases}
            Ax=b\\
            x\ge 0\\
        \end{cases}$$

程序如下:

# -*- coding: utf-8 -*-
# @Author : ZhaoKe
# @Time : 2022-10-03 16:34
import scipy.optimize as opt
import numpy as np

def qp_simplex(H, c, A, b):

    c0 = np.array(np.hstack((13*[0], 8*[1])))
    A0 = np.vstack((
        np.hstack((A, np.zeros((3, 3)), np.zeros((3, 5)), np.identity(3), np.zeros((3, 5)))),
        np.hstack((H, np.transpose(A), (-1)*np.identity(5), np.zeros((5, 3)), np.identity(5)))
    ))
    b0 = -1 * np.array(np.hstack((b, c, 3 * [0])))
    # print(A0)
    # print(b0)
    res = opt.linprog(c0.T, A_eq=A0, b_eq=b0, bounds=(0, None), method='simplex')
    print(res)


if __name__ == '__main__':
    H0 = [[2, 0], [0, 2]]
    H = np.vstack((np.hstack((H0, np.zeros((2, 3)))), np.hstack((np.zeros((3, 2)), np.zeros((3, 3))))))
    c = [-2, -5]
    A = [[-1, 2, 1, 0, 0], [1, 2, 0, 1, 0], [1, 2, 0, 0, 1]]
    b = [-2, -6, -2]
    qp_simplex(H, c, A, b)

结果如下:

     fun: -0.0
 message: 'Optimization terminated successfully.'
     nit: 8
   slack: array([], dtype=float64)
  status: 0
 success: True
       x: array([0.2, 0.9, 0.4, 4. , 0. , 0. , 1.6, 0. , 0. , 0. , 0. , 1.6, 0. ,
       0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])

Process finished with exit code 0

 

posted @ 2022-10-03 23:28  倦鸟已归时  阅读(291)  评论(0编辑  收藏  举报