5.1.5. Python 的LP建模与优化¶
在本节中,我们将使用 MindOpt Python API,以按行输入的形式来建模以及求解 线性规划问题示例 中的问题。
首先,引入 MindOpt Python 包:
24from mindoptpy import *
创建优化模型,并赋予一个名称:
29 model = Model("LP_01")
接下来,我们通过设置模型属性 ModelSense 将目标函数设置为 最小化 :
34 # Change to minimization problem.
35 model.ModelSense = MDO.MINIMIZE
调用 Model.addVar()
来添加四个优化变量(有关模型属性内容及其设置可参考 属性, 其他API请参考 Python API ):
36 # Add variables.
37 x = []
38 x.append(model.addVar(0.0, 10.0, 1.0, 'C', "x0"))
39 x.append(model.addVar(0.0, float('inf'), 2.0, 'C', "x1"))
40 x.append(model.addVar(0.0, float('inf'), 1.0, 'C', "x2"))
41 x.append(model.addVar(0.0, float('inf'), 1.0, 'C', "x3"))
接着,我们调用 Model.addConstr()
来添加线性约束:
43 # Add constraints.
44 model.addConstr(1.0 * x[0] + 1.0 * x[1] + 2.0 * x[2] + 3.0 * x[3] >= 1, "c0")
45 model.addConstr(1.0 * x[0] - 1.0 * x[2] + 6.0 * x[3] == 1, "c1")
问题输入完成后,再调用 Model.optimize()
求解优化问题:
47 # Step 3. Solve the problem and populate optimization result.
48 model.optimize()
求解完成后,通过属性 Status 和属性 ObjVal 来查看优化结果和最优目标值,并通过属性 X 来查看变量的取值。 其他的属性值请查看 属性 章节。
50 if model.status == MDO.OPTIMAL:
51 print(f"Optimal objective value is: {model.objval}")
52 print("Decision variables: ")
53 for v in x:
54 print(f"x[{v.VarName}] = {v.X}")
55 else:
56 print("No feasible solution.")
最后,通过 Model.dispose()
来释放模型。
66 model.dispose()
示例 mdo_lo_ex1.py 提供了完整源代码:
1"""
2/**
3 * Description
4 * -----------
5 *
6 * Linear optimization.
7 *
8 * Formulation
9 * -----------
10 *
11 * Minimize
12 * obj: 1 x0 + 2 x1 + 1 x2 + 1 x3
13 * Subject To
14 * c1 : 1 x0 + 1 x1 + 2 x2 + 3 x3 >= 1
15 * c2 : 1 x0 - 1 x2 + 6 x3 = 1
16 * Bounds
17 * 0 <= x0 <= 10
18 * 0 <= x1
19 * 0 <= x2
20 * 0 <= x3
21 * End
22 */
23"""
24from mindoptpy import *
25
26if __name__ == "__main__":
27
28 # Step 1. Create model.
29 model = Model("LP_01")
30
31 try:
32 # Step 2. Input model.
33 # Change to minimization problem.
34 model.ModelSense = MDO.MINIMIZE
35
36 # Add variables.
37 x = []
38 x.append(model.addVar(0.0, 10.0, 1.0, 'C', "x0"))
39 x.append(model.addVar(0.0, float('inf'), 2.0, 'C', "x1"))
40 x.append(model.addVar(0.0, float('inf'), 1.0, 'C', "x2"))
41 x.append(model.addVar(0.0, float('inf'), 1.0, 'C', "x3"))
42
43 # Add constraints.
44 model.addConstr(1.0 * x[0] + 1.0 * x[1] + 2.0 * x[2] + 3.0 * x[3] >= 1, "c0")
45 model.addConstr(1.0 * x[0] - 1.0 * x[2] + 6.0 * x[3] == 1, "c1")
46
47 # Step 3. Solve the problem and populate optimization result.
48 model.optimize()
49
50 if model.status == MDO.OPTIMAL:
51 print(f"Optimal objective value is: {model.objval}")
52 print("Decision variables: ")
53 for v in x:
54 print(f"x[{v.VarName}] = {v.X}")
55 else:
56 print("No feasible solution.")
57 except MindoptError as e:
58 print("Received Mindopt exception.")
59 print(" - Code : {}".format(e.errno))
60 print(" - Reason : {}".format(e.message))
61 except Exception as e:
62 print("Received other exception.")
63 print(" - Reason : {}".format(e))
64 finally:
65 # Step 4. Free the model.
66 model.dispose()