# Correct way to define constraints in Pyomo

Can I know if the constraint below can be defined as follows in Pyomo for convex optimization \begin{align}\forall k,\quad W_{ik}+G_{ik}\begin{cases}\in[0,m_i\Delta t],&\quad\forall i:t+k\Delta t\le d_i\\=0,&\quad\forall i:t+k\Delta t>d_i\end{cases}\end{align} where $$W$$ and $$G$$ are arrays of dimension $$M\times N$$?

del_t = 5
M = 2 # set of active tasks
N = 4 # 4 time steps
maxP = 0.14
d = np.array([20,20]) # deadline in seconds
curr_time = 0

## Third constraint START ##
m.c3 = []
for i in range(M):
for k in range(N):
if curr_time + k*del_t <= d[i] + curr_time:
c3_exp = m.W[i+1,k+1] + m.G[i+1,k+1] <= maxP*del_t
m.c3.append(Constraint(expr= c3_exp))
print(m.c3[i])
else:
c3_exp = m.W[i+1,k+1] + m.G[i+1,k+1] == 0
m.c3.append(Constraint(expr= c3_exp))
print(m.c3[i])
## Third constraint END ##

Can I also know if the output I get below when I run this code is correct?

• Can you please provide an MWE? BTW, it seems to me that the code has not completely adopted the Pyomo environment. You still can enhance that. Commented Mar 29, 2021 at 14:11

You should make use of sets. One way of doing it would be:

model = ConcreteModel()

# set
model.MNset = Set(initialize = [j for j in range(M*N))]) # j = M*(i-1) + k

# variables
model.W = Var(model.MNset, domain=Reals)
model.G = Var(model.MNset, domain=Reals)

# constraints
def WG_constraint_upper(m,j):
i = floor(j/M)+1
if tt + j*delta_t <= dd[i]:
return m.W[j] + m.G[j] <= 0
else :
return m.W[j] + m.G[j] <= mm[i]*delta_t

def WG_constraint_lower(m,j):
return m.W[j] + m.G[j] >= 0

model.WG_constraint_upper = Constraint(model.MNset,rule = WG_constraint_upper)
model.WG_constraint_lower = Constraint(model.MNset,rule = WG_constraint_lower )

Another way would be to define a two dimensional MNset so you would directly access i and k.

I also suggest you take a look at Pyomo Fundamentals