Skip to main content

How to return value of variables in python Gurobi interface

Answered

Comments

5 comments

  • Official comment
    Simranjit Kaur
    Gurobi Staff Gurobi Staff
    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?.
  • Matthias Miltenberger
    Gurobi Staff Gurobi Staff

    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 gp
    from 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
  • Matthias Miltenberger
    Gurobi Staff Gurobi Staff

    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
  • Matthias Miltenberger
    Gurobi Staff Gurobi Staff

    I deleted the previous comments for better readability.

    Cheers,
    Matthias

    0
  • Amogh Bhosekar
    Gurobi-versary
    Conversationalist
    Curious

    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.