conditionally apply constraints in optimization problems
回答済みIm working on a problem and chose guroby as a tool for it, however i am going through an issue. I want to apply a constraint if and only if one of the variables exceeds a certain threshold. Variables are integers, and my desired constraint is the following;
with variables x[0] x[1] x[2] x[3] being the load of products 1-4 carried by a truck x, if x[2] is above 3, make x[1] be at least 4. Otherwise if x[2] isnt >=3 ignore this constraint.
How could this be done through using gurobi?
m = gp.Model()
# Define the decision variables
x = m.addVars(4, name="x", ub=5)
y = m.addVars(4, name="y",ub=5)
z = m.addVars(4, name="z",ub=5)
w = m.addVars(4, name="w",ub=5)
#trucks
xtot = x[0]+x[1]+x[2]+x[3]
ytot = y[0]+y[1]+y[2]+y[3]
ztot = z[0]+z[1]+z[2]+z[3]
wtot = w[0]+w[1]+w[2]+w[3]
#box types:
foods=x[0]+y[0]+z[0]+w[0]
meds=x[1]+y[1]+z[1]+w[1]
surgs=x[2]+y[2]+z[2]+w[2]
cloths=x[3]+y[3]+z[3]+w[3]
# Define the objective function
m.setObjective(xtot + ytot + ztot + wtot, sense=gp.GRB.MAXIMIZE)
# Define the constraints
# max bus load
m.addConstr(xtot <= 10)
m.addConstr(ytot <= 10)
m.addConstr(ztot <= 9)
m.addConstr(wtot <= 9)
#boxes available
m.addConstr(foods <= 12)
m.addConstr(meds <= 17)
m.addConstr(surgs <= 11)
m.addConstr(cloths <= 18)
-
正式なコメント
This post is more than two 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 try Gurobot, our chatbot interface offering instant, expert-level support. -
Have you seen our Knowledge Base article How do I model conditional statements in Gurobi? This may be useful to you.
0 -
Thanks for the suggestion! I did read that one previously, and all the documentation i could find in gurobi, but it showed a result which differs with the one i need in the sense that:
1- it is continuous rather than discrete values
2- the condition compares the value of two variables rather than comparing a single variable to a threshold value.
Tryed to apply it to my code but i couldnt make it work, im sure the result is close to what that one article promotes, but im having a hard time adapting it to my case.
0 -
this is how i applyed it:
eps = 0.0001
M = 5 + eps
xb = m.addVar(vtype=gp.GRB.BINARY)
m.addConstr(x[2] >= 3 + eps - M * (1 - xb))
m.addConstr(x[2] <= 3 + M * xb)
m.addConstr((xb == 1) >> (x[1] >= 4))0 -
ok im so sorry for the dumb question, found out all i had to do is take out the 3 in the second constraint and substitute by a 2 since both statements were triggered with a x[2] == 3, thank you so much for the help, have a great day.
0 -
Since your x[2] variable is integer, you do not need the eps value in the first constraint, it might even lead to numerical issues (or forbid x[2] == 3 in some cases).
0
投稿コメントは受け付けていません。
コメント
6件のコメント