Retrieving value of a second objective function in single-objective function optimization
AnsweredHello,
I am currently working on a multi-objective optimization model in Gurobi Python, where the optimization model has two objective functions.
When optimizing the model, I would like to optimize only one of the objective functions in a first iteration and then, both objective functions in a second iteration.
Now, I was wondering if it is possible in the first iteration to not only retrieve the objective function value of function 1 that has been considered during this single-objective optimization process, but also the objective function value of function 2? In other words, is there perhaps sort of a Python command for Gurobi that would allow me to get the objective function value of the (not optimized) function 2 for the decision variable values obtained by optimizing objective function 1? Or is there no other way than to somehow manually calculate the value of objective function 2 in the first iteration?
Any help that could be provided is highly appreciated.
Kind regards,
Niklas
-
If you want to evaluate a function at the optimal solution of your single-objective solve, you could:
- Create a linear expression (or quadratic expression) representing the second objective function
- After optimizing, call LinExpr.getValue() (or QuadExpr.getValue()) to compute the value of the expression at the current solution
Below is an example code snippet that does this, modified from the mip1.py example:
import gurobipy as gp
from gurobipy import GRB
m = gp.Model()
x = m.addVar(vtype=GRB.BINARY, name="x")
y = m.addVar(vtype=GRB.BINARY, name="y")
z = m.addVar(vtype=GRB.BINARY, name="z")
m.addConstr(x + 2 * y + 3 * z <= 4, "c0")
m.addConstr(x + y >= 1, "c1")
# Set the objective function
obj1 = x + y + 2 * z
m.setObjective(obj1, GRB.MAXIMIZE)
# Function we want to evaluate after solving
obj2 = 3 * x + 2 * y + z
m.optimize()
print("Optimal objective value:", m.ObjVal)
print("Value of obj2 at current solution:", obj2.getValue())The output printed at the end is:
Optimal objective value: 3.0
Value of obj2 at current solution: 4.00 -
Hello Eli,
Thank you for the fast response. That's exactly what I was looking for!
Best regards,
Niklas
0
Please sign in to leave a comment.
Comments
2 comments