5.2.5. Python 的MILP建模与优化

在本节中,我们将使用 MindOpt ../../API2/python/index,以按行输入的形式来建模以及求解 混合整数线性规划问题示例 中的问题。

首先,引入 Python 包:

26from mindoptpy import *

创建优化模型,并赋予一个名称:

31    model = Model("MILP_01")

接下来,我们通过设置属性 ModelSense 将目标函数设置为 最小化

35        # Change to minimization problem.
36        model.modelsense = MDO.MINIMIZE

并调用 Model.addVar() 来添加四个优化变量(有关模型属性内容及其设置可参考 属性, 其他API请参考 Python API ):

38        # Add variables.
39        x = []
40        x.append(model.addVar(0.0,         10.0, 1.0, 'I', "x0"))
41        x.append(model.addVar(0.0, float('inf'), 2.0, 'I', "x1"))
42        x.append(model.addVar(0.0, float('inf'), 1.0, 'I', "x2"))
43        x.append(model.addVar(0.0, float('inf'), 1.0, 'C', "x3"))

接着,我们调用 Model.addConstr() 来添加线性约束:

45        # Add constraints.
46        model.addConstr(1.0 * x[0] + 1.0 * x[1] + 2.0 * x[2] + 3.0 * x[3] >= 1, "c0")
47        model.addConstr(1.0 * x[0]              - 1.0 * x[2] + 6.0 * x[3] == 1, "c1")

问题输入完成后,再调用 Model.optimize() 求解优化问题:

50        model.optimize() 

然后,通过属性 Status 和属性 ObjVal 来查看优化结果和最优目标值,并通过属性 X 来查看变量的取值。 其他的属性值请查看 属性 章节。

52        if model.status == MDO.OPTIMAL:
53            print("Optimal objective value is: {model.objval}")
54            print("Decision variables: ")
55            for v in x:
56                print(f"x[{v.VarName}] = {v.X}")
57        else:
58            print("No feasible solution.")

最后,通过 Model.dispose() 来释放模型。

68        model.dispose()

示例 mdo_lo_ex1.py 提供了完整源代码:

 1"""
 2/**
 3 *  Description
 4 *  -----------
 5 *
 6 *  Mixed Integer Linear optimization (row-wise input).
 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 *  Integers
22 *    x0 x1 x2
23 *  End
24 */
25"""
26from mindoptpy import *
27
28if __name__ == "__main__":
29
30    # Step 1. Create a model and change the parameters.
31    model = Model("MILP_01")
32
33    try:
34        # Step 2. Input model.xs
35        # Change to minimization problem.
36        model.modelsense = MDO.MINIMIZE
37        
38        # Add variables.
39        x = []
40        x.append(model.addVar(0.0,         10.0, 1.0, 'I', "x0"))
41        x.append(model.addVar(0.0, float('inf'), 2.0, 'I', "x1"))
42        x.append(model.addVar(0.0, float('inf'), 1.0, 'I', "x2"))
43        x.append(model.addVar(0.0, float('inf'), 1.0, 'C', "x3"))
44
45        # Add constraints.
46        model.addConstr(1.0 * x[0] + 1.0 * x[1] + 2.0 * x[2] + 3.0 * x[3] >= 1, "c0")
47        model.addConstr(1.0 * x[0]              - 1.0 * x[2] + 6.0 * x[3] == 1, "c1")
48  
49        # Step 3. Solve the problem and populate optimization result.
50        model.optimize() 
51
52        if model.status == MDO.OPTIMAL:
53            print("Optimal objective value is: {model.objval}")
54            print("Decision variables: ")
55            for v in x:
56                print(f"x[{v.VarName}] = {v.X}")
57        else:
58            print("No feasible solution.")
59    except MindoptError as e:
60        print("Received Mindopt exception.")
61        print(" - Code          : {}".format(e.errno))
62        print(" - Reason        : {}".format(e.message))
63    except Exception as e:
64        print("Received other exception.")
65        print(" - Reason        : {}".format(e))
66    finally:
67        # Step 4. Free the model.
68        model.dispose()