How to define contraints when the size of the set is determined within the model?
AnsweredHi,
I'm trying to write a model for which the size of some sets is defined from a variable within the model. The following constraint is giving me trouble: I want that, if the optimal "n" is "a", then from a+1 onwards, Q takes a value of zero. Note that "n" is a variable but it also determines the size of the set of the third index of the variable Q. I tried two approaches but none work:
#Approach 1:
for e in epoch_e:
if e>=n+1:
m.addConstrs((Q[j,k,e] == 0 for j in pods for k in dcs), "no delivery allowed at T")
#Approach 2:
m.addConstrs((Q[j,k,n+1] == 0 for j in pods for k in dcs))
I would like to define that the size of the set depends on the variable directly, but I haven't been able to do it. So far I'm defining large sets and working around them on all my other constraints. For the other constraints the variables after n+1 don't matter much, but the previous constraint is critical.
Thanks 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?. -
Hi Sofia,
Using an optimization variable to define the size of an index set is not possible. However, you can introduce binary variables to achieve what you are looking for. For simplicity, I will omit the \(j, k\) indices and assume that \(Q \geq 0\) in this example.
First, you have to determine the maximum possible size of the set, let's say it is \(N=5\). Then, introduce a binary variable for each possible size of the index set, i.e., \(b_i \in \{0,1\}\) with \(i \in \{0,\dots, N\}\). Next, define the inequality constraints
\[ \begin{align}
Q_i &\leq b_i M \quad i \in \{0,\dots, N\}
\end{align}\]The above inequalities force \(Q_i\) to 0 (since \(Q_i \geq 0 \)) whenever \(b_i = 0\) and set it "free" otherwise. Note that \(Q_i\) is not really a free variable then but is bounded by the big M. Next, we want to make sure that the size of the index set is connected, i.e., it does not happen that \(b_1=1, b_2=0, b_3=1\). We can achieve this via the inequalities
\[ b_i \geq b_{i+1} \quad i \in \{0,\dots, N-1\}\]
This way, if the size of the index set is 2, then \(b_0=b_1=b_2=1\) and \(b_3=b_4=0\).
Please note that you should always try to provide a not too large big M. This is to avoid numerical issues in the model. In order to then work with the optimization variable \(n\) as the size of the index set, you can introduce the constraint
\[\sum b_i = n\]
where \(n\) is an integer variable in \(\{0,\dots,N\}\).
Please note that there may be a more concise formulation for your particular problem and the above is not guaranteed to work best.
Best regards,
Jaromił1
Post is closed for comments.
Comments
2 comments