Gurobi 线性约束

Gurobi linear constraint

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

D 是给定的具有正项(常数)的矩阵。 b 是我的变量的向量。 T 和 K 给定常数。

这是一种方法。请注意,由于 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")

希望这能帮助你前进。

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