Gurobi线性约束

时间:2015-05-19 18:17:31

标签: python optimization constraints gurobi

在Python中将此约束添加到gurobi的最简单方法是什么。

D是具有正条目(恒定)的给定矩阵。 b是我变量的向量。 T和K给出了常数。

equation constraint

2 个答案:

答案 0 :(得分:2)

Gurobi在7.0版中增加了对Max,Min,Abs,And和Or的支持。请参阅http://www.gurobi.com/documentation/7.0/refman/py_model_addgenconstrmax.html上的model.addGenConstrMax的Gurobi文档。

现在可以编写一个更简单的解决方案:

Dmatrix = [[1,2], [3,4], [5,6]]                                          
m = grb.Model("test_max_constraint")

M = 3
N = 2

T = 20.0 #Const
K = 15 #Const

b = {}
for j in range(N):
    b[j] = m.addVar(name='b_'+str(j))

maxterm = {}
sumterm = {}
for i in range(M):
    maxterm[i] = m.addVar(name='maxvar_'+str(i))
    sumterm[i] = m.addVar(name='sumvar_'+str(i))

m.update() #integrate the b variables

#By looping twice, explicity create the individual terms
for i in range(M):
    sum_terms = 0
    for j in range(N):
        sum_terms += Dmatrix[i][j]*b[j]
    m.addConstr(sumterm[i] == sum_terms, 'sumterm' + str(i))
    m.addGenConstrMax(maxterm[i], [sumterm[i]], T, 'maxTsum' + str(i))

m.addConstr(grb.quicksum([maxterm[i] for i in range(M)]) >= K,  "Maxterms_GT_K_Constraint")

m.update()
m.write('gurmax.lp')

这会生成模型:

\ Model test_max_constraint
\ LP format - for model browsing. Use MPS format to capture full model detail.
Minimize

Subject To
 sumterm0: - b_0 - 2 b_1 + sumvar_0 = 0
 sumterm1: - 3 b_0 - 4 b_1 + sumvar_1 = 0
 sumterm2: - 5 b_0 - 6 b_1 + sumvar_2 = 0
Maxterms_GT_K_Constraint: maxvar_0 + maxvar_1 + maxvar_2 >= 15
Bounds
General Constraints
 maxTsum0: maxvar_0 = MAX ( sumvar_0 , 20 )
 maxTsum1: maxvar_1 = MAX ( sumvar_1 , 20 )
 maxTsum2: maxvar_2 = MAX ( sumvar_2 , 20 )
End

答案 1 :(得分:1)

这是一种方法。请注意,由于max()项有点棘手,我不使用列表推导,而是依赖于循环索引。 (我没有Gurobi方便测试以下内容。)

from gurobipy import *

Dmatrix = [[1,2], [3,4], [5,6]]
mod = Model("test_max_constraint")

M = 3
N = 2

T = 20 #Const
K = 15 #Const

for j in range(N):
    b[j] = model.addVar(name='b_'+str(j))

mod.update() #integrate the b variables

#By looping twice, explicity create the individual terms
maxterms = []
for i in range(M):
    current_term = 0
    for j in range(N):
        current_term += Dmatrix[i][j]*b[j]
    current_term = max(current_term-T,0)

    maxterms.append(current_term)
#A list called 'maxterms' is now ready. Add a constraint summing over these terms.

mod.addConstr( quicksum(maxterms) > K,  "Maxterms_GT_K_Constraint")

希望这有助于你前进。