5.3.4. Python 的QP建模与优化

在本节中,我们将使用 MindOpt Python 语言的 API 来建模以及求解 二次规划问题示例 中的问题。

5.3.4.1. 按行输入: mdo_qo_ex1

首先,引入 Python 包:

25from mindoptpy import *

并创建优化模型:

32    # Step 1. Create a model and change the parameters.
33    model = MdoModel()

接下来,我们通过 mindoptpy.MdoModel.set_int_attr() 将目标函数设置为 最小化 ,并调用 mindoptpy.MdoModel.add_var() 来添加四个优化变量,定义其下界、上界、名称和类型(有关 mindoptpy.MdoModel.set_int_attr()mindoptpy.MdoModel.add_var() 的详细使用方式,请参考 Python 接口函数):

36        # Step 2. Input model.
37        # Change to minimization problem.
38        model.set_int_attr(MDO_INT_ATTR.MIN_SENSE, 1)
39        
40        # Add variables.
41        x = []
42        x.append(model.add_var(0.0,         10.0, 1.0, None, "x0", False))
43        x.append(model.add_var(0.0, MDO_INFINITY, 1.0, None, "x1", False))
44        x.append(model.add_var(0.0, MDO_INFINITY, 1.0, None, "x2", False))
45        x.append(model.add_var(0.0, MDO_INFINITY, 1.0, None, "x3", False))

接着,我们开始添加线性约束:

46        # Add constraints.
47        # Note that the nonzero elements are inputted in a row-wise order here.
48        model.add_cons(1.0, MDO_INFINITY, 1.0 * x[0] + 1.0 * x[1] + 2.0 * x[2] + 3.0 * x[3], "c0")
49        model.add_cons(1.0,          1.0, 1.0 * x[0]              - 1.0 * x[2] + 6.0 * x[3], "c1")

然后,我们调用 mindoptpy.MdoModel.set_quadratic_elements() 来设置目标的二次项系数 \(Q\)。前两组输入向量分别表示二次项中所有非零项的两个变量的索引,最后一组输入向量是与之相对应的非零系数值。

Note

为了确保 \(Q\) 的对称性,用户只需要输入其下三角形部分,并且在求解器内部会乘以 1/2.

52        # Add quadratic objective matrix Q.
53        #
54        #  Note.
55        #  1. The objective function is defined as c^Tx + 1/2 x^TQx, where Q is stored with coordinate format.
56        #  2. Q will be scaled by 1/2 internally.
57        #  3. To ensure the symmetricity of Q, user needs to input only the lower triangular part.
58        #
59        # Q = [ 1.0  0.5  0    0   ]
60        #     [ 0.5  1.0  0    0   ]
61        #     [ 0.0  0.0  1.0  0   ]
62        #     [ 0    0    0    1.0 ]
63        model.set_quadratic_elements([ x[0], x[1], x[1], x[2], x[3] ], [ x[0], x[0], x[1], x[2], x[3] ], [  1.0,  0.5,  1.0,  1.0,  1.0 ])

问题输入完成后,再调用 mindoptpy.MdoModel.solve_prob() 求解优化问题,并用 mindoptpy.MdoModel.display_results() 来查看优化结果:

65        # Step 3. Solve the problem and populate the result.
66        model.solve_prob()
67        model.display_results()

最后,我们调用 mindoptpy.MdoModel.free_mdl() 来释放内存:

78        model.free_mdl()

文件链接 mdo_qo_ex1.py 提供了完整源代码:

 1"""
 2/**
 3 *  Description
 4 *  -----------
 5 *
 6 *  Quadratuc optimization (row-wise input).
 7 *
 8 *  Formulation
 9 *  -----------
10 *
11 *  Minimize
12 *    obj: 1 x0 + 1 x1 + 1 x2 + 1 x3
13 *         + 1/2 [ x0^2 + x1^2 + x2^2 + x3^2 + x0 x1]
14 *  Subject To
15 *   c1 : 1 x0 + 1 x1 + 2 x2 + 3 x3 >= 1
16 *   c2 : 1 x0 - 1 x2 + 6 x3 = 1
17 *  Bounds
18 *    0 <= x0 <= 10
19 *    0 <= x1
20 *    0 <= x2
21 *    0 <= x3
22 *  End
23 */
24"""
25from mindoptpy import *
26
27
28if __name__ == "__main__":
29
30    MDO_INFINITY = MdoModel.get_infinity()
31
32    # Step 1. Create a model and change the parameters.
33    model = MdoModel()
34
35    try:
36        # Step 2. Input model.
37        # Change to minimization problem.
38        model.set_int_attr(MDO_INT_ATTR.MIN_SENSE, 1)
39        
40        # Add variables.
41        x = []
42        x.append(model.add_var(0.0,         10.0, 1.0, None, "x0", False))
43        x.append(model.add_var(0.0, MDO_INFINITY, 1.0, None, "x1", False))
44        x.append(model.add_var(0.0, MDO_INFINITY, 1.0, None, "x2", False))
45        x.append(model.add_var(0.0, MDO_INFINITY, 1.0, None, "x3", False))
46
47        # Add constraints.
48        # Note that the nonzero elements are inputted in a row-wise order here.
49        model.add_cons(1.0, MDO_INFINITY, 1.0 * x[0] + 1.0 * x[1] + 2.0 * x[2] + 3.0 * x[3], "c0")
50        model.add_cons(1.0,          1.0, 1.0 * x[0]              - 1.0 * x[2] + 6.0 * x[3], "c1")
51
52        # Add quadratic objective matrix Q.
53        #
54        #  Note.
55        #  1. The objective function is defined as c^Tx + 1/2 x^TQx, where Q is stored with coordinate format.
56        #  2. Q will be scaled by 1/2 internally.
57        #  3. To ensure the symmetricity of Q, user needs to input only the lower triangular part.
58        #
59        # Q = [ 1.0  0.5  0    0   ]
60        #     [ 0.5  1.0  0    0   ]
61        #     [ 0.0  0.0  1.0  0   ]
62        #     [ 0    0    0    1.0 ]
63        model.set_quadratic_elements([ x[0], x[1], x[1], x[2], x[3] ], [ x[0], x[0], x[1], x[2], x[3] ], [  1.0,  0.5,  1.0,  1.0,  1.0 ])
64
65        # Step 3. Solve the problem and populate the result.
66        model.solve_prob()
67        model.display_results()
68
69    except MdoError as e:
70        print("Received Mindopt exception.")
71        print(" - Code          : {}".format(e.code))
72        print(" - Reason        : {}".format(e.message))
73    except Exception as e:
74        print("Received exception.")
75        print(" - Reason        : {}".format(e))
76    finally:
77        # Step 4. Free the model.
78        model.free_mdl()