# How to professionally write a constraint, where some variables take certain values of index and some variables should not take some values of index

I am using Pyomo's concrete model to model a MILP mathematical model, coming from multiproduct pipeline scheduling. Some of our continuous variables are: w[i,t], R[i,t], D[i,t]. Fixing the indices i, t, we have the constraint

w[i,t] = w[i,t-1]  +  R[i,t]  -D[i,t]


where, in R[i,t], $$i$$ takes its values from $$I_R \subset I$$ and in D, $$i$$ comes from $$I_D \subset I$$.

Now the problem is that how to model this constraint without conditional statements inside the rule of constraint. As we know, one way is the following code using conditional statement, but I do not want to use it. Is there any other way?

The rule for constraint:

def _cos(i,t):
if i not in I_D and i not in I_R:
return w[i,t] = w[i,t-1]
if i not in I_D and i in I_R:
return w[i,t] = w[i,t-1] +  R[i,t]
if i not in I_R and i in I_D:
return w[i,t] = w[i,t-1] -D[i,t]
if i in I_R and i in I_D:
return w[i,t] = w[i,t-1]  +  R[i,t]  -D[i,t]

• I am not a Pyomo user, but what you are looking for is something like you want to use a specific index, in your case $i$, to represent the outer loop on the two different sets. If so, why not define two different sets/subsets and use two for-loop to do that? Oct 24, 2021 at 18:56

I'm assuming your w, R, D variables are not in form of dictionaries (if they are the function below becomes much simpler). I go with "easier to ask for forgiveness than permission" (EAFP) programming.

def _cos(i,t):
try:
_r = R[i,t]
except KeyError:
_r = 0
try:
_d = D[i,t]
except KeyError:
_d = 0
return w[i,t] = w[i,t-1]  +  _r  - _d

• No, they are not dictionaries. Oct 24, 2021 at 18:56