Changeset 3309


Ignore:
Timestamp:
Dec 4, 2010 7:09:55 PM (10 years ago)
Author:
wehart
Message:

Finalizing the design of immutable parameters! This design follows CEP 4.
All model components are stored as attributes of model.components, and
immutable parameters are stored as float and dictionary attributes of
the model object.

This should make references to parameter values more intuitive.
Specifically, you can directly reference singleton parameter values,
rather than use the value() function. Additionally, these are constant values,
and thus they can be used in boolean expressions without generating
Pyomo expression objects.

HOWEVER, immutable parameter values do not have the rich representation/context
that is provided by the Pyomo Param class. For example, suppose that we have:

Z =[0,1]
model.A = Param(Z, default=1.0)

Then to query the index set for A you would need to do:

model.components.A.keys()

rather than

model.A.keys()

Both may be syntactically correct, but model.A is a dictionary whose
keys may be a subset of all valid keys for model.components.A.

The model attributes for immutable parameters are either (a) floats
(for singleton parameters) or (b) dictionaries (for indexed parameters).
Furthermore, the dictionary object used for indexed parameters has been
enhanced to support default values in a sparse manner.

Other changes:

  • The Block class was restructured to contain the 'components' attribute,

which itself is a new class that manages the indices for blocks.
Some of the functionality in Block was migrated into BlockComponents?
(which is used to define the 'components' attribute).

  • The semantics of the summation() function has been restricted somewhat.

If the 'index' option is not specified, then this function now validates
that the last argument is a variable component. This is necessary to
ensure that this argument contains a complete index set.

  • Many tests were updated due to these changes. However, these were

almost exclusively the tests for the parameter component itself.

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

Legend:

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

    r3242 r3309  
    165165        """Create a copy of this model"""
    166166
    167         for name in self._declarations:
    168             self._declarations[name].model = None
     167        for name in self.components:
     168            #print 'y',name
     169            #print 'z', type(self.components[name])
     170            self.components[name].model = None
    169171
    170172        instance = copy.deepcopy(self)
    171173
    172         for name in self._declarations:
    173             self._declarations[name].model = self
    174         for name in instance._declarations:
    175             instance._declarations[name].model = instance
     174        for name in self.components:
     175            self.components[name].model = self
     176        for name in instance.components:
     177            instance.components[name].model = instance
    176178        return instance
    177179
    178180    def reset(self):
    179         for name in self._declarations:
    180             self._declarations[name].reset()
     181        for name in self.components:
     182            self.components[name].reset()
    181183
    182184    def preprocess(self):
     
    267269                msg = "Cannot access undefined namespace: '%s'"
    268270                raise IOError, msg % namespace
    269         #print "HERE _load_model_data",self._declarations
    270         for tmp in self._declarations:
    271             if self._declarations[tmp].type() is Model:
     271        for tmp in self.components:
     272            if self.components[tmp].type() is Model:
    272273                continue
    273             declaration = self._declarations[tmp]
     274            declaration = self.components[tmp]
    274275            if tmp in modeldata._default.keys():
    275276                if declaration.type() is Set:
     
    298299                self.pprint()
    299300
     301            #declaration.construct(data)
    300302            try:
    301303                if isinstance(declaration, coopr.pyomo.base.constraint.Constraint) or isinstance(declaration, coopr.pyomo.base.objective.Objective):
  • coopr.pyomo/trunk/coopr/pyomo/base/__init__.py

    r2908 r3309  
    3535from rangeset import *
    3636
    37 import sys as _sys  # '_' so it won't be imported by the importing module
    38 if _sys.version_info[0:2] < (2, 5):
    39     # This is the hack to work around the deepcopy issues that Python 2.4
    40     # has.  Basically, exhaustively attach a manual __deepcopy__ to classes
    41     # that need it.
    42     from pyutilib.misc import create_deepcopy as _cd
    43     from param import _ParamArray, _ParamValue, _ParamElement
    44     from var import _VarBase, _VarArray, _VarElement, _VarValue
    45     from pyutilib.component.core import Plugin
    46 
    47     _to_deepcopy = (
    48         _ParamArray,
    49         _ParamElement,
    50         _ParamValue,
    51         _VarBase,
    52         _VarArray,
    53         _VarElement,
    54         _VarValue,
    55         _VirtualSet,
    56         Block,
    57         Constraint,
    58         Model,
    59         Objective,
    60         RangeSet,
    61         RealSet,
    62         SOSConstraint,
    63         Var,
    64 
    65         Plugin,
    66     )
    67     for _i in _to_deepcopy:
    68         _i.__deepcopy__ = _cd( _i )
    69 
    7037#
    7138# This is a hack to strip out modules, which shouldn't have been included in these imports
  • coopr.pyomo/trunk/coopr/pyomo/base/block.py

    r3212 r3309  
    4545
    4646
    47 class Block(IndexedComponent):
    48     """
    49     A block in an optimization model.  By default, this defers construction of
    50     components until data is loaded.
    51     """
    52 
    53     alias("Block", "Blocks are indexed components that contain one or more " + \
    54           "other model components.")
    55 
    56     def __init__(self, *args, **kwargs):
    57         """Constructor"""
    58         if 'ctype' in kwargs:
    59             tkwargs = {'ctype':kwargs['ctype']}
    60         else:
    61             tkwargs = {'ctype':Block}
    62         IndexedComponent.__init__(self, *args, **tkwargs)
    63         #
    64         self.name=kwargs.get('name', 'unknown')
    65         self._defer_construction=True
    66         # By default, a Block is a top-level (i.e. Model) block
    67         self.model = self
    68         self._parent_block = None
     47class BlockComponents(object):
     48
     49    def __init__(self):
    6950        #
    7051        # Define component dictionary: component type -> instance
     
    7960        self._declarations=OrderedDict()
    8061
    81         # Hack. Right now Block objects assume all attributes derived from
    82         # Component eventually inherit from NumValue, and so have a domain
    83         # attribute.
    84         self.domain = None
    85 
    86     def concrete_mode(self):
    87         """Configure block to immediately construct components"""
    88         self._defer_construction=False
    89 
    90     def symbolic_mode(self):
    91         """Configure block to defer construction of components"""
    92         self._defer_construction=True
     62    def __iter__(self):
     63        return self._declarations.iterkeys()
     64
     65    def __getitem__(self, name):
     66        if isinstance(name,basestring):
     67            return self._declarations.get(name, None)
     68        return self._component.get(name, None)
     69
     70    def _clear_attribute(self, name):
     71        val = self[name]
     72        if val is None:
     73            return
     74
     75        if isinstance(val, Block):
     76            val.__dict__['_parent_block'] = None
     77            val.model = val
     78        else:
     79            val.model = None
     80           
     81        del self._component[ val.type() ][name]
     82        del self._declarations[name]
     83        self.__dict__[name]=None
     84
     85    def _add_component(self, name, val):
     86        self._component[val.type()][name]=val
     87        self._declarations[name] = val
     88        self.__dict__[name]=val
     89
     90    def __setattr__(self,name,val):
     91            #
     92            # Try to set the value. This may fail if the attribute
     93            # does not already exist in this model, if the set_value
     94            # function is not defined, or if a bad value is
     95            # provided. In the latter case, a ValueError will be
     96            # thrown, which # we raise. Otherwise, this is an object
     97            # that we need to set directly.
     98            #
     99            try:
     100                self.__dict__[name].set_value(val)
     101            except ValueError, e:
     102                raise
     103            except Exception, e:
     104                self.__dict__[name]=val
    93105
    94106    def components(self, ctype=None):
     
    127139        return tmp
    128140
     141    def pprint(self, filename=None, ostream=None):
     142        """
     143        Print a summary of the model info
     144        """
     145        if ostream is None:
     146           ostream = sys.stdout
     147        if filename is not None:
     148           OUTPUT=open(filename,"w")
     149           self.pprint(ostream=OUTPUT)
     150           OUTPUT.close()
     151           return
     152        if ostream is None:
     153           ostream = sys.stdout
     154        #
     155        # We hard-code the order of the core Pyomo modeling
     156        # components, to ensure that the output follows the logical order
     157        # that expected by a user.
     158        #
     159        items = [Set, RangeSet, Param, Var, Objective, Constraint, Block]
     160        for item in ExtensionPoint(IModelComponent):
     161            if not item in items:
     162                items.append(item)
     163
     164        # Currently, model components are not actually being registered
     165        # with the IModelComponent extension point (1 Nov 2010), so as a
     166        # workaround, we will loop through the components and add any
     167        # new components that actually have defined members.
     168        extra_items = []
     169        for item, members in self._component.iteritems():
     170            if item not in items and len(members):
     171                extra_items.append(item)
     172        # extra items get added alphabetically (so output is consistent)
     173        items.extend(sorted(extra_items))
     174
     175        for item in items:
     176            if not item in self._component:
     177                continue
     178            keys = self._component[item].keys()
     179            keys.sort()
     180            #
     181            # NOTE: these conditional checks should not be hard-coded.
     182            #
     183            print >>ostream, len(keys), item.__name__+" Declarations"
     184            for key in keys:
     185                self._component[item][key].pprint(ostream=ostream)
     186            print >>ostream, ""
     187        #
     188        # Model Order
     189        #
     190        print >>ostream, len(self._declarations),"Declarations:",
     191        for name in self._declarations:
     192          print >>ostream, name,
     193        print >>ostream, ""
     194
     195
     196class Block(IndexedComponent):
     197    """
     198    A block in an optimization model.  By default, this defers construction of
     199    components until data is loaded.
     200    """
     201
     202    alias("Block", "Blocks are indexed components that contain one or more " + \
     203          "other model components.")
     204
     205    def __init__(self, *args, **kwargs):
     206        """Constructor"""
     207        if 'ctype' in kwargs:
     208            tkwargs = {'ctype':kwargs['ctype']}
     209        else:
     210            tkwargs = {'ctype':Block}
     211        IndexedComponent.__init__(self, *args, **tkwargs)
     212        #
     213        self.name=kwargs.get('name', 'unknown')
     214        self._defer_construction=True
     215        # By default, a Block is a top-level (i.e. Model) block
     216        self.model = self
     217        self._parent_block = None
     218        self.components =  BlockComponents()
     219
     220    def concrete_mode(self):
     221        """Configure block to immediately construct components"""
     222        self._defer_construction=False
     223
     224    def symbolic_mode(self):
     225        """Configure block to defer construction of components"""
     226        self._defer_construction=True
     227
     228    def components(self, ctype=None):
     229        """
     230        Return information about the block components.  If ctype is None, return the dictionary
     231        that maps {component type -> {name -> instance}}.  Otherwise, return the dictionary
     232        that maps {name -> instance} for the specified component type.
     233        """
     234        return self.components.components(ctype)
     235
     236    def active_components(self, _ctype=None):
     237        """
     238        Returns the active components in this block.  If _ctype is None, return the
     239        dictionary that maps {component type -> {name -> instance}}.  Otherwise, return
     240        the dictionary that maps {name -> instance} for the specified component type.
     241        """
     242        return self.components.active_components(_ctype)
     243       
    129244    def _add_temporary_set(self,val):
    130245        if val._index_set is not None:
     
    144259            val._index.name == "_unknown_":
    145260            self._construct_temporary_set(val._index,val.name+"_index")
    146         if val.domain is not None and val.domain.name == "_unknown_":
     261        if getattr(val,'domain',None) is not None and val.domain.name == "_unknown_":
    147262            self._construct_temporary_set(val.domain,val.name+"_domain")
    148263
     
    160275           return obj
    161276
    162     def _clear_attribute(self,name):
     277    def _clear_attribute(self, name, only_block=False):
    163278        """
    164279        Cleanup the pre-existing model attribute
    165280        """
    166         val = self._declarations.get(name, None)
    167         if val is None:
     281        #
     282        # We don't delete here because that would destruct the component, which might
     283        # be shared with another block.
     284        #
     285        self.__dict__[name]=None
     286        if only_block:
    168287            return
    169288
    170         if isinstance(val, Block):
    171             val.__dict__['_parent_block'] = None
    172             val.model = val
    173         else:
    174             val.model = None
    175            
    176         self.__dict__[name]=None # Any idea why we don't DEL here?
    177         del self._component[ val.type() ][name]
    178         del self._declarations[name]
     289        self.components._clear_attribute(name)
    179290
    180291    def _add_component(self, name, val):
     
    182293        val.name=name
    183294        self._add_temporary_set(val)
    184         self._component[val.type()][name]=val
    185         self._declarations[name] = val
     295        self.components._add_component(name,val)
    186296        self.__dict__[name]=val
    187297
     
    223333            # Component.__init__() assigns "self.model = None" before
    224334            # Block.__init__ defines the _declarations map.
    225             for subcomp in self.__dict__.get("_declarations", {}).itervalues():
    226                 subcomp.model = val
    227         elif name != "_component" and isinstance(val, Component):
     335            components = self.__dict__.get('components', None)
     336            if not components is None:
     337                for subcomp in components().itervalues():
     338                    subcomp.model = val
     339        elif name != "components" and isinstance(val, Component):
    228340            #
    229341            # If this is a component type, then simply set it
     
    250362        Print a summary of the model info
    251363        """
    252         if ostream is None:
    253            ostream = sys.stdout
    254         if filename is not None:
    255            OUTPUT=open(filename,"w")
    256            self.pprint(ostream=OUTPUT)
    257            OUTPUT.close()
    258            return
    259         if ostream is None:
    260            ostream = sys.stdout
    261         #
    262         # We hard-code the order of the core Pyomo modeling
    263         # components, to ensure that the output follows the logical order
    264         # that expected by a user.
    265         #
    266         items = [Set, RangeSet, Param, Var, Objective, Constraint, Block]
    267         for item in ExtensionPoint(IModelComponent):
    268             if not item in items:
    269                 items.append(item)
    270 
    271         # Currently, model components are not actually being registered
    272         # with the IModelComponent extension point (1 Nov 2010), so as a
    273         # workaround, we will loop through the components and add any
    274         # new components that actually have defined members.
    275         extra_items = []
    276         for item, members in self._component.iteritems():
    277             if item not in items and len(members):
    278                 extra_items.append(item)
    279         # extra items get added alphabetically (so output is consistent)
    280         items.extend(sorted(extra_items))
    281 
    282         for item in items:
    283             if not item in self._component:
    284                 continue
    285             keys = self._component[item].keys()
    286             keys.sort()
    287             #
    288             # NOTE: these conditional checks should not be hard-coded.
    289             #
    290             print >>ostream, len(keys), item.__name__+" Declarations"
    291             for key in keys:
    292                 self._component[item][key].pprint(ostream=ostream)
    293             print >>ostream, ""
    294         #
    295         # Model Order
    296         #
    297         print >>ostream, len(self._declarations),"Declarations:",
    298         for name in self._declarations:
    299           print >>ostream, name,
    300         print >>ostream, ""
     364        self.components.pprint(filename=filename, ostream=ostream)
    301365
    302366    def display(self, filename=None, ostream=None):
  • coopr.pyomo/trunk/coopr/pyomo/base/numvalue.py

    r3188 r3309  
    1414import pyutilib.math
    1515import sys
    16 from set_types import Reals
     16from set_types import Reals, Any
    1717
    1818
     
    307307        # NOTE: we in general don't perform domain validation of numeric constants,
    308308        #       especially because the user/caller has specified the value, and
    309         #       typically does not specify the domain. the domain might be useful
    310         #       with meta-level symbolic expression analysis, but even there the
    311         #       above default of a real domain is questionable.
     309        #       typically does not specify the domain. The domain might be useful
     310        #       with meta-level symbolic expression analysis, but for now we treat this as
     311        #       a Any.
    312312        NumericValue.__init__(self, name=name, domain=domain, value=value, validate_value=False)
    313313
  • coopr.pyomo/trunk/coopr/pyomo/base/param.py

    r3166 r3309  
    2323from sets import _BaseSet
    2424import pyomo
     25from pyutilib.misc import DictWithDefaultValue
    2526
    2627
     
    4243        return self.name
    4344
     45
     46class _ImmutableParamValue(_ParamValue):
     47
     48    def __init__(self, data, index, name=None, domain=None, value=None):
     49        self._immutable_data = data
     50        self._immutable_index = index
     51        _ParamValue.__init__(self, name=name, domain=domain, value=value)
     52
     53    def __getattr__(self, name):
     54        if name is 'value':
     55            return self._immutable_data[self._immutable_index]
     56        try:
     57            return self.__dict__[name]
     58        except:
     59            raise AttributeError, "Unknown attribute `"+str(name)+"' for object with type "+str(type(self))
     60
     61    def __setattr__(self,name,val):
     62        if name == "__class__":
     63           self.__class__ = val
     64           return
     65        if name[0] == "_":
     66           self.__dict__[name] = val
     67           return
     68        if name is 'value':
     69           if type(val) is dict:
     70              raise IOError
     71           self._immutable_data[self._immutable_index] = val
     72        self.__dict__[name] = val
    4473
    4574
     
    85114
    86115        self._paramval   = {}
     116        if not self.mutable:
     117            self._paramdata = DictWithDefaultValue(defaultval)
    87118        self._default = _ParamValue(
    88119          name   = self.name,
     
    115146                val = self._paramval[key].value
    116147             else:
    117                 val = self._paramval[key]
     148                val = self._paramdata[key]
    118149             print >>ostream, "\t"+str(key)+" : "+str(val)
    119150        if self._default.value is not None and not self._default.value is None:
     
    154185        """
    155186        if ndx in self._paramval:
    156             return self._paramval[ndx]
     187            #print 'HERE',ndx,self.mutable,self._paramdata,self._paramdata[ndx]
     188            if self.mutable:
     189                return self._paramval[ndx]
     190            else:
     191                return self._paramdata[ndx]
    157192        if ndx in self._index and self._default.value is not None:
    158193            return self._default.value
     
    175210                        )
    176211            else:
    177                 self._paramval[ndx]= val
     212                self._paramval[ndx]= _ImmutableParamValue(
     213                        self._paramdata,
     214                        ndx,
     215                        name   = create_name(self.name,ndx),
     216                        domain = self.domain,
     217                        value  = val
     218                        )
    178219            return
    179220        #
     
    200241                    )
    201242        else:
    202             self._paramval[ndx] = val
     243            self._paramval[ndx]= _ImmutableParamValue(
     244                        self._paramdata,
     245                        ndx,
     246                        name   = create_name(self.name,ndx),
     247                        domain = self.domain,
     248                        value  = val
     249                        )
    203250        #
    204251        # This is at the end, so the user can write their validation
     
    213260        if pyomo.debug("verbose"):      #pragma:nocover
    214261           print "Constructing Param, name="+self.name+", from data="+`data`
     262        #print 'ZZ',self.name,self._constructed
    215263        if self._constructed:
     264            raise IOError
    216265            return
    217266        self._constructed=True
     
    226275        try:
    227276            self._default.value = self.default
     277            if not self.mutable:
     278                self._paramdata.default = self.default
    228279        except:
    229280            pass
     
    312363                    tval = self._initialize(*tmp)
    313364                    self.__setitem__(val, tval)
     365        #
     366        #print 'zz',self.name,self._constructed,self.mutable
     367        if not self.mutable:
     368            if None in self._paramval:
     369                #print 'X',self.name, self._paramval[None].value
     370                setattr(self.model, self.name, self._paramval[None].value)
     371            else:
     372                #print 'Y',self.name, self._paramdata
     373                #print self.model, self.name, self._paramdata
     374                self.model._clear_attribute(self.name, only_block=True)
     375                #print self.model, self.name, self._paramdata
     376                setattr(self.model, self.name, self._paramdata)
     377                #print 'YY',self.name, self._paramdata
     378        #print 'BBB',self._paramdata
    314379
    315380    def _valid_indexed_value(self,value,index, use_exception):
     
    351416
    352417    def data(self):
    353         tmp = {}
     418        if not self.mutable:
     419            return self._paramdata
     420        tmp = DictWithDefaultValue(self._default.value)
    354421        for key in self.keys():
    355             if self.mutable:
    356                 tmp[key] = self._paramval[key].value
    357             else:
    358                 tmp[key] = self._paramval[key]
     422            tmp[key] = self._paramval[key].value
    359423        return tmp
    360424
     
    363427
    364428    def __init__(self, *args, **kwd):
    365 
    366         if kwd.pop('_deep_copying', None):
    367             # Hack for Python 2.4 compatibility
    368             # Deep copy will copy all items as necessary, so no need to
    369             # complete parsing
    370             return
    371 
    372429        _ParamValue.__init__(self, \
    373430                             name=kwd.get('name', None), \
    374                              domain=kwd.get('within', None), \
     431                             domain=kwd.get('within', Any), \
    375432                             value=kwd.get('default', None))
    376433        _ParamBase.__init__(self, *args, **kwd)
    377434
    378435        self._paramval[None] = self
    379 
    380     #def simplify(self, model):
    381         #return self
    382         #return NumericConstant(value=self.value)
    383436
    384437    def check_values(self):         #pragma:nocover
     
    389442            raise ValueError, "Undefined value for parameter "+self.name
    390443        if not self._valid_indexed_value(self.value,None,False):
    391             print "BUG",self.value,self._index
     444            #print "BUG",self.value,self._index
    392445            msg = "Parameter '%s' failed validation test.  Value: %s"
    393446            raise ValueError, msg % ( self.name, str(self.value) )
     
    395448    def __call__(self, exception=True):
    396449        return self._paramval[None].value
     450
     451
     452
     453class _ImmutableParamElement(_ParamBase,_ImmutableParamValue):
     454
     455    def __init__(self, *args, **kwd):
     456        _ParamBase.__init__(self, *args, **kwd)
     457        #print "HERE",self._index
     458        _ImmutableParamValue.__init__(self,
     459                            self._paramdata,
     460                            None,
     461                            name=kwd.get('name', None),
     462                            domain=kwd.get('within', Any),
     463                            value=kwd.get('default', None))
     464        #print "HERE",self._index
     465        self._paramval[None] = self
     466
     467    def check_values(self):         #pragma:nocover
     468        #
     469        # Validate the values
     470        #
     471        if None not in self._index:
     472            raise ValueError, "Undefined value for parameter "+self.name
     473        if not self._valid_indexed_value(self.value,None,False):
     474            #print "BUG",self.value,self._index
     475            msg = "Parameter '%s' failed validation test.  Value: %s"
     476            raise ValueError, msg % ( self.name, str(self.value) )
     477
     478    def __call__(self, exception=True):
     479        return self._paramdata[None]
    397480
    398481
     
    429512                val = self._paramval[key].value
    430513            else:
    431                 val = self._paramval[key]
     514                val = self._paramdata[key]
    432515            if not self._valid_indexed_value( val, key, False ):
    433516                msg = "Parameter %s[%s] failed validation test.  Value: %s"
     
    453536    def __new__(cls, *args, **kwds):
    454537        if args == ():
    455             self = _ParamElement(*args, **kwds)
     538            if kwds.get('mutable',False):
     539                self = _ParamElement(*args, **kwds)
     540            else:
     541                self = _ImmutableParamElement(*args, **kwds)
    456542        else:
    457543            self = _ParamArray(*args, **kwds)
  • coopr.pyomo/trunk/coopr/pyomo/base/util.py

    r2821 r3309  
    1313#
    1414
     15__all__ = ['summation', 'multisum', 'dot_product', 'sequence', 'xsequence', 'isfunctor']
     16
     17import var
    1518import expr
    1619
     
    4851    else: 
    4952        if len(args) > 0:
    50             index=args[-1].keys()
     53            iarg=args[-1]
     54            if not isinstance(iarg,var._VarBase):
     55                raise ValueError, "Error executing summation(): The last argument value must be a variable object if no 'index' option is specified"
    5156        else:
    52             index=denom[-1].keys()
     57            iarg=denom[-1]
     58            if not isinstance(iarg,var._VarBase):
     59                raise ValueError, "Error executing summation(): The last denom argument value must be a variable object if no 'index' option is specified"
     60        index = iarg.keys()
    5361
    5462    ans = 0
  • coopr.pyomo/trunk/coopr/pyomo/io/cpxlp.py

    r3257 r3309  
    745745        if sosn or sos1 or sos2:
    746746            writtenSOS = False
    747             constrs = model._component.get(SOSConstraint, {})
     747            constrs = model.components[SOSConstraint]
    748748            for name in constrs:
    749749                con = constrs[name]
  • coopr.pyomo/trunk/coopr/pyomo/tests/expr/test_canonical.py

    r2422 r3309  
    7575        self.model.x = Var(self.model.A, bounds=(-1,1))
    7676        def obj_rule(model):
    77             return summation(model.x, model.p)
     77            return summation(model.p, model.x)
    7878        self.model.obj = Objective(rule=obj_rule)
    7979        self.instance = self.model.create()
  • coopr.pyomo/trunk/coopr/pyomo/tests/unit/test_block.py

    r2865 r3309  
    5656        self.block.obj = Objective(rule=obj_rule)
    5757        #self.instance = self.block.create()
    58         self.block.pprint()
    59         self.block.display()
     58        #self.block.pprint()
     59        #self.block.display()
    6060
    6161    def Xtest_write2(self):
  • coopr.pyomo/trunk/coopr/pyomo/tests/unit/test_expr.py

    r3219 r3309  
    621621        model.a = Param()
    622622        model.b = Set(initialize=[1,2,3])
    623         model.c = Param(model.b,initialize=2, within=Reals)
     623        model.c = Param(model.b, initialize=2, within=Reals, mutable=True)
    624624        #try:
    625625            #model.a.value = 3
     
    677677        model.e = Param(model.b,model.b,initialize={(1,1):(2,3)}, validate=e_valid)
    678678        instance = model.create()
    679         instance.e.check_values()
     679        instance.components.e.check_values()
    680680        #try:
    681681            #instance.c.value = 'b'
  • coopr.pyomo/trunk/coopr/pyomo/tests/unit/test_model.py

    r3247 r3309  
    8686        self.model.x=Var(self.model.J)
    8787        def obj_rule(instance):
    88             return summation(instance.x, instance.w)
     88            return summation(instance.w, instance.x)
    8989        self.model.obj = Objective(rule=obj_rule)
    9090        self.instance = self.model.create()
  • coopr.pyomo/trunk/coopr/pyomo/tests/unit/test_modeldata.py

    r3066 r3309  
    248248        model=Model()
    249249        model.A=Set()
    250         model.B=Param(model.A)
     250        model.B=Param(model.A, mutable=True)
    251251        md.read(model)
    252252
     
    255255        md.add(currdir+"data8.dat")
    256256        model=Model()
    257         model.A=Param(within=Boolean)
    258         model.B=Param(within=Boolean)
     257        model.A=Param(within=Boolean, mutable=True)
     258        model.B=Param(within=Boolean, mutable=True)
    259259        model.Z=Set()
    260260        md.read(model)
     
    279279        os.chdir(currdir)
    280280        model=Model()
    281         model.a=Param()
    282         model.b=Param()
    283         model.c=Param()
    284         model.d=Param()
     281        model.a=Param(mutable=True)
     282        model.b=Param(mutable=True)
     283        model.c=Param(mutable=True)
     284        model.d=Param(mutable=True)
    285285        # Test 1
    286286        instance = model.create(currdir+'data14.dat', namespaces=['ns1','ns2'])
     
    386386        pyutilib.misc.reset_redirect()
    387387        model=Model()
    388         model.Z = Param(default=99.0)
     388        model.Z = Param(default=99.0, mutable=True)
    389389        instance = model.create(currdir+'importZ.dat')
    390         self.failUnlessEqual(instance.Z.value, 1.1)
     390        self.failUnlessEqual(instance.Z, 1.1)
    391391        os.remove(currdir+'importZ.dat')
    392392
     
    398398        model=Model()
    399399        model.A = Set(initialize=['A1','A2','A3','A4'])
    400         model.Y = Param(model.A)
     400        model.Y = Param(model.A, mutable=True)
    401401        instance = model.create(currdir+'importY.dat')
    402402        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3','A4']))
     
    413413        model=Model()
    414414        model.A = Set(initialize=['A1','A2','A3','A4'])
    415         model.X = Param(model.A)
    416         model.W = Param(model.A)
     415        model.X = Param(model.A, mutable=True)
     416        model.W = Param(model.A, mutable=True)
    417417        instance = model.create(currdir+'importXW.dat')
    418418        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3','A4']))
     
    428428        model=Model()
    429429        model.A = Set(initialize=['A1','A2','A3'])
    430         model.X = Param(model.A)
    431         model.W = Param(model.A)
     430        model.X = Param(model.A, mutable=True)
     431        model.W = Param(model.A, mutable=True)
    432432        instance = model.create(currdir+'importXW.dat')
    433433        self.failUnlessEqual(instance.X.data(), {'A1':3.3,'A2':3.4,'A3':3.5})
     
    442442        model=Model()
    443443        model.A = Set()
    444         model.X = Param(model.A)
    445         model.W = Param(model.A)
     444        model.X = Param(model.A, mutable=True)
     445        model.W = Param(model.A, mutable=True)
    446446        instance = model.create(currdir+'importXW.dat')
    447447        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3']))
     
    457457        model=Model()
    458458        model.B = Set()
    459         model.R = Param(model.B)
    460         model.S = Param(model.B)
     459        model.R = Param(model.B, mutable=True)
     460        model.S = Param(model.B, mutable=True)
    461461        instance = model.create(currdir+'importXW.dat')
    462462        self.failUnlessEqual(instance.B.data(), set(['A1','A2','A3']))
     
    473473        model.B = Set(initialize=['I1','I2','I3','I4'])
    474474        model.A = Set(initialize=['A1','A2','A3'])
    475         model.T = Param(model.A, model.B)
     475        model.T = Param(model.A, model.B, mutable=True)
    476476        instance = model.create(currdir+'importT.dat')
    477477        self.failUnlessEqual(instance.T.data(), {('A2', 'I1'): 2.3, ('A1', 'I2'): 1.4, ('A1', 'I3'): 1.5, ('A1', 'I4'): 1.6, ('A1', 'I1'): 1.3, ('A3', 'I4'): 3.6, ('A2', 'I4'): 2.6, ('A3', 'I1'): 3.3, ('A2', 'I3'): 2.5, ('A3', 'I2'): 3.4, ('A2', 'I2'): 2.4, ('A3', 'I3'): 3.5})
     
    486486        model.A = Set(initialize=['I1','I2','I3','I4'])
    487487        model.B = Set(initialize=['A1','A2','A3'])
    488         model.U = Param(model.A, model.B)
     488        model.U = Param(model.A, model.B, mutable=True)
    489489        instance = model.create(currdir+'importU.dat')
    490490        self.failUnlessEqual(instance.U.data(), {('I2', 'A1'): 1.4, ('I3', 'A1'): 1.5, ('I3', 'A2'): 2.5, ('I4', 'A1'): 1.6, ('I3', 'A3'): 3.5, ('I1', 'A2'): 2.3, ('I4', 'A3'): 3.6, ('I1', 'A3'): 3.3, ('I4', 'A2'): 2.6, ('I2', 'A3'): 3.4, ('I1', 'A1'): 1.3, ('I2', 'A2'): 2.4})
     
    500500        model=Model()
    501501        model.A = Set(initialize=['A1','A2','A3','A4'])
    502         model.S = Param(model.A)
     502        model.S = Param(model.A, mutable=True)
    503503        instance = model.create(currdir+'importS.dat')
    504504        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3','A4']))
     
    513513        model=Model()
    514514        model.J = Set(dimen=2)
    515         model.P = Param(model.J)
    516         model.O = Param(model.J)
     515        model.P = Param(model.J, mutable=True)
     516        model.O = Param(model.J, mutable=True)
    517517        instance = model.create(currdir+'importPO.dat')
    518518        self.failUnlessEqual(instance.J.data(), set([('A3', 'B3'), ('A1', 'B1'), ('A2', 'B2')]) )
     
    603603        pyutilib.misc.reset_redirect()
    604604        model=Model()
    605         model.Z = Param(default=99.0)
     605        model.Z = Param(default=99.0, mutable=True)
    606606        instance = model.create(currdir+'importZ.dat')
    607607        self.failUnlessEqual(instance.Z.value, 1.1)
     
    615615        model=Model()
    616616        model.A = Set(initialize=['A1','A2','A3','A4'])
    617         model.Y = Param(model.A)
     617        model.Y = Param(model.A, mutable=True)
    618618        instance = model.create(currdir+'importY.dat')
    619619        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3','A4']))
     
    630630        model=Model()
    631631        model.A = Set(initialize=['A1','A2','A3','A4'])
    632         model.X = Param(model.A)
    633         model.W = Param(model.A)
     632        model.X = Param(model.A, mutable=True)
     633        model.W = Param(model.A, mutable=True)
    634634        instance = model.create(currdir+'importXW.dat')
    635635        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3','A4']))
     
    645645        model=Model()
    646646        model.A = Set(initialize=['A1','A2','A3'])
    647         model.X = Param(model.A)
    648         model.W = Param(model.A)
     647        model.X = Param(model.A, mutable=True)
     648        model.W = Param(model.A, mutable=True)
    649649        instance = model.create(currdir+'importXW.dat')
    650650        self.failUnlessEqual(instance.X.data(), {'A1':3.3,'A2':3.4,'A3':3.5})
     
    659659        model=Model()
    660660        model.A = Set()
    661         model.X = Param(model.A)
    662         model.W = Param(model.A)
     661        model.X = Param(model.A, mutable=True)
     662        model.W = Param(model.A, mutable=True)
    663663        instance = model.create(currdir+'importXW.dat')
    664664        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3']))
     
    674674        model=Model()
    675675        model.B = Set()
    676         model.R = Param(model.B)
    677         model.S = Param(model.B)
     676        model.R = Param(model.B, mutable=True)
     677        model.S = Param(model.B, mutable=True)
    678678        instance = model.create(currdir+'importXW.dat')
    679679        self.failUnlessEqual(instance.B.data(), set(['A1','A2','A3']))
     
    690690        model.B = Set(initialize=['I1','I2','I3','I4'])
    691691        model.A = Set(initialize=['A1','A2','A3'])
    692         model.T = Param(model.A, model.B)
     692        model.T = Param(model.A, model.B, mutable=True)
    693693        instance = model.create(currdir+'importT.dat')
    694694        self.failUnlessEqual(instance.T.data(), {('A2', 'I1'): 2.3, ('A1', 'I2'): 1.4, ('A1', 'I3'): 1.5, ('A1', 'I4'): 1.6, ('A1', 'I1'): 1.3, ('A3', 'I4'): 3.6, ('A2', 'I4'): 2.6, ('A3', 'I1'): 3.3, ('A2', 'I3'): 2.5, ('A3', 'I2'): 3.4, ('A2', 'I2'): 2.4, ('A3', 'I3'): 3.5})
     
    703703        model.A = Set(initialize=['I1','I2','I3','I4'])
    704704        model.B = Set(initialize=['A1','A2','A3'])
    705         model.U = Param(model.A, model.B)
     705        model.U = Param(model.A, model.B, mutable=True)
    706706        instance = model.create(currdir+'importU.dat')
    707707        self.failUnlessEqual(instance.U.data(), {('I2', 'A1'): 1.4, ('I3', 'A1'): 1.5, ('I3', 'A2'): 2.5, ('I4', 'A1'): 1.6, ('I3', 'A3'): 3.5, ('I1', 'A2'): 2.3, ('I4', 'A3'): 3.6, ('I1', 'A3'): 3.3, ('I4', 'A2'): 2.6, ('I2', 'A3'): 3.4, ('I1', 'A1'): 1.3, ('I2', 'A2'): 2.4})
     
    717717        model=Model()
    718718        model.A = Set(initialize=['A1','A2','A3','A4'])
    719         model.S = Param(model.A)
     719        model.S = Param(model.A, mutable=True)
    720720        instance = model.create(currdir+'importS.dat')
    721721        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3','A4']))
     
    730730        model=Model()
    731731        model.J = Set(dimen=2)
    732         model.P = Param(model.J)
    733         model.O = Param(model.J)
     732        model.P = Param(model.J, mutable=True)
     733        model.O = Param(model.J, mutable=True)
    734734        instance = model.create(currdir+'importPO.dat')
    735735        self.failUnlessEqual(instance.J.data(), set([('A3', 'B3'), ('A1', 'B1'), ('A2', 'B2')]) )
     
    821821        pyutilib.misc.reset_redirect()
    822822        model=Model()
    823         model.Z = Param(default=99.0)
     823        model.Z = Param(default=99.0, mutable=True)
    824824        instance = model.create(currdir+'importZ.dat')
    825825        self.failUnlessEqual(instance.Z.value, 1.1)
     
    833833        model=Model()
    834834        model.A = Set(initialize=['A1','A2','A3','A4'])
    835         model.Y = Param(model.A)
     835        model.Y = Param(model.A, mutable=True)
    836836        instance = model.create(currdir+'importY.dat')
    837837        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3','A4']))
     
    848848        model=Model()
    849849        model.A = Set(initialize=['A1','A2','A3','A4'])
    850         model.X = Param(model.A)
    851         model.W = Param(model.A)
     850        model.X = Param(model.A, mutable=True)
     851        model.W = Param(model.A, mutable=True)
    852852        instance = model.create(currdir+'importXW.dat')
    853853        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3','A4']))
     
    863863        model=Model()
    864864        model.A = Set()
    865         model.X = Param(model.A)
    866         model.W = Param(model.A)
     865        model.X = Param(model.A, mutable=True)
     866        model.W = Param(model.A, mutable=True)
    867867        instance = model.create(currdir+'importXW.dat')
    868868        self.failUnlessEqual(instance.A.data(), set())
     
    878878        model=Model()
    879879        model.A = Set()
    880         model.X = Param(model.A)
    881         model.W = Param(model.A)
     880        model.X = Param(model.A, mutable=True)
     881        model.W = Param(model.A, mutable=True)
    882882        instance = model.create(currdir+'importXW.dat')
    883883        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3']))
     
    893893        model=Model()
    894894        model.B = Set()
    895         model.R = Param(model.B)
    896         model.S = Param(model.B)
     895        model.R = Param(model.B, mutable=True)
     896        model.S = Param(model.B, mutable=True)
    897897        instance = model.create(currdir+'importXW.dat')
    898898        self.failUnlessEqual(instance.B.data(), set(['A1','A2','A3']))
     
    909909        model.A = Set()
    910910        model.B = Set()
    911         model.T = Param(model.A, model.B)
     911        model.T = Param(model.A, model.B, mutable=True)
    912912        instance = model.create(currdir+'importT.dat')
    913913        self.failUnlessEqual(instance.T.data(), {('A2', 'I1'): 2.3, ('A1', 'I2'): 1.4, ('A1', 'I3'): 1.5, ('A1', 'I4'): 1.6, ('A1', 'I1'): 1.3, ('A3', 'I4'): 3.6, ('A2', 'I4'): 2.6, ('A3', 'I1'): 3.3, ('A2', 'I3'): 2.5, ('A3', 'I2'): 3.4, ('A2', 'I2'): 2.4, ('A3', 'I3'): 3.5})
     
    922922        model.A = Set()
    923923        model.B = Set()
    924         model.U = Param(model.A, model.B)
     924        model.U = Param(model.A, model.B, mutable=True)
    925925        instance = model.create(currdir+'importU.dat')
    926926        self.failUnlessEqual(instance.U.data(), {('I2', 'A1'): 1.4, ('I3', 'A1'): 1.5, ('I3', 'A2'): 2.5, ('I4', 'A1'): 1.6, ('I3', 'A3'): 3.5, ('I1', 'A2'): 2.3, ('I4', 'A3'): 3.6, ('I1', 'A3'): 3.3, ('I4', 'A2'): 2.6, ('I2', 'A3'): 3.4, ('I1', 'A1'): 1.3, ('I2', 'A2'): 2.4})
     
    936936        model=Model()
    937937        model.A = Set(initialize=['A1','A2','A3','A4'])
    938         model.S = Param(model.A)
     938        model.S = Param(model.A, mutable=True)
    939939        instance = model.create(currdir+'importS.dat')
    940940        self.failUnlessEqual(instance.A.data(), set(['A1','A2','A3','A4']))
     
    949949        model=Model()
    950950        model.J = Set(dimen=2)
    951         model.P = Param(model.J)
    952         model.O = Param(model.J)
     951        model.P = Param(model.J, mutable=True)
     952        model.O = Param(model.J, mutable=True)
    953953        instance = model.create(currdir+'importPO.dat')
    954954        self.failUnlessEqual(instance.J.data(), set([('A3', 'B3'), ('A1', 'B1'), ('A2', 'B2')]) )
     
    10341034        md.add(os.path.abspath(example_dir+'Z.tab'), format='param', param='Z')
    10351035        model=Model()
    1036         model.Z = Param(default=99.0)
     1036        model.Z = Param(default=99.0, mutable=True)
    10371037        md.read(model)
    10381038        instance = model.create(md)
     
    10451045        model=Model()
    10461046        model.A = Set(initialize=['A1','A2','A3','A4'])
    1047         model.Y = Param(model.A)
     1047        model.Y = Param(model.A, mutable=True)
    10481048        md.read(model)
    10491049        instance = model.create(md)
     
    10591059        model=Model()
    10601060        model.A = Set(initialize=['A1','A2','A3','A4'])
    1061         model.X = Param(model.A)
    1062         model.W = Param(model.A)
     1061        model.X = Param(model.A, mutable=True)
     1062        model.W = Param(model.A, mutable=True)
    10631063        md.read(model)
    10641064        instance = model.create(md)
     
    10731073        model=Model()
    10741074        model.A = Set(initialize=['A1','A2','A3'])
    1075         model.X = Param(model.A)
    1076         model.W = Param(model.A)
     1075        model.X = Param(model.A, mutable=True)
     1076        model.W = Param(model.A, mutable=True)
    10771077        md.read(model)
    10781078        instance = model.create(md)
     
    10861086        model=Model()
    10871087        model.A = Set()
    1088         model.X = Param(model.A)
    1089         model.W = Param(model.A)
     1088        model.X = Param(model.A, mutable=True)
     1089        model.W = Param(model.A, mutable=True)
    10901090        md.read(model)
    10911091        instance = model.create(md)
     
    11001100        model=Model()
    11011101        model.B = Set()
    1102         model.R = Param(model.B)
    1103         model.S = Param(model.B)
     1102        model.R = Param(model.B, mutable=True)
     1103        model.S = Param(model.B, mutable=True)
    11041104        md.read(model)
    11051105        instance = model.create(md)
     
    11151115        model.B = Set(initialize=['I1','I2','I3','I4'])
    11161116        model.A = Set(initialize=['A1','A2','A3'])
    1117         model.T = Param(model.A, model.B)
     1117        model.T = Param(model.A, model.B, mutable=True)
    11181118        md.read(model)
    11191119        instance = model.create(md)
     
    11271127        model.A = Set(initialize=['I1','I2','I3','I4'])
    11281128        model.B = Set(initialize=['A1','A2','A3'])
    1129         model.U = Param(model.A, model.B)
     1129        model.U = Param(model.A, model.B, mutable=True)
    11301130        md.read(model)
    11311131        instance = model.create(md)
     
    11401140        model=Model()
    11411141        model.A = Set(initialize=['A1','A2','A3','A4'])
    1142         model.S = Param(model.A)
     1142        model.S = Param(model.A, mutable=True)
    11431143        md.read(model)
    11441144        instance = model.create(md)
     
    11551155        model=Model()
    11561156        model.J = Set(dimen=2)
    1157         model.P = Param(model.J)
    1158         model.O = Param(model.J)
     1157        model.P = Param(model.J, mutable=True)
     1158        model.O = Param(model.J, mutable=True)
    11591159        md.read(model)
    11601160        instance = model.create(md)
  • coopr.pyomo/trunk/coopr/pyomo/tests/unit/test_param.py

    r3068 r3309  
    1919class PyomoModel(unittest.TestCase):
    2020
     21    def config_mutability(self):
     22        self.mutable = False
     23
    2124    def setUp(self):
     25        self.config_mutability()
    2226        self.model = Model()
    2327
     
    3640        # Create model instance
    3741        #
    38         self.model.A = Param(initialize=3.3)
     42        self.model.A = Param(initialize=3.3, mutable=self.mutable)
    3943        self.instance = self.model.create()
    4044
     
    8387    def test_setattr_default(self):
    8488        """Check the use of the __setattr__ method"""
    85         self.model.A = Param()
     89        self.model.A = Param(mutable=self.mutable)
    8690        self.model.A.default = 4.3
    8791        self.instance = self.model.create()
     
    103107        """Check the use of getitem"""
    104108        import coopr.pyomo.base.param
    105         self.failUnless(isinstance(self.instance.A[None], coopr.pyomo.base.param._ParamValue))
     109        #print 'xxx',self.instance.components.components()
     110        #print 'XXX',type(self.instance.A),self.instance.A,self.instance.components.A,'YY'
     111        #print 'yyy',self.model.A.mutable
     112        #print 'YYY', type(self.instance.A[None])
     113        if self.instance.A.mutable:
     114            self.failUnless(isinstance(self.instance.A[None], coopr.pyomo.base.param._ParamValue))
    106115        self.failUnlessEqual( self.instance.A[None], 3.3)
    107116
    108117    def test_check_values(self):
    109118        """Check the use of check_values"""
    110         self.instance.A.check_values()
     119        self.instance.components.A.check_values()
     120
     121
     122class MSimpleParam(SimpleParam):
     123
     124    def config_mutability(self):
     125        self.mutable = True
    111126
    112127
     
    122137        #
    123138        self.model.Z = Set(initialize=[1,3])
    124         self.model.A = Param(self.model.Z, initialize={1:1.3})
    125         self.instance = self.model.create()
     139        self.model.A = Param(self.model.Z, initialize={1:1.3}, mutable=self.mutable)
     140        #print 'Z',type(self.model.A)
     141        self.instance = self.model.create()
     142        #print 'Z',type(self.instance.A)
    126143
    127144    def test_simplify(self):
    128145        """Check the parameter can be simplified"""
    129146        try:
    130           tmp = self.instance.A.simplify(self.instance)
     147          tmp = self.instance.components.A.simplify(self.instance)
    131148        except ValueError:
    132149          pass
     
    143160        try:
    144161          tmp = float(self.instance.A)
     162        except TypeError:
     163          pass
    145164        except ValueError:
    146165          pass
     
    149168        try:
    150169          tmp = int(self.instance.A)
     170        except TypeError:
     171          pass
    151172        except ValueError:
    152173          pass
     
    184205        """Check the use of the __setattr__ method"""
    185206        import coopr.pyomo.base.param
    186         self.instance.A.value = 4.3
    187         self.instance.A = 4.3
    188         if self.instance.A.mutable:
     207        self.instance.components.A.value = 4.3
     208        #print type(self.instance.components.A)
     209        self.instance.components.A = 4.3
     210        #print type(self.instance.components.A)
     211        if self.instance.components.A.mutable:
    189212            self.instance.A[1].value = 4.3
    190213            self.failUnlessEqual( type(self.instance.A[1]), coopr.pyomo.base.param._ParamValue)
    191214        self.instance.A[1] = 4.3
    192         if self.instance.A.mutable:
     215        if self.instance.components.A.mutable:
    193216            self.failUnlessEqual( type(self.instance.A[1]), coopr.pyomo.base.param._ParamValue)
    194217        else:
     
    213236    def test_dim(self):
    214237        """Check the use of dim"""
    215         self.failUnlessEqual( self.instance.A.dim(), 1)
     238        self.failUnlessEqual( self.instance.components.A.dim(), 1)
    216239
    217240    def test_len(self):
     
    224247        import coopr.pyomo.base.param
    225248        try:
    226           self.failUnlessEqual( self.instance.A[None], 1.3)
     249            #print 'x',self.instance.A[None]
     250            self.failUnlessEqual( self.instance.A[None], 1.3)
    227251        except KeyError:
    228           pass
     252            pass
    229253        else:
    230254          self.fail("test_getitem")
    231         if self.instance.A.mutable:
     255        if self.instance.components.A.mutable:
    232256            self.failUnlessEqual(type(self.instance.A[1]), coopr.pyomo.base.param._ParamValue)
    233257        else:
     
    242266
    243267
     268class MArrayParam1(ArrayParam1):
     269
     270    def config_mutability(self):
     271        self.mutable = True
     272
     273
    244274class ArrayParam2(ArrayParam1):
    245275
     
    253283        #
    254284        self.model.Z = Set(initialize=[1,3])
    255         self.model.A = Param(self.model.Z, initialize={1:1.3}, default=0.0)
     285        self.model.A = Param(self.model.Z, initialize={1:1.3}, default=0.0, mutable=self.mutable)
    256286        self.instance = self.model.create()
    257287
     
    259289        """Check the use of the __setattr__ method"""
    260290        self.model.Z = Set(initialize=[1,3])
    261         self.model.A = Param(self.model.Z)
     291        self.model.A = Param(self.model.Z, mutable=self.mutable)
    262292        self.model.A.default = 4.3
    263293        self.instance = self.model.create()
    264294        self.failUnlessEqual( self.instance.A[3], 4.3)
     295
     296    def test_keys(self):
     297        """Check the use of keys"""
     298        if self.instance.components.A.mutable:
     299            self.failUnlessEqual( len(self.instance.A.keys()), 2)
     300        else:
     301            self.failUnlessEqual( len(self.instance.components.A.keys()), 2)
     302            self.failUnlessEqual( len(self.instance.A.keys()), 1)
     303
     304    def test_len(self):
     305        """Check the use of len"""
     306        if self.instance.components.A.mutable:
     307            self.failUnlessEqual( len(self.instance.A), 2)
     308        else:
     309            self.failUnlessEqual( len(self.instance.components.A), 2)
     310            self.failUnlessEqual( len(self.instance.A), 1)
     311
     312    def test_getitem(self):
     313        """Check the use of getitem"""
     314        try:
     315            self.failUnlessEqual( self.instance.A[None], 0.0)
     316        except KeyError:
     317            pass
     318        else:
     319            if self.instance.components.A.mutable:
     320                self.fail("test_getitem")
     321        self.failUnlessEqual( self.instance.A[1], 1.3)
     322        self.failUnlessEqual( self.instance.A[3], 0)
     323
     324
     325class MArrayParam2(ArrayParam2):
     326
     327    def config_mutability(self):
     328        self.mutable = True
     329
     330
     331class ArrayParam3(ArrayParam2):
     332
     333    def setUp(self):
     334        #
     335        # Create Model
     336        #
     337        PyomoModel.setUp(self)
     338        #
     339        # Create model instance
     340        #
     341        self.model.Z = Set(initialize=[1,3])
     342        self.model.A = Param(self.model.Z, initialize={1:1.3},default=99.0, mutable=self.mutable)
     343        self.instance = self.model.create()
     344
     345    def test_len(self):
     346        """Check the use of len"""
     347        if self.instance.components.A.mutable:
     348            self.failUnlessEqual( len(self.instance.A), 2)
     349        else:
     350            self.failUnlessEqual( len(self.instance.A), 1)
     351            self.failUnlessEqual( len(self.instance.components.A), 2)
     352
     353    def test_getitem(self):
     354        """Check the use of getitem"""
     355        try:
     356            self.failUnlessEqual( self.instance.A[None], 0.0)
     357        except AssertionError:
     358            if self.instance.components.A.mutable:
     359                self.fail("test_getitem")
     360        except KeyError:
     361            pass
     362        else:
     363            self.fail("test_getitem")
     364        self.failUnlessEqual( self.instance.A[1], 1.3)
     365        self.failUnlessEqual( self.instance.A[3], 99.0)
     366
     367
     368class MArrayParam3(ArrayParam3):
     369
     370    def config_mutability(self):
     371        self.mutable = True
     372
     373
     374class ArrayParam4(ArrayParam3):
     375
     376    def setUp(self):
     377        #
     378        # Create Model
     379        #
     380        PyomoModel.setUp(self)
     381        #
     382        # Create model instance
     383        #
     384        self.model.Z = Set(initialize=[1,3])
     385        self.model.A = Param(self.model.Z, initialize=1.3, mutable=self.mutable)
     386        self.instance = self.model.create()
    265387
    266388    def test_keys(self):
     
    275397        """Check the use of getitem"""
    276398        try:
    277           self.failUnlessEqual( self.instance.A[None], 0.0)
     399            self.failUnlessEqual( self.instance.A[None], 0.0)
    278400        except KeyError:
    279           pass
    280         else:
    281           self.fail("test_getitem")
    282         self.failUnlessEqual( self.instance.A[1], 1.3)
    283         self.failUnlessEqual( self.instance.A[3], 0)
    284 
    285 
    286 class ArrayParam3(ArrayParam2):
    287 
    288     def setUp(self):
    289         #
    290         # Create Model
    291         #
    292         PyomoModel.setUp(self)
    293         #
    294         # Create model instance
    295         #
    296         self.model.Z = Set(initialize=[1,3])
    297         self.model.A = Param(self.model.Z, initialize={1:1.3},default=99.0)
    298         self.instance = self.model.create()
    299 
    300     def test_len(self):
    301         """Check the use of len"""
    302         self.failUnlessEqual( len(self.instance.A), 2)
    303 
    304     def test_getitem(self):
    305         """Check the use of getitem"""
    306         try:
    307           self.failUnlessEqual( self.instance.A[None], 0.0)
    308         except AssertionError:
    309           print self.instance.A._paramval
    310         except KeyError:
    311           pass
    312         else:
    313           self.fail("test_getitem")
    314         self.failUnlessEqual( self.instance.A[1], 1.3)
    315         self.failUnlessEqual( self.instance.A[3], 99.0)
    316 
    317 
    318 class ArrayParam4(ArrayParam3):
    319 
    320     def setUp(self):
    321         #
    322         # Create Model
    323         #
    324         PyomoModel.setUp(self)
    325         #
    326         # Create model instance
    327         #
    328         self.model.Z = Set(initialize=[1,3])
    329         self.model.A = Param(self.model.Z, initialize=1.3)
    330         self.instance = self.model.create()
    331 
    332     def test_len(self):
    333         """Check the use of len"""
    334         self.failUnlessEqual( len(self.instance.A), 2)
    335 
    336     def test_getitem(self):
    337         """Check the use of getitem"""
    338         try:
    339           self.failUnlessEqual( self.instance.A[None], 0.0)
    340         except KeyError:
    341           pass
    342         else:
    343           self.fail("test_getitem")
     401            pass
     402        else:
     403            self.fail("test_getitem")
    344404        self.failUnlessEqual( self.instance.A[1], 1.3)
    345405        self.failUnlessEqual( self.instance.A[3], 1.3)
     406
     407
     408class MArrayParam4(ArrayParam4):
     409
     410    def config_mutability(self):
     411        self.mutable = True
    346412
    347413
     
    359425        def A_init(i,model):
    360426          return 1.3
    361         self.model.A = Param(self.model.Z, initialize=A_init)
    362         self.instance = self.model.create()
     427        self.model.A = Param(self.model.Z, initialize=A_init, mutable=self.mutable)
     428        self.instance = self.model.create()
     429
     430
     431class MArrayParam5(ArrayParam5):
     432
     433    def config_mutability(self):
     434        self.mutable = True
    363435
    364436
     
    375447                return 2+i
    376448            return -(2+i)
    377         self.model.B = Param(B_index, [True,False], initialize=B_init)
     449        self.model.B = Param(B_index, [True,False], initialize=B_init, mutable=self.mutable)
    378450        self.instance = self.model.create()
    379451        #self.instance.pprint()
     
    393465                return 2+i
    394466            return -(2+i)
    395         self.model.B = Param(B_index, [True,False], initialize=B_init)
     467        self.model.B = Param(B_index, [True,False], initialize=B_init, mutable=self.mutable)
    396468        self.instance = self.model.create()
    397469        #self.instance.pprint()
     
    410482                return 2+i
    411483            return -(2+i)
    412         self.model.B = Param(B_index, [True,False], initialize=B_init)
     484        self.model.B = Param(B_index, [True,False], initialize=B_init, mutable=self.mutable)
    413485        try:
    414486            self.instance = self.model.create()
     
    426498                return 2+i
    427499            return -(2+i)
    428         self.model.B = Param(B_index, [True,False], initialize=B_init)
     500        self.model.B = Param(B_index, [True,False], initialize=B_init, mutable=self.mutable)
    429501        try:
    430502            self.instance = self.model.create()
     
    438510        model.B = Set(dimen=3, initialize=[(1,1,1),(2,2,2),(3,3,3)])
    439511        model.C = Set(dimen=1, initialize=[9,8,7,6,5])
    440         model.x = Param(model.A, model.B, model.C, initialize=-1)
    441         model.y = Param(model.B, initialize=(1,1))
     512        model.x = Param(model.A, model.B, model.C, initialize=-1, mutable=self.mutable)
     513        model.y = Param(model.B, initialize=(1,1), mutable=self.mutable)
    442514        instance=model.create()
    443         self.failUnlessEqual( instance.x.dim(), 6)
    444         self.failUnlessEqual( instance.y.dim(), 3)
     515        self.failUnlessEqual( instance.components.x.dim(), 6)
     516        self.failUnlessEqual( instance.components.y.dim(), 3)
     517
     518
     519class MArrayParam6(ArrayParam6):
     520
     521    def config_mutability(self):
     522        self.mutable = True
    445523
    446524
     
    463541        print >>OUTPUT, "end;"
    464542        OUTPUT.close()
    465         self.model.A=Param()
     543        self.model.A=Param(mutable=self.mutable)
    466544        self.instance = self.model.create("param.dat")
    467545        self.failUnlessEqual( self.instance.A, 3.3 )
     
    478556        OUTPUT.close()
    479557        self.model.Z=Set()
    480         self.model.A=Param(self.model.Z)
     558        self.model.A=Param(self.model.Z, mutable=self.mutable)
    481559        self.instance = self.model.create("param.dat")
    482560        self.failUnlessEqual( len(self.instance.A), 3 )
     
    493571        OUTPUT.close()
    494572        self.model.Z=Set()
    495         self.model.A=Param(self.model.Z)
    496         self.model.B=Param(self.model.Z)
     573        self.model.A=Param(self.model.Z, mutable=self.mutable)
     574        self.model.B=Param(self.model.Z, mutable=self.mutable)
    497575        self.instance = self.model.create("param.dat")
    498576        self.failUnlessEqual( len(self.instance.A), 3 )
     
    514592        self.model.Z=Set()
    515593        self.model.Y=Set()
    516         self.model.A=Param(self.model.Y,self.model.Z)
     594        self.model.A=Param(self.model.Y,self.model.Z, mutable=self.mutable)
    517595        self.instance = self.model.create("param.dat")
    518596        self.failUnlessEqual( len(self.instance.Y), 3 )
     
    535613        self.model.Z=Set()
    536614        self.model.Y=Set()
    537         self.model.A=Param(self.model.Z,self.model.Y)
     615        self.model.A=Param(self.model.Z,self.model.Y, mutable=self.mutable)
    538616        self.instance = self.model.create("param.dat")
    539617        self.failUnlessEqual( len(self.instance.Y), 3 )
     
    553631        OUTPUT.close()
    554632        self.model.Z=Set()
    555         self.model.A=Param(self.model.Z)
    556         self.instance = self.model.create("param.dat")
    557         self.failUnlessEqual( len(self.instance.A), 3 )
     633        self.model.A=Param(self.model.Z, mutable=self.mutable)
     634        self.instance = self.model.create("param.dat")
     635        self.failUnlessEqual( len(self.instance.components.A), 3 )
    558636        self.failUnlessEqual( self.instance.A[3], 0.0 )
    559637
     
    565643        print >>OUTPUT, "end;"
    566644        OUTPUT.close()
    567         self.model.A=Param(within=Boolean)
    568         self.model.B=Param(within=Boolean)
     645        self.model.A=Param(within=Boolean, mutable=self.mutable)
     646        self.model.B=Param(within=Boolean, mutable=self.mutable)
    569647        self.instance = self.model.create("param.dat")
    570648        self.failUnlessEqual( self.instance.A.value, True )
     
    581659        OUTPUT.close()
    582660        self.model.A=Set()
    583         self.model.B=Param(self.model.A)
     661        self.model.B=Param(self.model.A, mutable=self.mutable)
    584662        self.instance = self.model.create("param.dat")
    585663        self.failUnlessEqual( self.instance.A.data(), set(['A','B','C']) )
     
    606684        OUTPUT.close()
    607685        self.model.A=Set()
    608         self.model.B=Param(self.model.A)
     686        self.model.B=Param(self.model.A, mutable=self.mutable)
    609687        self.instance = self.model.create("param.dat")
    610688        self.failUnlessEqual( self.instance.B['A'], 0.1)
     
    637715        self.model.A1=Set()
    638716        self.model.A2=Set()
    639         self.model.B=Param(self.model.A1,self.model.A2,self.model.A1)
     717        self.model.B=Param(self.model.A1,self.model.A2,self.model.A1, mutable=self.mutable)
    640718        self.instance = self.model.create("param.dat")
    641719        self.failUnlessEqual( set(self.instance.B.keys()), set([('e', 2, 'f'), ('c', 2, 'd'), ('a', 2, 'b'), ('i', 4, 'j'), ('g', 4, 'h'), ('k', 6, 'l')]))
    642720
    643721
     722class MTestIO(TestIO):
     723
     724    def config_mutability(self):
     725        self.mutable = True
     726
     727
    644728class TestParamError(PyomoModel):
    645729
    646730    def test_value(self):
    647         p = Param()
     731        p = Param(name='name', mutable=self.mutable)
    648732        try:
    649733            value(p)
     
    653737        self.failUnlessEqual(p.value,None)
    654738
     739
     740class MTestParamError(TestParamError):
     741
     742    def config_mutability(self):
     743        self.mutable = True
     744
     745
     746
    655747if __name__ == "__main__":
    656748   unittest.main()
  • coopr.pyomo/trunk/coopr/pyomo/transform/relax_integrality.py

    r2201 r3309  
    4040        # with logic about generating a specific relaxation.  That's probably a worse alternative.
    4141        #
    42         comp = M.components(Var)
     42        comp = M.components[Var]
    4343        for var in comp.values():
    4444            if isinstance(var.domain, BooleanSet):
Note: See TracChangeset for help on using the changeset viewer.