Passing multiple variables across Python function/methods
AnsweredHi all,
I wonder if I can pass multiple/all variables across Python functions considering many variables to pass on so that they are accessible and optimized outside the function. For example:
def vars_constrs(m):
# Create vars and constraints
a = m.addVars(range(10))
b = m.addVars(range(10))
......
z = m.addVars(range(10))
(Create some constraints here)
......
return All_variables
# Main program
m = gp.Model('all')
All_variables = vars_constrs(m)
( Unpack_all_variables(All_variables) )
m.optimize()
# Accessing all variable values
val_a = [a[i].X for i in range(10)]
...
val_z = [z[i].X for i in range(10)]
Is there any way to pack all variables in a function with a single expression All_variables in the function, and then access all the variables when it is called outside the function with Unpack_all_variables? It might be related to m.getvars(), but I am unsure how to do it without indexing.
Thank you.
Best, Panggah.
-
Hi,
You can pack variables as a List in the function:
All_variables = [a, b, c]
Then, variables can be unpacked outside the function like this:
a, b, c = All_variables
Is this the behavior you are looking for?
Thanks,
Ryuta1 -
Hi, Ryuta,
It can be applicable too, however, I will apply the function iteratively so it may not be easy to write down all the variables that are going to be packed.
Does Gurobi provide a way to automatically look for existing variables in the model or function before optimizing so that it can be called with just one argument?
For example, using model.getVars(), I can pack all variables. However, unpacking it will be too tedious because it is a list and I can only access it using an index without the information of the variable names and their tuplelist indices.Thank you,
Best, Panggah.0 -
Hi,
Unfortunately, Gurobi does not currently provide such a method. Is your goal to have each function take only Model object as arguments and refer to the necessary variable objects in the function? A variable object can be a member of a Model object.
m._a = a
m._b = bThis allows variable objects to be passed to each function along with the model object, so that they can be referenced as needed.
Thanks,
Ryuta0 -
Hi, Ryuta,
Sweet. Thank you for your explanation!
Best, Panggah.
0
Please sign in to leave a comment.
Comments
4 comments