How to set two sets of binary variables equal to each other when they have different keys?
AnsweredI have two sets of binary variables, aux and aux1. I am using them to make sure that two other variables only take on certain values from different lists.
aux looks like this (with 1 of them being 1 and the rest 0):
aux = m.addVars(allowed_values, vtype=GRB.BINARY, name='aux')

and aux1 looks like this (again, with only one of them being 1 and the rest 0):
aux1 = m.addVars(allowed_vals_occ, vtype=GRB.BINARY, name='aux1')

As you can see, the two sets of variables have different keys (they have the same length). I want to make sure they are both 1 at the same location. For example, if the first element of aux is 1, I want the first element of aux1 to be 1.
I tried: m.addConstrs(aux[i]==aux1[i] for i in range(len(aux)))
But this gives me an error because aux and aux1 have different keys.
m.addConstr(aux==aux1) gives a generator error.
How can I solve this problem?
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
The keys for \( \texttt{aux} \) are \( \texttt{allowed_values} \), and the keys for \( \texttt{aux1} \) are \( \texttt{allowed_vals_occ} \). Thus, we have to map back to these values when adding the constraints:
m.addConstrs(aux[allowed_values[i]] == aux1[allowed_vals_occ[i]] for i in range(len(aux)))
This is a bit messy. It would be much cleaner to use the same indices for each of these variables. The keys themselves don't need to be anything special, since we can easily map from an index to a specific "allowed" value with the \( \texttt{allowed_values} \) and \( \texttt{allowed_vals_occ} \) lists. So, we can use:
n = len(allowed_values)
aux = m.addVars(n, vtype=GRB.BINARY, name='aux')
aux1 = m.addVars(n, vtype=GRB.BINARY, name='aux1')
m.addConstrs((aux[i] == aux1[i] for i in range(n)), name='set_aux1')Even better, we could completely remove the \( \texttt{aux1} \) variables. Wherever we would use \( \texttt{aux1} \), we can just use the corresponding \( \texttt{aux} \) variable (since they would be equal anyways):
n = len(allowed_values)
aux = m.addVars(n, vtype=GRB.BINARY, name='aux')1 -
Thank you so much, Eli! This is very helpful.
0
Post is closed for comments.
Comments
3 comments