0

Can I initialize a Set() in pyomo with a list of sets? In other words, I'd like to do something like this:

from pyomo.environ import *

model = AbstractModel()
a = set([1,2,3])
b = set([4,5,6])
model.c = Set(initialize = [a,b])

instance = model.create_instance()

Unfortunately, this gives me an error:

ERROR: Constructing component 'a' from data=None failed:
TypeError: Problem inserting set([1, 2, 3]) into set c

Is there another way to achieve the same effect that I am missing?

TL;DR: I am working on a network interdiction model. My model Set represents a set of paths in the network. I want to use (python) sets to store the paths, because the model constraints are limited to feasible paths. Thus, I need to check if any edge in the path is interdicted, and the hash function will allow me to efficiently check if an interdicted edge is incident on a path. In other words, I have a function later on:

def is_feasible(model, path):
    return any([edge in path and model.Interdicts[edge].value] for edge in model.edges)

where path is an element of my Set, and model.Interdicts is a Var(model.edges, within = binary)

My fallback has been to initialize my Set with indices that references paths in an external list, but then I'm having to mix my pyomo model with non-model elements to evaluate the model constraints, which is a real headache (but then so is most network interdiction modeling ...)

1 Answer 1

1

First, assuming you can create a Pyomo Set object that looks like this, you might not be able to use it as in index set for other components because the entries are not hashable. It would be equivalent to doing the following

>>> x = set([1,2,3])
>>> y = dict()
>>> y[x] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

So you may have to resort to using something like frozenset as the elements in your Set.

I was planning on saying something else at this point having to do with how the Pyomo Set object requires that all entries have the same dimensionality (e.g., tuples of the same size), but it looks like using frozenset also allows you to get around this issue. The source of the error you were originally seeing had to do with the fact the Pyomo Set object was trying to populate its underlying storage set with the set objects you provided, which Python does not allow (same issue as using a set as a key for a dictionary).

1
  • 1
    Perfect! I replaced a = set([1,2,3]) and b = set([4,5,6]) in the above code with a = frozenset([1,2,3]) and b = frozenset([4,5,6]) respectively, and it works. Thank you!
    – Tim
    Commented Mar 14, 2017 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.