Indexing over specific sets depending on index of variable
Awaiting user inputHi,
I have a set of indices (U[v]) tied to the index of my decision-variable b[v,t] but I can't seem to make it work. A small version of the problem reads as follows:
T = [7,8,9]
V = [0,1,2,3]
U = [[0,1,2], [1,2], [2,3,4] [3,4]] #set of indices
b[t,v] is a set of tuples: [(t,i) for t in T_idx for i in Vp_idx]
The constraints will depend on the set of indices, for example v=0:
(b[t,0] <= sum(b[t+1, j] for j in U[0]) ) for all t in T[0:-1]
i.e. since U[0] = [0,1,2] i want:
b[7,0] <= b[8, 0] + b[8,1] + b[8,2], and
b[8,0] <= b[9,0] + b[9,1] + b[9,2],
for all v in V of course.
***
I've tried a couple different ways:
1:
for v in V:
m.addConstrs((gp.quicksum(b[t+1,j] for j in U[v]) >= b[t,v] for t in T[0:-1]), "test")
2:
for v in V:
for t in T:
m.addConstr(help_U[t,v] == sum(b[t,j] for j in U[v]))
m.addConstrs((help_U[t+1,v] >= b[t,v] for v in V for t in T[0:-1]), "test")
3.
m.addConstrs((gp.quicksum(b[t+1,j] for j in U[v]) >= b[t,v] for t in T[0:-1] for v in V, "test")
(With reservation that I might have made some typos when trying to generalize this somewhat)
Invariably I get KeyError: (1,107)
Any help would be appreciated!
-
Hi Johanna,
I think something like the following should work
import gurobipy as gp
m = gp.Model()
T = [7,8,9]
V = [0,1,2,3]
U = [[0,1,2], [1,2], [2,3,4], [3,4]] #set of indices
b = m.addVars(T,5,name="b") # here 5 is set as second dimension because the indices in U go up to 4
for v in V:
L = U[v] # get index list U[v]
for t in T[:-1]: # don't use last index in T to avoid key errors
m.addConstr(b[t,v] <= gp.quicksum(b[t+1, l] for l in L), name="con_v%d_t%d"%(v,t))
m.write("myLP.lp") # write human readable LP file to analyzeIs this what you were looking for? You can have a look at the generated \(\texttt{myLP.lp}\) file to check whether the constraints look as they should.
Best regards,
Jaromił0
Please sign in to leave a comment.
Comments
1 comment