Single Constraint with Sum of Binary Variable
AnsweredI am new to this community and am struggling with seemingly simple modeling question.
I would to create a single constraint that sums a set of binary variables x[i,j] where i = j for all i in V and sets it equal to a predefined value p.
Example:
x[1,1] + x[2,2] + ... +x[n,n] = p
The x[i,j] variable can be thought of as an edge on a graph, i and j are indexed on the vertices of the graph, and x[i,i] is an edge that goes back to the same vertex.
I am using python with gurobi and here is the code I tried:
m.addConstrs(x.sum(i, i) == p for i in V)
It returns a constraint for each value of i in V.
Any help would be appreciated.

Model.addConstrs() is used to add multiple constraints to the model. To add one constraint to the model, use Model.addConstr().
You are summing over all \(i\) in \(V\), so the \(\texttt{for}\) loop should be placed inside of the summation:
x = m.addVars(V, V, vtype=GRB.BINARY, name='x')
m.addConstr(gp.quicksum(x[i, i] for i in V) == p)0 
Eli  That did the trick. Thank you.
0
Please sign in to leave a comment.
Comments
2 comments