或工具约束,要求变量[或工具]等价

时间:2018-11-29 11:12:50

标签: or-tools

我想使用OR-Tools创建线性求解器模型。我有两个numVars,约束之一是这两个变量的相等性。但是我找不到设置带有变量的约束的方法。我可以使用gurobi库来做到这一点。以下是这两个库的代码。有没有办法将变量传递到约束的两端,例如xa == xb? 预先感谢。

Gurobi代码:

from gurobipy import Model, GRB
m = Model('rafinery')
xa = m.addVar(vtype=GRB.CONTINUOUS)
xb = m.addVar(vtype=GRB.CONTINUOUS)

# production constraint
m.addConstr(xa*400 + xb*300 >= 25000)
m.addConstr(xa*300 + xb*400 >= 27000)
m.addConstr(xa*200 + xb*500 >= 30000)
m.addConstr(xa>=0)
m.addConstr(xb>=0)
m.addConstr(xa==xb)

m.setObjective(xa * 20000 + xb * 25000, GRB.MINIMIZE)
m.update()
m.setObjective(xa + xb, GRB.MINIMIZE)
m.update()
m.optimize()

for v in m.getVars():
    print(v.varName, v.x)
print("Cost:", m.objVal)  

OR-Tools代码:

from ortools.linear_solver import pywraplp
solver = pywraplp.Solver('SolveSimpleSystem', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING)

# Create Variables
xa = solver.NumVar(0, solver.infinity(),'xa')
xb = solver.NumVar(0, solver.infinity(),'xb')

# Create Constraints
# xa*400 + xb*300 >= 25000
high = solver.Constraint(25000, solver.infinity())
high.SetCoefficient(xa, 400)
high.SetCoefficient(xb, 300)

# xa*300 + xb*400 >= 27000
middle = solver.Constraint(27000, solver.infinity())
middle.SetCoefficient(xa,300)
middle.SetCoefficient(xb,400)

# xa*200 + xb*500 >= 30000
high = solver.Constraint(30000, solver.infinity())
high.SetCoefficient(xa, 200)
high.SetCoefficient(xb, 500)

# another constraint that factories work for same days
# ******************** get error here ****************
noidle = solver.Constraint(xa,xa) 
noidle.SetCoefficient(xb,1)

# obj = minimize production cost which is
# xa * 20000 + xb * 25000
obj = solver.Objective()
obj.SetCoefficient(xa, 20000)
obj.SetCoefficient(xb, 25000)
obj.SetMinimization()

solver.Solve()
print("Rafinery Solution:")
print("Rafinery A work days:", xa.solution_value())
print("Rafinery B work days:", xb.solution_value())
print("Cost : ", solver.Objective().Value())

1 个答案:

答案 0 :(得分:0)

from ortools.linear_solver import pywraplp
solver = pywraplp.Solver('SolveSimpleSystem', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING)

# Create Variables
xa = solver.NumVar(0, solver.infinity(),'xa')
xb = solver.NumVar(0, solver.infinity(),'xb')

# production constraint
solver.Add(xa*400 + xb*300 >= 25000)
solver.Add(xa*300 + xb*400 >= 27000)
solver.Add(xa*200 + xb*500 >= 30000)
solver.Add(xa>=0)
solver.Add(xb>=0)
solver.Add(xa==xb)

solver.Minimize(xa * 20000 + xb * 25000)

solver.Solve()
print("Rafinery Solution:")
print("Rafinery A work days:", xa.solution_value())
print("Rafinery B work days:", xb.solution_value())
print("Cost : ", solver.Objective().Value())