import numpy as np
from mindoptpy import *

"""
/**
 *  Description
 *  -----------
 *
 *  考虑如下的线性规划问题
 *
 *  Formulation
 *  -----------
 *
 *  Minimize
 *    obj: 1 x0 + 2 x1 + 1 x2 + 1 x3 + 4 x4 - 2 x5 + 2x6
 *  Subject To
 *   c1 : 1 x0 + 1 x1 + 2 x2 + 3 x3 + x4 - 2 x5 + x6 >= 6
 *   c2 : 1 x0 - 1 x2 + 6 x3 + 4 x4 + 2 x5 + 2 x6 >= 7
 *   c3 : 3 x0 - 6 x1 - 4 x3 + 2 x5 - x6 <= 12
 *   c4 : 2 x0 + 3 x1 - 3 x4 - 3 x5 == 3
 *   c5 :        3 x1 - 1 x4 +   x5 + 2x6 <= 8
 *  Bounds
 *    0 <= x0
 *    0 <= x1
 *    0 <= x2
 *    0 <= x3
 *    0 <= x4
 *    0 <= x5
 *    1 <= x6 <= 8
 *  CONTINUOUS
 *    x0 x1 x2 x3 x4 x5 x6
 *  End
 */
"""

model = Model("LP_1")

# Step 2. Input model.
model.modelsense = MDO.MINIMIZE

# Add variables.
x = []
x.append(model.addVar(lb = 0.0, ub = float('inf'), obj = 1.0, vtype = 'C', name = "x0"))  

# 第一个参数lb: Lower Bound 决策变量的下界, 第二个参数ub: Upper Bound，决策变量的上界
# 第三个参数obj: 该变量对应的目标函数系数;
# 第四个参数vtype: 决策变量的类型: “C” 表示 "CONTINUOUS", 连续型
# 第五个参数name: 这个决策变量的名称

x.append(model.addVar(lb = 0.0, ub = float('inf'), obj = 2.0, vtype = 'C', name = "x1"))
x.append(model.addVar(lb = 0.0, ub = float('inf'), obj = 1.0, vtype = 'C', name = "x2"))
x.append(model.addVar(lb = 0.0, ub = float('inf'), obj = 1.0, vtype = 'C', name = "x3"))
x.append(model.addVar(lb = 0.0, ub = float('inf'), obj = 4.0, vtype = 'C', name = "x4"))
x.append(model.addVar(lb = 0.0, ub = float('inf'), obj = -2.0, vtype = 'C', name =  "x5"))
x.append(model.addVar(lb = 1.0, ub = 8.0, obj = 2.0, vtype = 'C', name = "x6"))

# 添加约束
model.addConstr(1.0 * x[0] + 1.0 * x[1] + 2.0 * x[2] + 3.0 * x[3] + 1.0 * x[4] - 2.0 * x[5] + 1.0 * x[6] >= 1, "c0")
model.addConstr(1.0 * x[0]              - 1.0 * x[2] + 6.0 * x[3] + 4.0 * x[4] + 2.0 * x[5] + 2.0 * x[6] >= 10, "c1")
model.addConstr(3.0 * x[0] - 6.0 * x[1]              - 4.0 * x[3]              + 2.0 * x[5] - 1.0 * x[6] <= 12, "c2")
model.addConstr(2.0 * x[0] + 3.0 * x[1]                           - 3.0 * x[4] - 3.0 * x[5]              == 3, "c3")
model.addConstr(             3.0 * x[1]                           - 1.0 * x[4] + 1.0 * x[5] + 2.0 * x[6] <= 8, "c4")

# Step 3. 求解: 单纯形法,启动!
model.optimize()

if model.status == MDO.OPTIMAL:
    print(f"最优目标函数: {model.objval}")
    print("决策变量取值:")
    for v in x:
        print(f"{v.VarName} = {v.X}")
else:
    print("没找到最优解。")

