4
$\begingroup$

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__'.

$\endgroup$
3
$\begingroup$

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()
| improve this answer | |
$\endgroup$
  • $\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 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 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.