Is it able to define setObjective function by def or lambda?
Hello.
I'd like to set setObjective by def or lambda. Because if I use setObjective in one line code, computation is so big!
tsp_model.setObjective(gp.quicksum(G[i][j] * x[i, j, k] for i in range(N) for j in range(N) for k in range(K)) / K +
(1 / K)
*
gp.quicksum(
(
gp.quicksum(G[i][j] * x[i, j, k] for i in range(N) for j in range(N))
-
(1 / K) * gp.quicksum(G[ii][jj] * x[ii, jj, kk] for ii in range(N) for jj in range(N) for kk in range(K))
) *
(
gp.quicksum(G[i][j] * x[i, j, k] for i in range(N) for j in range(N))
-
(1 / K) * gp.quicksum(G[ii][jj] * x[ii, jj, kk] for ii in range(N) for jj in range(N) for kk in range(K))
)
for k in range(K)
)
,
sense=gp.GRB.MINIMIZE)
I'd like to rewrite upcode to below.
def objective():
avg = gp.quicksum(G[i][j] * x[i, j, k] for i in range(N) for j in range(N) for k in range(K)) / K
ret = avg + gp.quicksum(gp.quicksum(G[i][j] * x[i, j, k] for i in range(N) for j in range(N)) - avg for k in range(K))
return ret
tsp_model.setObjective(objective, sense=gp.GRB.MINIMIZE)
If I can use function or lambda to setObjective, computation time will be faster.
Thank you.
-
Official comment
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?. -
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,
Matthias0 -
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.
Comments
3 comments