sum of square roors in objective
AnsweredHi!
I'm trying to set my objective function with a sum of square roots as following, where x1 … xn are my decision variables and c1... cn are constant:
min f = sqrt((x1-c1)^2) + sqrt((x2-c2)^2) + … +sqrt((xn-cn)^2)
I already tried a workaround by defining new variables using addGenConstrPow(), however as type(x1-c1) seems to be a LinExpr(), python raises the AttributeError: 'gurobipy.LinExpr' object has no attribute '__cindex__'
Is there anything i am overseeing or a smart way to solve the problem?
Thank you in advance!
-
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?. -
The first two arguments to Model.addGenConstrPow() should be Var objects, not LinExpr objects. To avoid this error, you can introduce auxiliary variables \( y_i = x_i - c_i \) for \( i = 1, \ldots, n \), then pass \( y_i \) as an argument to Model.addGenConstrPow().
However, your objective function is equivalent to
$$\begin{align}\min \sum_{i = 1}^n |x_i - c_i|.\end{align}$$
After introducing auxiliary variables \( y_i \) for \( i = 1, \ldots, n\), you can reformulate the above problem as follows:
$$\begin{alignat}{3}\min\ && \sum_{i = 1}^n & \ y_i && \\ \textrm{s.t.}\ && y_i &\geq x_i - c_i &&\quad i = 1, \ldots, n \\ && y_i &\geq c_i - x_i &&\quad i = 1, \ldots, n.\end{alignat}$$
Alternatively, you can use Model.addGenConstrAbs() or the abs_() helper function to model the absolute value terms. Like Model.addGenConstrPow(), using an absolute value general constraint requires you to introduce auxiliary variables for the \( x_i - c_i \) terms.
0 -
Thank you Eli, that helped
0
Post is closed for comments.
Comments
3 comments