Changeset 5757


Ignore:
Timestamp:
May 11, 2012 6:50:31 PM (7 years ago)
Author:
wehart
Message:

Replacing _VarBase with Var.

This change requires some class magic that allows the Var class
to replace itself with another class.

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

Legend:

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

    r4119 r5757  
    5151        if len(args) > 0:
    5252            iarg=args[-1]
    53             if not isinstance(iarg,var._VarBase):
     53            if not isinstance(iarg,var.Var):
    5454                raise ValueError, "Error executing summation(): The last argument value must be a variable object if no 'index' option is specified"
    5555        else:
    5656            iarg=denom[-1]
    57             if not isinstance(iarg,var._VarBase):
     57            if not isinstance(iarg,var.Var):
    5858                raise ValueError, "Error executing summation(): The last denom argument value must be a variable object if no 'index' option is specified"
    5959        index = iarg.keys()
  • coopr.pyomo/trunk/coopr/pyomo/base/var.py

    r5725 r5757  
    99#  _________________________________________________________________________
    1010
    11 __all__ = ['Var', 'VarList', 'VarStatus', '_VarBase', '_VarData']
     11__all__ = ['Var', 'VarList', 'VarStatus', '_VarData']
    1212
    1313import logging
     
    252252#
    253253
    254 class _VarBase(IndexedComponent):
     254class Var(IndexedComponent):
    255255    """A numeric variable, which may be defined over a index"""
    256256
     
    271271    """
    272272
     273    alias("Var", doc="Decision variables in a model.", subclass=True)
     274
     275    def __new__(cls, *args, **kwds):
     276        if cls != Var:
     277            return super(Var, cls).__new__(cls)
     278        if args == ():
     279            return _VarElement(*args, **kwds)
     280        else:
     281            return _VarArray(*args, **kwds)
     282
    273283    #
    274284    # IMPT: The default __getstate__ and __setstate__ are fine - this class owns no weakrefs or slots,
     
    276286    #
    277287
    278     # TODO: default and rule keywords are not used?  Need to talk to Bill ...?
    279     def __init__(self, *args, **kwd):
     288    # TODO: default and rule keywords are not used?
     289    def _initialize_(self, *args, **kwd):
    280290
    281291        # Default keyword values
     
    780790# a _VarElement is the implementation representing a "singleton" or non-indexed variable.
    781791# NOTE: this class derives from both a "slot"ized base class (_VarData) and a normal
    782 #       class with a dictionary (_VarBase) - beware (although I believe the __getstate__
     792#       class with a dictionary (Var) - beware (although I believe the __getstate__
    783793#       implementation should be attribute-independent).
    784794
    785 class _VarElement(_VarBase, _VarData):
     795class _VarElement(Var, _VarData):
    786796
    787797    def __init__(self, *args, **kwd):
    788 
    789798        _VarData.__init__(self,
    790799                            kwd.get('name', None),
    791800                            kwd.get('within', kwd.get('domain', Reals)),
    792801                            self)
    793         _VarBase.__init__(self, *args, **kwd)
     802        self._initialize_(*args, **kwd)
    794803        self._varval[None] = self
    795804        self._varval[None].index = None
     
    801810
    802811    def __getstate__(self):
    803 
     812        #
    804813        # picks up all slots in the _VarData class, and in particular
    805814        # makes sure the "var" and "component" values are not weakrefs,
    806815        # but the actual objects themselves.
    807 
     816        #
    808817        varvalue_result = _VarData.__getstate__(self)
    809818        varvalue_result['component'] = self
    810         varbase_result = _VarBase.__getstate__(self)
     819        varbase_result = Var.__getstate__(self)
    811820        return dict(varvalue_result.items() + varbase_result.items())
    812821
    813822    def __setstate__(self, state):
    814 
    815823        for (slot_name, value) in state.iteritems():
    816824            setattr(self, slot_name, value)
    817825
    818826        self._varval[None].component = weakref.ref(self)
    819 
    820827        # this is hackish, in that it replicates code from the base Component setstate method - revisit at some point.
    821828        if '_parent' in self.__dict__.keys() and self._parent is not None and type(self._parent) != weakref.ref:
     
    827834# a _VarArray is the implementation representing an indexed variable.
    828835
    829 class _VarArray(_VarBase):
     836class _VarArray(Var):
    830837   
    831838    def __init__(self, *args, **kwds):
    832         _VarBase.__init__(self, *args, **kwds)
     839        self._initialize_(*args, **kwds)
    833840        self._dummy_val = _VarData(kwds.get('name', None),
    834841                                    kwds.get('within', kwds.get('domain', Reals)),
     
    852859
    853860    def construct(self, data=None):
    854         _VarBase.construct(self, data)
     861        Var.construct(self, data)
    855862
    856863        for (ndx, var) in self._varval.iteritems():
    857864            var._tighten_bounds()
    858 
    859 
    860 class Var(Component):
    861     """
    862     Variable objects that are used to construct Pyomo models.
    863     """
    864 
    865     alias("Var", "Decision variables in a model.")
    866 
    867     def __new__(cls, *args, **kwds):
    868         if args == ():
    869             self = _VarElement(*args, **kwds)
    870         else:
    871             self = _VarArray(*args, **kwds)
    872         return self
    873865
    874866
     
    918910        self._nvars += 1
    919911        return self[self._nvars-1]
     912
     913
     914
  • coopr.pyomo/trunk/coopr/pyomo/io/ampl/ampl.py

    r5633 r5757  
    1919from coopr.pyomo.base import expr
    2020from coopr.pyomo.base import intrinsic_functions
    21 from coopr.pyomo.base.var import _VarData, Var, _VarElement, _VarBase
     21from coopr.pyomo.base.var import _VarData, Var, _VarElement
    2222from coopr.pyomo.base import numvalue
    2323from coopr.pyomo.base.param import _ParamData
  • coopr.pyomo/trunk/coopr/pyomo/preprocess/identify_vars.py

    r5633 r5757  
    1414from coopr.pyomo.base.connector import _ConnectorBase, _ConnectorValue
    1515from coopr.pyomo.base.numvalue import NumericConstant
    16 from coopr.pyomo.base.var import  _VarData, VarStatus, _VarArray, _VarBase, Var, VarList
     16from coopr.pyomo.base.var import  _VarData, VarStatus, _VarArray, Var, VarList
    1717from coopr.pyomo.base import IPyomoPresolver, IPyomoPresolveAction
    1818import logging
     
    127127        # Variable Base
    128128        #
    129         elif isinstance(exp,_VarBase):
     129        elif isinstance(exp,Var):
    130130            # FIXME: [JDS] I am pretty sure that the only way to get here
    131131            # will always raise the ValueError exception; the rest of
  • coopr.pyomo/trunk/coopr/pyomo/transform/eliminate_fixed_vars.py

    r5633 r5757  
    1111from coopr.pyomo.base import IModelTransformation
    1212from coopr.pyomo import Constraint, Objective, NumericConstant, Expression
    13 from coopr.pyomo.base.var import _VarBase, _VarData
     13from coopr.pyomo.base.var import Var, _VarData
    1414from coopr.pyomo.base.util import xsequence
    1515
     
    7272            if isinstance(expr._args[i],Expression):
    7373                _args.append( self._fix_vars(expr._args[i], model) )
    74             elif (isinstance(expr._args[i],_VarBase) or isinstance(expr._args[i],_VarData)) and expr._args[i].fixed:
     74            elif (isinstance(expr._args[i],Var) or isinstance(expr._args[i],_VarData)) and expr._args[i].fixed:
    7575                if expr._args[i].value != 0.0:
    7676                    _args.append( NumericConstant(None,None,expr._args[i].value) )
  • coopr.pyomo/trunk/coopr/pyomo/transform/isomorphism.py

    r2798 r5757  
    11from coopr.pyomo import *
    22from pyutilib.component.core import implements, Plugin, Interface
    3 from coopr.pyomo.base import IModelTransformation, _VarBase
     3from coopr.pyomo.base import IModelTransformation, Var
    44
    55__all__ = ["IIsomophicTransformation", "IsomorphicTransormation"]
     
    4444
    4545        for c in model.active_components():
    46             if isinstance(c, _VarBase):
     46            if isinstance(c, Var):
    4747                pass
    4848
  • coopr.pyomo/trunk/coopr/pyomo/transform/nonnegative_transform.py

    r5633 r5757  
    77from util import collectAbstractComponents
    88from coopr.pyomo.transform import *
    9 from coopr.pyomo.base.var import _VarElement, _VarBase, _VarData
     9from coopr.pyomo.base.var import _VarElement, Var, _VarData
    1010from coopr.pyomo.base.expr import _SumExpression, _ProductExpression, \
    1111     _AbsExpression, _PowExpression, _IdentityExpression
     
    235235        toRemove = []
    236236        for (attr_name, attr) in nonneg.__dict__.items():
    237             if isinstance(attr, _VarBase):
     237            if isinstance(attr, Var):
    238238                toRemove.append(attr_name)
    239239        for attr_name in toRemove:
  • coopr.pyomo/trunk/coopr/pyomo/transform/transformation.py

    r2805 r5757  
    11from coopr.pyomo import *
    22from pyutilib.component.core import implements, Plugin, Interface
    3 from coopr.pyomo.base import IModelTransformation, _VarBase
     3from coopr.pyomo.base import IModelTransformation
    44
    55__all__ = ["Transformation"]
Note: See TracChangeset for help on using the changeset viewer.