Use value of Var as dictionary key
AnsweredHi all,
I have the following Var and corresponding constraints:
m = gurobi.Model()
s_vars = m.addVars(4, lb=0, ub=5, vtype=gurobi.GRB.CONTINUOUS, name='s')
m.update()m.addConstr(s_vars[0] == 2)
m.addConstr(s_vars[1] == 2)
m.addConstr(s_vars[2] == 0)
m.addConstr(s_vars[3] == 3)m.optimize()
In addition, I have a dictionary:
optimal_values = defaultdict(int)
optimal_values[0] = 0
optimal_values[1] = 10
optimal_values[2] = 100
optimal_values[3] = 1000
If I run
gurobi.quicksum([optimal_values[s_var] for s_var in s_vars])
the output is
<gurobi.LinExpr: 11100.0>
I expected this to be 12000
Running
gurobi.quicksum([optimal_values[s_var.Xn] for s_var in s_vars.values()])
shows
<gurobi.LinExpr: 12000.0>
Although the second option gives the right output, I am note sure whether this is the appropriate methodology. Maybe I am mistaken, but I haven't seen any other code that uses Xn in quicksum. Please advice
-
Hi,
The addVars function returns a tupledict. As a consequence, the values of \(\texttt{s_var}\) in the
for s_var in s_vars
loop return the keys to the variables, i.e., values \(0-3\). Thus, the \(\texttt{quicksum}\)
gp.quicksum([optimal_values[s_var] for s_var in s_vars])
returns the sum over
optimal_values[0], optimal_values[1], optimal_values[2], optimal_values[3]
However, the second quicksum
gp.quicksum([optimal_values[s_var.X] for s_var in s_vars.values()])
actually accesses the variable objects because you loop over the variable objects as you use \(\texttt{s_vars.values()}\). This then sums the values
optimal_values[s_var[0].X], optimal_values[s_var[1].X], optimal_values[s_var[2].X], optimal_values[s_var[3].X]
This is the same as
gp.quicksum([optimal_values[s_vars[s_var].X] for s_var in s_vars])
This is OK as long as you can ensure that the variable solution values are integer and within the \(0-3\) range.
Best regards,
Jaromił0
Please sign in to leave a comment.
Comments
1 comment