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 problem-specific 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
m = gp.Model()
# add vars...
x = m.addVars(station_station_indices, vtype=GRB.BINARY, name="visit_truck")
# ...more vars...
# add constraints...
# add objectives...
# process to output the results based on values of the variables
# main function
if __name__ == '__main__':
model = model_create_and_solve()
Currently, I'm using the following APIs to retrieve the variables:
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?
Please sign in to leave a comment.