L1 distance
AnsweredHi,
I'm having an hard time in formulate the following model in gurobipy:

I added the last constrain just to show that my implementation that follows doesn't return the correct result:
def abs_diff(x_1, x_2, m):
z = m.addVar()
y = m.addVar()
m.addConstr(z == (x_1 - x_2))
m.addConstr(y == gp.abs_(z))
return y
def abs_diff_constr(x_1, x_2, d, m):
z = m.addVar()
y = m.addVar()
m.addConstr(z == (x_1 - x_2))
m.addConstr(y == gp.abs_(z))
m.addConstr((y - d) <= 0)
m = gp.Model("isoG1D")
# Create variables
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
x3 = m.addVar(name="x3")
# set objective
obj = - (abs_diff(x1, x2, m) + abs_diff(x2, x3, m) + abs_diff(x1, x3, m) + abs_diff(x3, x1, m))
m.setObjective(obj, GRB.MINIMIZE)
# add constraints
abs_diff_constr(x1, x2, 1, m)
abs_diff_constr(x2, x3, 1, m)
abs_diff_constr(x1, x3, 2, m)
abs_diff_constr(x3, x1, 2, m)
m.optimize()
I would expect the optimal solution to be -6 but instead I'm getting 0.
Can anyone help me with this?
0
-
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 Lorenzo,
The default lower bound of variables is 0. However, you want that your \(\texttt{z}\) variables also attain negative values. Thus, you have to write
z = m.addVar(lb=-GRB.INFINITY)
in both \(\texttt{abs_diff}\) functions.
Best regards,
Jaromił1 -
Amazing!... thanks a lot Jaromił!
0
Post is closed for comments.
Comments
3 comments