Skip to main content

How to obtain a feasible solution within constraints?

Answered

Comments

5 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

    Could you please elaborate a bit more on what exactly is your issue? Gurobi can solve models with constant objective functions. After a call to optimize() and a successful optimization run, you can access the feasible solution point via the X attribute.

    0
  • Linne Li
    • Gurobi-versary
    • First Comment
    • First Question

    I upload some details. Actually, after optimization, the var in m.getVars() has no accessible X attribute. I tried several ways with different objective functions, but they weren't working at all.  Does this mean the optimization didn't run properly? but I got no error or warning. My test is 

    Optimisation(np.array([[1,1],[1,1]]), N)
    0
  • Linne Li
    • Gurobi-versary
    • First Comment
    • First Question

    OK, I got it. The problem is my bound N, I got no assigned value because I have no feasible solution at all. Very negligent. Thanks for your time!

    0
  • Jaromił Najman
    • Gurobi Staff

    This is a scoping issue. The model you define lives only within the \(\texttt{Optimisation}\) function. There are two ways to deal with this. The first option is to gather all solution information you need at the end of the \(\texttt{Optimization}\) function and return this information

    def Optimisation(...)
    [...]
    m.optimize()
    result = []
     for x in m.getVars():
          result.append((x.VarName,x.X))

    return result

    # outside of the Optimisation function
    res = Optimisation(np.array([[1,1],[1,1]]), 1)
    print(res)

    An alternative would be to generate the model before the function call and pass it as an argument

    def Optimisation(m, distance, P, log_file=None):
    [...]
    m.optimize()

    # outside of the Optimisation function
    # Create a new model: resource assignment problem
    m = gp.Model()
    Optimisation(m, np.array([[1,1],[1,1]]), 1)
    for v in m.getVars():
      print("%s: %f"%(v.VarName,v.X))

    Any of the two works. Note that I removed the call to the terminate method, because it only interrupts a currently running optimization process and does nothing when called after optimization has already been performed. Moreover, you should always check for a model's Status attribute before accessing the solution point, because a solution point will not be available if the model is infeasible.

    Best regards, 
    Jaromił

    0

Post is closed for comments.