简体   繁体   中英

Pyomo — initialize a Set() with a list of (python) sets

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 ...)

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 (eg, 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM