How to make a copy of a Gurobi model and add constraints to the copy in Python?
You are on the right track with getVars() - you really do need to get the variables of the copied model again to be able to add new constraints. The variables of the original model are only going to refer to the original model, even if they may have the same name. Think of the variables as handles for the actual variables in the model - they can only refer to one model.
I'm trying to implement a dive-and-fix algorithm in Gurobi. What I want to build is a function into which you put an optimized model last_model, make a deepcopy of this model called new_model and add certain constraints to new_model accoording to certain optimized values of last_model.
I found the function .copy() that would make a deepcopy for me. But I’m still having an awful time adding constraints to my copied new_model as I can’t in any way alter my constraints. (And yes, i am using last_model.update() before copying)
If I don’t do anything to my variables after new_model = last_model.copy() and tried to add a constant on z, it would tell me that Variable not in model.
I’ve tried .getVarByName(‘z’), which would tell me that z was a NoneType. (I found this on stackexchange)
I’ve tried new_model._data = last_model._data, which just returns that the function _data does not exist. (I found this on the gurobi support site)
I’ve tried .getVars which would just create a list and does not allow me to add any constraints on the actual variables.