Use objective value from objectivefunction as constraint
AnsweredI am using Gurobi Python to elaborate a linear program in diet problems. And I have constraints that depend on the objective value.
My objective function is to maximize the food's energy. The function contains a set of quantity foods that I can separate in meals after the solver.
I have a set of constraints that are the maximum and minimum nutrients to be consumed per day. Also, I have a second set of constraints that control how much nutrients you need according to the total energy of the food.
The first set has fixed values which I determined; the second set has changeable values, however. This second set needs the total energy value which is only got by the objective function. This value is got after the optimization when the model is finished, giving the total energy and quantity of each food.
Example:
MAX e1*x1 + e2*x2 + ... + eN*xN = TotalEnergy
constraints,
c1*x1 + c2*x2 + ... + cN*xN >= ConstraintA
e1*x1 + e2*x2 >= 40%TotalEnergy
I would like to know if I can get the objective function value during optimization and use it as a constraint. Like taking an attempt at a solution or subsolution from the gurubi when solving the problem.
Two of the solutions are making the second model or adding those new constraints and optimize again but I would like if is possible making all in one model in code

You can create a new variable and add a constraint requiring it to be equal to the energyweighted sum of the \( x \) variables. Then, set your objective function equal to this new variable. You can use this variable in the constraints as needed. For example:
$$\begin{alignat*}{2} \max_{x,z}\ && z \qquad \qquad \qquad \quad & \\ \textrm{s.t.}\ && e_1 x_1 + \ldots + e_n x_n &= z \\ && c_1 x_1 + \ldots + c_n x_n &\geq b \\ && e_1 x_1 + e_2 x_2 &\geq 0.4 z \\ && x, z &\geq 0. \end{alignat*}$$
1 
The answer of Eli Towle helped me to solve my problem.
I've created a variable \(z\) that received the sum of \(x_i \) foods multiplied with \(e_i\) food's energy and I set this variable into objectivefunction.
Then, I implemented the second set of constraints are changeable values that need the objectivefunction value.
\[\begin{align} z = \sum_{i=1}^n x_i e_i \\ \max_{x,z} z \\ \text{s.t } c_1 x_1 + ... + c_n x_n \geq b \\ e_1 x_1 + e_2 x_2 \geq 0.4 z \\ e_3 x_3 + e_4 x_4 \geq 0.6 z \\ x, z \geq 0. \end{align}\]
In Python, looks like it worked. I have tested it and most of the results respected the restrictions. Of course, the model sometimes results in unfeasible states. Maybe I will work with relaxation functions.
It was expected that the variable \(z\) updates every time Gurobi tries to do a new calculation during its optimization. Therefore, the values of the mutable constraints change too.
0
Please sign in to leave a comment.
Comments
2 comments