Get variables indexes
AnsweredHi everyone,
I have a binary variable, named X, with two indexes (X_i,j). After running the optimization, I want to know for what index in i, is the binary variable X equal to one. I've written the script as in below, however, this way, the v.index is the multiplication of i times j. I would also like to know, for each i (where X_i,j == 1), what are the j's for which X_i,j == 1. If I print, the binary variable, it looks like this: X[221,8759] (value 0.0)>}.
In short, what I want is a list, with the i indexes for which X_i,j ==1, but not with repeated i's and another list with the j indexes corresponding to each i for wich X_i,j == 1.
X_index = []
for v in X.values():
if v.X == 1:
X_index.append(v.index)

Hi José,
"v.index" will give you the index of the variable in the model. This is different from your indices i and j, as it is an internal Gurobi variable counter.
I believe what you want is the following (assuming that X is a tupledict created using model.addVars()):
import collections
nonzeros_ij = collections.defaultdict(list)
any_nonzero_i = set()
for (i, j), v in X.items():
if v.X > 0.9: # best to allow for numerical tolerances
nonzeros_ij[i].append(j)
any_nonzero_i.add(i)"nonzeros_ij" will then be a mapping from an index i to a list of j indices such that X[i,j] is nonzero, while "any_nonzero_i" will be a set of i indices for which X[i,j] is nonzero for some j
0 
Hi Simon,
Thank you so much for your reply, it is exactly what I was looking for. Nevertheless, there is something still troubling me.
I have another variable with the same i and j, HP which is a tupledict created using model.addVars() and this time it's continuous. In this case, besides doing the same as you wrote above, I would also like to get the value of the variable HP, in different lists according to each i at every j. Actually, it's quite similar to getting the nonzeros_ij dictionary that you wrote but this time appending the variable value instead of the j.
Could you write down how to do it since I'm not being able to?
Thank you once more,
José Rodrigues
0 
You can retrieve variable values after optimizing with the X variable attribute. For example, Simon used this attribute check with the variable value \(\texttt{v.X}\) is greater than 0.9 in the conditional \(\texttt{if v.X > 0.9}\). For more details, see How do I retrieve variable values after optimizing?
0
Please sign in to leave a comment.
Comments
3 comments