Changeset 1962


Ignore:
Timestamp:
Dec 5, 2009 2:59:02 PM (11 years ago)
Author:
wehart
Message:

Some changes to allow list comprehensions and generator expressions to be used as arguments for
set initialization. These changes still don't allow these techniques to be used to define
the set indices.

Location:
coopr.pyomo/trunk/coopr/pyomo
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • coopr.pyomo/trunk/coopr/pyomo/base/sets.py

    r1788 r1962  
    4848                          and returns true if the data belongs in the set
    4949           dimen         Specify the set's arity.
     50           doc           Documentation for this object
     51           virtual       Indicate that this is a virtual set that does not
     52                            have concrete members.
    5053    """
    51     def __init__(self, *args, **kwds):
    52         #self._index_set=None
    53         #try:
    54           #tmp=getattr(self,"_class_override")
    55         #except:
    56           #self._class_override=True
    57         #if args == ():
    58            #if self._class_override:
    59               #object.__setattr__(self,'__class__',_SetContainer)
    60            #self._index=[None]
    61            #self._ndim=0
    62            #self.value=set()
    63         #else:
    64            #self._index_set=None
    65            #if self._class_override:
    66               #object.__setattr__(self,'__class__',_SetArray)
    67            #self.value={}
    68            #self._ndim=len(args)
    69            #if len(args) == 1:
    70               #self._index=args[0]
    71            #else:
    72               #self._index=None
    73               #self._index_set=args
     54    def __init__(self, **kwds):
    7455        self.initialize=None
    7556        self.name="_unknown_"
     
    7960        self.order=[]
    8061        self.domain=None
    81         self.dimen = 1
     62        self.dimen = None
    8263        self.virtual = False
    8364        self._bounds=None
     
    10687              raise ValueError, "Option dimen "+str(kwds["dimen"])+" is different from the dimen of superset "+self.within.name+": "+str(self.dimen)
    10788           self.dimen = kwds["dimen"]
     89        if not type(self.initialize) is types.FunctionType and self.dimen is None:
     90            # If we are initializing with a function, then we leave the dimension as None.  Otherwise, we
     91            # set the default to 1
     92            self.dimen=1
    10893        if self.initialize is not None:
     94           #
     95           # Convert generators to lists, since a generator is not copyable
     96           #
     97           if type(self.initialize) is types.GeneratorType:
     98              self.initialize = list(self.initialize)
    10999           #
    110100           # Try to guess dimen from the initialize list
     
    183173        self._ndim=0
    184174        self.value=set()
    185         _BaseSet.__init__(self,*args,**kwds)
     175        _BaseSet.__init__(self,**kwds)
    186176
    187177    def _construct(self, model=None, values=None):
     
    211201                self._bounds = (first,last)
    212202        #
     203        # Construct using the rule
     204        #
     205        elif type(self.initialize) is types.FunctionType:
     206           if model is None:
     207              raise ValueError, "Must pass a model in to initialize with a function"
     208           if self.initialize.func_code.co_argcount == 1:
     209              #
     210              # Using a rule of the form f(model) -> iterator
     211              #
     212              tmp = self.initialize(model)
     213              for val in tmp:
     214                if self.dimen is None:
     215                   if type(val) in [tuple,list]:
     216                        self.dimen=len(val)
     217                   else:
     218                        self.dimen=1
     219                self.add(val)
     220           else:
     221              #
     222              # Using a rule of the form f(z,model) -> element
     223              #
     224              ctr=0
     225              val = self.initialize(ctr,model)
     226              if self.dimen is None:
     227                   if type(val) in [tuple,list]:
     228                        self.dimen=len(val)
     229                   else:
     230                        self.dimen=1
     231              while val is not None:
     232                self.add(val)
     233                ctr += 1
     234                val = self.initialize(ctr,model)
     235           #
     236           # We should be verifying as part of the add() method
     237           #
     238           #for val in self.value:
     239             #self._verify(val)
     240        #
    213241        # Construct using the default values
    214242        #
    215         elif type(self.initialize) is not types.FunctionType:
    216            if self.initialize is not None:
     243        elif self.initialize is not None:
    217244              if type(self.initialize) is dict:
    218245                 raise ValueError, "Cannot initialize set "+self.name+" with dictionary data"
     
    236263              if all_numeric:
    237264                self._bounds = (first,last)
    238        
    239              
    240         #
    241         # Construct using the rule
    242         #
    243         else:
    244            if model is None:
    245               raise ValueError, "Must pass a model in to initialize with a function"
    246            if self.initialize.func_code.co_argcount == 1:
    247               #
    248               # Using a rule of the form f(model) -> list()
    249               #
    250               tmp = self.initialize(model)
    251               for val in tmp:
    252                 self.add(val)
    253            else:
    254               #
    255               # Using a rule of the form f(z,model) -> element
    256               #
    257               ctr=0
    258               val = self.initialize(ctr,model)
    259               while val is not None:
    260                 self.add(val)
    261                 ctr += 1
    262                 val = self.initialize(ctr,model)
    263            for val in self.value:
    264              self._verify(val)
    265265
    266266    def data(self):
     
    397397           return self.order.__iter__()
    398398        return self.value.__iter__()
    399 
    400     def X__cmp__(self,other):       #pragma:nocover
    401         """
    402         Three way comparison
    403 
    404         WEH - Is this function needed?
    405         """
    406         tmp = self._set_repn(other)
    407         if self.dimen != other.dimen:
    408            raise ValueError, "Cannot perform set operation with sets "+self.name+" and "+other.name+" that have different element dimensions: "+str(self.dimen)+" "+str(other.dimen)
    409         if self.virtual:
    410            raise TypeError, "Cannot perform set operations with virtual set '"+self.name+"'"
    411         if other.virtual:
    412            raise TypeError, "Cannot perform set operations with virtual set '"+other.name+"'"
    413         return self.value.__cmp__( tmp )
    414399
    415400    def __hash__(self):
     
    622607           self._index=None
    623608           self._index_set=args
    624         _BaseSet.__init__(self,*args,**kwds)
     609        _BaseSet.__init__(self,**kwds)
    625610        self.value={}
    626611
     
    721706             self.value[tmpkey]._construct(model)
    722707        #
    723         # Construct using the default values
    724         #
    725         elif type(self.initialize) is not types.FunctionType:
    726            if self.initialize is not None:
    727               if type(self.initialize) is not dict:
    728                  for key in self._index:
    729                    self.value[key] = Set(initialize=self.initialize,within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
    730                    self.value[key].model = model
    731                    self.value[key]._construct(model)
    732               else:
    733                  for key in self.initialize:
    734                    self.value[key] = Set(initialize=self.initialize[key],within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
    735                    self.value[key].model = model
    736                    self.value[key]._construct(model)
    737         #
    738708        # Construct using the rule
    739709        #
    740         else:
     710        elif type(self.initialize) is types.FunctionType:
    741711           if model is None:
    742712              raise ValueError, "Need model to construct a set array with a function"
     
    751721                tmp.append(model)
    752722                tmp = tuple(tmp)
    753                 rule_list = self.initialize(*tmp)
     723                rule_list = list(self.initialize(*tmp))
    754724             else:
    755725                rule_list=[]
     
    762732                  args = tuple(tmp+[ctr,model])
    763733                  val = self.initialize(*args)
     734             if self.dimen is None and len(rule_list) > 0:
     735                   if type(rule_list[0]) in [tuple,list]:
     736                        self.dimen=len(rule_list[0])
     737                   else:
     738                        self.dimen=1
    764739             self.value[key] = Set(initialize=rule_list,within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
    765740             self.value[key].model = model
    766741             self.value[key]._construct(model)
     742        #
     743        # Construct using the default values
     744        #
     745        else:
     746           if self.initialize is not None:
     747              if type(self.initialize) is not dict:
     748                 for key in self._index:
     749                   self.value[key] = Set(initialize=self.initialize,within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
     750                   self.value[key].model = model
     751                   self.value[key]._construct(model)
     752              else:
     753                 for key in self.initialize:
     754                   self.value[key] = Set(initialize=self.initialize[key],within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
     755                   self.value[key].model = model
     756                   self.value[key]._construct(model)
    767757
    768758
  • coopr.pyomo/trunk/coopr/pyomo/tests/unit/test_set.py

    r1515 r1962  
    13541354        PyomoModel.setUp(self)
    13551355
    1356     def test_initialize(self):
     1356    def test_initialize1(self):
    13571357        self.model.A = Set(initialize=[1,2,3,'A'])
     1358        self.instance = self.model.create()
     1359        self.failUnlessEqual(len(self.instance.A),4)
     1360       
     1361    def test_initialize2(self):
     1362        self.model.A = Set(initialize=[(i,j) for i in range(0,3) for j in range(1,4) if (i+j)%2 == 0])
     1363        self.instance = self.model.create()
     1364        self.failUnlessEqual(len(self.instance.A),4)
     1365
     1366    def test_initialize3(self):
     1367        self.model.A = Set(initialize=((i,j) for i in range(0,3) for j in range(1,4) if (i+j)%2 == 0))
    13581368        self.instance = self.model.create()
    13591369        self.failUnlessEqual(len(self.instance.A),4)
Note: See TracChangeset for help on using the changeset viewer.