Mike
Mike

Reputation: 385

improve speed nested loops for pyomo constraint

I am trying to add this type of constraint "constraint1" to my Pyomo model by looping across a (symmetric) matrix of size "n" and performing a check, given the parameter a(i,j):

model.con1=ConstraintList()
for i in range(1,n):
    for j in range(1,i):
        if model.a[i,j]==1:
            model.con1.add((model.x[i] + model.x[j] )  <= 1 )

The code seems to work, but I would like to know if there is a more computationally efficient way to write the same.

Thank you

Upvotes: 0

Views: 427

Answers (1)

Qi Chen
Qi Chen

Reputation: 1718

You could try the following to see if it would work better:

model.n = RangeSet(n)
model.triangular = Set(within=model.n * model.n, filter=lambda i, j: j < i)

@model.Constraint(model.triangular)
def con(m, i, j):
    if model.a[i, j] == 1:
        return model.x[i] + model.x[j] <= 1
    else:
        return Constraint.Skip

Upvotes: 1

Related Questions