Skip to main content

How to print the value of Vars within a solution?

Answered

Comments

7 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?.
  • Runqing Zhao
    Gurobi-versary
    Conversationalist
    First Question

    x is a variable in my model

    0
  • Eli Towle
    Gurobi Staff Gurobi Staff

    Hi Runqing,

    tupledict.prod() returns a LinExpr object. You can use the LinExpr.getValue() method to retrieve the value of a linear expression evaluated at the current solution. In your case, you should be able to print the desired value using

    x.prod(cost).getValue()

    Thanks,

    Eli

    0
  • Runqing Zhao
    Gurobi-versary
    Conversationalist
    First Question

    Thank you very much for you help!

    I have solved this problem by your solution.

    -------------------------------------------------------

    I just come up with another question:

    I wanna print the sum of these four items, but it is linear expression again, and getValue is not available because they are list.

    y_flow.select('*', '*', 1)
    y_flow.select('*', '*', 2)
    y_flow.select('*', '*', 3)
    y_flow.select('*', '*', 4)

    How can I solve this one?

    0
  • Jose Vindel
    Gurobi-versary
    Thought Leader
    Investigator

    Hello, 

    Will .getValue() work on something like this?

    \[\max\pi\]
    \[\sum (1 - y_i) \,\leq\,k\]
    \[A \nu = b\]
    \[l_{i} \hat{y}_{i}^{R} \, \leq v_{i} \, \leq u_{i} \hat{y}_{i}^{R}\]
    \[\pi\,\leq f_{0}(\tilde\nu^R)\,-\,M\sum\limits_{i \in I_{R}^{+}}(1 - y_{i})\tilde\nu_{i}^R\,+\,M\sum\limits_{i \in I_{R}^{-}}(1-y_{i})\tilde\nu_{i}^{R}\]

    I am interested in getting the values of v and pi so I can add some lazy cuts

    0
  • Eli Towle
    Gurobi Staff Gurobi Staff

    Hi Runqing,

    Although y_flow.select('*', '*', 1) is not a linear expression object, y_flow.sum('*', '*', 1) is. Thus, you could use the getValue() method of this expression instead. More information on the tupledict.sum() method can be found here.

    Alternatively, you could sum the variable values using the X attribute:

    sum(y.X for y in y_flow.select('*', '*', 1))

    Jose, you can query the individual values of variables with the X attribute. To do this inside of a callback when a new feasible MIP solution is found, you can use Model.cbGetSolution() in the MIPSOL callback. For code examples of this, I recommend looking at callback.py and tsp.py from the examples library.

    Thanks,

    Eli

    1
  • Runqing Zhao
    Gurobi-versary
    Conversationalist
    First Question

    Hi Eli,

    Your suggestion works well. Thank you very much!

     

    Runqing

    0

Post is closed for comments.