Conditional constraint
Answeredfor j in range(100):
C=[]
for i in range(100):
if (c[i]<s[j]) :
C.append(i)
model.addConstr(v[j]== quicksum(c[x] for x in C))
I could not run the program. How could I collect all nodes that c is less than s and use the addConstr function and quicksum function.
-
Hi,
What are the types of c and s? Are they scalars or decision variables?
If they are decision variables: One cannot use a model's decision variables in if-conditions while building the model (since those values are not yet known).
Instead you have to model the if-conditions using MIP constraints. Gurobi offers different types of general constraints that can help you modeling this. In particular, the indicator constraints may be helpful.
In this case, you could introduce some binary auxiliary variables b[i,j] such that b[i,j] == 1 if and only if c[i] < s[j].
Using indicator variables, you could implement this as follows:
b = model.addVars(100, 100, vtype=GRB.BINARY, name="b")
model.addConstrs((b[i, j] == 1) >> (c[i] <= s[j] - epsilon) for i in range(100) for j in range(100))
model.addConstrs((b[i, j] == 0) >> (c[i] >= s[j]) for i in range(100) for j in range(100))Note that I added two sets of indicator constraints for both "directions" of the if and only if condition. Also since Gurobi does not support strict inequalities (<), you should instead use <= with a suitable tolerance epsilon. I would recommend choosing epsilon about as big as FeasibilityTol.
You can then sum up all b[i,j] * c[i]:
model.addConstrs(v[j] == quicksum(b[i, j] * c[i] for i in range(100)) for j in range(100))
Note though that these constraints become quadratic then which may make the model more difficult to solve. If the model becomes too difficult, you could lineare the quadratic terms, but this would further increase the model size.
Best regards
Silke0
Please sign in to leave a comment.
Comments
1 comment