1

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

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

方程约束

4

2 回答 2

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
于 2017-01-23T22:59:50.660 回答
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")

希望这可以帮助您继续前进。

于 2015-05-19T23:02:53.917 回答