5.1.4. LP 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 Linear Programming.

First of all, import MindOpt Python package:

24from mindoptpy import *

Create an optimization model model named “LP_01”:

29    model = Model("LP_01")

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

34        # Change to minimization problem.
35        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):

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

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

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

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

47        # Step 3. Solve the problem and populate optimization result.
48        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.

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

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

66        model.dispose()

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