Skip to main content

Passing variables to a function for evaluation then returning the result for optimization

Answered

Comments

2 comments

  • Official comment
    Simranjit Kaur
    • 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 try Gurobot, our chatbot interface offering instant, expert-level support.
  • Jaromił Najman
    • Gurobi Staff

    Hi Marcus,

    You can pass optimization variables as arguments to other functions. However, note that you cannot access their values before an optimization run has been performed. It is because the Var object does not have any value. The parameter fields of a Var object get filled after/during an optimization run and can be accessed via its attributes.

    A simple function to construct some objective function would be:

    import gurobipy as gp
    from gurobipy import GRB

    def myfunc(x,I):
      lexpr = gp.quicksum((i+1) * x[i] for i in range(I))
      return lexpr

    m = gp.Model("test")
    x = m.addVars(5)
    m.setObjective(myfunc(x,5))

    In the above function \(\texttt{myfunc}\) computes the LinExpr object \(1 x_0 + 2 x_1 + 3 x_2 + 4 x_3 + 5 x_4\).

    Best regards, 
    Jaromił

    0

Post is closed for comments.