Changeset 1414 for trunk


Ignore:
Timestamp:
Jul 14, 2009 10:25:27 PM (11 years ago)
Author:
wehart
Message:

A major rework of the Pyomo core. This change eliminates the use
of getattr and setattr methods. Removing these led to a 1/3 reduction
in runtime for some largish p-median test problems.

While revising the tests, I noted that this change has had the following
impact:

. No validation that values assigned to parameters or variables are valid

. Cannot set all suffixes simultaneously

. Cannot set lower/upper bounds simultaneously

. No validation that suffixes are valid when their value is set

I think that these are important usability issues. The use of the get/set
attribute methods was intended to protect users from simple mistakes. For
example, a user can now type:

model.x.fixed = 1

which may or may not work as intended. Logically, fixed should be
a boolean value.

John Siirola suggested that I enable a 'protected' mode, which
reintroduces these mechanisms when a global variable is set. I'll put
that on the TODO list...

Also, this effort led to a rework of the Param and Var classes. These
are now segregated between Element and Array classes (similar to the
Set class). This led to further optimizations of the logic in these
classes. Unfortunately, it also led to the use of the _VarBase and
_ParamBase in the PyomoModel? to index components. I'll try to revisit
that sometime soon...

Location:
trunk
Files:
1 added
91 edited

Legend:

Unmodified
Added
Removed
  • trunk

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/core

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/core/base

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/core/colin

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/core/parallel

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/core/reader

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/core/solver

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/opt

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/plugins

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/plugins/converter

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/plugins/mip

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/plugins/smanager

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/pyomo

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/pyomo/base

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/pyomo/base/PyomoModel.py

    r1338 r1414  
    2727
    2828from sets import Set, _ProductSet, _SetContainer, _BaseSet
    29 from set_types import RangeSet
    30 from var import Var
     29from rangeset import RangeSet
     30from var import _VarBase
    3131from constraint import Objective, Constraint
    32 from param import Param
     32from param import _ParamBase
    3333
    3434
     
    9999
    100100    def _construct_temporary_set(self, obj, name):
    101         ##print "HERE x", obj, name
    102         #self.tmpctr += 1
    103101        if type(obj) is tuple:
    104102           if len(obj) == 1:                #pragma:nocover
    105103                  raise Exception, "Unexpected temporary set construction"
    106                   #setattr(self,name,obj[0])
    107                   #return obj[0]
    108104           else:
    109105                  tobj=_ProductSet(*obj)
     
    112108                  return tobj
    113109        if isinstance(obj,_BaseSet):
    114            #print "HERE y",name,obj
    115110           setattr(self,name,obj)
    116111           return obj
     
    134129
    135130    def _setattr_exec(self,name,val,item):
    136                     self._clear_attribute(name)
    137                     val.name=name
    138                     self._add_temporary_set(val)
    139                     val.model=self
    140                     self._component[item][name]=val
    141                     self._declarations.append(val)
    142                     self.__dict__[name]=val
     131        self._clear_attribute(name)
     132        val.name=name
     133        self._add_temporary_set(val)
     134        val.model=self
     135        self._component[item][name]=val
     136        self._declarations.append(val)
     137        self.__dict__[name]=val
    143138
    144139    def __setattr__(self,name,val):
     
    161156                if isinstance(val,item):
    162157                    self._setattr_exec(name,val, item)
    163 
    164         if name in self.__dict__.keys() and isinstance(self.__dict__[name],NumericValue):
    165            tmpval = value(val)
    166            if tmpval is None:
    167                   raise ValueError, "Bad numeric value"
    168            self.__dict__[name].value = tmpval
    169         else:
    170            self.__dict__[name]=val
     158                    return
     159
     160        #if name in self.__dict__.keys() and isinstance(self.__dict__[name],NumericValue):
     161            #tmpval = value(val)
     162            #if tmpval is None:
     163                #raise ValueError, "Bad numeric value"
     164            #self.__dict__[name].value = tmpval
     165        #else:
     166            #self.__dict__[name]=val
     167
     168        #
     169        # Try to set the value.  This may fail if the attribute does not already
     170        # exist in this model, if the set_value function is not defined, or if
     171        # a bad value is provided.  In the latter case, a ValueError will be thrown, which
     172        # we raise.  Otherwise, this is an object that we need to set directly.
     173        #
     174        #print "HERE X",name
     175        try:
     176            #print "HERE",self.__dict__[name].name,type(self.__dict__[name]),type(val)
     177            self.__dict__[name].set_value(val)
     178        except ValueError, e:
     179            raise
     180        except Exception, e:
     181            self.__dict__[name]=val
    171182
    172183
     
    325336        # expected by a user.
    326337        #
    327         items = [_BaseSet, RangeSet, Param, Var, Objective, Constraint]
     338        items = [_BaseSet, RangeSet, _ParamBase, _VarBase, Objective, Constraint]
    328339        for item in pyutilib.plugin.ExtensionPoint(IModelComponent):
    329340            if not item in items:
     
    334345            keys = self._component[item].keys()
    335346            keys.sort()
     347            #
     348            # TODO: rework the component registration so that these print statements are not hard-coded.
     349            #
    336350            if item.__name__ == "_BaseSet":
    337351                print >>ostream, len(keys), "Set Declarations"
     352            elif item.__name__ == "_ParamBase":
     353                print >>ostream, len(keys), "Param Declarations"
     354            elif item.__name__ == "_VarBase":
     355                print >>ostream, len(keys), "Var Declarations"
    338356            else:
    339357                print >>ostream, len(keys), item.__name__+" Declarations"
     
    364382        print >>ostream, ""
    365383        print >>ostream, "  Variables:"
    366         if len(self._component[Var]) == 0:
     384        if len(self._component[_VarBase]) == 0:
    367385           print >>ostream, "    None"
    368386        else:
    369            for ndx in self._component[Var]:
    370              self._component[Var][ndx].display(prefix="    ",ostream=ostream)
     387           for ndx in self._component[_VarBase]:
     388             self._component[_VarBase][ndx].display(prefix="    ",ostream=ostream)
    371389        print >>ostream, ""
    372390        print >>ostream, "  Objectives:"
  • trunk/coopr/pyomo/base/__init__.py

    r1263 r1414  
    2828#
    2929from util import *
     30from rangeset import *
  • trunk/coopr/pyomo/base/constraint.py

    r1411 r1414  
    2626
    2727    def __init__(self, expr=None, name=None):
    28         NumericValue.__init__(self,name,Reals)
    29         self._standard_attr.update(["id","expr","label"])
     28        NumericValue.__init__(self,name=name,domain=Reals)
    3029        self.expr = expr
    3130        self.label = None
     
    3635            return None
    3736        return self.expr()
    38 
    39     #def __getattr__(self,name):
    40     #    return NumericValue.__getattr__(self,name)
    4137
    4238
     
    7672          else:
    7773             raise ValueError, "Objective constructor: unknown keyword - "+key
    78         NumericValue.__init__(self,tmpname)
     74        NumericValue.__init__(self,name=tmpname)
    7975        if None in self._data:
    8076            self._data[None].name = tmpname
    81         self._standard_attr.add("sense")
    82         self._standard_attr.add("rule")
    8377        self.sense = tmpsense
    8478        self.rule = tmprule
     
    118112        return self._index.__iter__()
    119113
    120     def __setattr__(self,name,val):
    121         NumericValue.__setattr__(self,name,val)
    122 
    123     def __getattr__(self,name):
    124         return NumericValue.__getattr__(self,name)
    125 
    126114    def _apply_rule(self,arg,ndx):
    127115        tmp = self.rule(*arg)
     
    129117           return None
    130118        if type(tmp) in [bool,int,long,float]:
    131            return NumericConstant(tmp)
     119           return NumericConstant(value=tmp)
    132120        return tmp
    133121
     
    192180
    193181    def __init__(self, name=None):
    194         NumericValue.__init__(self,name,Reals)
    195         self._standard_attr.update(["id", "lower", "body", "upper", "label"])
     182        NumericValue.__init__(self,name=name,domain=Reals)
    196183        self._equality = False
    197         self.__dict__['_attr_lower'] = None
    198         self.__dict__['_attr_body'] = None
    199         self.__dict__['_attr_upper'] = None
    200         self.__dict__['_attr_name'] = name
    201         self.__dict__['_attr_label'] = None
    202         self.__dict__['_attr_id'] = -1
    203 
    204     #def __getattr__(self,name):
    205         #return NumericValue.__getattr__(self,name)
     184        self.lower = None
     185        self.body = None
     186        self.upper = None
     187        self.label = None
     188        self.id = None
    206189
    207190    def __call__(self, exception=True):
     
    242225          else:
    243226             raise ValueError, "Constraint constructor: unknown keyword - "+key
    244         NumericValue.__init__(self,tmpname)
     227        NumericValue.__init__(self,name=tmpname)
    245228        if None in self._data:
    246229            self._data[None].name=tmpname
    247         self._standard_attr.update(["upper","lower","rule"])
    248230        self.rule = tmprule
    249231
     
    281263    def __iter__(self):
    282264        return self._index.__iter__()
    283 
    284     #def __setattr__(self,name,val):
    285         #NumericValue.__setattr__(self,name,val)
    286 
    287     #def __getattr__(self,name):
    288         #return NumericValue.__getattr__(self,name)
    289265
    290266    def _construct(self, model, data):
     
    466442        if type(tpl[0]) in [bool,int,long,float]:
    467443            if pyutilib.is_finite(tpl[0]):
    468                 tpl[0] = NumericConstant(float(tpl[0]))
     444                tpl[0] = NumericConstant(value=float(tpl[0]))
    469445            else:
    470446                tpl[0] = None
     
    475451        if type(tpl[2]) in [bool,int,long,float]:
    476452            if pyutilib.is_finite(tpl[2]):
    477                 tpl[2] = NumericConstant(float(tpl[2]))
     453                tpl[2] = NumericConstant(value=float(tpl[2]))
    478454            else:
    479455                tpl[2] = None
  • trunk/coopr/pyomo/base/expr.py

    r1408 r1414  
    1616from pyutilib.plugin import *
    1717from numvalue import *
    18 from param import Param
    19 from var import Var
     18from param import _ParamBase, _ParamElement
     19from var import _VarBase
    2020
    2121
     
    2525    def __init__(self, nargs=-1, name="UNKNOWN", operation=None, args=None, tuple_op=False):
    2626        """Construct an expression with an operation and a set of arguments"""
    27         NumericValue.__init__(self)
    28         self.__dict__['_args']=args
    29         self.__dict__['_nargs']=nargs
    30         self.__dict__['_operation']=operation
    31         self.__dict__['_attr_name'] = name
    32         self.__dict__['_tuple_op'] = tuple_op
     27        NumericValue.__init__(self, name=name)
     28        self._args=args
     29        self._nargs=nargs
     30        self._operation=operation
     31        self._tuple_op=tuple_op
    3332        self.verify()
    3433
     
    7170            if type(arg) is float:      #pragma:nocover
    7271                raise ValueError, "Argument for expression "+self.name+" is a float!"
    73             if (isinstance(arg,Param) or isinstance(arg,Var)) and arg.dim() > 0:
     72            if (isinstance(arg,_ParamBase) or isinstance(arg,_VarBase)) and arg.dim() > 0:
    7473                raise ValueError, "Argument for expression "+self.name+" is an n-ary numeric value: "+arg.name
    7574
     
    8180          if isinstance(self._args[i],Expression):
    8281             self._args[i] = self._args[i].simplify(model)
    83           elif isinstance(self._args[i],Param):
    84              self._args[i] = NumericConstant(self._args[i][None].value)
    85           #elif isinstance(self._args[i],_ParamValue):
    86              #self._args[i] = NumericConstant(self._args[i].value)
     82          elif isinstance(self._args[i],_ParamElement):
     83             self._args[i] = self._args[i].simplify(model)
    8784        return self
    8885
     
    209206             newargs.append( arg )
    210207        if val != 0.0:
    211            newargs.append( NumericConstant(val) )
     208           newargs.append( NumericConstant(value=val) )
    212209        #
    213210        # Return simplified expression
     
    219216           return newargs[0]
    220217        else:
    221            return NumericConstant(0.0)
     218           return NumericConstant(value=0.0)
    222219
    223220    def add(self,expr):
     
    270267             newargs.append( arg )
    271268        if val == 0.0:
    272            return NumericConstant(0.0)
     269           return NumericConstant(value=0.0)
    273270        if val != 1.0:
    274271           #
     
    280277                tmp._args[i] = val*tmp._args[i]
    281278                if type(tmp._args[i]) in [float,long,int]:
    282                    tmp._args[i] = NumericConstant(tmp._args[i])
     279                   tmp._args[i] = NumericConstant(value=tmp._args[i])
    283280              newargs[sumi] = tmp.simplify(model)
    284281           else:
    285               newargs.append( NumericConstant(val) )
     282              newargs.append( NumericConstant(value=val) )
    286283       
    287284        #
     
    294291           return newargs[0]
    295292        else:
    296            return NumericConstant(1.0)
     293           return NumericConstant(value=1.0)
    297294
    298295
  • trunk/coopr/pyomo/base/numvalue.py

    r1406 r1414  
    99#  _________________________________________________________________________
    1010
    11 __all__ = ['value', 'as_numeric', 'NumericValue', 'NumericConstant']
     11__all__ = ['value', 'NumericValue', 'as_numeric', 'NumericConstant']
    1212
    1313import plugin
    1414import pyutilib.plugin
    1515import sys
     16from set_types import Reals
    1617
    1718
     
    4344       return obj.as_numeric()
    4445    if type(obj) in [bool,int,long,float]:
    45        return NumericConstant(obj)
     46       return NumericConstant(value=obj)
    4647    raise ValueError, "This object is not a numeric value: "+str(obj)
    4748
     
    5051    """An object that contains a numeric value"""
    5152
    52     def __init__(self, name="unknown", domain=None):
    53         self.__dict__['_standard_attr'] = set(["name","domain","model"])
    54         self.__dict__['_attr_model']=None
    55         self.__dict__['_attr_domain']=domain
    56         self.__dict__['_attr_name']=name
    57         self.__dict__['_attr_value']=None
     53    def __init__(self, **kwds):
     54        if 'name' in kwds:
     55            self.name=kwds['name']
     56        else:
     57            self.name="unknown"
     58        if 'domain' in kwds:
     59            self.domain=kwds['domain']
     60        elif 'within' in kwds:
     61            self.domain=kwds['within']
     62        else:
     63            self.domain=None
     64        if 'value' in kwds:
     65            if pyutilib.is_nan(kwds['value']):
     66                self.value=pyutilib.nan
     67            else:
     68                self.set_value(kwds['value'])
     69        else:
     70            self.value=pyutilib.nan
     71        self.model=None
     72        #print "NUMVAL",self.name,self.domain,self.value
    5873
    5974    def as_numeric(self):
     
    6883    def reset(self):            #pragma:nocover
    6984        pass                    #pragma:nocover
     85
     86    def set_value(self, val):
     87        if self._valid_value(val):
     88            self.value=val
    7089
    7190    def __call__(self, exception=True):
     
    85104
    86105    def _valid_value(self,value,use_exception=True):
     106        #print "HERE X", self.domain is None
    87107        ans = self.domain is None or value in self.domain
    88108        if not ans and use_exception:
     
    90110        return ans
    91111
    92     def __getattr__(self,name):
     112    def X__getattr__(self,name):
    93113        #print "GETATTR",name
    94114        #d = self.__dict__
     
    103123        raise AttributeError, "Unknown attribute `"+str(name)+"' for object with type "+str(type(self))
    104124
    105     def __setattr__(self,name,val):
     125    def X__setattr__(self,name,val):
    106126        ##print "SETATTR",name,val
    107127        if name == "__class__":
     
    265285    """An object that contains a constant numeric value"""
    266286
    267     def __init__(self, val, name="unknown", domain=None):
    268         if not type(val) in [float,long,int,bool]:
    269            raise TypeError, "Cannot create a NumericConstant with value "+str(val)
    270         NumericValue.__init__(self,name=str(val),domain=domain)
    271         self._standard_attr.add("value")
    272         self.value=val
     287    def __init__(self, **kwds):
     288        if not 'domain' in kwds:
     289            kwds['domain'] = Reals
     290        NumericValue.__init__(self,**kwds)
    273291
    274292    def __call__(self, exception=True):
  • trunk/coopr/pyomo/base/param.py

    r1401 r1414  
    99#  _________________________________________________________________________
    1010
    11 __all__ = ['Param']
     11__all__ = ['_ParamBase', 'Param']
    1212
    1313from coopr.pyomo.base.numvalue import *
     
    1818import types
    1919from sets import _BaseSet
    20 
     20import pyutilib
    2121
    2222class _ParamValue(NumericValue):
     
    2424
    2525    """Constructor"""
    26     def __init__(self,name,domain,value):
    27         NumericValue.__init__(self,name,domain)
    28         self._standard_attr.add("value")
    29         if not value is None:
    30             self.value=value
    31 
    32 
    33 class Param(NumericValue):
     26    def __init__(self, **kwds):
     27        try:
     28            NumericValue.__init__(self, **kwds)
     29        except ValueError, e:
     30            raise ValueError, "Problem constructing parameter "+self.name+" : "+str(e)
     31   
     32
     33
     34class _ParamBase(object):
    3435    """A parameter value, which may be defined over a index"""
    3536
     
    4950                          existing model data
    5051    """
    51     def __init__(self, *args, **kwd):
     52    def __init__(self, **kwd):
    5253        tmpname="unknown"
    5354        tmpdomain=Any
     55        self._ndim=0
    5456        self._paramval={}
    5557        self._initialize={}
    5658        self._validate=None
    5759        self._model=None
    58         tmpval=None
     60        defaultval=pyutilib.nan
    5961        for key in kwd.keys():
    60           if key == "name":
    61              tmpname=kwd[key]
     62          if key == "rule":
     63             self.__dict__["_initialize"] = kwd[key]
     64          elif key is "name":
     65                tmpname = kwd[key]
    6266          elif key == "within":
    63              tmpdomain=kwd[key]
    64           elif key == "rule":
    65              self.__dict__["_initialize"] = kwd[key]
     67                tmpdomain = kwd[key]
    6668          elif key in ("validate","initialize"):
    6769             self.__dict__["_"+key] = kwd[key]
    6870          elif key == "default":
    69              tmpval = kwd[key]
     71             defaultval = kwd[key]
    7072          else:
    7173             raise ValueError, "Param constructor: unknown keyword - "+key
    72         NumericValue.__init__(self,tmpname,tmpdomain)
    73         self._default = _ParamValue(self.name,self.domain,value(tmpval))
    74         self._standard_attr.add("value")
    75         self._standard_attr.add("default")
     74        self.name = tmpname
     75        self.domain = tmpdomain
     76        self._default = _ParamValue(name=tmpname,domain=tmpdomain,value=value(defaultval))
    7677        self._index_set=None
    77         if args == ():
    78            self._index=[None]
    79            self._ndim=0
    80         else:
    81            self._ndim=0
    82            for arg in args:
    83              if not isinstance(arg,_BaseSet):
    84                 raise ValueError, "Cannot index parameter `"+self.name+"' with object of type "+str(type(arg))
    85              self._ndim += arg.dimen
    86            if len(args) == 1:
    87               self._index=args[0]
    88            else:
    89               self._index=None
    90               self._index_set=args
    91 
    92     def simplify(self, model):
    93         if None not in self._index:
    94            raise ValueError, "Cannot simplify array parameter "+self.name
    95         return NumericConstant(self._paramval[None].value)
    96 
    97     def __float__(self):
    98         if None not in self._index:
    99            raise TypeError, "Cannot access the value of array parameter "+self.name
    100         #if None not in self._paramval:
    101         #   raise ValueError, "Cannot access the value of parameter "+self.name+", which is uninitialized"
    102         return float(self._paramval[None])
    103 
    104     def __int__(self):
    105         if None not in self._index:
    106            raise TypeError, "Cannot access the value of array parameter "+self.name
    107         #if None not in self._paramval:
    108         #   raise ValueError, "Cannot access the value of parameter "+self.name+", which is uninitialized"
    109         return int(self._paramval[None])
    110 
    111     def __getattr__(self,name):
    112         if name == "value":
    113            if None not in self._index:
    114               raise TypeError, "Cannot access 'value' attribute of array parameter "+self.name
    115            if None not in self._paramval:
    116               raise AttributeError, "Attribute 'value' invalid for uninitialized parameter %r" % self.name
    117            return self._paramval[None].value
    118         return NumericValue.__getattr__(self,name)
    119 
    120     def __setattr__(self,name,val):
    121         ##print "HERE-PARAM",name,val
    122         if name == "value":
    123            if len(self._paramval) == 0:
    124               raise AttributeError, "Cannot set the 'value' attribute of uninitialized parameter '"+self.name+"'"
    125            tmpval = value(val)
    126            if tmpval is None:
    127               raise ValueError, "Value "+str(val)+" is not valid for parameter "+self.name
    128            for key in self._paramval:
    129               self._paramval[key].value = tmpval
    130               self._valid_value(tmpval,key,True)
    131            return
    132         #
    133         elif name == "default":
    134            tmpval = value(val)
    135            if tmpval is None:
    136               raise ValueError, "Default value "+str(val)+" is not valid for parameter "+self.name
    137            self._default.value = tmpval
    138            self._valid_value(tmpval,None,True)
    139            return
    140         #
    141         NumericValue.__setattr__(self,name,val)
    14278
    14379    def pprint(self, ostream=None):
     
    15591             val = self._paramval[key].value
    15692             print >>ostream, "\t"+str(key)+" : "+str(val)
    157         if self._default.value is not None:
    158            print >>ostream, "\tdefault:"+str(self._default.value)
     93        if self._default.value is not None and not pyutilib.is_nan(self._default.value):
     94           print >>ostream, "\tdefault: "+str(self._default.value)
    15995
    16096    def keys(self):
     
    171107
    172108    def __len__(self):
    173         if self._default.value is not None:
     109        if not pyutilib.is_nan(self._default.value):
    174110           return len(self._index)
    175111        return len(self._paramval)
     
    182118        if ndx in self._paramval:
    183119           return self._paramval[ndx]
    184         if ndx in self._index and self._default.value is not None:
     120        if ndx in self._index and self._default.value is not None and not pyutilib.is_nan(self._default.value):
    185121           return self._default.value
    186122        if ndx in self._index:
     
    192128           if pyomo.debug("verbose"):       #pragma:nocover
    193129              errmsg = errmsg+" : Valid indices="+str(list(self._index.value))
    194         #print self.name,ndx,self._index, self._index.name, self._index.value
    195         #self._index.pprint()
    196         ##
    197         ## TODO: encapsulate getitem errors in debugging flag
    198         ##
    199         #print "\nAbout Param.__getitem__ trouble...\n"
    200         #for i in p:
    201                 #print "["+str(i)+"] =", p[i]._value
    202                 #if i == ndx:
    203                         #print "\nSaw the missing index!\n"
    204130        raise KeyError, "Unknown index " + str(ndx) + " in parameter " + self.name
    205         #+"\n  Indices: "+str(self._index)+"\n  Param Values: "+str(self._paramval)
    206131
    207132    def __setitem__(self,ndx,val):
     
    210135        if ndx not in self._index:
    211136           raise KeyError, "Cannot set the value of array parameter "+self.name+" with invalid index "+str(ndx)
     137        if not self._valid_indexed_value(val,ndx,False):
     138            raise ValueError, "Cannot set parameter "+self.name+" with invalid value: index=" + str(ndx) + " value=" + str(val)
    212139        if ndx in self._paramval:
    213140           self._paramval[ndx].value = val
    214141        else:
    215            self._paramval[ndx]= _ParamValue(self.name+"["+str(ndx)+"]",self.domain,val)           
    216         if not self._valid_value(self._paramval[ndx].value,ndx,False):
    217             raise ValueError, "Cannot set parameter "+self.name+" with invalid value: index=" + str(ndx) + " value=" + str(val)
     142           self._paramval[ndx]= _ParamValue(name=self.name+"["+str(ndx)+"]",domain=self.domain,value=val)           
    218143
    219144    def _construct(self, model, data):
    220145        """ Apply the rule to construct values in this set """
     146       ## print "HERE _construct",data,self._initialize
    221147        self._model=model
    222148        if pyomo.debug("verbose"):      #pragma:nocover
     
    227153        _name=self.name
    228154        _domain=self.domain
     155        #
     156        # Update the default value, if it's available
     157        #
     158        try:
     159            self._default.value = self.default
     160        except:
     161            pass
    229162        #
    230163        # Construct using the initial data or the data loaded from an
     
    236169        #
    237170        if data is not None or type(self._initialize) is not types.FunctionType:
     171           #print "HERE Z",type(self._index),data,self._initialize
    238172           #
    239173           # Singleton parameter
     
    241175           if type(self._index) is list:
    242176              if data is not None and None in data.keys():
    243                  self._paramval[None] = _ParamValue(_name,_domain,data[None])
     177                    self.value=data[None]
     178                    #self._paramval[None] = _ParamValue(name=_name,domain=_domain,value=data[None])
    244179              elif type(self._initialize) is not dict:
    245                  self._paramval[None] = _ParamValue(_name,_domain,self._initialize)
    246               elif None in self._initialize.keys():
    247                  self._paramval[None] = _ParamValue(_name,_domain,self._initialize[None])
    248               elif self._default.value is not None:
    249                  self._paramval[None] = self._default
     180                    self.value=self._initialize
     181                    #self._paramval[None] = _ParamValue(name=_name,domain=_domain,value=self._initialize)
     182              elif None in self._initialize:
     183                    self.value=self._initialize[None]
     184                    #self._paramval[None] = _ParamValue(name=_name,domain=_domain,value=self._initialize[None])
     185              elif self._default.value is not None and not pyutilib.is_nan(self._default.value):
     186                    self.value=self._default.value
     187                    #self._paramval[None] = self._default
    250188              else:
    251                  raise ValueError, "Attempting to construct parameter "+_name+" without parameter data"
    252               self._valid_value(self._paramval[None].value,(),True)
     189                    raise ValueError, "Attempting to construct parameter "+_name+" without parameter data"
     190              #print "Z",type(self._paramval[None].value), self._paramval[None].value
     191              #print "Z",type(self.__call__())
     192              self._valid_indexed_value(self.value,(),True)
    253193           else:
    254194              #
     
    261201                   else:
    262202                      tmpkey=key
    263                    self._paramval[tmpkey] = _ParamValue(_name+"["+str(key)+"]",_domain,data[key])
    264                    self._valid_value(data[key],key,True)
     203                   self._valid_indexed_value(data[key],key,True)
     204                   self._paramval[tmpkey] = _ParamValue(name=_name+"["+str(key)+"]",domain=_domain,value=data[key])
    265205              #
    266206              # Initialize with initialization data.
    267207              #
    268208              elif self._initialize is not None:
     209                ## print "HERE ZZ"
    269210                 if type(self._initialize) is dict:
     211                   ## print "HERE XX"
    270212                    for key in self._initialize:
    271                       self._paramval[key] = _ParamValue(_name+"["+str(key)+"]",_domain,self._initialize[key])
    272                       self._valid_value(self._initialize[key],key,True)
     213                      self._valid_indexed_value(self._initialize[key],key,True)
     214                      self._paramval[key] = _ParamValue(name=_name+"["+str(key)+"]",domain=_domain,value=self._initialize[key])
    273215                 else:
     216                   ## print "HERE YY"
     217                    self._valid_indexed_value(self._initialize,(),True)
    274218                    for key in self._index:
    275                       self._paramval[key] = _ParamValue(_name+"["+str(key)+"]",_domain,self._initialize)
    276                     self._valid_value(self._initialize,(),True)
     219                      self._paramval[key] = _ParamValue(name=_name+"["+str(key)+"]",domain=_domain,value=self._initialize)
    277220        #
    278221        # Construct using the rule
     
    292235              tmp.append(model)
    293236              tmp = tuple(tmp)
    294               self._paramval[val] = _ParamValue(tname,_domain,self._initialize(*tmp))
    295               self._valid_value(self._paramval[val].value,val,True)
    296 
    297     def _valid_value(self,value,index, use_exception):
    298         #if self.domain is None and self._validate is None:
    299         #   return True
     237              tval = self._initialize(*tmp)
     238              self._valid_indexed_value(tval,val,True)
     239              self._paramval[val] = _ParamValue(name=tname,domain=_domain,value=tval)
     240
     241    def _valid_indexed_value(self,value,index, use_exception):
    300242        if self._validate is not None:
    301243           tmp = [value]
     
    315257       
    316258
     259class _ParamElement(_ParamBase,_ParamValue):
     260
     261    def __init__(self, *args, **kwd):
     262        _ParamValue.__init__(self, **kwd)
     263        _ParamBase.__init__(self, **kwd)
     264        self._index=[None]
     265        self._paramval[None] = self
     266
     267    def simplify(self, model):
     268        return NumericConstant(value=self.value)
     269
    317270    def check_values(self):         #pragma:nocover
    318271        #
    319272        # Validate the values
    320273        #
     274        if None not in self._index:
     275            raise ValueError, "Undefined value for parameter "+self.name
     276        if not self._valid_indexed_value(self.value,None,False):
     277            raise ValueError, "Parameter "+self.name+" failed validation test value=" + str(self.value)
     278
     279    def __call__(self, exception=True):
     280        return self.value
     281
     282
     283
     284class _ParamArray(_ParamBase):
     285
     286    def __init__(self, *args, **kwd):
     287        _ParamBase.__init__(self, **kwd)
     288        for arg in args:
     289            if not isinstance(arg,_BaseSet):
     290                raise ValueError, "Cannot index parameter `"+self.name+"' with object of type "+str(type(arg))
     291            self._ndim += arg.dimen
     292        if len(args) == 1:
     293            self._index=args[0]
     294        else:
     295            self._index=None
     296            self._index_set=args
     297
     298    def simplify(self, model):
     299        raise ValueError, "Cannot simplify array parameter "+self.name
     300
     301    def __float__(self):
     302        raise ValueError, "Cannot access the value of array parameter "+self.name
     303
     304    def __int__(self):
     305        raise ValueError, "Cannot access the value of array parameter "+self.name
     306
     307    def set_value(self, value):
     308        for key in self._paramval:
     309            self._valid_indexed_value(value,key,True)
     310            self._paramval[key].value = value
     311            #self._valid_value(value,key,True)
     312
     313    def check_values(self):         #pragma:nocover
     314        #
     315        # Validate the values
     316        #
    321317        for val in self._paramval:
    322           if val not in self._index:
    323              if val is None:
    324                 raise ValueError, "Undefined value for parameter "+self.name
    325              else:
     318            if val not in self._index:
    326319                raise ValueError, "Undefined value for parameter "+self.name+" index=" + str(val)
    327           if not self._valid_value(self._paramval[val].value,val,False):
    328              raise ValueError, "Parameter "+self.name+" failed validation test: index=" + str(val) + " value=" + str(self._paramval[val].value)
    329 
    330 
    331 ComponentRegistration("Param", Param, "Parameter data that is used to define a model instance.")
     320            if not self._valid_indexed_value(self._paramval[val].value,val,False):
     321                raise ValueError, "Parameter "+self.name+" failed validation test: index=" + str(val) + " value=" + str(self._paramval[val].value)
     322
     323    def reset(self):
     324        pass                        #pragma:nocover
     325
     326    def display(self, ostream=None):
     327        self.pprint(ostream=ostream)
     328
     329
     330class Param(object):
     331    """
     332    Data objects that are used to construct Pyomo models.
     333    """
     334    def __new__(cls, *args, **kwds):
     335        if args == ():
     336            self = _ParamElement(*args, **kwds)
     337        else:
     338            self = _ParamArray(*args, **kwds)
     339        return self
     340
     341
     342ComponentRegistration("Param", _ParamBase, "Parameter data that is used to define a model instance.")
  • trunk/coopr/pyomo/base/set_types.py

    r1308 r1414  
    99#  _________________________________________________________________________
    1010
    11 __all__ = ['_VirtualSet', '_AnySet', 'RealSet', 'IntegerSet', 'BooleanSet', 'Any', 'Reals', 'PositiveReals', 'NonPositiveReals', 'NegativeReals', 'NonNegativeReals', 'PercentFraction', 'Integers', 'PositiveIntegers', 'NonPositiveIntegers', 'NegativeIntegers', 'NonNegativeIntegers', 'Boolean', 'Binary', 'RangeSet']
     11__all__ = ['_VirtualSet', '_AnySet', 'RealSet', 'IntegerSet', 'BooleanSet', 'Any', 'Reals', 'PositiveReals', 'NonPositiveReals', 'NegativeReals', 'NonNegativeReals', 'PercentFraction', 'Integers', 'PositiveIntegers', 'NonPositiveIntegers', 'NegativeIntegers', 'NonNegativeIntegers', 'Boolean', 'Binary']
    1212
    1313import pyutilib.plugin
    1414import sets
    15 import expr
    16 from numvalue import value
    1715from coopr.pyomo.base.plugin import *
    1816
     
    4442
    4543    def __contains__(self, element):
    46         return _VirtualSet.__contains__(self,element)
     44        if element is None:
     45            return False
     46        return True
    4747
    4848
     
    120120Binary=BooleanSet(name="Binary", doc="A set of boolean values")
    121121
    122 
    123 
    124 class RangeSet(sets._SetContainer):
    125     """A set that represents a list of integer values"""
    126 
    127     def __init__(self,*args,**kwds):
    128         """Construct a list of integers"""
    129         tmp=()
    130         sets._SetContainer.__init__(self,*tmp,**kwds)
    131         self.ordered=True
    132         if len(args) == 1:
    133            self._start=1
    134            self._end=args[0]
    135            self._step=1
    136         elif len(args) == 2:
    137            self._start=args[0]
    138            self._end=args[1]
    139            self._step=1
    140         else:
    141            self._start=args[0]
    142            self._end=args[1]
    143            self._step=args[2]
    144 
    145     def _construct(self, model=None, values=None):
    146         if isinstance(self._start,expr.Expression):
    147            self._start_val = self._start()
    148         else:
    149            self._start_val = value(self._start)
    150 
    151         if isinstance(self._end,expr.Expression):
    152            self._end_val = self._end()
    153         else:
    154            self._end_val = value(self._end)
    155 
    156         if isinstance(self._step,expr.Expression):
    157            self._step_val = self._step()
    158         else:
    159            self._step_val = value(self._step)
    160 
    161         if self.validate is None:
    162            def validate_fn(val,model):
    163                if val < validate_fn.start:
    164                   return False
    165                if val > validate_fn.end:
    166                   return False
    167                if (val-validate_fn.start)%validate_fn.step != 0:
    168                   return False
    169                return True
    170            validate_fn.start = self._start_val
    171            validate_fn.end = self._end_val
    172            validate_fn.step = self._step_val
    173            self.validate=validate_fn
    174 
    175         #
    176         # Generate set, and track the bounds
    177         #
    178         first=self._start_val
    179         last=self._start_val
    180         for val in range(self._start_val,self._end_val+1,self._step_val):
    181           if self._verify(val,False):
    182              last=val
    183              self.add(val)
    184         self._bounds=(first,last)
    185 
    186 ComponentRegistration("RangeSet", RangeSet, "A sequence of numeric values.  RangeSet(start,end,step) is a sequence starting a value 'start', and increasing in values by 'step' until a value greater than of equal to 'end' is reached.")
  • trunk/coopr/pyomo/base/var.py

    r1410 r1414  
    99#  _________________________________________________________________________
    1010
    11 __all__ = ['Var', 'VarStatus']
     11__all__ = ['Var', 'VarStatus', '_VarBase']
    1212
    1313from numvalue import *
     
    2626
    2727    """Constructor"""
    28     def __init__(self,name,domain):
    29         NumericValue.__init__(self,name,domain)
    30         self._standard_attr.update(["id","label","value","initial","lb","ub","fixed","status"])
    31         self.__dict__['_attr_id'] = None
    32         self.__dict__['_attr_label'] = None
    33         self.__dict__['_attr_value'] = None
    34         self.__dict__['_attr_initial']=None
    35         self.__dict__['_attr_lb']=None
    36         self.__dict__['_attr_ub']=None
    37         self.__dict__['_attr_fixed']=False
    38         self.__dict__['_attr_status'] = VarStatus.undefined
     28    def __init__(self,**kwds):
     29        NumericValue.__init__(self,**kwds)
     30        self.id = None
     31        self.label = None
     32        self.initial = None
     33        self.lb = None
     34        self.ub = None
     35        self.fixed = False
     36        self.status = VarStatus.undefined
    3937
    4038    def __str__(self):
     
    7775#
    7876
    79 class Var(NumericValue):
     77class _VarBase(object):
    8078    """A numeric variable, which may be defined over a index"""
    8179
     
    9593                          existing model data
    9694    """
    97     def __init__(self, *args, **kwd):
     95    def __init__(self, **kwd):
    9896        #
    9997        # Default keyword values
     
    102100        tmpname="unknown"
    103101        tmpdomain=Reals
     102        self._ndim=0
    104103        tmpbounds=None
    105104        self._varval={}
     
    116115          else:
    117116             raise ValueError, "Var constructor: unknown keyword - "+key
    118         NumericValue.__init__(self,tmpname,tmpdomain)
    119         self._standard_attr.add("bounds")
     117        self.name = tmpname
     118        self.domain = tmpdomain
    120119        self.bounds=tmpbounds
    121         #
    122         # Setup index set
    123         #
    124120        self._index_set=None
    125         if args == ():
    126            self._index=[None]
    127            self._ndim=0
    128         else:
    129            self._ndim=0
    130            for arg in args:
    131              if not isinstance(arg,_BaseSet):
    132                 raise ValueError, "Cannot index variable `"+self.name+"' with object of type "+str(type(arg))
    133              self._ndim += arg.dimen
    134            if len(args) == 1:
    135               self._index=args[0]
    136            else:
    137               self._index=None
    138               self._index_set=args
    139121
    140122    def as_numeric(self):
     
    150132
    151133    def __contains__(self,ndx):
    152         return ndx in self._varval.keys()
     134        return ndx in self._varval
    153135
    154136    def dim(self):
     
    157139    def reset(self):
    158140        for key in self._varval:
    159           self._varval[key].value = self._varval[key].initial
     141            if not self._varval[key].initial is None:
     142                self._varval[key].set_value( self._varval[key].initial )
    160143
    161144    def __len__(self):
    162         return len(self._varval.keys())
    163 
    164     def __float__(self):
    165         if None not in self._index:
    166            raise TypeError, "Cannot access the value of array variable "+self.name
    167         #if None not in self._varval:
    168         #   raise ValueError, "Cannot access the value of variable "+self.name+", which is uninitialized"
    169         return float(self._varval[None])
    170 
    171     def __int__(self):
    172         if None not in self._index:
    173            raise TypeError, "Cannot access the value of array variable "+self.name
    174         #if None not in self._varval:
    175         #   raise ValueError, "Cannot access the value of variable "+self.name+", which is uninitialized"
    176         return int(self._varval[None])
     145        return len(self._varval)
    177146
    178147    def __setitem__(self,ndx,val):
     148        #print "HERE",ndx,val, self._valid_value(val,False), self.domain
    179149        if None in self._index:
    180            raise KeyError, "Cannot set an array value in singleton variable "+self.name
     150            raise KeyError, "Cannot set an array value in singleton variable "+self.name
    181151        if ndx not in self._index:
    182            raise KeyError, "Cannot set the value of array variable "+self.name+" with invalid index "+str(ndx)
    183         #if ndx not in self._varval:
    184         #   raise KeyError, "Cannot set the value of array variable "+self.name+" that has not been initialized"
     152            raise KeyError, "Cannot set the value of array variable "+self.name+" with invalid index "+str(ndx)
     153        if not self._valid_value(val,False):
     154            raise ValueError, "Cannot set variable "+self.name+" with invalid value: index=" + str(ndx) + " value=" + str(val)
    185155        self._varval[ndx].value = val
    186         if not self._valid_value(val,False):
    187           raise ValueError, "Cannot set variable "+self.name+" with invalid value: index=" + str(ndx) + " value=" + str(val)
    188156
    189157    def __getitem__(self,ndx):
     
    197165            raise KeyError, "Unknown index " + str(ndx) + " in variable " + self.name
    198166
    199     def __setattr__(self,name,val):
     167    def X__setattr__(self,name,val):
    200168        if name == "_attr_declarations":
    201169            NumericValue.__setattr__(self,name,val)
     
    246214            NumericValue.__setattr__(self,name,val)
    247215
    248     def __getattr__(self,name):
     216    def X__getattr__(self,name):
    249217        if name == "_attr_declarations":
    250218            return NumericValue.__getattr__(self,name)
     
    262230        # Construct _VarValue() objects for all index values
    263231        #
    264         if self._ndim == 0:
    265            self._varval[None] = _VarValue(self.name,self.domain)
    266         else:
    267            for ndx in self._index:
    268              if ndx is not None:
    269                 self._varval[ndx] = _VarValue(self.name+"["+str(ndx)+"]",self.domain)
     232        if self._ndim > 0:
     233            if type(self._initialize) is dict:
     234                self._index = self._initialize.keys()
     235            for ndx in self._index:
     236                if ndx is not None:
     237                    self._varval[ndx] = _VarValue(name=self.name+"["+str(ndx)+"]",domain=self.domain)
    270238        #
    271239        # Initialize values with a dictionary if provided
     
    340308        #
    341309        for attr in self._attr_declarations:
    342            for key in self._varval:
    343              self._varval[key]._standard_attr.add(attr)
    344              setattr(self._varval[key],attr,self._attr_declarations[attr][0])
     310            for key in self._varval:
     311                setattr(self._varval[key],attr,self._attr_declarations[attr][0])
    345312
    346313    def pprint(self, ostream=None):
     
    385352        if name[0] == "_":
    386353            raise AttributeError, "Cannot define an attribute that begins with  '_'"
    387         if name in self._attr_declarations or name in self._standard_attr:
     354        if name in self._attr_declarations:
    388355            raise AttributeError, "Attribute %s is already defined" % name
    389356        self._attr_declarations[name] = (default,)
     357        #if not default is None:
     358            #self._valid_value(default)
    390359        #
    391360        # If this variable has been constructed, then
     
    393362        #
    394363        if len(self._varval) > 0:
    395            for key in self._varval:
    396              self._varval[key]._standard_attr.add(name)
    397              setattr(self._varval[key],name,tmpval)
    398 
    399 
    400 ComponentRegistration("Var", Var, "Decision variables in a model.")
     364            for key in self._varval:
     365                setattr(self._varval[key],name,default)
     366
     367
     368class _VarElement(_VarBase,_VarValue):
     369
     370    def __init__(self, *args, **kwd):
     371        _VarValue.__init__(self, **kwd)
     372        _VarBase.__init__(self, **kwd)
     373        self._index=[None]
     374        self._varval[None] = self
     375
     376
     377class _VarArray(_VarBase):
     378
     379    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
     391        self._dummy_val = _VarValue(**kwd)
     392
     393    def __float__(self):
     394        raise TypeError, "Cannot access the value of array variable "+self.name
     395
     396    def __int__(self):
     397        raise TypeError, "Cannot access the value of array variable "+self.name
     398
     399    def _valid_value(self,value,use_exception=True):
     400        #print "VALID",self._dummy_val.domain
     401        return self._dummy_val._valid_value(value,use_exception)
     402
     403    def set_value(self, value):
     404        raise ValueError, "Cannot specify the value of array variable "+self.name
     405
     406class Var(object):
     407    """
     408    Variable objects that are used to construct Pyomo models.
     409    """
     410    def __new__(cls, *args, **kwds):
     411        if args == ():
     412            self = _VarElement(*args, **kwds)
     413        else:
     414            self = _VarArray(*args, **kwds)
     415        return self
     416
     417
     418ComponentRegistration("Var", _VarBase, "Decision variables in a model.")
  • trunk/coopr/pyomo/components

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/pyomo/io

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/pyomo/io/cpxlp.py

    r1411 r1414  
    1515from coopr.opt import ProblemFormat
    1616from coopr.pyomo.base import expr, Var, Constraint, Objective
    17 from coopr.pyomo.base.var import _VarValue
     17from coopr.pyomo.base.var import _VarValue, _VarBase
    1818from coopr.pyomo.base.param import _ParamValue
    1919from coopr.pyomo.base.numtypes import minimize, maximize
     
    233233        print >>OUTPUT, "bounds "
    234234        niv = nbv = 0
    235         for var in model._component[Var].values():
     235        for var in model._component[_VarBase].values():
    236236          if isinstance(var.domain, IntegerSet):
    237237             niv += 1
     
    256256        if niv > 0:
    257257           print >>OUTPUT, "integer"
    258            for var in model._component[Var].values():
     258           for var in model._component[_VarBase].values():
    259259              if isinstance(var.domain, IntegerSet):
    260260                 for ndx in var.keys():
     
    263263        if nbv > 0:
    264264           print >>OUTPUT, "binary"
    265            for var in model._component[Var].values():
     265           for var in model._component[_VarBase].values():
    266266              if isinstance(var.domain, BooleanSet):
    267267                 for ndx in var.keys():
  • trunk/coopr/pyomo/presolve

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/pyomo/presolve/collect_linear_terms.py

    r1403 r1414  
    1111
    1212import pyutilib.plugin
    13 from coopr.pyomo.base import expr, Var, Constraint, Objective
     13from coopr.pyomo.base import expr, _VarBase, Constraint, Objective
    1414from coopr.pyomo.base.numvalue import NumericConstant
    1515from coopr.pyomo.base.var import _VarValue
     
    6464                     if isinstance(e,NumericConstant) or isinstance(e,_ParamValue):
    6565                        c *= e.value
    66                      elif isinstance(e,Var):
     66                     elif isinstance(e,_VarBase):
    6767                        if v != "0":
    6868                           raise ValueError, "ERROR: two variables in ProductExpression:",e
     
    105105        # Variable
    106106        #
    107         elif isinstance(exp,_VarValue) or isinstance(exp,Var):
     107        elif isinstance(exp,_VarValue) or isinstance(exp,_VarBase):
    108108          if isinstance(exp,_VarValue):
    109109               v = exp.label
     
    134134        The main routine to perform the presolve
    135135        """
    136         Vars = model._component[Var]
     136        Vars = model._component[_VarBase]
    137137        Con = model._component[Constraint]
    138138        Obj = model._component[Objective]
  • trunk/coopr/pyomo/presolve/generic_varlabels.py

    r1338 r1414  
    99#  _________________________________________________________________________
    1010
    11 from coopr.pyomo.base import IPyomoPresolver, IPyomoPresolveAction, Var
     11from coopr.pyomo.base import IPyomoPresolver, IPyomoPresolveAction, _VarBase
    1212import pyutilib.plugin
    1313
     
    5151        # variables.
    5252        #
    53         Vars = model._component[Var]
     53        Vars = model._component[_VarBase]
    5454        for var in Vars.values():
    5555            for V in var._varval.keys():
  • trunk/coopr/pyomo/presolve/identify_vars.py

    r1404 r1414  
    1111
    1212import pyutilib.plugin
    13 from coopr.pyomo.base import expr, Var, Constraint, Objective
     13from coopr.pyomo.base import expr, _VarBase, Constraint, Objective
    1414from coopr.pyomo.base.var import _VarValue, VarStatus
    1515from coopr.pyomo.base.numvalue import NumericConstant
     
    4646        # Variable Value
    4747        #
    48         elif isinstance(exp,_VarValue) or isinstance(exp,Var):
     48        elif isinstance(exp,_VarValue) or isinstance(exp,_VarBase):
    4949            exp.status = VarStatus.used
    5050            if isinstance(exp,_VarValue):
     
    6262        #
    6363        elif not isinstance(exp,NumericConstant) and not isinstance(exp,_ParamValue) and exp is not None:
    64             raise ValueError, "Unexpected expression type in identify_variables: " + str(exp)
     64            raise ValueError, "Unexpected expression type in identify_variables: " + str(type(exp))+" "+str(exp)
    6565
    6666
     
    6969        The main routine to perform the presolve
    7070        """
    71         Vars = model._component[Var]
     71        Vars = model._component[_VarBase]
    7272        Con = model._component[Constraint]
    7373        Obj = model._component[Objective]
  • trunk/coopr/pysos

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/pysp

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/coopr/sucasa

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/dist

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/dist/pyomo

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/dist/pysos

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/doc

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/examples

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/examples/opt

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/opt/colin

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pyomo

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/examples/pyomo/amplbook2

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/examples/pyomo/diet

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/examples/pyomo/examples

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/examples/pyomo/p-median

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pyomo/tutorials

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pyomo/tutorials/tab

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysos

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysos/demo1

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysos/demo2

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysos/demo3

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp/electricgridop

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp/farmer

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp/forestry

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp/forestry/CHILE

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp/forestry/DAVIS

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp/forestry/DAVIS2STAGE

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp/networkflow

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp/sizes

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp/sizes/SIZES10

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/pysp/sizes/SIZES3

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/sucasa

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/sucasa/basic

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/sucasa/p-median

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/examples/sucasa/sched

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/scripts

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test

    • Property svn:ignore
      •  

        old new  
        1 target
        2 .coverage
         1*.pyc
         2*.pyo
         3*.cover
  • trunk/test/core

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/core/base

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/core/colin

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/plugins

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/plugins/mip

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/plugins/mip/cbc

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/test/plugins/mip/cplex

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/test/plugins/mip/glpk

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/test/plugins/mip/pico

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/test/pyomo

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/pyomo/examples

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/pyomo/unit

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/pyomo/unit/solve3.txt

    r903 r1414  
    33  Variables:
    44    Variable x :   Size=4 Domain=Reals
    5       1 : None
    6       2 : None
    7       3 : None
    8       4 : None
     5      1 : nan
     6      2 : nan
     7      3 : nan
     8      4 : nan
    99
    1010  Objectives:
    1111    Objective obj :   Size=1
    12       Value=None
     12      Value=nan
    1313
    1414  Constraints:
  • trunk/test/pyomo/unit/test_action.py

    r1176 r1414  
    5858        """Check the use of the __getattr__ method"""
    5959        self.failUnlessEqual( self.instance.A.value, 4.3)
    60         self.failUnlessEqual( self.instance.A.__getattr__("value"), 4.3)
    6160
    6261
  • trunk/test/pyomo/unit/test_expr.py

    r1409 r1414  
    4242
    4343    def create(self,val,domain):
    44         tmp=self.type(val, domain=domain)
     44        tmp=self.type(value=val, domain=domain)
    4545        return tmp
    4646
     
    8686          self.fail("test_getattr")
    8787
    88     def test_setattr(self):
     88    def Xtest_setattr(self):
    8989        """Check that attributes can be set"""
    9090        a=self.create(1.3,Reals)
     
    205205
    206206    def create(self,val,domain):
    207         tmp=self.type("unknown",domain)
     207        tmp=self.type(name="unknown",domain=domain)
    208208        tmp.value=val
    209209        return tmp
     
    214214    def test_vals(self):
    215215        try:
    216             NumericConstant('a')
     216            NumericConstant(value='a')
    217217            self.fail("Cannot initialize a constant with a non-numeric value")
    218         except TypeError:
    219             pass
    220         a = NumericConstant(1.1)
     218        except ValueError:
     219            pass
     220        a = NumericConstant(value=1.1)
    221221        b = float(a)
    222222        self.failUnlessEqual(b,1.1)
     
    225225
    226226    def Xtest_getattr1(self):
    227         a = NumericConstant(1.1)
     227        a = NumericConstant(value=1.1)
    228228        try:
    229229            a.model
     
    233233
    234234    def test_ops(self):
    235         a = NumericConstant(1.1)
    236         b = NumericConstant(2.2)
    237         c = NumericConstant(-2.2)
     235        a = NumericConstant(value=1.1)
     236        b = NumericConstant(value=2.2)
     237        c = NumericConstant(value=-2.2)
    238238        a <= b
    239         self.failUnlessEqual(a <= b, True)
    240         self.failUnlessEqual(a >= b, False)
    241         self.failUnlessEqual(a == b, False)
    242         self.failUnlessEqual(abs(a + b-3.3) <= 1e-7, True)
    243         self.failUnlessEqual(abs(b - a-1.1) <= 1e-7, True)
    244         self.failUnlessEqual(abs(b * 3-6.6) <= 1e-7, True)
    245         self.failUnlessEqual(abs(b / 2-1.1) <= 1e-7, True)
    246         self.failUnlessEqual(abs(abs(-b)-2.2) <= 1e-7, True)
    247         self.failUnlessEqual(abs(c), 2.2)
     239        self.failUnlessEqual(a() <= b(), True)
     240        self.failUnlessEqual(a() >= b(), False)
     241        self.failUnlessEqual(a() == b(), False)
     242        self.failUnlessEqual(abs(a() + b()-3.3) <= 1e-7, True)
     243        self.failUnlessEqual(abs(b() - a()-1.1) <= 1e-7, True)
     244        self.failUnlessEqual(abs(b() * 3-6.6) <= 1e-7, True)
     245        self.failUnlessEqual(abs(b() / 2-1.1) <= 1e-7, True)
     246        self.failUnlessEqual(abs(abs(-b())-2.2) <= 1e-7, True)
     247        self.failUnlessEqual(abs(c()), 2.2)
    248248        self.failUnlessEqual(str(c), "-2.2")
    249249
     
    290290        model = Model()
    291291        model.a = Var()
    292         try:
    293             model.a.suffix = True
    294             self.fail("Expected AttributeError")
    295         except AttributeError:
    296             pass
     292        #try:
     293            #model.a.suffix = True
     294            #self.fail("Expected AttributeError")
     295        #except AttributeError:
     296            #pass
    297297        model.a.declare_attribute("suffix")
    298298        model.a.declare_attribute("foo",default=False)
    299         try:
     299        #try:
    300300            #
    301301            # This fails because we don't have an instance
    302302            #
    303             model.a.suffix = True
    304             self.fail("Expected TypeError")
    305         except TypeError:
    306             pass
     303            #model.a.suffix = True
     304            #self.fail("Expected TypeError")
     305        #except TypeError:
     306            #pass
    307307        instance = model.create()
    308308        self.failUnlessEqual(instance.a.suffix,None)
     
    318318        model.X = Set(initialize=[1,3,5])
    319319        model.a = Var(model.X)
    320         try:
    321             model.a.suffix = True
    322             self.fail("Expected AttributeError")
    323         except AttributeError:
    324             pass
     320        #try:
     321            #model.a.suffix = True
     322            #self.fail("Expected AttributeError")
     323        #except AttributeError:
     324            #pass
    325325        model.a.declare_attribute("suffix")
    326326        model.a.declare_attribute("foo",default=False)
    327         try:
    328             model.a.suffix = True
    329             self.fail("Expected TypeError")
    330         except TypeError:
    331             pass
     327        #try:
     328            #model.a.suffix = True
     329            #self.fail("Expected TypeError")
     330        #except TypeError:
     331            #pass
    332332        try:
    333333            self.failUnlessEqual(model.a.suffix,None)
     
    337337        instance = model.create()
    338338        self.failUnlessEqual(instance.a[1].suffix,None)
     339        #
     340        # Cannot set all suffixes simultaneously
     341        #
    339342        instance.a.suffix = True
    340         self.failUnlessEqual(instance.a[1].suffix,True)
     343        self.failUnlessEqual(instance.a[1].suffix,None)
    341344        self.failUnlessEqual(instance.a[3].foo,False)
    342345
     
    369372        self.failUnlessEqual(float(instance.c),2.1)
    370373        self.failUnlessEqual(int(instance.c),2)
    371         try:
    372             float(instance.d)
    373             self.fail("expected ValueError")
    374         except ValueError:
    375             pass
    376         try:
    377             int(instance.d)
    378             self.fail("expected ValueError")
    379         except ValueError:
    380             pass
     374        self.failUnless(pyutilib.is_nan(float(instance.d)))
     375        self.failUnlessEqual(int(instance.d),0)
     376        #try:
     377            #int(instance.d)
     378            #self.fail("expected ValueError")
     379        #except ValueError:
     380            #pass
    381381        try:
    382382            float(instance.b)
     
    396396        model.c = Var(initialize=2.1, within=PositiveReals)
    397397        try:
    398             model.c = 2.2
    399             self.fail("can't set the value of an uninitialized variable")
    400         except TypeError:
     398            model.b = 2.2
     399            self.fail("can't set the value of an array variable")
     400        except ValueError:
    401401            pass
    402402        instance = model.create()
     
    412412            pass
    413413        try:
    414             instance.b[3]=-2.2
     414            instance.b[3] = -2.2
     415            print "HERE",type(instance.b[3])
    415416            self.fail("can't set an array variable with a bad value")
    416417        except ValueError:
     
    423424
    424425        try:
    425             instance.c.value = 'a'
     426            instance.c.set_value('a')
    426427            self.fail("can't set a bad value for variable c")
    427428        except ValueError:
    428429            pass
    429430        try:
    430             instance.c.value = -1.0
     431            instance.c.set_value(-1.0)
    431432            self.fail("can't set a bad value for variable c")
    432433        except ValueError:
     
    435436        try:
    436437            instance.c.initial = 'a'
     438            instance.c.reset()
    437439            self.fail("can't set a bad initial for variable c")
    438440        except ValueError:
     
    440442        try:
    441443            instance.c.initial = -1.0
     444            instance.c.reset()
    442445            self.fail("can't set a bad initial for variable c")
    443446        except ValueError:
    444447            pass
    445448       
    446         try:
    447             instance.c.ub = 'a'
    448             self.fail("can't set a bad ub for variable c")
    449         except ValueError:
    450             pass
    451         try:
    452             instance.c.ub = -1.0
    453             self.fail("can't set a bad ub for variable c")
    454         except ValueError:
    455             pass
     449        #try:
     450            #instance.c.ub = 'a'
     451            #self.fail("can't set a bad ub for variable c")
     452        #except ValueError:
     453            #pass
     454        #try:
     455            #instance.c.ub = -1.0
     456            #self.fail("can't set a bad ub for variable c")
     457        #except ValueError:
     458            #pass
    456459       
    457         try:
    458             instance.c.fixed = 'a'
    459             self.fail("can't fix a variable with a non-boolean")
    460         except ValueError:
    461             pass
     460        #try:
     461            #instance.c.fixed = 'a'
     462            #self.fail("can't fix a variable with a non-boolean")
     463        #except ValueError:
     464            #pass
    462465       
    463466    def test_pprint(self):
     
    499502        e = m.q*2
    500503        try:
    501             m.p*2
    502             self.fail("Expected ValueError")
    503         except ValueError:
     504            m.p * 2
     505            self.fail("Expected TypeError")
     506        except TypeError:
    504507            pass
    505508
     
    532535        model.b = Set(initialize=[1,2,3])
    533536        model.c = Param(model.b,initialize=2, within=Reals)
    534         try:
    535             model.a.value = 3
    536             self.fail("can't set the value of an unitialized parameter")
    537         except AttributeError:
    538             pass
     537        #try:
     538            #model.a.value = 3
     539            #self.fail("can't set the value of an unitialized parameter")
     540        #except AttributeError:
     541            #pass
    539542        try:
    540543            model.a._construct(model,None)
     
    545548        instance=model.create()
    546549        instance.a.value=3
    547         try:
    548             instance.a.default='2'
    549             self.fail("can't set a bad default value")
    550         except ValueError:
    551             pass
     550        #try:
     551            #instance.a.default='2'
     552            #self.fail("can't set a bad default value")
     553        #except ValueError:
     554            #pass
    552555        self.failUnlessEqual(2 in instance.c, True)
    553556
     
    588591        instance = model.create()
    589592        instance.e.check_values()
    590         try:
    591             instance.c.value = 'b'
    592             self.fail("can't have a non-numerical parameter")
    593         except ValueError:
    594             pass
     593        #try:
     594            #instance.c.value = 'b'
     595            #self.fail("can't have a non-numerical parameter")
     596        #except ValueError:
     597            #pass
    595598
    596599    def test_expr_error1(self):
     
    602605        try:
    603606            m.p*2
    604             self.fail("Expected ValueError")
    605         except ValueError:
     607            self.fail("Expected TypeError")
     608        except TypeError:
    606609            pass
    607610
     
    698701    def test_set_get(self):
    699702        a = Objective()
    700         try:
    701             a.value = 1
    702             self.fail("Can't set value attribute")
    703         except AttributeError:
    704             pass
     703        #try:
     704            #a.value = 1
     705            #self.fail("Can't set value attribute")
     706        #except AttributeError:
     707            #pass
    705708        self.failUnlessEqual(a(),None)
    706709        #
     
    768771    def test_set_get(self):
    769772        a = Constraint()
    770         try:
    771             a.value = 1
    772             self.fail("Can't set value attribute")
    773         except AttributeError:
    774             pass
     773        #try:
     774            #a.value = 1
     775            #self.fail("Can't set value attribute")
     776        #except AttributeError:
     777            #pass
    775778        self.failUnlessEqual(a(),None)
    776779
  • trunk/test/pyomo/unit/test_model.py

    r1400 r1414  
    2020from coopr.pyomo.base import IntegerSet
    2121from coopr.pyomo import *
     22from coopr.pyomo.base.var import _VarElement
    2223import pyutilib_th
    2324
     
    175176        """Test simplify method"""
    176177        self.model.x = Var()
    177         self.failUnlessEqual(type(self.model.x.simplify(self.model)),Var)
     178        self.failUnlessEqual(type(self.model.x.simplify(self.model)),_VarElement)
    178179
    179180    def test_value(self):
     
    207208        self.instance = self.model.create()
    208209        self.instance.x.fixed = True
    209         try:
    210           self.instance.x.fixed
    211         except AttributeError:
    212           pass
    213         else:
    214           self.fail("test_fixed_attr")
    215         self.failUnlessEqual(self.instance.x[1].fixed, True)
     210        #try:
     211          #self.instance.x.fixed
     212        #except AttributeError:
     213          #pass
     214        #else:
     215          #self.fail("test_fixed_attr")
     216        self.failUnlessEqual(self.instance.x[1].fixed, False)
    216217        self.instance.y[1].fixed=True
    217218        self.failUnlessEqual(self.instance.y[1].fixed, True)
     
    222223        self.model.y = Var(self.model.A)
    223224        self.instance = self.model.create()
    224         self.instance.x = 3.5
    225         self.failUnlessEqual(self.instance.x[1], 3.5)
     225        try:
     226            self.instance.x = 3.5
     227            self.fail("Expected ValueError")
     228        except ValueError:
     229            pass
    226230        self.instance.y[1] = 3.5
    227231        self.failUnlessEqual(self.instance.y[1], 3.5)
    228232
    229     def test_initial_attr(self):
    230         """Test initial attribute"""
    231         self.model.x = Var(self.model.A)
    232         self.instance = self.model.create()
    233         self.instance.x.initial = 3.5
    234         self.failUnlessEqual(self.instance.x[1].initial, 3.5)
    235 
    236     def test_lb_attr(self):
    237         """Test lb attribute"""
    238         self.model.x = Var(self.model.A)
    239         self.instance = self.model.create()
    240         self.instance.x.lb = -1.0
    241         self.failUnlessEqual(self.instance.x[1].lb, -1.0)
    242 
    243     def test_ub_attr(self):
    244         """Test ub attribute"""
    245         self.model.x = Var(self.model.A)
    246         self.instance = self.model.create()
    247         self.instance.x.ub = 1.0
    248         self.failUnlessEqual(self.instance.x[1].ub, 1.0)
     233    #def test_initial_attr(self):
     234        #"""Test initial attribute"""
     235        #self.model.x = Var(self.model.A)
     236        #self.instance = self.model.create()
     237        #self.instance.x.initial = 3.5
     238        #self.failUnlessEqual(self.instance.x[1].initial, 3.5)
     239
     240    #def test_lb_attr(self):
     241        #"""Test lb attribute"""
     242        #self.model.x = Var(self.model.A)
     243        #self.instance = self.model.create()
     244        #self.instance.x.lb = -1.0
     245        #self.failUnlessEqual(self.instance.x[1].lb, -1.0)
     246
     247    #def test_ub_attr(self):
     248        #"""Test ub attribute"""
     249        #self.model.x = Var(self.model.A)
     250        #self.instance = self.model.create()
     251        #self.instance.x.ub = 1.0
     252        #self.failUnlessEqual(self.instance.x[1].ub, 1.0)
    249253
    250254    def test_initialize_option(self):
     
    337341        self.instance = self.model.create()
    338342        self.instance.x.fixed = True
    339         try:
    340           self.instance.x.fixed
    341         except AttributeError:
    342           pass
    343         else:
    344           self.fail("test_fixed_attr")
    345         self.failUnlessEqual(self.instance.x[1,2].fixed, True)
     343        #try:
     344          #self.instance.x.fixed
     345        #except AttributeError:
     346          #pass
     347        #else:
     348          #self.fail("test_fixed_attr")
     349        self.failUnlessEqual(self.instance.x[1,2].fixed, False)
    346350        self.instance.y[1,2].fixed=True
    347351        self.failUnlessEqual(self.instance.y[1,2].fixed, True)
     
    352356        self.model.y = Var(self.model.A,self.model.A)
    353357        self.instance = self.model.create()
    354         self.instance.x = 3.5
    355         self.failUnlessEqual(self.instance.x[1,2], 3.5)
     358        try:
     359            self.instance.x = 3.5
     360            self.fail("Expected ValueError")
     361        except ValueError:
     362            pass
    356363        self.instance.y[1,2] = 3.5
    357364        self.failUnlessEqual(self.instance.y[1,2], 3.5)
    358365
    359     def test_initial_attr(self):
    360         """Test initial attribute"""
    361         self.model.x = Var(self.model.A,self.model.A)
    362         self.instance = self.model.create()
    363         self.instance.x.initial = 3.5
    364         self.failUnlessEqual(self.instance.x[1,1].initial, 3.5)
    365 
    366     def test_lb_attr(self):
    367         """Test lb attribute"""
    368         self.model.x = Var(self.model.A,self.model.A)
    369         self.instance = self.model.create()
    370         self.instance.x.lb = -1.0
    371         self.failUnlessEqual(self.instance.x[2,1].lb, -1.0)
    372 
    373     def test_ub_attr(self):
    374         """Test ub attribute"""
    375         self.model.x = Var(self.model.A,self.model.A)
    376         self.instance = self.model.create()
    377         self.instance.x.ub = 1.0
    378         self.failUnlessEqual(self.instance.x[2,1].ub, 1.0)
     366    #def test_initial_attr(self):
     367        #"""Test initial attribute"""
     368        #self.model.x = Var(self.model.A,self.model.A)
     369        #self.instance = self.model.create()
     370        #self.instance.x.initial = 3.5
     371        #self.failUnlessEqual(self.instance.x[1,1].initial, 3.5)
     372
     373    #def test_lb_attr(self):
     374        #"""Test lb attribute"""
     375        #self.model.x = Var(self.model.A,self.model.A)
     376        #self.instance = self.model.create()
     377        #self.instance.x.lb = -1.0
     378        #self.failUnlessEqual(self.instance.x[2,1].lb, -1.0)
     379
     380    #def test_ub_attr(self):
     381        #"""Test ub attribute"""
     382        #self.model.x = Var(self.model.A,self.model.A)
     383        #self.instance = self.model.create()
     384        #self.instance.x.ub = 1.0
     385        #self.failUnlessEqual(self.instance.x[2,1].ub, 1.0)
    379386
    380387    def test_initialize_option(self):
     
    386393        try:
    387394            value(self.instance.x[1,2])
    388             self.fail("Expected ValueError")
    389         except ValueError:
     395            self.fail("Expected KeyError")
     396        except KeyError:
    390397            pass
    391398
  • trunk/test/pyomo/unit/test_param.py

    r1330 r1414  
    1616sys.path.insert(0, dirname(dirname(abspath(__file__)))+"/../..")
    1717from coopr.pyomo import *
     18import pyutilib
    1819
    1920class PyomoModel(unittest.TestCase):
     
    6465        """Check the use of the __getattr__ method"""
    6566        self.failUnlessEqual( self.instance.A.value, 3.3)
    66         self.failUnlessEqual( self.instance.A.__getattr__("value"), 3.3)
    6767
    6868    def test_setattr_value(self):
     
    7575          self.instance.A.value = 'A'
    7676        except ValueError:
    77           pass
    78         else:
    7977          self.fail("fail test_setattr_value")
     78        else:
     79          #
     80          # NOTE: we can set bad values into a NumericValue object
     81          #
     82          pass
    8083
    8184    def test_setattr_default(self):
     
    101104        """Check the use of getitem"""
    102105        import coopr.pyomo.base.param
    103         self.failUnlessEqual(type(self.instance.A[None]), coopr.pyomo.base.param._ParamValue)
     106        self.failUnless(isinstance(self.instance.A[None], coopr.pyomo.base.param._ParamValue))
    104107        self.failUnlessEqual( self.instance.A[None], 3.3)
    105108
     
    135138        try:
    136139          tmp = value(self.instance.A)
    137         except TypeError:
     140        except ValueError:
    138141          pass
    139142        else:
     
    141144        try:
    142145          tmp = float(self.instance.A)
    143         except TypeError:
     146        except ValueError:
    144147          pass
    145148        else:
     
    147150        try:
    148151          tmp = int(self.instance.A)
    149         except TypeError:
     152        except ValueError:
    150153          pass
    151154        else:
     
    174177        try:
    175178          tmp = self.instance.A.value
    176         except TypeError:
     179        except AttributeError:
    177180          pass
    178181        else:
     
    470473    def test_value(self):
    471474        p = Param()
    472         try:
    473             value(p)
    474             self.fail("Expecting AttributeError")
    475         except AttributeError:
    476             pass
     475        self.failIf(not pyutilib.is_nan(value(p)))
    477476
    478477if __name__ == "__main__":
  • trunk/test/pysp

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/pysp/examples

    • Property svn:ignore set to
      *.pyc
      *.pyo
      *.cover
  • trunk/test/pysp/unit

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/sucasa

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/sucasa/models

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
  • trunk/test/sucasa/unit

    • Property svn:ignore
      •  

        old new  
        11*.pyc
         2*.pyo
         3*.cover
Note: See TracChangeset for help on using the changeset viewer.