Suppose I have made a Gurobi model in Python model = Model()
, defined variables, constraints, objective function, and solved it. However, I want to make a deepcopy of model
denoted as new_model
. How should I make a deepcopy of this model? I have tried new_model = copy.deepcopy(model)
, but it causes an error KeyError: '__deepcopy__'
.
$\begingroup$
$\endgroup$
-
$\begingroup$ How about this? gurobi.com/documentation/9.0/refman/py_model_copy.html $\endgroup$ – dhasson Apr 29 '20 at 5:20
-
$\begingroup$ Thank you. But, when I want to add more constraints, it results in an error "GurobiError: Variable not in model" $\endgroup$ – Katatonia Apr 29 '20 at 5:29
$\begingroup$
$\endgroup$
This question and answer are directly related to your question. But you can also look at Gurobi's discussion about copying a model in its own website, or this google group. In summary, you need to name your variable, and after copying the model remap your variable with those names(which need to be saved before).
from gurobipy import Model
# A model with 10 variables...
variable_names = {}
model = Model("test")
variables = {}
for i in range(10):
variable_names[i] = "var{0}".format(i)
variables[i] = model.addVar(lb=-1, ub=1, name=variable_names[i])
model.update()
new_model = model.copy()
new_var = {}
for i in range(10):
model.addConstr(variables[i] <= 0)
new_var[i] = new_model.getVarByName(variable_names[i])
new_model.addConstr(new_var[i] >= 0)
model.update()
new_model.update()
-
$\begingroup$ Thank you so much. But, what if we define variables as Y = model.addVars(J, N, vtype=GRB.BINARY, name='Y_Variable') $\endgroup$ – Katatonia Apr 29 '20 at 8:06
-
$\begingroup$ I think whatever you have in the declaration of each variable, is iterable and can be done inside a loop. If you have more than one index, maybe two nested loops. $\endgroup$ – Oguz Toragay Apr 29 '20 at 14:39