Wrapper for Gurobi var?
AnsweredHello, everyone
I'm writing a Benders algorithm and there is a programming problem that I just cannot solve.
As you know, Benders is an iterative method that goes back and forth between a master problem and a subproblem. Its upper bound (for minimization problems) is not necessarily decreasing so you could very well find one optimal solution in the first iteration and spend the rest of the time just improving the LB.
The thing is: is there any way to write a wrapper for Gurobi vars in Python with a x property that instead of returning the vars' x of the last time the model was run, it returns the vars' x for the best solution found in BD? What I'm trying to do is to create a wrapper that behaves just as a var except when the x property is accessed, so I can seamlessly switch between BD and a direct approach with Gurobi without having to change too much of the code. I would say that this would be generally possible in Python, but I'm not sure it is possible with gurobipy. Whenever I try to inherent gurobipy.Var, I get a RecursionError.
P.S: reoptimizing the models is not an option. I'm also open to suggestions other than wrappers.
Thanks in advance!
Bruno
-
Hi Bruno,
An alternative to extension through inheritance, is composition. You can also make use of automatic delegation.However trying to use either approach, to substitute an object from a 3rd party API (such as gurobipy) is very risky as there may be type checking under the hood, and cause unexpected behavior that you do not realize.
Would it be possible in your case to just define a method to switch between the solution values and monkey patch it on (for aesthetics)? E.g.
def set_BD_solution(var, x):
var._BD_solution = x
def get_BD_solution(var):
return var._BD_solution
def switch_X(var, BD=False):
if BD:
return get_BD_solution(var)
return var.X
# monkey patch if required
gp.Var._X = switch_X
gp.Var._set_BD_solution = set_BD_solution
gp.Var._get_BD_solution = get_BD_solution
# define variables after monkeypatching
# for a variable "var" access like so
var._X() # optimal solution
var._X(BD=True) # Benders solution
- Riley1 -
Hey, Riley
Thanks for the tip! At the end, I chose to follow your advice and it's working just fine
Thanks!0
Please sign in to leave a comment.
Comments
2 comments