adding constraint under pyomo environment

922 views Asked by At

I am working under pyomo.environ package. I tried to adding a constraint something like this https://i.stack.imgur.com/r1Smc.jpg. i and j are the index of nodes.

The node_set contains N0 to N5, six nodes in total. Arc_set is a set that store the links between nodes, say, [N1, N2], and it doesn't not contain any self loop arc, say, [N1, N1]. F set contains [F1, F2, F3]

So, I did something like this:

def c1_rule(m, j):
    return sum(m.X[e[0], j, f] for e in m.arc_set if e[1] != 'N0' for f in m.f_set) == 1
m.c1_cons = pe.Constraint(m.node_set, rule= c1_rule)

However, I realized that this would trigger errors when my j is equal to i, which is e[0] here, since the index of m.X[i, j, k] doesn't have something like [N1, N1, F1]. I have one idea is that adding self loop arcs to the arc set. Is there any other way I can avoid this error?

1

There are 1 answers

0
Jon Cardoso-Silva On

First, a warning: the constraint you showed assumes that X[i,j,f] exists for all i and j:

constraint

Otherwise, it would have been described as something like that:

constraints

So, if you are following this constraint strictly, your code is correct, you just need to make sure all entries (including when i == j) for parameter/variable X exist.


Now, you get an error because your constraint rule is generated for all j and f regardless of what is in arc_set.

So it happens that if you have [N1, N2] in arc_set, the variable e will be equals to [N1, N2] and when j = N1 and f = F1, the following rule:

m.X[e[0], j, f]

will be translated to:

m.X[N1, N1, F1]

This can trigger errors if X is a parameter of your model and entry X[N1, N1, F1] doesn't exist.

The way you fix this is by including e[0] != j in your list comprehension for the constraint rule:

def c1_rule(m, j):
    return sum(m.X[e[0], j, f] for e in m.arc_set for f in m.f_set
                               if e[1] != 'N0' and e[0] != j) == 1
m.c1_cons = pe.Constraint(m.node_set, rule= c1_rule)