Changeset 1972


Ignore:
Timestamp:
Dec 6, 2009 6:24:46 PM (11 years ago)
Author:
wehart
Message:

Merged revisions 1948-1971 via svnmerge from
https://software.sandia.gov/svn/public/coopr/coopr.pyomo/trunk

........

r1953 | jwatson | 2009-11-25 19:39:46 -0700 (Wed, 25 Nov 2009) | 1 line


Improved error diagnostics relating to illegal/unexpected set initialization data

........

r1958 | wehart | 2009-12-03 22:50:51 -0700 (Thu, 03 Dec 2009) | 2 lines


Reverting the change in r1953, which causes an error in our unit tests.

........

r1959 | wehart | 2009-12-04 12:43:06 -0700 (Fri, 04 Dec 2009) | 30 lines


Extended the constraint generation logic to evaluate whether the constraint
expression contains constant values. This extension allows the following
types of constraints to be specified:


def f(model)

return 0 < model.x


def g(model)

return model.x == model.y


def h(model)

return model.y > model.z


However, it's pretty clear now that the following cannot be supported in Python:


def j(model)

return 0 < model.x < 1


To add upper and lower bounds, a user will need to return a tuple value:


def j(model)

return (0, model.x, 1)


or return an expression that is generated incrementally:


def j(model)

e = 0 < model.x
return e < 1

........

r1961 | wehart | 2009-12-05 00:46:24 -0700 (Sat, 05 Dec 2009) | 2 lines


Documentation updates for sets.

........

r1962 | wehart | 2009-12-05 12:59:02 -0700 (Sat, 05 Dec 2009) | 4 lines


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.

........

r1963 | wehart | 2009-12-06 10:01:57 -0700 (Sun, 06 Dec 2009) | 4 lines


Reworking SetArray? constructor to create temporary set objects for non-set
index arguments. These arguments are passed into a Set object
with the 'initialize' argument.

........

r1964 | wehart | 2009-12-06 11:19:03 -0700 (Sun, 06 Dec 2009) | 3 lines


Adding tests that verify that index-generating functions can be
supplied as arguments to Set declarations.

........

r1966 | jwatson | 2009-12-06 12:31:56 -0700 (Sun, 06 Dec 2009) | 3 lines


Transferring the reduced-cost variable attributes (if present) in the solution to the model instance variables.

........

r1967 | wehart | 2009-12-06 15:00:00 -0700 (Sun, 06 Dec 2009) | 4 lines


Creating the ComponentBase? class, which manages the initialization of
components. This consolidates the mechanism needed to generalize
the component indexing operations.

........

r1968 | wehart | 2009-12-06 15:02:14 -0700 (Sun, 06 Dec 2009) | 2 lines


Bug fix when an expression has no arguments.

........

Location:
coopr.pyomo/stable/2.1
Files:
18 edited
1 copied

Legend:

Unmodified
Added
Removed
  • coopr.pyomo/stable/2.1

  • coopr.pyomo/stable/2.1/coopr/pyomo/base/PyomoModel.py

    r1948 r1972  
    8282    def _add_temporary_set(self,val):
    8383        if val._index_set is not None:
    84            ##print "HERE Y1"
    85            val._index = self._construct_temporary_set(val._index_set,val.name+"_index")
     84            ctr=0
     85            for tset in val._index_set:
     86                if tset.name == "_unknown_":
     87                    self._construct_temporary_set(tset,val.name+"_index_"+str(ctr))
     88                ctr+=1
     89            val._index = self._construct_temporary_set(val._index_set,val.name+"_index")
    8690        if isinstance(val._index,_SetContainer) and \
    87            val._index.name == "_unknown_":
    88            ##print "HERE Y2"
    89            self._construct_temporary_set(val._index,val.name+"_index")
     91            val._index.name == "_unknown_":
     92            self._construct_temporary_set(val._index,val.name+"_index")
    9093        if val.domain is not None and val.domain.name == "_unknown_":
    91            ##print "HERE Y3"
    92            self._construct_temporary_set(val.domain,val.name+"_domain")
     94            self._construct_temporary_set(val.domain,val.name+"_domain")
    9395
    9496
     
    306308             if self._name_varmap[name].fixed is True:
    307309                raise TypeError, "Variable '"+name+"' in model '"+self.name+"' is currently fixed - new value is not expected in solution"
     310
     311             # the value is always present in any legal solution.
    308312             self._name_varmap[name].value = soln.variable[name].value
    309313
     314             # the reduced-cost might be present, depending on what the solver is reporting.
     315             if hasattr(soln.variable[name],"rc"):
     316                self._name_varmap[name].rc = soln.variable[name].rc
    310317
    311318    def write(self,filename=None,format=ProblemFormat.cpxlp):
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/PyomoModelData.py

    r1768 r1972  
    277277          if type(cmd[i]) is not tuple:
    278278            if flag:
     279               #if type(cmd[i]) is not tuple:
     280               #   raise ValueError, "Problem initializing set="+sname+" with input data="+str(cmd)+" - first element was interpreted as a tuple, but element="+str(i)+" is of type="+str(type(cmd[i]))+"; types must be consistent"
    279281               tmpval=tmp
    280282               tmpval[ndx] = self._data_eval([cmd[i]])[0]
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/constraint.py

    r1948 r1972  
    1616import pyomo
    1717from var import Var, _VarValue
    18 from sets import Set, _BaseSet
     18from component import ComponentBase
     19from sets import _BaseSet
    1920import pyutilib.misc
    2021import pyutilib.math
     
    3839
    3940
    40 class Objective(NumericValue):
     41class Objective(NumericValue, ComponentBase):
    4142    """An object that defines a objective expression"""
    4243
     
    4546           expression
    4647        """
     48        ComponentBase.__init__(self, *args)
    4749        tmpname="unknown"
    4850        tmpsense = minimize
    4951        tmprule = None
    50         self._index_set=None
    5152        self._data = {}
    5253        if args == ():
    53            self._index=[None]
    5454           self._data[None] = ObjectiveData()
    55            self._ndim=0
    56         else:
    57            self._ndim=0
    58            for arg in args:
    59              self._ndim += arg.dimen
    60            if len(args) == 1:
    61               self._index=args[0]
    62            else:
    63               self._index=None
    64               self._index_set=args
    6555        self._quad_subexpr = None # this is a hack for now; we eventually want a "QuadraticObjective" class.       
    6656        for key in kwd.keys():
     
    122112
    123113    def _construct(self, model, data):
     114        #
     115        # Update the index set dimension
     116        #
     117        self._compute_dim()
    124118        ##print "HERE",self.rule,self._ndim
    125119        if self.rule is not None:
     
    195189
    196190
    197 class Constraint(NumericValue):
     191class Constraint(NumericValue, ComponentBase):
    198192    """An object that defines a objective expression"""
    199193
     
    202196           expression
    203197        """
     198        ComponentBase.__init__(self, *args)
    204199        tmpname="unknown"
    205200        tmprule=None
    206         self._index_set=None
    207201        self._data = {}
    208202        if args == ():
    209            self._index=[None]
    210203           self._data[None]=ConstraintData()
    211            self._ndim=0
    212         else:
    213            self._ndim=0
    214            for arg in args:
    215              self._ndim += arg.dimen
    216            if len(args) == 1:
    217               self._index=args[0]
    218            else:
    219               self._index=None
    220               self._index_set=args
    221204        for key in kwd.keys():
    222205          if key == "name":
     
    268251    def _construct(self, model, data):
    269252        self._model = model
    270        
     253        #
     254        # Update the index set dimension
     255        #
     256        self._compute_dim()
     257
    271258        if pyomo.debug("verbose") or pyomo.debug("normal"):     #pragma:nocover
    272259           print "Construcing constraint "+self.name
     
    340327            _expr_args0 = expr._args[0]
    341328            _expr_args1 = expr._args[1]
     329
     330            #_expr_args0.pprint()
     331            #print "HERE", is_constant(_expr_args0)
     332            #_expr_args1.pprint()
     333            #print "HERE", is_constant(_expr_args1)
    342334        #
    343335        # If the constructor rule returns an equality expression, then
     
    346338        if isinstance(expr,_EqualToExpression):
    347339            _self_data[val]._equality = True
    348             if isinstance(_expr_args0,Expression) or\
    349                     isinstance(_expr_args0,Var) or\
    350                     isinstance(_expr_args0,_VarValue):
     340            if is_constant(_expr_args1):
    351341                tpl = [ _expr_args1,_expr_args0,_expr_args1 ]
     342            elif is_constant(_expr_args1):
     343                tpl = [ _expr_args0,_expr_args1,_expr_args0 ]
    352344            else:
    353                 tpl = [ _expr_args0,_expr_args1,_expr_args0 ]
     345                tpl = [ 0.0 , _expr_args0 - _expr_args1, 0.0 ]
    354346        #
    355347        # If the constructor rule returns a greater-than expression, then
     
    361353            if isinstance(_expr_args0,_GreaterThanExpression) or\
    362354                    isinstance(_expr_args0,_GreaterThanOrEqualExpression):
    363                 tpl = [ _expr_args0._args[0],_expr_args0._args[1],_expr_args1 ]
     355                tpl = [ _expr_args1, _expr_args0._args[1], _expr_args0._args[0] ]
    364356
    365357            elif isinstance(_expr_args0,_LessThanExpression) or\
    366358                    isinstance(_expr_args0,_LessThanOrEqualExpression):
    367                 tpl = [ _expr_args0._args[1],_expr_args0._args[0],_expr_args1 ]
     359                tpl = [ _expr_args1, _expr_args0._args[0], _expr_args0._args[1] ]
    368360
    369361            elif isinstance(_expr_args1,_GreaterThanExpression) or\
    370362                    isinstance(_expr_args1,_GreaterThanOrEqualExpression):
    371                 tpl = [ _expr_args0,_expr_args1._args[0],_expr_args1._args[1] ]
     363                tpl = [ _expr_args1._args[1], _expr_args1._args[0], _expr_args0 ]
    372364
    373365            elif isinstance(_expr_args1,_LessThanExpression) or\
    374366                    isinstance(_expr_args1,_LessThanOrEqualExpression):
    375                 tpl = [ _expr_args0,_expr_args1._args[1],_expr_args1._args[0] ]
     367                tpl = [ _expr_args1._args[0], _expr_args1._args[1], _expr_args0 ]
    376368
    377369            elif isinstance(_expr_args0,_EqualToExpression) or\
     
    379371                raise ValueError, "Bound error: > expression used with an = expression."
    380372
    381             elif isinstance(_expr_args0,Expression) or\
    382                     isinstance(_expr_args0,_VarValue) or\
    383                     isinstance(_expr_args0,Var):
    384                 tpl = [ None,_expr_args0,_expr_args1 ]
    385 
     373            elif _expr_args0.is_constant():
     374                tpl = [ None, _expr_args1, _expr_args0 ]
     375            elif _expr_args1.is_constant():
     376                tpl = [ _expr_args1, _expr_args0, None ]
    386377            else:
    387                 tpl = [ _expr_args0,_expr_args1,None ]
     378                tpl = [ 0.0, _expr_args0-_expr_args1, None ]
     379
    388380        #
    389381        # If the constructor rule returns a less-than expression, then
     
    413405                raise ValueError, "Bound error: < expression used with an = expression."+str(expr)+str(expr._args)
    414406
    415             elif isinstance(_expr_args0,Expression) or\
    416                     isinstance(_expr_args0,_VarValue) or\
    417                     isinstance(_expr_args0,Var):
    418                 tpl = [ None,_expr_args0,_expr_args1 ]
    419 
     407            elif _expr_args0.is_constant():
     408                tpl = [ _expr_args0, _expr_args1, None ]
     409            elif _expr_args1.is_constant():
     410                tpl = [ None, _expr_args0, _expr_args1 ]
    420411            else:
    421                 tpl = [ _expr_args0,_expr_args1,None ]
     412                tpl = [ 0.0, _expr_args1 - _expr_args0, None ]
    422413        #
    423414        # If the constructor rule returns a tuple or list, then convert
     
    435426            if len(expr) == 2:
    436427                _self_data[val]._equality = True
    437                 if isinstance(expr[0],Expression) or\
    438                         isinstance(expr[0],Var) or\
    439                         isinstance(expr[0],_VarValue):
     428                if is_constant(expr[1]):
    440429                    tpl = [ expr[1],expr[0],expr[1] ]
    441430                else:
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/expr.py

    r1835 r1972  
    7373            if (isinstance(arg,_ParamBase) or isinstance(arg,_VarBase)) and arg.dim() > 0:
    7474                raise ValueError, "Argument for expression "+self.name+" is an n-ary numeric value: "+arg.name
     75
     76    #
     77    # this method contrast with the fixed_value() method.
     78    # the fixed_value() method returns true iff the value is
     79    # an atomic constant.
     80    # this method returns true iff all composite arguments
     81    # in this sum expression are constant, i.e., numeric
     82    # constants or parametrs. the parameter values can of
     83    # course change over time, but at any point in time,
     84    # they are constant. hence, the name.
     85    #
     86    def is_constant(self):
     87        if self._args is None:
     88            return True
     89        for arg in self._args:
     90            if not arg.is_constant():
     91                return False
     92        return True
    7593
    7694    def simplify(self, model):
     
    412430        tmp._const = self._const
    413431        return tmp
    414     #
    415     # this method contrast with the fixed_value() method.
    416     # the fixed_value() method returns true iff the value is
    417     # an atomic constant.
    418     # this method returns true iff all composite arguments
    419     # in this sum expression are constant, i.e., numeric
    420     # constants or parametrs. the parameter values can of
    421     # course change over time, but at any point in time,
    422     # they are constant. hence, the name.
    423     #
    424     def evaluates_to_constant(self):
    425         for arg in self._args:
    426             if arg.fixed_value() is False:
    427                 return False
    428         return True
    429432
    430433    def scale(self, val):
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/numvalue.py

    r1768 r1972  
    99#  _________________________________________________________________________
    1010
    11 __all__ = ['value', 'NumericValue', 'as_numeric', 'NumericConstant', 'ZeroConstant', 'OneConstant']
     11__all__ = ['value', 'NumericValue', 'as_numeric', 'NumericConstant', 'ZeroConstant', 'OneConstant', 'is_constant']
    1212
    1313import plugin
     
    3838        raise ValueError, "No value for uninitialized NumericValue object "+obj.name
    3939    return tmp
    40    
     40
     41def is_constant(obj):
     42    """
     43    A utility function that returns a boolean that indicates whether the object is a constant
     44    """
     45    if obj is None:
     46        return False   
     47    elif type(obj) in [bool,int,long,float]:
     48        return True
     49    if not isinstance(obj, NumericValue):
     50        return False
     51    return obj.is_constant()
    4152
    4253def as_numeric(obj):
     
    7586        #print "NUMVAL",self.name,self.domain,self.value
    7687
     88    def is_constant(self):
     89        return True
     90
    7791    def fixed_value(self):
    7892        return False
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/param.py

    r1768 r1972  
    1717import sys
    1818import types
    19 from sets import _BaseSet
     19from component import ComponentBase
    2020
    2121
     
    3737
    3838
    39 class _ParamBase(object):
     39class _ParamBase(ComponentBase):
    4040    """A parameter value, which may be defined over a index"""
    4141
     
    5555                          existing model data
    5656    """
    57     def __init__(self, **kwd):
     57    def __init__(self, *args, **kwd):
     58        ComponentBase.__init__(self, *args)
    5859        tmpname="unknown"
    5960        tmpdomain=Any
    60         self._ndim=0
    6161        self._paramval={}
    6262        self._initialize={}
     
    8080        self.domain = tmpdomain
    8181        self._default = _ParamValue(name=tmpname,domain=tmpdomain,value=value(defaultval))
    82         self._index_set=None
    8382
    8483    def pprint(self, ostream=None):
     
    161160        if pyomo.debug("verbose"):      #pragma:nocover
    162161           print "Constructing Param, name="+self.name+", from data="+`data`
     162        #
     163        # Update the index set dimension
     164        #
     165        self._compute_dim()
    163166        #
    164167        # Code optimization with local variables
     
    278281    def __init__(self, *args, **kwd):
    279282        _ParamValue.__init__(self, **kwd)
    280         _ParamBase.__init__(self, **kwd)
    281         self._index=[None]
     283        _ParamBase.__init__(self, *args, **kwd)
    282284        self._paramval[None] = self
    283285
     
    298300        return self._paramval[None].value
    299301
     302
    300303class _ParamArray(_ParamBase):
    301304
    302305    def __init__(self, *args, **kwd):
    303         _ParamBase.__init__(self, **kwd)
    304         for arg in args:
    305             if not isinstance(arg,_BaseSet):
    306                 raise ValueError, "Cannot index parameter `"+self.name+"' with object of type "+str(type(arg))
    307             self._ndim += arg.dimen
    308         if len(args) == 1:
    309             self._index=args[0]
    310         else:
    311             self._index=None
    312             self._index_set=args
     306        _ParamBase.__init__(self, *args, **kwd)
    313307
    314308    def simplify(self, model):
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/sets.py

    r1788 r1972  
    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):
     
    618603        self._ndim=len(args)
    619604        if len(args) == 1:
    620            self._index=args[0]
    621         else:
    622            self._index=None
    623            self._index_set=args
    624         _BaseSet.__init__(self,*args,**kwds)
     605            if isinstance(args[0],_BaseSet):
     606                self._index=args[0]
     607            else:
     608                self._index=Set(initialize=args[0])
     609        else:
     610            self._index=None
     611            tmp = []
     612            for arg in args:
     613                if isinstance(arg,_BaseSet):
     614                    tmp.append(arg)
     615                else:
     616                    tmp.append( Set(initialize=arg) )
     617            self._index_set=tuple(tmp)
     618        _BaseSet.__init__(self,**kwds)
    625619        self.value={}
    626620
     
    721715             self.value[tmpkey]._construct(model)
    722716        #
    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         #
    738717        # Construct using the rule
    739718        #
    740         else:
     719        elif type(self.initialize) is types.FunctionType:
    741720           if model is None:
    742721              raise ValueError, "Need model to construct a set array with a function"
     
    751730                tmp.append(model)
    752731                tmp = tuple(tmp)
    753                 rule_list = self.initialize(*tmp)
     732                rule_list = list(self.initialize(*tmp))
    754733             else:
    755734                rule_list=[]
     
    762741                  args = tuple(tmp+[ctr,model])
    763742                  val = self.initialize(*args)
     743             if self.dimen is None and len(rule_list) > 0:
     744                   if type(rule_list[0]) in [tuple,list]:
     745                        self.dimen=len(rule_list[0])
     746                   else:
     747                        self.dimen=1
    764748             self.value[key] = Set(initialize=rule_list,within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
    765749             self.value[key].model = model
    766750             self.value[key]._construct(model)
     751        #
     752        # Construct using the default values
     753        #
     754        else:
     755           if self.initialize is not None:
     756              if type(self.initialize) is not dict:
     757                 for key in self._index:
     758                   self.value[key] = Set(initialize=self.initialize,within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
     759                   self.value[key].model = model
     760                   self.value[key]._construct(model)
     761              else:
     762                 for key in self.initialize:
     763                   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)
     764                   self.value[key].model = model
     765                   self.value[key]._construct(model)
    767766
    768767
     
    803802        ans=0
    804803        for set in self.set_tuple:
    805           if set.dimen == 1:
    806              ans += 1
    807           else:
    808              ans += set.dimen
    809         self.dimen= ans
     804            if set.dimen is None:
     805                self.dimen=None
     806                return
     807            else:
     808                ans += set.dimen
     809        self.dimen = ans
    810810
    811811    def _verify(self,element,use_exception=True):
     
    814814        to ensure that the element is in each of the underlying sets.
    815815        """
    816         #print "HERE y",element
    817816        tmp = _SetContainer._verify(self,element,use_exception)
    818         #print "HERE z",element, tmp, self.virtual
    819817        if not tmp or not self.virtual:
    820            #print "HERE z1",element, tmp, self.virtual
    821            return tmp
     818            return tmp
    822819
    823820        next_tuple_index = 0
     
    835832    def _construct(self, model=None, values=None):
    836833        """ Apply the rule to construct values in this set """
    837         #print "HERE PS construct"
    838834        log.debug("Constructing _ProductSet, name="+self.name+", from data="+repr(values))
    839835        if self.virtual:
     
    844840              for val in self.set_tuple:
    845841                self._len *= len(val)
    846            return
    847842        #
    848843        # Construct using the values list
    849844        #
    850         if values is not None:
     845        elif values is not None:
    851846           for val in values[None]:
    852847             self.add(val)
    853848        #
     849        # Construct using the rule
     850        #
     851        elif type(self.initialize) is types.FunctionType:
     852           for val in self.initialize(model):
     853             self.add(val)
     854        #
    854855        # Construct using the default values
    855856        #
    856         elif type(self.initialize) is not types.FunctionType:
     857        else:
    857858           if self.initialize is not None:
    858859              if type(self.initialize) is dict:
     
    865866                self.add(val)
    866867        #
    867         # Construct using the rule
    868         #
    869         else:
    870            tmp = self.initialize(model)
    871            for val in tmp:
    872              self.add(val)
    873         self._len=len(self.value)
     868        if not self.virtual:
     869            self._len=len(self.value)
     870        self._compute_dimen()
     871        if self.dimen is None:
     872            raise ValueError, "The product set dimension must be computeable after constructing this set!"
    874873
    875874
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/var.py

    r1948 r1972  
    1515import types
    1616from set_types import *
    17 from sets import _BaseSet
     17from component import ComponentBase
    1818import pyutilib.math
    1919import pyutilib.misc
     
    7373        return False
    7474
     75    def is_constant(self):
     76        if self.fixed:
     77            return True
     78        return False
     79
    7580    def simplify(self, model):
    7681        return self                 #pragma:nocover
     
    109114#
    110115
    111 class _VarBase(object):
     116class _VarBase(ComponentBase):
    112117    """A numeric variable, which may be defined over a index"""
    113118
     
    127132                          existing model data
    128133    """
    129     def __init__(self, **kwd):
     134    def __init__(self, *args, **kwd):
     135        ComponentBase.__init__(self,*args)
    130136        #
    131137        # Default keyword values
     
    134140        tmpname="unknown"
    135141        tmpdomain=Reals
    136         self._ndim=0
    137142        tmpbounds=None
    138143        self._varval={}
     
    152157        self.domain = tmpdomain
    153158        self.bounds=tmpbounds
    154         self._index_set=None
    155159        self._model=None
    156160
     
    206210        self._model = model
    207211        #
     212        # Update the index set dimension
     213        #
     214        self._compute_dim()
     215        #
    208216        # Construct _VarValue() objects for all index values
    209217        #
     
    215223                    self._varval[ndx] = _VarValue(name=self.name+"["+str(ndx)+"]",domain=self.domain)
    216224                    self._varval[ndx].var = self
    217                    
    218225        #
    219226        # Initialize values with a dictionary if provided
     
    369376    def __init__(self, *args, **kwd):
    370377        _VarValue.__init__(self, **kwd)
    371         _VarBase.__init__(self, **kwd)
    372         self._index=[None]
     378        _VarBase.__init__(self, *args, **kwd)
    373379        self._varval[None] = self
    374380        self._varval[None].var = self
    375381
     382    def is_constant(self):
     383        return _VarValue.is_constant(self)
     384
    376385
    377386class _VarArray(_VarBase):
    378387
    379388    def __init__(self, *args, **kwd):
    380         _VarBase.__init__(self, **kwd)
    381         for arg in args:
    382             if not isinstance(arg,_BaseSet):
    383                 raise ValueError, "Cannot index variable `"+self.name+"' with object of type "+str(type(arg))
    384             self._ndim += arg.dimen
    385         if len(args) == 1:
    386             self._index=args[0]
    387         else:
    388             self._index=None
    389             self._index_set=args
    390         #print "X",kwd
     389        _VarBase.__init__(self, *args, **kwd)
    391390        self._dummy_val = _VarValue(**kwd)
    392391
  • coopr.pyomo/stable/2.1/coopr/pyomo/components/action.py

    r1338 r1972  
    1313from coopr.pyomo.base.numvalue import *
    1414from coopr.pyomo.base.plugin import ComponentRegistration
    15 from coopr.pyomo.base.sets import _BaseSet
     15from coopr.pyomo.base.component import ComponentBase
    1616import types
    1717from coopr.pyomo.base import pyomo
     
    2121
    2222
    23 class BuildAction(object):
     23class BuildAction(ComponentBase):
    2424    """A build action, which executes a rule for all valid indices"""
    2525
     
    3333    """
    3434    def __init__(self, *args, **kwd):
     35        ComponentBase.__init__(self, *args)
    3536        tmpname="unknown"
    3637        self.domain=None
     
    4445          else:
    4546             raise ValueError, "BuildAction constructor: unknown keyword - "+key
    46         self._index_set=None
    47         if args == ():
    48            self._index=[None]
    49            self._ndim=0
    50         else:
    51            self._ndim=0
    52            for arg in args:
    53              if not isinstance(arg,_BaseSet):
    54                 raise ValueError, "Cannot index parameter `"+self.name+"' with object of type "+str(type(arg))
    55              self._ndim += arg.dimen
    56            if len(args) == 1:
    57               self._index=args[0]
    58            else:
    59               self._index=None
    60               self._index_set=args
    6147        if not type(self._rule) is types.FunctionType:
    6248            raise ValueEror, "BuildAction must have an 'rule' option specified whose value is a function"
     
    7258        if pyomo.debug("verbose"):      #pragma:nocover
    7359           print "Constructing Param, name="+self._name+", from data="+`data`
     60        #
     61        # Update the index set dimension
     62        #
     63        self._compute_dim()
    7464        for val in self._index:
    7565              if isinstance(val,tuple):
  • coopr.pyomo/stable/2.1/coopr/pyomo/components/check.py

    r1338 r1972  
    1313from coopr.pyomo.base.numvalue import *
    1414from coopr.pyomo.base.plugin import ComponentRegistration
    15 from coopr.pyomo.base.sets import _BaseSet
     15from coopr.pyomo.base.component import ComponentBase
    1616import types
    1717from coopr.pyomo.base import pyomo
    1818
    1919
    20 class BuildCheck(object):
     20class BuildCheck(ComponentBase):
    2121    """A build check, which executes a rule for all valid indices"""
    2222
     
    3030    """
    3131    def __init__(self, *args, **kwd):
     32        ComponentBase.__init__(self,*args)
    3233        tmpname="unknown"
    3334        self.domain=None
     
    4142          else:
    4243             raise ValueError, "BuildCheck constructor: unknown keyword - "+key
    43         self._index_set=None
    44         if args == ():
    45            self._index=[None]
    46            self._ndim=0
    47         else:
    48            self._ndim=0
    49            for arg in args:
    50              if not isinstance(arg,_BaseSet):
    51                 raise ValueError, "Cannot index parameter `"+self.name+"' with object of type "+str(type(arg))
    52              self._ndim += arg.dimen
    53            if len(args) == 1:
    54               self._index=args[0]
    55            else:
    56               self._index=None
    57               self._index_set=args
    5844        if not type(self._rule) is types.FunctionType:
    5945            raise ValueEror, "BuildCheck must have an 'rule' option specified whose value is a function"
     
    6955        if pyomo.debug("verbose"):      #pragma:nocover
    7056           print "Constructing Param, name="+self._name+", from data="+`data`
     57        #
     58        # Update the index set dimension
     59        #
     60        self._compute_dim()
    7161        for val in self._index:
    7262              if isinstance(val,tuple):
  • coopr.pyomo/stable/2.1/coopr/pyomo/presolve/collect_linear_terms.py

    r1804 r1972  
    9292                   if e.fixed_value():
    9393                       c /= e.value
    94                    elif (isinstance(e, expr._SumExpression) is True) and (e.evaluates_to_constant() is True):
    95                       # the following logic should be extended to product expressions and all other types
    96                       # of core expressions; this is experimental, based on issues with logically valid
    97                       # expressions being flagged as "nonlinear, with variables". in particular, the
    98                       # evaluates_to_constant() should be a method of the base class.
     94                   elif e.is_constant():
     95                      # This is experimental, based on issues with logically valid
     96                      # expressions being flagged as "nonlinear, with variables".
    9997                      try:
    10098                         c /= e()
  • coopr.pyomo/stable/2.1/coopr/pyomo/tests/unit/test_expr.py

    r1768 r1972  
    416416        try:
    417417            instance.b[3] = -2.2
    418             print "HERE",type(instance.b[3])
     418            #print "HERE",type(instance.b[3])
    419419            self.fail("can't set an array variable with a bad value")
    420420        except ValueError:
     
    477477            return (3.0,model.b[1])
    478478        def c5_rule(i,model):
    479             return (0.0,model.b[i])
     479            return (model.b[i],0.0)
     480
     481        def c6_rule(model):
     482            return 0.0 <= model.c
     483        def c7_rule(model):
     484            return model.c <= 1.0
     485        def c8_rule(model):
     486            return model.c == 2.0
     487        def c9_rule(model):
     488            return model.A+model.A <= model.c
     489        def c10_rule(model):
     490            return model.c <= model.B+model.B
     491        def c11_rule(model):
     492            return model.c == model.A+model.B
     493
     494        def c12_rule(model):
     495            return model.c == model.d
     496        def c13_rule(model):
     497            return model.c <= model.d
     498        def c14_rule(model):
     499            return model.c >= model.d
     500
     501        def c20_rule(model):
     502            return model.A > model.c > model.B
     503        def c21_rule(model):
     504            return model.A > model.c < model.B
     505        def c22_rule(model):
     506            return model.A < model.c > model.B
     507        def c23_rule(model):
     508            return model.A < model.c < model.B
     509
    480510        def o2_rule(i,model):
    481511            return model.b[i]
     
    484514        model.b = Var(model.a,initialize=1.1,within=PositiveReals)
    485515        model.c = Var(initialize=2.1, within=PositiveReals)
     516        model.d = Var(initialize=3.1, within=PositiveReals)
     517        model.e = Var(initialize=4.1, within=PositiveReals)
     518        model.A = Param(default=-1)
     519        model.B = Param(default=-2)
    486520        #model.o1 = Objective()
    487521        model.o2 = Objective(model.a,rule=o2_rule)
     
    492526        model.c4 = Constraint(rule=c4_rule)
    493527        model.c5 = Constraint(model.a,rule=c5_rule)
     528
     529        model.c6 = Constraint(rule=c6_rule)
     530        model.c7 = Constraint(rule=c7_rule)
     531        model.c8 = Constraint(rule=c8_rule)
     532        model.c9 = Constraint(rule=c9_rule)
     533        model.c10 = Constraint(rule=c10_rule)
     534        model.c11 = Constraint(rule=c11_rule)
     535
     536        model.c12 = Constraint(rule=c12_rule)
     537        model.c13 = Constraint(rule=c13_rule)
     538        model.c14 = Constraint(rule=c14_rule)
     539
     540        #model.c20 = Constraint(rule=c20_rule)
     541        #model.c21 = Constraint(rule=c21_rule)
     542        #model.c22 = Constraint(rule=c22_rule)
     543        #model.c23 = Constraint(rule=c23_rule)
     544
    494545        instance=model.create()
    495546        OUTPUT=open(currdir+"varpprint.out","w")
  • coopr.pyomo/stable/2.1/coopr/pyomo/tests/unit/test_model.py

    r1948 r1972  
    465465        self.failUnlessEqual( type(tmp), int)
    466466        self.failUnlessEqual( tmp, 3 )
     467
     468
     469class TestVarComplexArray(PyomoModel):
     470
     471    def test_index1(self):
     472        self.model.A = Set(initialize=range(0,4))
     473        def B_index(model):
     474            for i in model.A:
     475                if i%2 == 0:
     476                    yield i
     477        def B_init(i,j,model):
     478            if j:
     479                return 2+i
     480            return -(2+i)
     481        self.model.B = Var(B_index, [True,False], initialize=B_init)
     482        self.instance = self.model.create()
     483        #self.instance.pprint()
     484        self.failUnlessEqual(set(self.instance.B.keys()),set([(0,True),(2,True),(0,   False),(2,False)]))
     485        self.failUnlessEqual(self.instance.B[0,True],2)
     486        self.failUnlessEqual(self.instance.B[0,False],-2)
     487        self.failUnlessEqual(self.instance.B[2,True],4)
     488        self.failUnlessEqual(self.instance.B[2,False],-4)
    467489
    468490
  • coopr.pyomo/stable/2.1/coopr/pyomo/tests/unit/test_param.py

    r1768 r1972  
    355355
    356356
     357class ArrayParam6(PyomoModel):
     358
     359    def test_index1(self):
     360        self.model.A = Set(initialize=range(0,4))
     361        def B_index(model):
     362            for i in model.A:
     363                if i%2 == 0:
     364                    yield i
     365        def B_init(i,j,model):
     366            if j:
     367                return 2+i
     368            return -(2+i)
     369        self.model.B = Param(B_index, [True,False], initialize=B_init)
     370        self.instance = self.model.create()
     371        #self.instance.pprint()
     372        self.failUnlessEqual(set(self.instance.B.keys()),set([(0,True),(2,True),(0,   False),(2,False)]))
     373        self.failUnlessEqual(self.instance.B[0,True],2)
     374        self.failUnlessEqual(self.instance.B[0,False],-2)
     375        self.failUnlessEqual(self.instance.B[2,True],4)
     376        self.failUnlessEqual(self.instance.B[2,False],-4)
     377
     378
    357379class TestIO(PyomoModel):
    358380
  • coopr.pyomo/stable/2.1/coopr/pyomo/tests/unit/test_set.py

    r1515 r1972  
    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'])
    13581358        self.instance = self.model.create()
    13591359        self.failUnlessEqual(len(self.instance.A),4)
    13601360       
     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))
     1368        self.instance = self.model.create()
     1369        self.failUnlessEqual(len(self.instance.A),4)
     1370       
     1371    def test_initialize4(self):
     1372        self.model.A = Set(initialize=range(0,4))
     1373        def B_index(model):
     1374            return (i for i in model.A if i%2 == 0)
     1375        def B_init(i,model):
     1376            return range(i,2+i)
     1377        self.model.B = Set(B_index, initialize=B_init)
     1378        self.instance = self.model.create()
     1379        #self.instance.pprint()
     1380        self.failUnlessEqual(self.instance.B[0].data(),set([0,1]))
     1381        self.failUnlessEqual(self.instance.B[2].data(),set([2,3]))
     1382        self.failUnlessEqual(self.instance.B.keys(),[0,2])
     1383
     1384    def test_initialize5(self):
     1385        self.model.A = Set(initialize=range(0,4))
     1386        def B_index(model):
     1387            for i in model.A:
     1388                if i%2 == 0:
     1389                    yield i
     1390        def B_init(i,model):
     1391            return range(i,2+i)
     1392        self.model.B = Set(B_index, initialize=B_init)
     1393        self.instance = self.model.create()
     1394        #self.instance.pprint()
     1395        self.failUnlessEqual(self.instance.B[0].data(),set([0,1]))
     1396        self.failUnlessEqual(self.instance.B[2].data(),set([2,3]))
     1397        self.failUnlessEqual(self.instance.B.keys(),[0,2])
     1398
     1399    def test_initialize6(self):
     1400        self.model.A = Set(initialize=range(0,4))
     1401        def B_index(model):
     1402            for i in model.A:
     1403                if i%2 == 0:
     1404                    yield i
     1405        def B_init(i,j,model):
     1406            if j:
     1407                return range(i,2+i)
     1408            return []
     1409        self.model.B = Set(B_index, [True,False], initialize=B_init)
     1410        self.instance = self.model.create()
     1411        #self.instance.pprint()
     1412        self.failUnlessEqual(set(self.instance.B.keys()),set([(0,True),(2,True),(0,False),(2,False)]))
     1413        self.failUnlessEqual(self.instance.B[0,True].data(),set([0,1]))
     1414        self.failUnlessEqual(self.instance.B[2,True].data(),set([2,3]))
     1415
    13611416    def test_dimen(self):
    13621417        #
  • coopr.pyomo/stable/2.1/coopr/pyomo/tests/unit/varpprint.txt

    r1484 r1972  
    990 RangeSet Declarations
    1010
    11 0 Param Declarations
     112 Param Declarations
     12   A :  Size=1  Domain=Any
     13        -1
     14        default: -1
     15   B :  Size=1  Domain=Any
     16        -2
     17        default: -2
    1218
    13 2 Var Declarations
     194 Var Declarations
    1420   b :  Size=3  Domain=PositiveReals
    1521        Key : Initial Value : Lower Bound : Upper Bound : Current Value: Fixed
     
    2026        Initial Value : Lower Bound : Upper Bound : Current Value: Fixed
    2127        2.1 : 0 : None : None : False
     28   d :  Size=1  Domain=PositiveReals
     29        Initial Value : Lower Bound : Upper Bound : Current Value: Fixed
     30        3.1 : 0 : None : None : False
     31   e :  Size=1  Domain=PositiveReals
     32        Initial Value : Lower Bound : Upper Bound : Current Value: Fixed
     33        4.1 : 0 : None : None : False
    2234
    23352 Objective Declarations
     
    2840   o3 :         Size=0  Index= o3_index
    2941
    30 5 Constraint Declarations
     4214 Constraint Declarations
    3143   c1 :         Size=1
    3244        None
    3345                identity( 1.0 )
    3446                identity( b[1] )
     47                Inf
     48   c10 :        Size=1
     49        None
     50                -Inf
     51                identity( c )
     52                sum( B , B )
     53   c11 :        Size=1
     54        None
     55                sum( A , B )
     56                identity( c )
     57                sum( A , B )
     58   c12 :        Size=1
     59        None
     60                identity( 0.0 )
     61                sum( c , -1 *  d )
     62                identity( 0.0 )
     63   c13 :        Size=1
     64        None
     65                identity( 0.0 )
     66                sum( d , -1 *  c )
     67                Inf
     68   c14 :        Size=1
     69        None
     70                identity( 0.0 )
     71                sum( c , -1 *  d )
    3572                Inf
    3673   c2 :         Size=1
     
    6299                identity( b[3] )
    63100                identity( 0.0 )
     101   c6 :         Size=1
     102        None
     103                identity( 0.0 )
     104                identity( c )
     105                Inf
     106   c7 :         Size=1
     107        None
     108                -Inf
     109                identity( c )
     110                identity( 1.0 )
     111   c8 :         Size=1
     112        None
     113                identity( 2.0 )
     114                identity( c )
     115                identity( 2.0 )
     116   c9 :         Size=1
     117        None
     118                sum( A , A )
     119                identity( c )
     120                Inf
    64121
    65 11 Declarations: a b c o2 o3_index o3 c1 c2 c3 c4 c5
     12224 Declarations: a b c d e A B o2 o3_index o3 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14
  • coopr.pyomo/stable/2.1/doc/pyomo/ref-set.tex

    r1808 r1972  
    1919\subsection{Set Declarations}
    2020
    21 A simple instance of \code{Set} objects declares an unordered set of arbitrary objects:
     21A simple instance of the \code{Set} object declares an unordered set of arbitrary objects:
    2222\begin{lstlisting}
    2323model.A = Set()
    2424\end{lstlisting}
    25 A set array can also be specified by providing sets as options
    26 to the \code{Set} object.  Multi-dimensional set arrays can be declared by simply including a list of sets as options to the \code{Set} object:
     25A set array can also be specified by providing a set as an option
     26to the \code{Set} object, and  multi-dimensional set arrays can be declared by simply including a list of sets as options to the \code{Set} object:
    2727\begin{lstlisting}
    2828model.B = Set()
     
    4848\end{lstlisting}
    4949
     50
    5051\subsection{Set Initialization}
    5152
    52 By default, a set object refers to an abstract set in a model.  However,
    53 a set can be initialized with data by using the \code{initialize} option, which is a function
    54 that accepts the set indices and model and returns the value of that set
    55 element:
     53By default, a set object refers to an abstract set in a model. 
     54However, a set can be explicitly initialized by adding set elements:
     55\begin{lstlisting}
     56model.J = Set()
     57model.J.add(1,4,9)
     58\end{lstlisting}
     59The \code{initialize} option can also be used to specify the values in
     60a set:
     61\begin{lstlisting}
     62model.K = Set(initialize=[1,4,9])
     63model.K_2 = Set(initialize=[(1,4),(9,16)])
     64\end{lstlisting}
     65The value of the \code{initialize} option can be a Python iterator.
     66Thus, sophisticated list comprehensions and generator expressions can be used:
     67\begin{lstlisting}
     68model.L = Set(initialize=(i for i in model.K if i%2 == 0))
     69\end{lstlisting}
     70
     71Two types of functions can be used with the \code{initialize} option.  If the
     72function accepts a model object, then this function is expected to return
     73an iterator containing data for the set:
    5674\begin{lstlisting}
    5775def I_init(model):
     
    6179        ans.append( (a,b) )
    6280    return ans
    63 model.I = model.A*model.B
    64 model.I.initialize = I_init
    65 \end{lstlisting}
    66 Note that the set \code{model.I} is not created when this set object is
    67 constructed.  Instead, \code{I\_init()} is called during the construction of a
    68 problem instance.
    69 
    70 A set can also be explicitly constructed by add set elements:
    71 \begin{lstlisting}
    72 model.J = Set()
    73 model.J.add(1,4,9)
    74 \end{lstlisting}
    75 The \code{initialize} option can also be used to specify the values in
    76 a set.  These default values may be overriden by later construction
    77 steps, or by data in an input file:
    78 \begin{lstlisting}
    79 model.K = Set(initialize=[1,4,9])
    80 model.K_2 = Set(initialize=[(1,4),(9,16)],dimen=2)
    81 \end{lstlisting}
    82 
    83 A set array can be constructed with the \code{initialize} option, which is a
    84 function that accepts the set indices and model and returns the set for that
    85 array index:
    86 \begin{lstlisting}
    87 def P_init(i, j, model):
    88     return range(0,i*j)
    89 model.P = Set(model.B,model.B)
    90 model.P.initialize = P_init
    91 \end{lstlisting}
    92 The \code{initialize} option can also be used to specify the values in
    93 a set array.  These default values are defined in a dictionary, which
     81model.I = Set(initialize=I_init)
     82\end{lstlisting}
     83If the function accepts a index and model, then this function is expected to return the set value assocated with that index:
     84\begin{lstlisting}
     85def M_init(i, model):
     86    return 2*i+1
     87model.M = Set(initialize=M_init)
     88\end{lstlisting}
     89
     90The \code{initialize} option can be used to specify the values in
     91a set array.  These values are defined in a dictionary, which
    9492specifies how each array element is initialized:
    9593\begin{lstlisting}
     
    117115after the execution of \code{model.create()}.
    118116
     117The \code{initialize} option can also specify a function that is used to provide values for a set array.  The function accepts the set indices and model and returns the set for that array index:
     118\begin{lstlisting}
     119def P_init(i, j, model):
     120    return range(0,i*j)
     121model.P = Set(model.B,model.B)
     122model.P.initialize = P_init
     123\end{lstlisting}
     124
     125Note that set data is not created when this set object is constructed.
     126Instead, initialization functions like \code{I\_init()} are called during
     127the construction of a problem instance.
     128Also, note that these values may be overriden by later construction
     129steps in a Pyomo model.  For example, data specified in an input file
     130will override the data specified by the \code{initialize} options.
     131
    119132
    120133\subsection{Data Validation}
     
    159172model.T = Set(model.B, validate=M_validate)
    160173\end{lstlisting}
     174
    161175
    162176\subsection{Set Options}
     
    199213\end{lstlisting}
    200214
     215
    201216\subsection{Class Attributes}
    202217
Note: See TracChangeset for help on using the changeset viewer.