Is it possible to retrieve variables as tuplelist outside the model definition scope in gurobipy?
AnsweredHello,
I'm using gurobipy to solve a model.
Now I would like to make the definition of the model (variables, constraints, and objectives), and the output of the result in separate functions in order to make the output more readable. For example, in problems like VRP or TSP, the binary variables x[i,j] indicate whether or not the vehicle travels from station i to j. Then, to retrieve the sequential route and compute some problemspecific values like emissions/travel time, some logic is better implemented in a single function. So the coding structure would be like:
import gurobipy as gp
def model_create_and_solve():
m = gp.Model()
# add vars...
x = m.addVars(station_station_indices, vtype=GRB.BINARY, name="visit_truck")
# ...more vars...
# add constraints...
# add objectives...
m.optimize()
return m
def result_post_process(m):
# process to output the results based on values of the variables
# main function
if __name__ == '__main__':
model = model_create_and_solve()
result_post_process(model)
Currently, I'm using the following APIs to retrieve the variables:
model.getVars()
model.getVarByName()
It works but is not that convenient compared to the direct use of x (the variable used in the definition, which is not accessible out of the scope). The major inconvenience is that with x (as a tupledict), I could call methods like x.select to easily access the variables with certain indices. But using getVars/getVarsByName, the indices are wrapped into the variable names as strings, so that I have to write additional codes to parse the indices, e.g.,
for var in model.getVars():
varName = var.VarName
i, j = varName[varName.find('[') + 1:varName.find(']')].split(',')
So is there any way that allows me to access the variables as a tupledict() outside the model definition scope after solving?

Hi Runqiu,
You can store the data structure containing the variables as a new member of the model object:
def model_create_and_solve():
m = gp.Model()
# add vars...
x = m.addVars(station_station_indices, vtype=GRB.BINARY, name="visit_truck")
# ...more vars...
# add constraints...
# add objectives...
m.optimize()
# store interesting variables for later inspection
m._x = x
return m
def result_post_process(m):
# process to output the results based on values of the variables
x = m._x
...Alternatively, you could also return the variables separately with the model. Keeping a reference in the model itself is probably easier, though.
I hope that helps.
Cheers,
Matthias0
Please sign in to leave a comment.
Comments
1 comment