5.2.4. MILP Modeling and Optimization in PythonΒΆ

In this section, we will utilize MindOpt Python API to model and solve the linear optimization problem in Example of Mixed-Integer Linear Programming.

First of all, import MindOpt Python package:

26from mindoptpy import *

Create an optimization model model:

31    model = Model("MILP_01")

Next, we set the optimization sense to minimization via setting attribute ModelSense:

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

Add four decision variables using Model.addVar() (please refer to Attributes for the detailed usages of model attributes, and Python API for other Python API information):

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"))

Next, we call Model.addConstr() to input the linear constraints:

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")

Once the model is constructed, we call Model.optimize() to solve the problem:

50        model.optimize() 

We can check the solution status via the attribute Status, and retrieive the optimal objective value and solutions via attributes ObjVal and X. For other attribute information, please check Attributes.

52        if model.status == MDO.OPTIMAL:
53            print(f"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.")

Lastly, we free the model using Model.dispose():

68        model.dispose()

Complete example codes are provided in mdo_milo_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(f"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.code))
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()