Branch and Bound algorithm
AnsweredHello :)
I'm currently working on implementing the Branch and Bound algorithm with Python.
My values are binary integers.
For implementing I'm using a CSV. In this CSV my program is able to get the values of the Objective function and also my constraints.
After this I implement the variables depending on the number of rows in my CSV.
This leads to my problem. I want to create an algorithm. This means that my program needs to be adjusted depending on the number of variables and accordingly I can not use the expression "x1_value = milp_model.getVarByName("x1").x" and so on. Because in some kind of cases I have two variables and therefore I only need x1_value and x2_value and in other cases i have four variables and the programm needs to adapt to this.
Is there any other option to get the value of my variable? I thought about something like this:
def update_values(n, milp_model):
values = []
for i in range(1, n+1):
variable_name = f"x{i}"
value = milp_model.getVarByName(variable_name).x
values.append(value)
return values
but in this case I have the problem that variable_name must be enclosed in quotation marks, so this doesn't work.
I would appreciate any help!
Kind regards
Chiara

Hi Chiara,
The best way to do this is to simply keep your variables in memory.
model = gp.Model()
x = model.addVars(N)
def update_values(N, x): values = [] for i in range(N): value = x[i].X values.append(value)
# also values = [x[i].X for i in range(N)] return valuesThis will give you easy access to the solution values without having to call \(\texttt{model.getVarByName}\).
Cheers,
David0 
Thanks a lot David :)
This is the perfect way to solve my problem.
Have a nice day!0
Please sign in to leave a comment.
Comments
2 comments