Why Variable is not in model after model.copy()
AnsweredI have built a model called m and a linear expression lin_exp with variables x.
And I used the function m.copy() to create another model n.
Now, I want to modify the objective function of n.
I tried to call the function n.setObjective(lin_exp).
Unfortunately, gurobi told me "Variable not in model".
Besides, I tried to simplify the model m with function ps_m = m.presolve().
The function ps_m.setObjective(lin_exp) is still errored with "Variable not in model".
A simplified code block is as shown as follows:
m = gp.Model() # variables, constraints, objective function are defined
lin_exp = gp.LinExpr(x) # a long linear expression
m.update()
n = m.copy()
n.setObjective(lin_exp) # ERROR "Variable not in model"
ps_m = m.presolve()
ps_m.setObjective(lin_exp) # ERROR "Variable not in model"
-
Hi Runfeng,
in Gurobi a variable is an object which is tied to a model instance. Whenever you create a new model instance (e.g. by copying or creating a presolved model) you also generate "new" variables.
One way to go about this could be, for example, trying to recreate the LinExpr by storing the names of the variables which are included in it in a list and then rebuilding it by, say:
LinExprN = gp.LinExpr([1 for _ in var_names_to_include], [n.getVarByName(i) for i in var_names_to_include])
Perhaps someone from Gurobi team can offer a more efficient approach?
Best regards
Jonasz0 -
Hi Jonasz,
Thank you for your plain explanation and timely reply!
And I will try this method to recreate my codes.Best regards,
Runfeng0 -
Hi Runfeng, hi Jonasz,
Perhaps someone from Gurobi team can offer a more efficient approach?
Jonasz reply is correct, a Gurobi Var object is always associated with a particular model. It is not possible to create variables (or constraints) only once and use them on multiple models.
Rebuilding the LinExpr as Jonasz suggests is the way to go.
Best regards,
Elisabeth
0 -
Hi Elisabeth,
Thank for your reply! And it really helps.
Best regards,
Runfeng0
Please sign in to leave a comment.
Comments
4 comments