Skip to main content

Is it able to define setObjective function by def or lambda?

Comments

3 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

    Hi!

    I don't understand what you mean by "computation is big". Gurobi does not accept implicit objective functions. You need to specify all coefficients explicitly. You can, of course, split the code into several parts and add up multiple expressions when setting the objective.

    Cheers,
    Matthias

    0
  • Yu Iwasaki
    Gurobi-versary
    First Comment
    First Question

    Hello, Miltenerge!

    Thank you for your message.

     

    "Computation is big" means that "If I have to write objective function as one line, gurobi will compute uselessly."

     

    I have to compute like below simplely.

    I'd like to minimize "sum + variance", however, If I write objective function as one line, variance code have to compute "sum" twice.

     

    ```

    import math
    import tsplib95
    import time
    import gurobipy as gp

    a = [1, 2, 3, 4, 5]

    tsp_model = gp.Model(name="tsp")

    tsp_model.setObjective(
    # sum
    sum(a) +

    # variance
    sum(
    [(x - sum(a) / len(a)) * (x - sum(a) / len(a)) for x in a]
    )
    )

    ```

     

    So, I'd like to change like below.

     

    ```

    a = [1, 2, 3, 4, 5]

    tsp_model = gp.Model(name="tsp")

    def user_objective():
    s = sum(a)
    variance = sum((x - s / len(a)) * (x - s / len(a))for x in a)

    tsp_model.setObjective(user_objective)

    ```

    This code can save computation about sum, so O(N^2) -> O(N).

    However, this setObjective will not work.

     

    Could you teach me , when setting the objective, how should I set up multiple expressions?

     

     

    Thank you!

     

    0

Post is closed for comments.