5.2.5. 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 retrieve the optimal objective value and solutions via attributes ObjVal and X. For other attribute information, please check Attributes.

52        # Step 4. Retrive model status and objective.
53        # For MIP(MILP,MIQP, MIQCP) problems, if the solving process
54        # terminates early due to reasons such as timeout or interruption,
55        # the model status will indicate termination by timeout (or
56        # interruption, etc.). However, suboptimal solutions may still
57        # exist, making it necessary to check the SolCount property.
58        if model.status == MDO.OPTIMAL or model.status == MDO.SUB_OPTIMAL or model.solcount !=0:

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

68        print(" - Reason        : {}".format(e.message))

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        # Step 4. Retrive model status and objective.
53        # For MIP(MILP,MIQP, MIQCP) problems, if the solving process
54        # terminates early due to reasons such as timeout or interruption,
55        # the model status will indicate termination by timeout (or
56        # interruption, etc.). However, suboptimal solutions may still
57        # exist, making it necessary to check the SolCount property.
58        if model.status == MDO.OPTIMAL or model.status == MDO.SUB_OPTIMAL or model.solcount !=0:
59            print(f"Optimal objective value is: {model.objval}")
60            print("Decision variables: ")
61            for v in x:
62                print(f"x[{v.VarName}] = {v.X}")
63        else:
64            print("No feasible solution.")
65    except MindoptError as e:
66        print("Received Mindopt exception.")
67        print(" - Code          : {}".format(e.errno))
68        print(" - Reason        : {}".format(e.message))
69    except Exception as e:
70        print("Received other exception.")
71        print(" - Reason        : {}".format(e))
72    finally:
73        # Step 4. Free the model.
74        model.dispose()