Absolute value modelling
AnsweredHi,
I am having problem with this part of my implementation
model = gp.Model()
model.reset()
x = model.addMVar(n1,lb=-1,ub=1)
y = np.zeros(n1)
sum = 0
for i in range(n1-1):
sum += y[i]
objective = model.setObjective(sum, GRB.MINIMIZE)
for i in range(n1-1):
for j in range(m1-1):
constraints1 = model.addConstr(A1[j][i]*x[i] == b[j])
for i in range(n1-1):
if x[i] >= 0:
constraints2 = model.addConstr(y[i] == x[i])
elif x[i] <= 0:
constraints3 = model.addConstr(y[i] == -x[i])
I am trying to get the absolute value of the decision variable x, for the objective of minimizing the sum of the x values. However, I keep getting this error. How do I get over it?
GurobiError: Constraint has no bool value (are you trying "lb <= expr <= ub"?)-
The error is for constraints2 and constraints3. Sorry for not including that
0 -
Hi Peter,
I think there are several things we can look at here:
1) \(\texttt{y = np.zeros(n1)}\) : you will need these to be variables also, as their value depends on x variables.
2) \(\texttt{for i in range(n1-1)}\) : you will want to use \(\texttt{for i in range(n1)}\) instead. For example, run \(\texttt{print(range(3))}\) and look at the result.
3) \(\texttt{objective = model.setObjective(sum, GRB.MINIMIZE)}\) this line is indented when it should not be and you are overwriting \(\texttt{objective}\) each time in the for-loop.
4) \(\texttt{if x[i] >= 0:}\) : you will not know the value of the variables until the model is optimized and so you cannot use them in this way. You need to encode this "if .. then .." logic using mathematics.
Below I have rewritten your code to help your understandingmodel = gp.Model()
model.reset()
m,n = A.shape
x = model.addVars(range(n),lb=-1,ub=1)
y = model.addVars(range(n),lb=0,ub=1)
objective = model.setObjective(y.sum(), gp.GRB.MINIMIZE)
for i in range(n):
model.addConstr(y[i] >= x[i])
model.addConstr(y[i] >= -x[i])
for j in range(m):
model.addConstr(gp.quicksum(A[j][i]*x[i] for i in range(n)) == b[j])
model.optimize()
However my instinct tells me that this formulation does not accurately model your problem, but I cannot address this without knowing your exact problem.
I think it will be worth your time to start with some modeling basics, and this webinar is a good place to start.
Let me know if you need any clarification on what I've written above, and good luck! I hope you enjoy learning to use Gurobi.
- Riley0 -
Thanks a lot!
This was extremely helpful.0
Please sign in to leave a comment.
Comments
3 comments