Variables and constraints
Answeredhello,Can you help me? What I want to ask is: how to achieve summation by column or summation by row inside the constraint, but the summation is just the integer variable 'x' without any coefficients. For example, if 'b' represents each column, 'p' represents each row, and 'x' is the variable is an unknown integer, I want to write xp1b1+xp1b2+xp1b3==30 (row summation) how to express it? (My model is MIP)
I set X=m.addVars(P,B,lb=0,ub=21,vtype=GRB.INTEGER, name='X') .
Tried c1=m.addConstrs((X.sum(p, "*")== 30 for p in P));
Also tried c1=m.addConstr((sum(X.select('*',p))== 30 for p in SP)), the results obtained are not correct.
-
I expect the first approach to work correctly:
c1 = m.addConstrs((X.sum(p, '*') == 30 for p in P))
The second approach should work correctly as well (after fixing a few typos), though the first is more clear and concise. What makes you believe the constraints are incorrect? As a sanity check, you could save each of the \( |P| \) row summations as a LinExpr object. Then, after calling Model.optimize(), call LinExpr.getValue() to check the values of the row summations in the optimal solution:
rowsum = {p: X.sum(p, '*') for p in P}
c1 = m.addConstrs((rowsum[p] == 30 for p in P))
# ...
m.optimize()
# check row summation values at optimal solution
for p in P:
print(rowsum[p], '=', rowsum[p].getValue())The result should be something like this:
<gurobi.LinExpr: X[0,0] + X[0,1] + X[0,2] + X[0,3] + X[0,4]> = 30.0
<gurobi.LinExpr: X[1,0] + X[1,1] + X[1,2] + X[1,3] + X[1,4]> = 30.0
<gurobi.LinExpr: X[2,0] + X[2,1] + X[2,2] + X[2,3] + X[2,4]> = 30.0
<gurobi.LinExpr: X[3,0] + X[3,1] + X[3,2] + X[3,3] + X[3,4]> = 30.0You could also use Model.write() to write out an LP file of the model, then visually inspect the constraints for correctness:
m.write('model.lp')
0
Please sign in to leave a comment.
Comments
1 comment