How to return value of variables in python Gurobi interface
AnsweredHi,
I have a MIP problem coded in python. Following is a code for illustration
def problem():
- m = Model()
- add variables : x = {}
- add constraints: ax <=b
- add objective: min cTx
- m.optimize()
- return x
Next, I call the function
xvalue = problem()
- print(xvalue) #print command 2
Now xvalue does not give me the value of the variable.
I get the following (1, 1, 1, 1): <gurobi.Var *Awaiting Model Update*>, Can anyone help me with this?
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Gurobi does not store all data that belongs to a variable inside the Python Var object. You need to have the Model object still around for querying solution data for example. In your code, though, everything related to the Model is only available within the function scope but not outside.
A possible solution would be to pass the solution values along with the variable names in a dictionary:
import gurobipy as gpfrom gurobipy import GRB
def opti():m = gp.Model("mip1")x = m.addVar(name="x")y = m.addVar(name="y")z = m.addVar(name="z")m.setObjective(x + y + 2 * z, GRB.MAXIMIZE)m.addConstr(x + 2 * y + 3 * z <= 4, "c0")m.addConstr(x + y >= 1, "c1")m.optimize()return {x.varName: x.X}
print(opti())1 -
Well, then you can change the last line to:
solvals = opti()
The main point here is that you need to store the values you need in some other form because you cannot access them outside the scope where Model exists.
1 -
I deleted the previous comments for better readability.
Cheers,
Matthias0 -
Hello,
I was not clear with my objective. I am not looking to print those in a function. I need to use the value of variables for next iteration.
I hope now my objective is clear.
Amogh
0
Post is closed for comments.
Comments
5 comments