Changeset 2070


Ignore:
Timestamp:
Dec 30, 2009 12:45:45 AM (10 years ago)
Author:
wehart
Message:

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

........

r1974 | wehart | 2009-12-06 17:20:56 -0700 (Sun, 06 Dec 2009) | 2 lines


Updating PyPI categories

........

r1975 | wehart | 2009-12-07 16:47:43 -0700 (Mon, 07 Dec 2009) | 2 lines


Bug fix. The ProductExpression? was not correctly testing for constant-ness.

........

r1976 | wehart | 2009-12-08 16:49:14 -0700 (Tue, 08 Dec 2009) | 3 lines


A hack to make the default 'dimen' be 1 when computing the
ndim for a index set.

........

r1990 | jwatson | 2009-12-12 13:29:45 -0700 (Sat, 12 Dec 2009) | 3 lines


Added code to throw a ValueError? exception when attempting to output a CPLEX LP format file with a variable "e" - this causes nothing but confusion for solver parsers, who attempt to interpret the "e" as the e in numeric values expressed in scientific notation. Ultimately, this could be avoided by mapping the "e" to some other constant string, and then inverse-mapping when the solution is obtained - but this will require a more fully-featured bi-directional mapping capability.

........

r1992 | wehart | 2009-12-12 23:33:59 -0700 (Sat, 12 Dec 2009) | 26 lines


A rework of component management in Pyomo. This was initially
started as an effort to add the component activate()/deactivate()
methods. However, this naturally led to a rework of
component management that I've been planning for a while.


Component types are now managed with the natural class types (e.g.
Var for variables, rather than _VarBase). Further, the components
should now be accessed with model methods: components() or active_components().
For example,


model.components(Var)


returns a dictionary of the Var components.


NOTE:


  1. I suspect that this commit will break PySP to the extent that it uses the model._component data structure.


  1. This adds support for component-level deactivation, but not component index deactivation.


  1. I haven't added unit tests to validate this type of deactivation, but all of the standard unit tests work.

........

r1993 | wehart | 2009-12-12 23:57:00 -0700 (Sat, 12 Dec 2009) | 31 lines


Adding support for component index deactivation. Again,
this isn't tested except that all the normal tests pass.


This supports the following semantics:


model.C = Constraint(model.A)


model.C[index].deactivate()


Note that the current implementation requires the user to
query whether each index is active:


if model.C[index].active:

# Do something


I could have alternatively changed the iterator for the
constraint, but then that could mask the existence of a
constraint, making it difficult to reactivate.


Finally, note that this activation mechanism is independent
of the component level activation/deactivation:


model.C.deactivate()
# All C constraints are deactivated
model.C[index].deactivate
# You can still manipulate the C constraint
model.C.activate()
# Now, the C constraint is active, except for the '
# 'index' constraint

........

r1994 | wehart | 2009-12-13 11:01:57 -0700 (Sun, 13 Dec 2009) | 10 lines


Initial setup of the PyomoModel?._name_conmap data structure.
I've set this up to load data, but it currently does not correctly load
data for range constraints.


Misc rework of tests, segregating model/var/objective/constraint tests.


Added some tests for activation/deactivation of constraints. This
required some changes to the 'display()' methods in Pyomo, to
hide constraints that are deactivated.

........

r1995 | wehart | 2009-12-13 11:32:57 -0700 (Sun, 13 Dec 2009) | 2 lines


Adding a 'create_name' function that simplifies the setup of indexed component names.

........

r1996 | wehart | 2009-12-13 11:39:45 -0700 (Sun, 13 Dec 2009) | 4 lines


JP's benders example with some misc edits.


This runs, though I'm not sure it runs correctly.

........

r1999 | wehart | 2009-12-14 08:18:45 -0700 (Mon, 14 Dec 2009) | 2 lines


Python 2.5 portability fixes.

........

r2000 | wehart | 2009-12-14 09:13:52 -0700 (Mon, 14 Dec 2009) | 2 lines


Bug fix.

........

r2001 | wehart | 2009-12-15 22:22:06 -0700 (Tue, 15 Dec 2009) | 7 lines


Adding a plugin interface for model transformations.
This can be accessed in a generic manner, using the
apply_transformation() function:


new_model = apply_transformation('relax_integrality', old_model)

........

r2002 | wehart | 2009-12-15 22:34:06 -0700 (Tue, 15 Dec 2009) | 3 lines


Adding some tests to validate various types of output that
are expected from apply_transformation().

........

r2004 | wehart | 2009-12-16 20:19:50 -0700 (Wed, 16 Dec 2009) | 11 lines


  1. Added --model-name option, which allos the specification of an object other than 'model' for the model that is optimized.


  1. Added support for create_model(), which accepts a dictionary or pyutilib.misc.Container object containing the options specified with the --model-options option. This function returns a model that is optimized.


  1. Added the 'errors' debugging mode. When specified, exceptions dump a traceback. Otherwise, exceptions are caught and only the exception string is printed.

........

r2005 | wehart | 2009-12-16 23:47:41 -0700 (Wed, 16 Dec 2009) | 5 lines


Adding tests to exercise the Pyomo command-line.


Reworked error management a bit.
Updated output of virtual sets.

........

r2008 | wehart | 2009-12-17 14:21:41 -0700 (Thu, 17 Dec 2009) | 4 lines


Adding helper functions for accessing constraints, variables and objectives.


Adding a method for getting the model solution, as a vector.

........

r2009 | wehart | 2009-12-17 14:22:36 -0700 (Thu, 17 Dec 2009) | 3 lines


Adding an 'index' attribute to variable value objects, which
allows a variable object to find itself in the variable indexes.

........

r2010 | wehart | 2009-12-17 14:23:58 -0700 (Thu, 17 Dec 2009) | 2 lines


Adding a transformation for eliminating fixed variables.

........

r2011 | wehart | 2009-12-17 15:50:59 -0700 (Thu, 17 Dec 2009) | 5 lines


A change in semantics for setting up dimen and dim. This change requires
that users specify dimen in situtations where it is not obvious from the
component declaration. For example, if you initialize from a function, then you'll need
to specify dimen if the function returns n-tuples.

........

r2012 | jwatson | 2009-12-17 16:00:00 -0700 (Thu, 17 Dec 2009) | 3 lines


Some fixes to Benders example, identified when baseline-ing AMPL against Pyomo in the reduced-costs and duals departments.

........

r2015 | wehart | 2009-12-17 19:33:08 -0700 (Thu, 17 Dec 2009) | 2 lines


Adding tests to confirm that set/index dimensionality checks work as expected.

........

r2016 | wehart | 2009-12-17 19:48:51 -0700 (Thu, 17 Dec 2009) | 2 lines


Adding helper functions that denote the number of constraints, variables, etc.

........

r2017 | wehart | 2009-12-17 21:34:38 -0700 (Thu, 17 Dec 2009) | 2 lines


Preliminary rework of the amplbook2 examples.

........

r2018 | wehart | 2009-12-17 21:59:26 -0700 (Thu, 17 Dec 2009) | 2 lines


Bug fix due to updates in results object.

........

r2020 | wehart | 2009-12-17 22:25:59 -0700 (Thu, 17 Dec 2009) | 2 lines


Misc updates. Cleaning out old models that are no longer used. Simplifying some test problems.

........

r2021 | wehart | 2009-12-18 09:35:15 -0700 (Fri, 18 Dec 2009) | 2 lines


Misc rework of exception management within Pyomo.

........

r2022 | wehart | 2009-12-18 09:47:09 -0700 (Fri, 18 Dec 2009) | 2 lines


Removing debugging IO

........

r2023 | jwatson | 2009-12-18 16:38:37 -0700 (Fri, 18 Dec 2009) | 3 lines


Pyomo Benders example prettification and cleanup.

........

r2024 | wehart | 2009-12-21 10:22:03 -0700 (Mon, 21 Dec 2009) | 2 lines


Added check to avoid printing an objective with an empty linear sum.

........

r2025 | wehart | 2009-12-21 23:23:57 -0700 (Mon, 21 Dec 2009) | 20 lines


Reworking how components interact with models. Now, components can
only be initialized using data from the model that they are associated with.
Thus, models and components are tightly coupled. This allows the following
syntax:


model.x = Param(model.A)
model.construct()


The construction process uses the model data that is associated with the
parameter. Also, this commmit allows models to be components of another
model:


m1=Model()
m2=Model()
m2.m1 = m1


Note, however, that model construct is required to be done separately. When
model m2 is constructed, the m1 component is not constructed.

........

r2027 | wehart | 2009-12-22 07:24:38 -0700 (Tue, 22 Dec 2009) | 3 lines


Simplified the syntax for adding a constraint to a
Constraint object.

........

r2028 | jwatson | 2009-12-22 09:50:49 -0700 (Tue, 22 Dec 2009) | 3 lines


Changed some references to "._model" to the new+improved ".model".

........

r2031 | jwatson | 2009-12-22 14:56:55 -0700 (Tue, 22 Dec 2009) | 3 lines


More prettification of the Benders example.

........

r2032 | jwatson | 2009-12-22 15:30:46 -0700 (Tue, 22 Dec 2009) | 3 lines


More readability improvements to the Benders example.

........

r2036 | jwatson | 2009-12-22 21:31:23 -0700 (Tue, 22 Dec 2009) | 3 lines


Added "--solver-mipgap" option to the pyomo script, mirroring recent useful updates to the PH script.

........

r2044 | wehart | 2009-12-26 11:58:59 -0700 (Sat, 26 Dec 2009) | 2 lines


Adding a 'random' solver.

........

r2045 | wehart | 2009-12-26 12:23:44 -0700 (Sat, 26 Dec 2009) | 2 lines


Bug fix to 'random' solver

........

r2046 | wehart | 2009-12-26 16:13:07 -0700 (Sat, 26 Dec 2009) | 4 lines


Resolving #3970. When a parameter is specified with a default
value, we should be able to refer to its index set directly, since
all values are tacitly defined.

........

r2049 | wehart | 2009-12-26 17:06:22 -0700 (Sat, 26 Dec 2009) | 2 lines


coopr.pyomo baseline changes due to change in GLPK output.

........

r2050 | wehart | 2009-12-26 23:42:43 -0700 (Sat, 26 Dec 2009) | 3 lines


Adding support for denoting constraint inequalities as 'strict'. Adding
tests to verify that strict inequalities are recognized.

........

r2051 | wehart | 2009-12-27 00:22:44 -0700 (Sun, 27 Dec 2009) | 2 lines


Bug fix in the NEWGAP computation.

........

r2052 | wehart | 2009-12-27 00:29:01 -0700 (Sun, 27 Dec 2009) | 4 lines


Updating to variable naming. Special symbols are mapped to
a name that contains _Q#_, where # the ASCII decimal representation for
that symbol.

........

r2053 | wehart | 2009-12-27 00:50:39 -0700 (Sun, 27 Dec 2009) | 4 lines


Adding ability to load a list or tuple of values into a
Pyomo model. These are loaded into the variables in the
order in which the variables are identified.

........

r2054 | wehart | 2009-12-28 14:07:19 -0700 (Mon, 28 Dec 2009) | 3 lines


Pleliminary commit for a capability that can extract a canonical
representation for expressions.

........

r2055 | wehart | 2009-12-28 14:15:54 -0700 (Mon, 28 Dec 2009) | 2 lines


Some additional documentation.

........

r2056 | wehart | 2009-12-28 21:18:44 -0700 (Mon, 28 Dec 2009) | 2 lines


Fixes and tests for generating canonical representations.

........

r2057 | wehart | 2009-12-28 23:54:40 -0700 (Mon, 28 Dec 2009) | 2 lines


Misc cleanup of debugging facilities.

........

r2063 | wehart | 2009-12-29 14:56:35 -0700 (Tue, 29 Dec 2009) | 2 lines


Reformatting this example to make it narrower.

........

r2064 | wehart | 2009-12-29 15:16:16 -0700 (Tue, 29 Dec 2009) | 4 lines


Misc rework of variable presolving. Now, model
statistics are stored in a more obvious location, and using more
verbose names.

........

r2066 | jwatson | 2009-12-29 20:54:59 -0700 (Tue, 29 Dec 2009) | 3 lines


Removed some TBD notes in the Benders example, and checked in the full benders script (a debug version was committed initially, that only dealt with iteration 1). This version replicates, to within precision, the AMPL execution. Should terminate in 5 master iterations.

........

Location:
coopr.pyomo/stable/2.1
Files:
5 deleted
41 edited
36 copied

Legend:

Unmodified
Added
Removed
  • coopr.pyomo/stable/2.1

  • coopr.pyomo/stable/2.1/coopr/pyomo/__init__.py

    r1768 r2070  
    1616from base import *
    1717import base.pyomo as pyomo
     18from expr import *
    1819import io
    1920from components import *
    2021import presolve
    2122import coopr.opt
     23import transform
    2224
    2325pyutilib.plugin.core.PluginGlobals.pop_env()
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/PyomoModel.py

    r1972 r2070  
    1818import pyutilib.plugin.core
    1919from pyutilib.math import *
    20 from pyutilib.misc import quote_split, tuplize
     20from pyutilib.misc import quote_split, tuplize, Container
    2121
    2222from coopr.opt import ProblemFormat, ResultsFormat, guess_format
     
    2626import pyomo
    2727
     28from component import Component
    2829from sets import Set, _ProductSet, _SetContainer, _BaseSet
    2930from rangeset import RangeSet
    30 from var import _VarBase
    31 from constraint import Objective, Constraint
    32 from param import _ParamBase
    33 
    34 
    35 class Model(object):
     31from var import Var
     32from constraint import Objective, Constraint, ConstraintData
     33from param import Param
     34
     35
     36class Model(Component):
    3637    """
    3738    The MINLP model that will be analyzed by the user.
     
    4344    def __init__(self):
    4445        """Constructor"""
     46        Component.__init__(self, ctype=Model)
    4547        #
    4648        # Define component dictionary: component type -> instance
     
    5456        #
    5557        self._declarations=[]
    56         # the _name_varmap is assigned when the problem definition
     58        # the _name_varmap and _name_conmap dictionarys are assigned when
     59        # the problem definition
    5760        # file is written, i.e., via the write() command. intent
    5861        # is to map names that will be coming back from a solver
    5962        # into Pyomo variables. Values are of type _VarValue.
    6063        self._name_varmap={}
     64        self._name_conmap={}
     65        self._name_objmap={}
    6166        self.name="unknown"
    6267        self.tmpctr=0
    6368        self._varctr=0
    64         #self._varmap={}
    6569        self._presolvers = ["simple_presolver"]
    6670        #
     
    7074        self._con = {}
    7175        self._obj = {}
    72 
     76        #
     77        # Model statistics
     78        #
     79        self.statistics = Container()
     80
     81    def components(self, ctype=None):
     82        if ctype is None:
     83            return self._component
     84        if ctype in self._component:
     85             return self._component[ctype]
     86        raise KeyError, "Unknown component type: %s" % str(ctype)
     87
     88    def nvariables(self):
     89        return self.statistics.number_of_variables
     90
     91    def variable(self, name):
     92        if isinstance(name,basestring):
     93            return self._name_varmap[name]
     94        else:
     95            return self._var[name]
     96
     97    def variables(self):
     98        return self._name_varmap
     99
     100    def nconstraints(self):
     101        return self.statistics.number_of_constraints
     102
     103    def constraint(self, name):
     104        if isinstance(name,basestring):
     105            return self._name_conmap[name]
     106        else:
     107            return self._con[name]
     108
     109    def constraints(self):
     110        return self._name_conmap
     111
     112    def nobjectives(self):
     113        return self.statistics.number_of_objectives
     114
     115    def objective(self, name):
     116        if isinstance(name,basestring):
     117            return self._name_objmap[name]
     118        else:
     119            return self._obj[name]
     120
     121    def objectives(self):
     122        return self._name_objmap
     123
     124
     125    def active_components(self, _ctype=None):
     126        tmp = {}
     127        if _ctype is None:
     128            for ctype in self._component:
     129                tmp[ctype]={}
     130        elif _ctype in self._component:
     131            tmp[_ctype]={}
     132        else:
     133            raise KeyError, "Unknown component type: %s" % str(ctype)
     134        for ctype in tmp:
     135            for name in self._component[ctype]:
     136                comp = self._component[ctype][name]
     137                if comp.active:
     138                    tmp[ctype][name] = comp
     139        if not _ctype is None:
     140            return tmp[_ctype]
     141        print "ACTIVE",tmp
     142        return tmp
    73143
    74144    def num_used_variables(self):
     
    125195            i += 1
    126196
    127     def _setattr_exec(self,name,val,item):
     197    def _setattr_exec(self,name,val):
    128198        self._clear_attribute(name)
    129199        val.name=name
    130200        self._add_temporary_set(val)
    131         val.model=self
    132         self._component[item][name]=val
     201        self._component[val.type()][name]=val
    133202        self._declarations.append(val)
    134203        self.__dict__[name]=val
     204        if not val.type() is Model:
     205            val.model=self
    135206
    136207    def __setattr__(self,name,val):
     
    143214            # If this is a component type, then simply set it
    144215            #
    145             if type(val) in self._component:
    146                 self._setattr_exec(name,val, type(val))
     216            if isinstance(val,Component):
     217                self._setattr_exec(name,val)
    147218                return
    148             #
    149             # Otherwise, see if this is an instance of a component type
    150             #
    151             for item in self._component:
    152                 #print "HERE z",name,val,item,isinstance(val,item)
    153                 if isinstance(val,item):
    154                     self._setattr_exec(name,val, item)
    155                     return
    156 
    157         #if name in self.__dict__.keys() and isinstance(self.__dict__[name],NumericValue):
    158             #tmpval = value(val)
    159             #if tmpval is None:
    160                 #raise ValueError, "Bad numeric value"
    161             #self.__dict__[name].value = tmpval
    162         #else:
    163             #self.__dict__[name]=val
    164 
    165219        #
    166220        # Try to set the value.  This may fail if the attribute does not already
     
    169223        # we raise.  Otherwise, this is an object that we need to set directly.
    170224        #
    171         #print "HERE X",name
    172225        try:
    173             #print "HERE",self.__dict__[name].name,type(self.__dict__[name]),type(val)
    174226            self.__dict__[name].set_value(val)
    175227        except ValueError, e:
     
    179231
    180232
    181     def create(self,filename=None):
     233    def create(self, filename=None, name=None):
    182234        """
    183235        Create a concrete instance of this Model, possibly using data
     
    187239        instance.load(filename)
    188240        instance.presolve()
     241        if not name is None:
     242            instance.name=name
    189243        return instance
    190244
     
    215269    def solution(self):
    216270        """Return the solution"""
    217         pass                            #pragma:nocover
    218 
    219 
    220     def load(self,arg):
     271        soln = []
     272        for i in range(len(self._var)):
     273            soln.append( self._var[i].value )
     274        return soln
     275
     276
     277    def load(self, arg):
    221278        """ Load the model with data from a file or a Solution object """
    222279        if arg is None or type(arg) is str:
     
    237294           self._load_solution(arg)
    238295           return True
     296        elif type(arg) in (tuple, list):
     297           self._load_solution(arg)
     298           return True
    239299        else:
    240300           raise ValueError, "Cannot load model with object of type "+str(type(arg))
     
    260320        #print "HERE _load_model_data",self._declarations
    261321        for declaration in self._declarations:
    262           tmp = declaration.name
    263           if tmp in modeldata._default.keys():
    264              if isinstance(declaration,_BaseSet):
    265                 declaration.default = self._tuplize(modeldata._default[tmp],declaration)
    266              else:
    267                 declaration.default = modeldata._default[tmp]
    268           if tmp in modeldata._data.keys():
    269              #print "HERE", declaration.name, str(declaration.dimen),modeldata._data[tmp]
    270              if isinstance(declaration,_BaseSet):
    271                 data = self._tuplize(modeldata._data[tmp],declaration)
    272              else:
    273                 data = modeldata._data[tmp]
    274           else:
    275              data = None
    276           if pyomo.debug("generate"):           #pragma:nocover
    277              print "About to generate '"+declaration.name+"' with data: "+str(data)
    278              self.pprint()
    279           declaration._construct(self,data)
    280           try:
    281             ##declaration._construct(self,data)
    282             pass
    283           except Exception, err:
    284             print "Error constructing declaration "+str(declaration.name)+" from data="+str(data)
    285             print "ERROR: "+str(err)
    286             raise err
    287 
    288     def _load_solution(self,soln, symbol_map=None):
     322            if declaration.type() is Model:
     323                continue
     324            tmp = declaration.name
     325            if tmp in modeldata._default.keys():
     326                if declaration.type() is Set:
     327                    declaration.default = self._tuplize(modeldata._default[tmp],declaration)
     328                else:
     329                    declaration.default = modeldata._default[tmp]
     330            if tmp in modeldata._data.keys():
     331                #print "HERE", declaration.name, str(declaration.dimen),modeldata._data[tmp]
     332                if declaration.type() is Set:
     333                    data = self._tuplize(modeldata._data[tmp],declaration)
     334                else:
     335                    data = modeldata._data[tmp]
     336            else:
     337                data = None
     338            if pyomo.debug("generate"):           #pragma:nocover
     339                print "About to generate '"+declaration.name+"' with data: "+str(data)
     340                self.pprint()
     341            declaration.construct(data)
     342            try:
     343                pass
     344            except Exception, err:
     345                print "Error constructing declaration "+str(declaration.name)+" from data="+str(data)
     346                print "ERROR: "+str(err)
     347                raise err
     348
     349    def _load_solution(self, soln, symbol_map=None):
    289350        """
    290351        Load a solution.
    291352        """
     353        # Load list or tuple into the variables, based on their order
     354        if type(soln) in (list, tuple):
     355            if len(soln) != len(self._var):
     356                raise ValueError, "Attempting to load a list/tuple solution into a model, but its length is %d while the model has %d variables" % (len(soln), len(self._var))
     357            for i in range(len(soln)):
     358                self._var[i].value = soln[i]
     359            return
     360        #
     361        # Load variable data
     362        #
    292363        for name in soln.variable:
    293364          #
     
    309380                raise TypeError, "Variable '"+name+"' in model '"+self.name+"' is currently fixed - new value is not expected in solution"
    310381
    311              # the value is always present in any legal solution.
    312              self._name_varmap[name].value = soln.variable[name].value
    313 
    314              # the reduced-cost might be present, depending on what the solver is reporting.
    315              if hasattr(soln.variable[name],"rc"):
    316                 self._name_varmap[name].rc = soln.variable[name].rc
     382             #print "HERE",soln.variable[name].keys()
     383             for _key in soln.variable[name].keys():
     384                key = _key[0].lower() + _key[1:]
     385                if key == 'value':
     386                    self._name_varmap[name].value = soln.variable[name].value
     387                elif not key == 'id':
     388                    setattr(self._name_varmap[name], key, getattr(soln.variable[name], _key))
     389        #
     390        # Load constraint data
     391        #
     392        for name in soln.constraint:
     393             #
     394             # This is a hack
     395             #
     396             if name.endswith('ONE_VAR_CONSTANT'):
     397                continue
     398             if symbol_map is not None:
     399                name = symbol_map[name]
     400             #
     401             # This is a hack.  Is there a standard convention for constraint
     402             # names that we can apply to all data formats?
     403             #
     404             if name[0:2] == 'c_':
     405                _name = name[4:-1]
     406             #print "HERE",_name
     407             if _name not in self._name_conmap:
     408                names=""
     409                raise KeyError, "Constraint name '"+name+"' is not in model "+self.name+".  Valid constraint names: "+str(self._name_conmap.keys())
     410             if not isinstance(self._name_conmap[_name],ConstraintData):
     411                raise TypeError, "Constraint '"+name+"' in model '"+self.name+"' is type "+str(type(self._name_conmap[_name]))
     412
     413             #print "HERE",soln.constraint[name].keys()
     414             for _key in soln.constraint[name].keys():
     415                key = _key[0].lower() + _key[1:]
     416                if key == 'value':
     417                    self._name_conmap[name].value = soln.constraint[name].value
     418                elif not key == 'id':
     419                    setattr(self._name_conmap[_name], key, getattr(soln.constraint[name], _key))
    317420
    318421    def write(self,filename=None,format=ProblemFormat.cpxlp):
     
    352455        # expected by a user.
    353456        #
    354         items = [_BaseSet, RangeSet, _ParamBase, _VarBase, Objective, Constraint]
     457        items = [Set, RangeSet, Param, Var, Objective, Constraint]
    355458        for item in pyutilib.plugin.core.ExtensionPoint(IModelComponent):
    356459            if not item in items:
     
    364467            # NOTE: these conditional checks should not be hard-coded.
    365468            #
    366             if item.__name__ == "_BaseSet":
    367                 print >>ostream, len(keys), "Set Declarations"
    368             elif item.__name__ == "_ParamBase":
    369                 print >>ostream, len(keys), "Param Declarations"
    370             elif item.__name__ == "_VarBase":
    371                 print >>ostream, len(keys), "Var Declarations"
    372             else:
    373                 print >>ostream, len(keys), item.__name__+" Declarations"
     469            print >>ostream, len(keys), item.__name__+" Declarations"
    374470            for key in keys:
    375471                self._component[item][key].pprint(ostream)
     
    384480
    385481
    386     def display(self,filename=None, ostream=None):
     482    def display(self, filename=None, ostream=None):
    387483        """
    388484        Print the Pyomo model in a verbose format.
     
    398494        print >>ostream, ""
    399495        print >>ostream, "  Variables:"
    400         if len(self._component[_VarBase]) == 0:
    401            print >>ostream, "    None"
    402         else:
    403            for ndx in self._component[_VarBase]:
    404              self._component[_VarBase][ndx].display(prefix="    ",ostream=ostream)
     496        VAR = self.active_components(Var)
     497        if len(VAR) == 0:
     498            print >>ostream, "    None"
     499        else:
     500            for ndx in VAR:
     501                VAR[ndx].display(prefix="    ",ostream=ostream)
    405502        print >>ostream, ""
    406503        print >>ostream, "  Objectives:"
    407         if len(self._component[Objective]) == 0:
    408            print >>ostream, "    None"
    409         else:
    410            for ndx in self._component[Objective]:
    411              self._component[Objective][ndx].display(prefix="    ",ostream=ostream)
     504        OBJ = self.active_components(Objective)
     505        if len(OBJ) == 0:
     506            print >>ostream, "    None"
     507        else:
     508            for ndx in OBJ:
     509                OBJ[ndx].display(prefix="    ",ostream=ostream)
    412510        print >>ostream, ""
     511        CON = self.active_components(Constraint)
    413512        print >>ostream, "  Constraints:"
    414         if len(self._component[Constraint]) == 0:
    415            print >>ostream, "    None"
    416         else:
    417            for ndx in self._component[Constraint]:
    418              self._component[Constraint][ndx].display(prefix="    ",ostream=ostream)
    419 
     513        if len(CON) == 0:
     514            print >>ostream, "    None"
     515        else:
     516            for ndx in CON:
     517                CON[ndx].display(prefix="    ",ostream=ostream)
     518
     519ComponentRegistration("Model", Model, "Model objects can be used as a component of other models.")
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/component.py

    r1972 r2070  
    11
    2 from sets import _BaseSet, Set
     2class Component(object):
    33
    4 class ComponentBase(object):
     4    def __init__(self, ctype):
     5        self.active=True
     6        self._type=ctype
     7        self.model=None
    58
    6     def __init__(self, *args):
    7         self._ndim=0
    8         self._index_set=None
    9         self._index=[]
    10         if len(args) == 0:
    11             self._index=[None]
    12         elif len(args) == 1:
    13             if isinstance(args[0],_BaseSet):
    14                 self._index=args[0]
    15             elif isinstance(args[0],ComponentBase):
    16                     raise ValueError, "Cannot index a component with a non-set component"
    17             else:
    18                 self._index=Set(initialize=args[0])
    19         else:
    20             tmp = []
    21             for arg in args:
    22                 if isinstance(arg,_BaseSet):
    23                     tmp.append(arg)
    24                 elif isinstance(arg,ComponentBase):
    25                     raise ValueError, "Cannot index a component with a non-set component"
    26                 else:
    27                     tmp.append( Set(initialize=arg) )
    28             self._index_set=tuple(tmp)
    29         self._compute_dim()
     9    def activate(self):
     10        self.active=True
    3011
    31     def _compute_dim(self):
    32         if self._ndim is None or self._ndim is 0:
    33             if self._index_set is None:
    34                 if type(self._index) is list:
    35                     self._ndim = 0
    36                 else:
    37                     self._ndim = self._index.dimen
    38             else:
    39                 self._ndim = 0
    40                 for iset in self._index_set:
    41                     if iset.dimen is None:
    42                         self._ndim = None
    43                         return
    44                     self._ndim += iset.dimen
     12    def deactivate(self):
     13        self.active=False
    4514
     15    def type(self):
     16        return self._type
     17
     18    def construct(self, data=None):
     19        pass
     20
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/constraint.py

    r1972 r2070  
    1212
    1313from numvalue import *
     14from numvalue import create_name
    1415from expr import *
    1516from plugin import ComponentRegistration
    1617import pyomo
    1718from var import Var, _VarValue
    18 from component import ComponentBase
     19from indexed_component import IndexedComponent
    1920from sets import _BaseSet
    2021import pyutilib.misc
     
    3233        self.label = None
    3334        self.id = -1
     35        self.active = True
    3436
    3537    def __call__(self, exception=True):
     
    3840        return self.expr()
    3941
    40 
    41 class Objective(NumericValue, ComponentBase):
     42    def activate(self):
     43        self.active=True
     44
     45    def deactivate(self):
     46        self.active=False
     47
     48
     49class Objective(NumericValue, IndexedComponent):
    4250    """An object that defines a objective expression"""
    4351
     
    4654           expression
    4755        """
    48         ComponentBase.__init__(self, *args)
     56        tkwd = {'ctype':Objective}
     57        IndexedComponent.__init__(self, *args, **tkwd)
    4958        tmpname="unknown"
    5059        tmpsense = minimize
     
    5766          if key == "name":
    5867             tmpname=kwd[key]
     68          elif key == "doc":
     69             self.doc=kwd[key]
    5970          elif key == "rule":
    6071             tmprule = kwd[key]
     
    7283        if len(self._data) == 0:
    7384            return None
    74         if None in self._index:
     85        if None in self._data:
    7586            if self._data[None].expr is None:
    7687                return None
     
    8697
    8798    def keys(self):
    88         return self._index
     99        return self._data.keys()
     100        #return self._index
    89101
    90102    def __contains__(self,ndx):
    91         return ndx in self._index
     103        return ndx in self._data
     104        #return ndx in self._index
    92105
    93106    def __getitem__(self,ndx):
     
    101114
    102115    def __iter__(self):
    103         return self._index.__iter__()
     116        return self._data.keys().__iter__()
     117        #return self._index.__iter__()
    104118
    105119    def _apply_rule(self,arg,ndx):
     
    111125        return tmp
    112126
    113     def _construct(self, model, data):
    114         #
    115         # Update the index set dimension
    116         #
    117         self._compute_dim()
    118         ##print "HERE",self.rule,self._ndim
     127    def construct(self, data=None):
    119128        if self.rule is not None:
    120129           if self._ndim==0:
    121               tmp = self._apply_rule((model,),None)
     130              tmp = self._apply_rule((self.model,),None)
    122131              if not tmp is None and not (type(tmp) in [int,long,float] and tmp == 0):
    123132                 self._data[None].expr = tmp
     
    129138                else:
    130139                   tmp = [val]
    131                 tmp.append(model)
     140                tmp.append(self.model)
    132141                tmp = tuple(tmp)
    133142                tmp = self._apply_rule(tmp,val)
    134143                if not tmp is None and not (type(tmp) in [int,long,float] and tmp == 0):
    135                    self._data[val] = ObjectiveData(expr=tmp, name=_name+"["+str(val)+"]")
    136            self._index = self._data.keys()
     144                   self._data[val] = ObjectiveData(expr=tmp, name=create_name(_name,val))
     145           #self._index = self._data.keys()
    137146               
    138147        for val in self._data:
    139148            if self._data[val].expr is not None:
    140                 self._data[val].expr = self._data[val].expr.simplify(model)
     149                self._data[val].expr = self._data[val].expr.simplify(self.model)
    141150
    142151    def pprint(self, ostream=None):
     
    168177        else:
    169178           for key in self._data:
     179             if not self._data[key].active:
     180                continue
    170181             val = self._data[key].expr(exception=False)
    171182             print >>ostream, prefix+"  "+str(key)+" : "+str(val)
     
    178189        self._equality = False
    179190        self.lower = None
     191        self.lower_ineq_strict = None
    180192        self.body = None
    181193        self.upper = None
     194        self.upper_ineq_strict = None
    182195        self.label = None
    183196        self.id = None
     197        self.active = True
    184198
    185199    def __call__(self, exception=True):
     
    188202        return self.body()
    189203
    190 
    191 class Constraint(NumericValue, ComponentBase):
     204    def activate(self):
     205        self.active=True
     206
     207    def deactivate(self):
     208        self.active=False
     209
     210
     211class Constraint(NumericValue, IndexedComponent):
    192212    """An object that defines a objective expression"""
    193213
     
    196216           expression
    197217        """
    198         ComponentBase.__init__(self, *args)
     218        tkwd = {'ctype':Constraint}
     219        IndexedComponent.__init__(self, *args, **tkwd)
    199220        tmpname="unknown"
    200221        tmprule=None
    201222        self._data = {}
    202         if args == ():
    203            self._data[None]=ConstraintData()
     223        #if args == ():
     224        #   self._data[None]=ConstraintData()
    204225        for key in kwd.keys():
    205226          if key == "name":
    206227             tmpname=kwd[key]
     228          elif key == "doc":
     229             self.doc=kwd[key]
    207230          elif key == "rule":
    208231             tmprule = kwd[key]
     
    213236            self._data[None].name=tmpname
    214237        self.rule = tmprule
    215         self._model = None
    216238
    217239    def __call__(self, exception=True):
    218240        if len(self._data) == 0:
    219241            return None
    220         if None in self._index:
     242        if None in self._data:
    221243            if self._data[None].body is None:
    222244                return None
     
    232254
    233255    def keys(self):
    234         return self._index
     256        return self._data.keys()
     257        #return self._index
    235258
    236259    def __contains__(self,ndx):
    237         return ndx in self._index
     260        return ndx in self._data
     261        #return ndx in self._index
    238262
    239263    def __getitem__(self,ndx):
     
    247271
    248272    def __iter__(self):
    249         return self._index.__iter__()
    250 
    251     def _construct(self, model, data):
    252         self._model = model
    253         #
    254         # Update the index set dimension
    255         #
    256         self._compute_dim()
     273        return self._data.keys().__iter__()
     274
     275    def construct(self, data=None):
    257276
    258277        if pyomo.debug("verbose") or pyomo.debug("normal"):     #pragma:nocover
    259278           print "Construcing constraint "+self.name
    260279        if self.rule is None:
    261            self._index = []
    262280           self._data={}
    263281           return
    264         constructed_indices=[]
    265282        #
    266283        # Local variables for code optimization
    267284        #
    268         _self_name=self.name
    269285        _self_rule = self.rule
    270286        #
     
    272288            if pyomo.debug("verbose"):                            #pragma:nocover
    273289                print "   Constructing constraint indices with rule that returns a dictionary"
    274             constraints = _self_rule(model)
     290            constraints = _self_rule(self.model)
    275291            for val in constraints:
    276292                if val not in self._index:
    277293                    raise IndexError, "The index "+str(val)+" generated by the constructor rule is not valid"
    278                 constructed_indices.append(val)
    279                 self._initialize_constraint(val, constraints[val], model, _self_name)
     294                ##constructed_indices.append(val)
     295                self.add(val, constraints[val])
    280296        else:
    281297            for val in self._index:
     
    283299                    print "   Constructing constraint index "+str(val)
    284300                if val is None:
    285                     expr = _self_rule(model)
     301                    expr = _self_rule(self.model)
    286302                    if expr is None or (type(expr) in [int,long,float] and expr == 0):
    287303                        continue
     
    291307                    else:
    292308                        tmp=[val]
    293                     tmp.append(model)
     309                    tmp.append(self.model)
    294310                    tmp=tuple(tmp)
    295311                    expr = _self_rule(*tmp)
    296312                    if expr is None or (type(expr) in [int,long,float] and expr == 0):
    297313                        continue
    298                 constructed_indices.append(val)
    299                 self._initialize_constraint(val, expr, model, _self_name)
    300         self._index=constructed_indices
    301 
    302     def _initialize_constraint(self, val, expr, model, _name):
    303         # val: the constraint index (should probably be renamed)
     314                ##constructed_indices.append(val)
     315                self.add(val, expr)
     316        #self._index=constructed_indices
     317
     318    def add(self, index, expr):
     319        # index: the constraint index (should probably be renamed)
    304320        # expr: the constraint expression
    305321        # model: the parent model
    306         # _name: the name of the constraint
    307322
    308323        #
     
    316331        #
    317332        if isinstance(expr,Expression) is False and isinstance(expr,tuple) is False and isinstance(expr, list) is False:
    318            raise ValueError, "Non-expression object of "+str(type(expr))+" supplied to initialize constraint="+_name+", index="+str(val)
     333           raise ValueError, "Non-expression object of "+str(type(expr))+" supplied to initialize constraint="+self.name+", index="+str(index)
    319334           
    320335        #
     
    323338        #
    324339        _self_data = self._data
    325         _self_data[val] = ConstraintData(name=_name+"["+str(val)+"]")
     340        _self_data[index] = ConstraintData(name=create_name(self.name,index))
    326341        if not type(expr) in [tuple,list]:
    327342            _expr_args0 = expr._args[0]
     
    337352        #
    338353        if isinstance(expr,_EqualToExpression):
    339             _self_data[val]._equality = True
     354            _self_data[index]._equality = True
    340355            if is_constant(_expr_args1):
    341                 tpl = [ _expr_args1,_expr_args0,_expr_args1 ]
     356                tpl = [ _expr_args1,_expr_args0,_expr_args1, False, False ]
    342357            elif is_constant(_expr_args1):
    343                 tpl = [ _expr_args0,_expr_args1,_expr_args0 ]
     358                tpl = [ _expr_args0,_expr_args1,_expr_args0, False, False ]
    344359            else:
    345                 tpl = [ 0.0 , _expr_args0 - _expr_args1, 0.0 ]
     360                tpl = [ 0.0 , _expr_args0 - _expr_args1, 0.0, False, False ]
    346361        #
    347362        # If the constructor rule returns a greater-than expression, then
     
    353368            if isinstance(_expr_args0,_GreaterThanExpression) or\
    354369                    isinstance(_expr_args0,_GreaterThanOrEqualExpression):
    355                 tpl = [ _expr_args1, _expr_args0._args[1], _expr_args0._args[0] ]
     370                tpl = [ _expr_args1, _expr_args0._args[1], _expr_args0._args[0],
     371                        isinstance(expr,_GreaterThanExpression), isinstance(_expr_args0,_GreaterThanExpression) ]
    356372
    357373            elif isinstance(_expr_args0,_LessThanExpression) or\
    358374                    isinstance(_expr_args0,_LessThanOrEqualExpression):
    359                 tpl = [ _expr_args1, _expr_args0._args[0], _expr_args0._args[1] ]
     375                tpl = [ _expr_args1, _expr_args0._args[0], _expr_args0._args[1],
     376                        isinstance(expr,_GreaterThanExpression), isinstance(_expr_args0,_LessThanExpression) ]
    360377
    361378            elif isinstance(_expr_args1,_GreaterThanExpression) or\
    362379                    isinstance(_expr_args1,_GreaterThanOrEqualExpression):
    363                 tpl = [ _expr_args1._args[1], _expr_args1._args[0], _expr_args0 ]
     380                tpl = [ _expr_args1._args[1], _expr_args1._args[0], _expr_args0,
     381                        isinstance(_expr_args1,_GreaterThanExpression), isinstance(expr,_GreaterThanExpression) ]
    364382
    365383            elif isinstance(_expr_args1,_LessThanExpression) or\
    366384                    isinstance(_expr_args1,_LessThanOrEqualExpression):
    367                 tpl = [ _expr_args1._args[0], _expr_args1._args[1], _expr_args0 ]
     385                tpl = [ _expr_args1._args[0], _expr_args1._args[1], _expr_args0, 
     386                        isinstance(_expr_args1,_LessThanExpression), isinstance(expr,_GreaterThanExpression) ]
    368387
    369388            elif isinstance(_expr_args0,_EqualToExpression) or\
     
    372391
    373392            elif _expr_args0.is_constant():
    374                 tpl = [ None, _expr_args1, _expr_args0 ]
     393                tpl = [ None, _expr_args1, _expr_args0,
     394                        True, isinstance(expr,_GreaterThanExpression) ]
    375395            elif _expr_args1.is_constant():
    376                 tpl = [ _expr_args1, _expr_args0, None ]
     396                tpl = [ _expr_args1, _expr_args0, None,
     397                        isinstance(expr,_GreaterThanExpression), True]
    377398            else:
    378                 tpl = [ 0.0, _expr_args0-_expr_args1, None ]
     399                tpl = [ 0.0, _expr_args0-_expr_args1, None,
     400                        isinstance(expr,_GreaterThanExpression), True ]
    379401
    380402        #
     
    387409            if isinstance(_expr_args0,_LessThanExpression) or\
    388410                    isinstance(_expr_args0,_LessThanOrEqualExpression):
    389                 tpl = [ _expr_args0._args[0],_expr_args0._args[1],_expr_args1 ]
     411                tpl = [ _expr_args0._args[0],_expr_args0._args[1],_expr_args1,
     412                        isinstance(_expr_args0,_LessThanExpression), isinstance(expr,_LessThanExpression) ]
    390413
    391414            elif isinstance(_expr_args0,_GreaterThanExpression) or\
    392415                    isinstance(_expr_args0,_GreaterThanOrEqualExpression):
    393                 tpl = [ _expr_args0._args[1],_expr_args0._args[0],_expr_args1 ]
     416                tpl = [ _expr_args0._args[1],_expr_args0._args[0],_expr_args1,
     417                        isinstance(_expr_args0,_GreaterThanExpression), isinstance(expr,_LessThanExpression) ]
    394418
    395419            elif isinstance(_expr_args1,_LessThanExpression) or\
    396420                    isinstance(_expr_args1,_LessThanOrEqualExpression):
    397                 tpl = [ _expr_args0,_expr_args1._args[0],_expr_args1._args[1] ]
     421                tpl = [ _expr_args0,_expr_args1._args[0],_expr_args1._args[1],
     422                        isinstance(expr,_LessThanExpression), isinstance(_expr_args1,_LessThanExpression) ]
    398423
    399424            elif isinstance(_expr_args1,_GreaterThanExpression) or\
    400425                    isinstance(_expr_args1,_GreaterThanOrEqualExpression):
    401                 tpl = [ _expr_args0,_expr_args1._args[1],_expr_args1._args[0] ]
     426                tpl = [ _expr_args0,_expr_args1._args[1],_expr_args1._args[0],
     427                        isinstance(expr,_LessThanExpression), isinstance(_expr_args1,_GreaterThanExpression) ]
    402428
    403429            elif isinstance(_expr_args0,_EqualToExpression) or\
     
    406432
    407433            elif _expr_args0.is_constant():
    408                 tpl = [ _expr_args0, _expr_args1, None ]
     434                tpl = [ _expr_args0, _expr_args1, None,
     435                        isinstance(expr,_LessThanExpression), True ]
    409436            elif _expr_args1.is_constant():
    410                 tpl = [ None, _expr_args0, _expr_args1 ]
     437                tpl = [ None, _expr_args0, _expr_args1,
     438                        True, isinstance(expr,_LessThanExpression) ]
    411439            else:
    412                 tpl = [ 0.0, _expr_args1 - _expr_args0, None ]
     440                tpl = [ 0.0, _expr_args1 - _expr_args0, None,
     441                        isinstance(expr,_LessThanExpression), True ]
    413442        #
    414443        # If the constructor rule returns a tuple or list, then convert
     
    425454            #
    426455            if len(expr) == 2:
    427                 _self_data[val]._equality = True
     456                _self_data[index]._equality = True
    428457                if is_constant(expr[1]):
    429                     tpl = [ expr[1],expr[0],expr[1] ]
     458                    tpl = [ expr[1], expr[0], expr[1], False, False ]
    430459                else:
    431                     tpl = [ expr[0],expr[1],expr[0] ]
     460                    tpl = [ expr[0], expr[1], expr[0], False, False ]
    432461            #
    433462            # Form inequality expression
    434463            #
    435464            elif len(expr) == 3:
    436                 tpl=expr
     465                tpl=list(expr)+[expr[0] is None, expr[2] is None]
    437466            else:
    438467                raise ValueError, "Constructor rule for constraint "+self.name+" returned a tuple of length "+str(len(expr))
     
    455484        if type(tpl[1]) in [bool,int,long,float]:
    456485            raise ValueError, "Constraint \""+self.name+"\" has a numeric body.  Expecting Expression instance."
    457         if _self_data[val]._equality:
     486        if _self_data[index]._equality:
    458487            tpl[2] = tpl[0]
    459488        elif type(tpl[2]) in [bool,int,long,float]:
     
    468497        # 'infinite' RHS
    469498        #
    470         if (tpl[0] is None or tpl[2] is None) and _self_data[val]._equality:
     499        if (tpl[0] is None or tpl[2] is None) and _self_data[index]._equality:
    471500            raise ValueError, "Equality constraint "+self.name+" defined with infinity RHS"
    472501        #
     
    476505            if not isinstance(tpl[0],Expression):
    477506                tpl[0] = _IdentityExpression(tpl[0])
    478             tpl[0] = tpl[0].simplify(model)
     507            tpl[0] = tpl[0].simplify(self.model)
    479508        if tpl[1] is not None:
    480509            if not isinstance(tpl[1],Expression):
    481510                tpl[1] = _IdentityExpression(tpl[1])
    482             tpl[1] = tpl[1].simplify(model)
     511            tpl[1] = tpl[1].simplify(self.model)
    483512        if tpl[2] is not None:
    484513            if not isinstance(tpl[2],Expression):
    485514                tpl[2] = _IdentityExpression(tpl[2])
    486             tpl[2] = tpl[2].simplify(model)
     515            tpl[2] = tpl[2].simplify(self.model)
    487516        #
    488517        # Finally, setup the data
    489518        #
    490         _self_data[val].lower = tpl[0]
    491         _self_data[val].body = tpl[1]
    492         _self_data[val].upper = tpl[2]
     519        _self_data[index].lower = tpl[0]
     520        _self_data[index].lower_ineq_strict = tpl[3]
     521        _self_data[index].body = tpl[1]
     522        _self_data[index].upper = tpl[2]
     523        _self_data[index].upper_ineq_strict = tpl[4]
    493524
    494525
     
    503534           print >>ostream,""
    504535        for val in self._data:
    505           print >>ostream, "\t"+`val`
     536          if not val is None:
     537             print >>ostream, "\t"+`val`
    506538          if self._data[val].lower is not None:
    507539             print >>ostream, "\t\t",
     
    509541          else:
    510542             print >>ostream, "\t\t-Inf"
     543          if self._data[val].lower_ineq_strict:
     544             print >>ostream, "\t\t<"
     545          else:
     546             print >>ostream, "\t\t<="
    511547          if self._data[val].body is not None:
    512548             print >>ostream, "\t\t",
     
    514550          #else:                         #pragma:nocover
    515551             #raise ValueError, "Unexpected empty constraint body"
     552          if self._data[val].upper_ineq_strict:
     553             print >>ostream, "\t\t<"
     554          else:
     555             print >>ostream, "\t\t<="
    516556          if self._data[val].upper is not None:
    517557             print >>ostream, "\t\t",
     
    531571           print >>ostream, prefix+"  Value="+pyutilib.misc.format_io(self._data[None].body())
    532572        else:
    533            print >>ostream, prefix+"        \tLower\tBody\t\tUpper"
     573           flag=True
    534574           for key in self._data:
     575             if not self._data[key].active:
     576                continue
     577             if flag:
     578                print >>ostream, prefix+"        \tLower\tBody\t\tUpper"
     579                flag=False
    535580             if self._data[key].lower is not None:
    536581                lval = str(self._data[key].lower())
     
    543588                uval = "Infinity"
    544589             print >>ostream, prefix+"  "+str(key)+" :\t"+lval+"\t"+val+"\t"+uval
     590           if flag:
     591                print >>ostream, prefix+"  None active"
    545592
    546593
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/expr.py

    r1972 r2070  
    8585    #
    8686    def is_constant(self):
    87         if self._args is None:
    88             return True
    8987        for arg in self._args:
    9088            if not arg.is_constant():
     
    201199        self.coef = 1
    202200        Expression.__init__(self,nargs=-1,name='prod')
     201
     202    def is_constant(self):
     203        for arg in self._numerator:
     204            if not arg.is_constant():
     205                return False
     206        for arg in self._denominator:
     207            if not arg.is_constant():
     208                return False
     209        return True
    203210
    204211    def invert(self):
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/numvalue.py

    r1972 r2070  
    2323##
    2424##------------------------------------------------------------------------
     25
     26def create_name(name, ndx):
     27    if ndx is None:
     28        return name
     29    if type(ndx) is tuple:
     30        tmp = str(ndx).replace(', ',',')
     31        return name+"["+tmp[1:-1]+"]"
     32    return name+"["+str(ndx)+"]"
    2533
    2634def value(obj):
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/param.py

    r1972 r2070  
    1111__all__ = ['_ParamBase', 'Param']
    1212
     13from numvalue import create_name
    1314from coopr.pyomo.base.numvalue import *
    1415from coopr.pyomo.base.plugin import ComponentRegistration
     16from sets import _BaseSet
    1517from set_types import *
    1618import pyomo
    1719import sys
    1820import types
    19 from component import ComponentBase
     21from indexed_component import IndexedComponent
    2022
    2123
     
    3739
    3840
    39 class _ParamBase(ComponentBase):
     41class _ParamBase(IndexedComponent):
    4042    """A parameter value, which may be defined over a index"""
    4143
     
    5658    """
    5759    def __init__(self, *args, **kwd):
    58         ComponentBase.__init__(self, *args)
     60        tkwd = {'ctype':Param}
     61        IndexedComponent.__init__(self, *args, **tkwd)
    5962        tmpname="unknown"
    6063        tmpdomain=Any
     
    6265        self._initialize={}
    6366        self._validate=None
    64         self._model=None
    6567        defaultval=None
    6668        for key in kwd.keys():
     
    6971          elif key is "name":
    7072                tmpname = kwd[key]
     73          elif key == "doc":
     74             self.doc=kwd[key]
    7175          elif key == "within":
    7276                tmpdomain = kwd[key]
     
    99103
    100104    def keys(self):
    101         return self._paramval.keys()
     105        if self._default.value is None:
     106            return self._paramval.keys()
     107        else:
     108            if not isinstance(self._index,_BaseSet):
     109                raise ValueError, "Expected a set object for _index"
     110            return self._index
    102111
    103112    def __contains__(self, element):
    104         return element in self._paramval
     113        if self._default.value is None:
     114            return element in self._paramval
     115        else:
     116            return element in self._index
    105117
    106118    def __iter__(self):
    107         return self._paramval.keys().__iter__()
     119        if self._default.value is None:
     120            return self._paramval.keys().__iter__()
     121        else:
     122            return self._index.keys().__iter__()
    108123
    109124    def dim(self):
     
    139154           # this is a "hack", in that we still need to check for legal sub-components in the input index.
    140155           if ndx in self._paramval:
    141               self._paramval[ndx].value = val
     156                self._paramval[ndx].value = val
    142157           else:
    143               self._paramval[ndx]= _ParamValue(name=self.name+"["+str(ndx)+"]",domain=self.domain,value=val)
     158                self._paramval[ndx]= _ParamValue(name=create_name(self.name,ndx),domain=self.domain,value=val)
    144159           return
    145160
     
    151166           self._paramval[ndx].value = val
    152167        else:
    153            self._paramval[ndx]= _ParamValue(name=self.name+"["+str(ndx)+"]",domain=self.domain,value=val)           
     168           self._paramval[ndx]= _ParamValue(name=create_name(self.name,ndx),domain=self.domain,value=val)           
    154169        if not self._valid_indexed_value(val,ndx,False):
    155170            raise ValueError, "Cannot set parameter "+self.name+" with invalid value: index=" + str(ndx) + " value=" + str(val)
    156171
    157     def _construct(self, model, data):
     172    def construct(self, data=None):
    158173        """ Apply the rule to construct values in this set """
    159         self._model=model
    160174        if pyomo.debug("verbose"):      #pragma:nocover
    161175           print "Constructing Param, name="+self.name+", from data="+`data`
    162         #
    163         # Update the index set dimension
    164         #
    165         self._compute_dim()
    166176        #
    167177        # Code optimization with local variables
     
    188198           # Singleton parameter
    189199           #
    190            if type(self._index) is list:
     200           if type(self._index) is dict:
    191201              if data is not None and None in data.keys():
    192202                    self.value=data[None]
    193                     #self._paramval[None] = _ParamValue(name=_name,domain=_domain,value=data[None])
    194203              elif type(self._initialize) is not dict:
    195204                    self.value=self._initialize
    196                     #self._paramval[None] = _ParamValue(name=_name,domain=_domain,value=self._initialize)
    197205              elif None in self._initialize:
    198206                    self.value=self._initialize[None]
    199                     #self._paramval[None] = _ParamValue(name=_name,domain=_domain,value=self._initialize[None])
    200207              elif self._default.value is not None and not self._default.value is None:
    201208                    self.value=self._default.value
     
    216223                   else:
    217224                      tmpkey=key
    218                    self._paramval[tmpkey] = _ParamValue(name=_name+"["+str(key)+"]",domain=_domain,value=data[key])
     225                   self._paramval[tmpkey] = _ParamValue(name=create_name(_name,key),domain=_domain,value=data[key])
    219226                   self._valid_indexed_value(data[key],key,True)
    220227              #
     
    224231                 if type(self._initialize) is dict:
    225232                    for key in self._initialize:
    226                       self._paramval[key] = _ParamValue(name=_name+"["+str(key)+"]",domain=_domain,value=self._initialize[key])
     233                      self._paramval[key] = _ParamValue(name=create_name(_name,key),domain=_domain,value=self._initialize[key])
    227234                      self._valid_indexed_value(self._initialize[key],key,True)
    228235                 else:
    229236                    for key in self._index:
    230                       self._paramval[key] = _ParamValue(name=_name+"["+str(key)+"]",domain=_domain,value=self._initialize)
     237                      self._paramval[key] = _ParamValue(name=create_name(_name,key),domain=_domain,value=self._initialize)
    231238                    self._valid_indexed_value(self._initialize,(),True)
    232239        #
     
    234241        #
    235242        elif type(self._initialize) is types.FunctionType:
    236            if (type(self._index) is list) and (None in self._index):
     243           if (type(self._index) is dict) and (None in self._index):
    237244              # singleton
    238245              tmp = []
    239               tmp.append(model)
     246              tmp.append(self.model)
    240247              tval = self._initialize(*tmp)
    241248              self.value = tval
     
    250257                    tmp = [val]
    251258                 if len(tmp) > 0:
    252                        tname=_name+"["+str(val)+"]"
     259                       tname=create_name(_name,val)
    253260                 else:
    254261                       tname=_name
    255                  tmp.append(model)
     262                 tmp.append(self.model)
    256263                 tmp = tuple(tmp)
    257264                 tval = self._initialize(*tmp)
     
    266273           if index is not None:
    267274              tmp = tmp + list(index)
    268            tmp.append(self._model)
     275           tmp.append(self.model)
    269276           tmp = tuple(tmp)
    270277           if self._validate(*tmp):
     
    295302            raise ValueError, "Undefined value for parameter "+self.name
    296303        if not self._valid_indexed_value(self.value,None,False):
     304            print "BUG",self.value,self._index
    297305            raise ValueError, "Parameter "+self.name+" failed validation test value=" + str(self.value)
    298306
     
    353361
    354362
    355 ComponentRegistration("Param", _ParamBase, "Parameter data that is used to define a model instance.")
     363ComponentRegistration("Param", Param, "Parameter data that is used to define a model instance.")
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/plugin.py

    r1768 r2070  
    1212        'IPyomoSet', 'IModelComponent', 'ComponentRegistration',
    1313        'ComponentFactory',
    14         'IPyomoPresolver', 'IPyomoPresolveAction']
     14        'IPyomoPresolver', 'IPyomoPresolveAction',
     15        'IModelTransformation',
     16        'apply_transformation']
    1517
    1618from pyutilib.plugin.core import *
     
    127129
    128130
     131
     132class IModelTransformation(Interface):
     133
     134    def apply(self, model, **kwds):
     135        """Apply a model transformation and return a new model instance"""
     136
     137    def __call__(self, model, **kwds):
     138        """Use this plugin instance as a functor to apply a transformation"""
     139        return self.apply(model, **kwds)
     140
     141
     142def apply_transformation(*args, **kwds):
     143    ep = ExtensionPoint(IModelTransformation)
     144    if len(args) is 0:
     145        return map(lambda x:x.name, ep())
     146    service = ep.service(args[0])
     147    if len(args) == 1 or service is None:
     148        return service
     149    tmp=(args[1],)
     150    return service.apply(*tmp, **kwds)
     151   
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/pyomo.py

    r1768 r2070  
    1313from plugin import *
    1414
    15 Debug = Enum('none', 'reader', 'preprocess', 'instance', 'all', 'verbose', 'generate', 'normal')
     15Debug = Enum('none', 'reader', 'preprocess', 'instance', 'all', 'verbose', 'generate', 'normal', 'errors')
    1616
    1717_debug = []
     
    4545
    4646def predefined_sets():
    47     ep = pyutilib.plugin.core.ExtensionPoint(IPyomoSet)
     47    import set_types
    4848    ans = []
    49     for item in ep:
     49    for item in set_types._virtual_sets:
    5050        ans.append( (item.name,item.doc) )
    5151    return ans
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/rangeset.py

    r1768 r2070  
    1111__all__ = ['RangeSet']
    1212
    13 #import pyutilib.plugin.core
    1413import sets
    1514import expr
     
    3332       return True
    3433
     34
    3535class RangeSet(sets._SetContainer):
    3636    """A set that represents a list of integer values"""
     
    4040        tmp=()
    4141        sets._SetContainer.__init__(self,*tmp,**kwds)
     42        self._type=RangeSet
    4243        self.ordered=True
    4344        if len(args) == 1:
     
    5455           self._step=args[2]
    5556
    56     def _construct(self, model=None, values=None):
     57    def construct(self, values=None):
    5758        if isinstance(self._start,expr.Expression):
    5859           self._start_val = self._start()
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/set_types.py

    r1768 r2070  
    1616
    1717
     18_virtual_sets = []
     19
    1820class _VirtualSet(sets._SetContainer, pyutilib.plugin.core.Plugin):
    1921    """
     
    3234        sets._SetContainer.__init__(self,*args,**kwds)
    3335        self.virtual=True
     36        #
     37        global _virtual_sets
     38        _virtual_sets.append(self)
    3439
    3540
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/sets.py

    r1972 r2070  
    1313import pyutilib.plugin.core
    1414from coopr.pyomo.base.plugin import ComponentRegistration
     15from component import Component
    1516import pyutilib.misc
    1617import sys
     
    2627##------------------------------------------------------------------------
    2728
    28 class _BaseSet(object):
     29class _BaseSet(Component):
    2930    """The base class for set objects that are used to index other Pyomo objects
    3031
     
    5354    """
    5455    def __init__(self, **kwds):
     56        Component.__init__(self, ctype=Set)
    5557        self.initialize=None
    5658        self.name="_unknown_"
    5759        self.validate=None
    58         self.model=None
    5960        self.ordered=False
    6061        self.order=[]
     
    8788              raise ValueError, "Option dimen "+str(kwds["dimen"])+" is different from the dimen of superset "+self.within.name+": "+str(self.dimen)
    8889           self.dimen = kwds["dimen"]
    89         if not type(self.initialize) is types.FunctionType and self.dimen is None:
    90             # If we are initializing with a function, then we leave the dimension as None.  Otherwise, we
    91             # set the default to 1
     90        if self.dimen is None:
     91            # We set the default to 1
    9292            self.dimen=1
    9393        if self.initialize is not None:
     
    175175        _BaseSet.__init__(self,**kwds)
    176176
    177     def _construct(self, model=None, values=None):
     177    def construct(self, values=None):
    178178        """ Apply the rule to construct values in this set """
    179179        log.debug("Constructing _SetContainer, name="+self.name+", from data="+repr(values))
     
    204204        #
    205205        elif type(self.initialize) is types.FunctionType:
    206            if model is None:
     206           if self.model is None:
    207207              raise ValueError, "Must pass a model in to initialize with a function"
    208208           if self.initialize.func_code.co_argcount == 1:
     
    210210              # Using a rule of the form f(model) -> iterator
    211211              #
    212               tmp = self.initialize(model)
     212              tmp = self.initialize(self.model)
    213213              for val in tmp:
    214214                if self.dimen is None:
     
    223223              #
    224224              ctr=0
    225               val = self.initialize(ctr,model)
     225              val = self.initialize(ctr,self.model)
    226226              if self.dimen is None:
    227227                   if type(val) in [tuple,list]:
     
    232232                self.add(val)
    233233                ctr += 1
    234                 val = self.initialize(ctr,model)
     234                val = self.initialize(ctr,self.model)
    235235           #
    236236           # We should be verifying as part of the add() method
     
    544544        if self.dimen != other.dimen:
    545545           raise ValueError, "Cannot perform set operation with sets "+self.name+" and "+other.name+" that have different element dimensions: "+str(self.dimen)+" "+str(other.dimen)
    546         def SetSymmetricDifferenceRule(model):
    547             Set1 = getattr(model,SetSymmetricDifferenceRule.Set1)
    548             Set2 = getattr(model,SetSymmetricDifferenceRule.Set2)
     546        def SetSymmetricDifferenceRule(M):
     547            Set1 = getattr(M,SetSymmetricDifferenceRule.Set1)
     548            Set2 = getattr(M,SetSymmetricDifferenceRule.Set2)
    549549            data = set()
    550550            for val in Set1:
     
    648648        else:
    649649           self.value[key] = Set(initialize=val,within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
    650            self.value[key]._construct(self.model)
     650           self.value[key].construct()
    651651
    652652    def __len__(self):
     
    694694          print >>ostream, "\t",self.name+"["+str(val)+"]\t",ttmp
    695695
    696     def _construct(self, model=None, values=None):
     696    def construct(self, values=None):
    697697        """ Apply the rule to construct values in each set"""
    698         self.model=model
    699698        log.debug("Constructing _SetArray, name="+self.name+", from data="+repr(values))
    700699        if self.virtual:                                #pragma:nocover
     
    712711                raise KeyError, "Cannot set index "+str(tmpkey)+" in array set "+self.name
    713712             self.value[tmpkey] = Set(initialize=values[key],within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(tmpkey)+"]",dimen=self.dimen)
    714              self.value[tmpkey].model = model
    715              self.value[tmpkey]._construct(model)
     713             self.value[tmpkey].model = self.model
     714             self.value[tmpkey].construct()
    716715        #
    717716        # Construct using the rule
    718717        #
    719718        elif type(self.initialize) is types.FunctionType:
    720            if model is None:
     719           if self.model is None:
    721720              raise ValueError, "Need model to construct a set array with a function"
    722721           if self._index is None:
     
    728727                tmp = [key]
    729728             if self.initialize.func_code.co_argcount == len(tmp)+1:
    730                 tmp.append(model)
     729                tmp.append(self.model)
    731730                tmp = tuple(tmp)
    732731                rule_list = list(self.initialize(*tmp))
     
    734733                rule_list=[]
    735734                ctr=0
    736                 args = tuple(tmp+[ctr,model])
     735                args = tuple(tmp+[ctr,self.model])
    737736                val = self.initialize(*args)
    738737                while val is not None:
    739738                  rule_list.append(val)
    740739                  ctr += 1
    741                   args = tuple(tmp+[ctr,model])
     740                  args = tuple(tmp+[ctr,self.model])
    742741                  val = self.initialize(*args)
    743742             if self.dimen is None and len(rule_list) > 0:
     
    747746                        self.dimen=1
    748747             self.value[key] = Set(initialize=rule_list,within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
    749              self.value[key].model = model
    750              self.value[key]._construct(model)
     748             self.value[key].model = self.model
     749             self.value[key].construct()
    751750        #
    752751        # Construct using the default values
     
    757756                 for key in self._index:
    758757                   self.value[key] = Set(initialize=self.initialize,within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
    759                    self.value[key].model = model
    760                    self.value[key]._construct(model)
     758                   self.value[key].model = self.model
     759                   self.value[key].construct()
    761760              else:
    762761                 for key in self.initialize:
    763762                   self.value[key] = Set(initialize=self.initialize[key],within=self.domain,validate=self.validate,ordered=self.ordered,name=self.name+"["+str(key)+"]",dimen=self.dimen)
    764                    self.value[key].model = model
    765                    self.value[key]._construct(model)
     763                   self.value[key].model = self.model
     764                   self.value[key].construct()
    766765
    767766
     
    830829        return True
    831830       
    832     def _construct(self, model=None, values=None):
     831    def construct(self, values=None):
    833832        """ Apply the rule to construct values in this set """
    834833        log.debug("Constructing _ProductSet, name="+self.name+", from data="+repr(values))
     
    850849        #
    851850        elif type(self.initialize) is types.FunctionType:
    852            for val in self.initialize(model):
     851           for val in self.initialize(self.model):
    853852             self.add(val)
    854853        #
     
    889888
    890889
    891 ComponentRegistration("Set", _BaseSet, "Set data that is used to define a model instance.")
    892 
     890ComponentRegistration("Set", Set, "Set data that is used to define a model instance.")
     891
  • coopr.pyomo/stable/2.1/coopr/pyomo/base/var.py

    r1972 r2070  
    1212
    1313from numvalue import *
     14from numvalue import create_name
    1415from plugin import ComponentRegistration
    1516import types
    1617from set_types import *
    17 from component import ComponentBase
     18from indexed_component import IndexedComponent
    1819import pyutilib.math
    1920import pyutilib.misc
     
    3132        NumericValue.__init__(self,**kwds)
    3233        self.var = None # the "parent" variable.
     34        self.index = None # the index of this variable within the "parent"
    3335        self.id = None
    3436        self.label = None
    3537        self.initial = None
     38        self.active = True
    3639        # IMPORTANT: in contrast to the initial value, the lower and upper bounds
    3740        #            of a variable can in principle be either numeric constants,
     
    4548    def __str__(self):
    4649        return self.name
     50
     51    def activate(self):
     52        self.active=True
     53
     54    def deactivate(self):
     55        self.active=False
    4756
    4857    def setlb(self, value):
     
    7887        return False
    7988
     89    def is_binary(self):
     90        return self.var.is_binary()
     91
     92    def is_integer(self):
     93        return self.var.is_integer()
     94
     95    def is_continuous(self):
     96        return self.var.is_continuous()
     97
    8098    def simplify(self, model):
    8199        return self                 #pragma:nocover
     
    114132#
    115133
    116 class _VarBase(ComponentBase):
     134class _VarBase(IndexedComponent):
    117135    """A numeric variable, which may be defined over a index"""
    118136
     
    133151    """
    134152    def __init__(self, *args, **kwd):
    135         ComponentBase.__init__(self,*args)
     153        tkwd = {'ctype':Var}
     154        IndexedComponent.__init__(self, *args, **tkwd)
    136155        #
    137156        # Default keyword values
     
    148167          elif key == "within" or key=="domain":
    149168             tmpdomain=kwd[key]
     169          elif key == "doc":
     170             self.doc=kwd[key]
    150171          elif key == "initialize":
    151172             self.__dict__["_"+key] = kwd[key]
     
    157178        self.domain = tmpdomain
    158179        self.bounds=tmpbounds
    159         self._model=None
    160180
    161181    def as_numeric(self):
     
    204224            raise KeyError, "Unknown index " + str(ndx) + " in variable " + self.name
    205225
     226    def is_binary(self):
     227        return isinstance(self.domain, BooleanSet)
     228
     229    def is_integer(self):
     230        return isinstance(self.domain, IntegerSet)
     231
     232    def is_continuous(self):
     233        return not (self.is_binary() or self.is_integer())
     234
    206235    def simplify(self, model):
    207236        return self
    208237
    209     def _construct(self, model, data):
    210         self._model = model
    211         #
    212         # Update the index set dimension
    213         #
    214         self._compute_dim()
     238    def construct(self, data=None):
    215239        #
    216240        # Construct _VarValue() objects for all index values
     
    221245            for ndx in self._index:
    222246                if ndx is not None:
    223                     self._varval[ndx] = _VarValue(name=self.name+"["+str(ndx)+"]",domain=self.domain)
     247                    self._varval[ndx] = _VarValue(name=create_name(self.name,ndx),domain=self.domain)
    224248                    self._varval[ndx].var = self
     249                    self._varval[ndx].index = ndx
    225250        #
    226251        # Initialize values with a dictionary if provided
     
    248273             else:
    249274                tmp = [key]
    250              tmp.append(model)
     275             tmp.append(self.model)
    251276             tmp = tuple(tmp)
    252277             self._varval[key].value = None
     
    272297               else:
    273298                  tmp = [key]
    274                tmp.append(model)
     299               tmp.append(self.model)
    275300               tmp = tuple(tmp)
    276301               (lb, ub) = self.bounds(*tmp)
     
    379404        self._varval[None] = self
    380405        self._varval[None].var = self
     406        self._varval[None].index = None
    381407
    382408    def is_constant(self):
     
    418444
    419445
    420 ComponentRegistration("Var", _VarBase, "Decision variables in a model.")
     446ComponentRegistration("Var", Var, "Decision variables in a model.")
  • coopr.pyomo/stable/2.1/coopr/pyomo/components/action.py

    r1972 r2070  
    1313from coopr.pyomo.base.numvalue import *
    1414from coopr.pyomo.base.plugin import ComponentRegistration
    15 from coopr.pyomo.base.component import ComponentBase
     15from coopr.pyomo.base.indexed_component import IndexedComponent
    1616import types
    1717from coopr.pyomo.base import pyomo
    1818
    19 #from set_types import *
    20 #import sys
    2119
    22 
    23 class BuildAction(ComponentBase):
     20class BuildAction(IndexedComponent):
    2421    """A build action, which executes a rule for all valid indices"""
    2522
     
    3330    """
    3431    def __init__(self, *args, **kwd):
    35         ComponentBase.__init__(self, *args)
     32        tkwd = {'ctype':BuildAction}
     33        IndexedComponent.__init__(self, *args, **tkwd)
    3634        tmpname="unknown"
    3735        self.domain=None
    38         self._model=None
    3936        self._rule=None
    4037        for key in kwd.keys():
     
    5350        print >>ostream, "  ",self.name,":",
    5451
    55     def _construct(self, model, data):
     52    def construct(self, data=None):
    5653        """ Apply the rule to construct values in this set """
    57         self._model=model
    5854        if pyomo.debug("verbose"):      #pragma:nocover
    5955           print "Constructing Param, name="+self._name+", from data="+`data`
     
    6965              else:
    7066                 tmp = [val]
    71               tmp.append(model)
     67              tmp.append(self.model)
    7268              tmp = tuple(tmp)
    7369              self._rule(*tmp)
  • coopr.pyomo/stable/2.1/coopr/pyomo/components/check.py

    r1972 r2070  
    1313from coopr.pyomo.base.numvalue import *
    1414from coopr.pyomo.base.plugin import ComponentRegistration
    15 from coopr.pyomo.base.component import ComponentBase
     15from coopr.pyomo.base.indexed_component import IndexedComponent
    1616import types
    1717from coopr.pyomo.base import pyomo
    1818
    1919
    20 class BuildCheck(ComponentBase):
     20class BuildCheck(IndexedComponent):
    2121    """A build check, which executes a rule for all valid indices"""
    2222
     
    3030    """
    3131    def __init__(self, *args, **kwd):
    32         ComponentBase.__init__(self,*args)
     32        tkwd = {'ctype':BuildCheck}
     33        IndexedComponent.__init__(self, *args, **tkwd)
    3334        tmpname="unknown"
    3435        self.domain=None
    35         self._model=None
    3636        self._rule=None
    3737        for key in kwd.keys():
     
    5050        print >>ostream, "  ",self.name,":",
    5151
    52     def _construct(self, model, data):
     52    def construct(self, data=None):
    5353        """ Apply the rule to construct values in this set """
    54         self._model=model
    5554        if pyomo.debug("verbose"):      #pragma:nocover
    5655           print "Constructing Param, name="+self._name+", from data="+`data`
     
    6665              else:
    6766                 tmp = [val]
    68               tmp.append(model)
     67              tmp.append(self.model)
    6968              tmp = tuple(tmp)
    7069              res = self._rule(*tmp)
  • coopr.pyomo/stable/2.1/coopr/pyomo/io/ampl.py

    r1948 r2070  
    5656        #
    5757        nc = no = neqn = nrange = 0
    58         Obj = model._component[Objective]
    59         Con = model._component[Constraint]
    60         Vars = model._component[_VarBase]
     58        Obj = model.active_components(Objective)
     59        Con = model.active_components(Constraint)
     60        Vars = model.active_components(Var)
    6161        Onontriv = model.Onontriv
    6262        for obj in Onontriv:
     
    128128        # LINE 2
    129129        #
    130         print >>OUTPUT, " " + str(model.vnum), nc, no, nrange, str(neqn) +\
     130        print >>OUTPUT, " " + str(model.statistics.number_of_variables), nc, no, nrange, str(neqn) +\
    131131                "\t# vars, constraints, objectives, ranges, eqns"
    132132        #
     
    165165        # LINE 8
    166166        #
    167         nsno = model.vnum
     167        nsno = model.statistics.number_of_variables
    168168        ngc = ngo = 0
    169         for key in model._component[Objective]:
    170                 for obj in model._component[Objective][key]._linterm:
    171                     ngo += len(model._component[Objective][key]._linterm[obj])
     169        for key in Obj:
     170                for obj in Obj[key]._linterm:
     171                    ngo += len(Obj[key]._linterm[obj])
    172172        cu = {}
    173173        for i in xrange(nsno):
    174174                cu[i] = 0
    175         Con = model._component[Constraint]
     175        #Con = model.components(Constraint)
    176176        for key in Cnontriv:
    177177                C = Con[key]
     
    294294        # "k" lines
    295295        #
    296         n1 = model.vnum - 1
     296        n1 = model.statistics.number_of_variables - 1
    297297        print >>OUTPUT, "k" + str(n1)
    298298        ktot = 0
  • coopr.pyomo/stable/2.1/coopr/pyomo/io/cpxlp.py

    r1948 r2070  
    1010
    1111#
    12 # Problem Writer for LPX (LPSolve) LP Format Files
     12# Problem Writer for CPLEX LP Format Files
    1313#
    1414
     
    9797           output_label = i
    9898           if (self._output_prefixes is True) and (isinstance(x[i][1], _VarValue) is True):
    99               parent_model = x[i][1].var._model
     99              parent_model = x[i][1].var.model
    100100              if parent_model is None:
    101101                 raise ValueError, "Variable="+x[i][1].var.name+" has no parent model defined - required when outputting LP files when _output_prefixes is enabled"
     
    200200    def _print_model_LP(self, model, OUTPUT):
    201201
    202         _obj = model._component[Objective]
     202        _obj = model.active_components(Objective)
    203203       
    204204        #
     
    216216           obj = _obj[ _obj.keys()[0] ]
    217217           for key in obj._linterm:
    218              self._print_linterm(obj._linterm[key], OUTPUT, print_mult=False, cleanup_names=True, print_offset=True)
     218                if (len(obj._linterm[key]) == 0) or ((len(obj._linterm[key]) == 1) and (obj._linterm[key].keys()[0] == "0")):
     219                    continue
     220                self._print_linterm(obj._linterm[key], OUTPUT, print_mult=False, cleanup_names=True, print_offset=True)
    219221           if obj._quad_subexpr is not None:
    220222               self._print_quadterm(obj._quad_subexpr, (_obj[ _obj.keys()[0] ].sense == minimize), OUTPUT)
     
    240242              print >>OUTPUT, "s.t."
    241243           
     244           CON = model.active_components(Constraint)
    242245           for key in model.Cnontriv:
    243246             i=0
    244              C = model._component[Constraint][key]
     247             C = CON[key]
    245248             for cndx in C.keys():
     249               if not C[cndx].active:
     250                    continue
    246251               try:
    247252                  # there are conditions, e.g., when fixing variables, under which a constraint block might be empty.
     
    252257                     prefix = ""
    253258                     if self._output_prefixes is True:
    254                         if C._model is None:
     259                        if C.model is None:
    255260                           raise RuntimeError, "Constraint="+C._data[cndx].label+" has no model attribute - no label prefix can be assigned"
    256                         prefix = C._model.name+"_"
     261                        prefix = C.model.name+"_"
    257262
    258263                     if C._data[cndx]._equality:
     
    313318           # track the number of integer and binary variables, so you can output their status later.
    314319           niv = nbv = 0
    315            for var in model._component[_VarBase].values():
     320           VAR = model.active_components(Var)
     321           for var in VAR.values():
    316322              if isinstance(var.domain, IntegerSet):
    317323                 niv += 1
     
    321327              if self._output_continuous_variables is True:
    322328                 for ndx in var._varval.keys():
     329                    if not var._varval[ndx].active:
     330                        continue
    323331                    prefix = ""
    324332                    if self._output_prefixes is True:
    325                        prefix = convert_name(var._model.name)+"_"
     333                       prefix = convert_name(var.model.name)+"_"
    326334
    327335                    if var[ndx].id != -1: # if the variable isn't referenced in the model, don't output bounds...
     
    334342                       else:
    335343                          print >>OUTPUT, " -inf <= ",
    336                        print >>OUTPUT, prefix+convert_name(var[ndx].label),
     344                       name_to_output = prefix+convert_name(var[ndx].label)
     345                       if name_to_output == "e":
     346                          raise ValueError, "Attempting to write variable with name=e in a CPLEX LP formatted file - will cause a parse failure due to confusion with numeric values expressed in scientific notation"
     347                       print >>OUTPUT, name_to_output,
    337348                       if var[ndx].ub is not None:
    338349                          print >>OUTPUT, " <= " + str(value(var[ndx].ub())),
     
    350361              prefix = ""
    351362              if self._output_prefixes is True:
    352                  prefix = convert_name(var._model.name)+"_"
    353 
    354               for var in model._component[_VarBase].values():
     363                 prefix = convert_name(var.model.name)+"_"
     364
     365              for var in VAR.values():
    355366                 if isinstance(var.domain, IntegerSet):
    356367                    for ndx in var.keys():
     368                       if not var[ndx].active:
     369                            continue
    357370                       if var[ndx].id != -1: # if the variable isn't referenced, skip.
    358371                          print >>OUTPUT, "   ", prefix+convert_name(var[ndx].label)
     
    367380              prefix = ""
    368381              if self._output_prefixes is True:
    369                  prefix = convert_name(var._model.name)+"_"
    370 
    371               for var in model._component[_VarBase].values():
     382                 prefix = convert_name(var.model.name)+"_"
     383
     384              for var in VAR.values():
    372385                 if isinstance(var.domain, BooleanSet):
    373386                    for ndx in var.keys():
     387                       if not var[ndx].active:
     388                            continue
    374389                       if var[ndx].id != -1: # if the variable isn't referenced, skip.
    375390                          print >>OUTPUT, "   ", prefix+convert_name(var[ndx].label)
  • coopr.pyomo/stable/2.1/coopr/pyomo/io/problem_utils.py

    r1290 r2070  
    208208
    209209    def _Collect(self,model):
    210          Vars = model._component[Var]
    211          Con = model._component[Constraint]
    212          Obj = model._component[Objective]
     210         Vars = model.active_components(Var)
     211         Con = model.active_components(Constraint)
     212         Obj = model.active_components(Objective)
    213213         Con1 = []
    214214         #
  • coopr.pyomo/stable/2.1/coopr/pyomo/main_script.py

    r1768 r2070  
    142142        type="string",
    143143        default=[])
     144parser.add_option("--solver-mipgap",
     145        help="The solver termination mipgap",
     146        action="store",
     147        dest="solver_mipgap",
     148        type="float",
     149        default=None)
     150parser.add_option("--model-name",
     151        help="The name of the model object that is created in the specified Pyomo module",
     152        action="store",
     153        dest="model_name",
     154        type="string",
     155        default="model")
     156parser.add_option("--model-options",
     157        help="Options passed into a create_model() function to construct the model",
     158        action="append",
     159        dest="model_options",
     160        type="string",
     161        default=[])
    144162parser.add_option("--disable-gc",
    145163        help="Disable the garbage collecter",
     
    165183# These options are depricated until we have a specific use-case for them
    166184#
    167 if False:
    168   parser.add_option("--seed",
    169         help="Specify a seed to derandomize the solver",
    170         action="store",
    171         dest="seed",
    172         type="int",
    173         default=0)
    174   parser.add_option("--first-feasible",
    175         help="Terminate after the first feasible incumbent",
    176         action="store_true",
    177         dest="ff",
    178         default=False)
     185##if False:
     186##  parser.add_option("--seed",
     187##        help="Specify a seed to derandomize the solver",
     188##        action="store",
     189##        dest="seed",
     190##        type="int",
     191##        default=0)
     192##  parser.add_option("--first-feasible",
     193##        help="Terminate after the first feasible incumbent",
     194##        action="store_true",
     195##        dest="ff",
     196##        default=False)
    179197parser.usage="pyomo [options] <model.py> [<model.dat>]"
    180198
     
    198216        print ""
    199217        print "----------------------------------------------------------------"
    200         print "Predefined Pyomo Sets:"
     218        print "Pyomo Virtual Sets:"
    201219        print "----------------------------------------------------------------"
    202220        pyomo_sets = pyomo.predefined_sets()
     
    274292    usermodel = pyutilib.misc.import_file(args[0])
    275293    filter_excepthook=False
    276     if "model" not in dir(usermodel):
     294    if options.model_name in dir(usermodel):
     295        model = getattr(usermodel, options.model_name)
     296        if model is None:
     297            print ""
     298            raise SystemExit, "'%s' object equals 'None' in module %s" % (options.model_name, args[0])
     299            sys.exit(0)
     300    elif 'create_model' in dir(usermodel):
     301        model = getattr(usermodel, 'create_model')( pyutilib.misc.Container(*options.model_options) )
     302    else:
    277303       print ""
    278        print "Exiting pyomo: No 'model' object created in module "+args[0]
    279        sys.exit(0)
    280     if usermodel.model is None:
    281        print ""
    282        print "Exiting pyomo: 'model' object equals 'None' in module "+args[0]
    283        sys.exit(0)
     304       raise SystemExit, "Neither '%s' nor 'create_model' are available in module %s" % (options.model_name,args[0])
     305       #sys.exit(0)
    284306    #
    285307    # Create Problem Instance
     
    288310       suffix = (args[1]).split(".")[-1]
    289311       if suffix == "dat":
    290           instance = usermodel.model.create(args[1])
     312          instance = model.create(args[1])
    291313       elif suffix == "py":
    292314          userdata = pyutilib.misc.import_file(args[1])
    293315          if "modeldata" not in dir(userdata):
    294316             print ""
    295              print "Exiting pyomo: No 'modeldata' object created in module "+args[1]
     317             print "pyomo: No 'modeldata' object created in module "+args[1]
    296318             sys.exit(0)
    297319          if userdata.modeldata is None:
    298320             print ""
    299              print "Exiting pyomo: 'modeldata' object equals 'None' in module "+args[1]
    300              sys.exit(0)
    301           userdata.modeldata.read(usermodel.model)
    302           instance = usermodel.model.create(userdata.modeldata)
     321             raise SystemExit, "Exiting pyomo: 'modeldata' object equals 'None' in module "+args[1]
     322          userdata.modeldata.read(model)
     323          instance = model.create(userdata.modeldata)
    303324       else:
    304325          raise ValueError, "Unknown data file type: "+args[1]
    305326    else:
    306        instance = usermodel.model.create()
     327       instance = model.create()
    307328    if pyomo.debug("instance"):
    308329       print "MODEL INSTANCE"
     
    329350    if options.timelimit == 0:
    330351       options.timelimit=None
     352    if options.solver_mipgap is not None:
     353       opt.mipgap = options.solver_mipgap
    331354    solver_mngr = SolverManagerFactory( options.smanager_type )
    332355    if solver_mngr is None:
     
    350373        instance.load(results)
    351374    except Exception, e:
    352         raise ValueError, "Problem loading solver results: "+str(e)
     375        print "Problem loading solver results"
     376        raise
    353377    print ""
    354378    results.write(num=1)
     
    420444        # Call the main Pyomo runner without profiling
    421445        #
    422         ans = run_pyomo(options, args)
     446        try:
     447            ans = run_pyomo(options, args)
     448        except SystemExit, err:
     449            if pyomo.debug('errors'):
     450                sys.exit(0)
     451            print 'Exiting pyomo:', str(err)
     452            ans = None
     453        except Exception, err:
     454            if pyomo.debug('errors'):
     455                raise
     456            print ""
     457            print "ERROR:",str(err)
     458            ans = None
    423459
    424460    gc.enable()
  • coopr.pyomo/stable/2.1/coopr/pyomo/presolve/collect_linear_terms.py

    r1972 r2070  
    1111
    1212import pyutilib.plugin.core
    13 from coopr.pyomo.base import expr, _VarBase, Constraint, Objective
     13from coopr.pyomo.base import expr, Var, Constraint, Objective
    1414from coopr.pyomo.base.numvalue import NumericConstant
    1515from coopr.pyomo.base.var import _VarValue
     
    159159        The main routine to perform the presolve
    160160        """
    161         Vars = model._component[_VarBase]
    162         Con = model._component[Constraint]
    163         Obj = model._component[Objective]
     161        #Vars = model.active_components(Var)
     162        Con = model.active_components(Constraint)
     163        Obj = model.active_components(Objective)
    164164        #
    165165        # Collect the linear terms
     
    174174            nt = 0
    175175            for ondx in obj._data:
     176                if not obj._data[ondx].active:
     177                    continue
    176178                if obj._data[ondx].expr is None:
    177179                    raise ValueError, "No expression has been defined for objective %s" % str(key)
     
    207209           nt = 0 # track number of constraint indicies with non-trivial bodies
    208210           for cndx in C.keys():
     211              if not C._data[cndx].active:
     212                    continue
    209213                 
    210214#              print "Collecting linear terms for constraint="+key+"["+str(cndx)+"]"
  • coopr.pyomo/stable/2.1/coopr/pyomo/presolve/generic_varlabels.py

    r1768 r2070  
    99#  _________________________________________________________________________
    1010
    11 from coopr.pyomo.base import IPyomoPresolver, IPyomoPresolveAction, _VarBase
     11from coopr.pyomo.base import IPyomoPresolver, IPyomoPresolveAction, Var, Constraint
    1212import pyutilib.plugin.core
    1313
    14 ignore = set(['"', ' ', "'", '`'])
    15 #underscore = set(['[', ']', "(", ')', ',', '-'])
    16 underscore = set(['-'])
     14ignore = set(['"', "'", '`'])
     15remap = {}
     16# Remap as underscores
     17remap['-']='_'
     18remap['_']='_'
     19remap[' ']='_'
     20remap['(']='['
     21remap['{']='['
     22remap[')']=']'
     23remap['}']=']'
     24# Remap as Q+ASCII-Dec
     25remap['!']='_Q33_'
     26remap['#']='_Q35_'
     27remap['$']='_Q36_'
     28remap['%']='_Q37_'
     29remap['&']='_Q38_'
     30remap['*']='_Q42_'
     31remap['+']='_Q43_'
     32#remap[',']='_Q44_'
     33remap['.']='_Q46_'
     34remap['/']='_Q47_'
     35remap[';']='_Q59_'
     36remap['<']='_Q60_'
     37remap['=']='_Q61_'
     38remap['>']='_Q62_'
     39remap['?']='_Q63_'
     40remap['@']='_Q63_'
     41remap['\\']='_Q92_'
     42remap['^']='_Q94_'
     43remap['|']='_Q124_'
     44remap['~']='_Q126_'
    1745
    1846class GenericVarLabelsPresolver(pyutilib.plugin.core.SingletonPlugin):
     
    3361    def _name_fix(self, name):
    3462        global ignore
    35         global underscore
     63        global remap
    3664        tmp=""
    3765        for c in name:
    38             if c in underscore:
    39                 tmp += '_'
    40             elif c is '(':
    41                 tmp += '['
    42             elif c is ')':
    43                 tmp += ']'
     66            if c in remap:
     67                tmp += remap[c]
    4468            elif not c in ignore:
    4569                tmp += c
     
    5579        # variables.
    5680        #
    57         Vars = model._component[_VarBase]
     81        Vars = model.active_components(Var)
    5882        for var in Vars.values():
    5983            for V in var._varval.keys():
    6084                var._varval[V].label = self._name_fix( var._varval[V].name )
    6185                model._name_varmap[ var._varval[V].label ] = var._varval[V]
    62         for id in model._con:
    63             model._con[id].label = self._name_fix( model._con[id].name )
     86        Cons = model.active_components(Constraint)
     87        for con in Cons.values():
     88            for C in con._data:
     89                con._data[C].label = self._name_fix( con._data[C].name )
     90                model._name_conmap[ con._data[C].label ] = con._data[C]
    6491        return model
    6592           
  • coopr.pyomo/stable/2.1/coopr/pyomo/presolve/identify_vars.py

    r1768 r2070  
    1111
    1212import pyutilib.plugin.core
    13 from coopr.pyomo.base import expr, _VarBase, Constraint, Objective
     13from coopr.pyomo.base import expr, _VarBase, Var, Constraint, Objective
    1414from coopr.pyomo.base.var import _VarValue, VarStatus
    1515from coopr.pyomo.base.numvalue import NumericConstant
     
    7070                tmp.id = self.vnum
    7171                model._var[self.vnum] = tmp
     72            if model._var[self.vnum].is_binary():
     73                model.statistics.number_of_binary_variables += 1
     74            elif model._var[self.vnum].is_integer():
     75                model.statistics.number_of_integer_variables += 1
     76            else:
     77                model.statistics.number_of_continuous_variables +=1
    7278            self.vnum += 1
    7379        #
     
    8288        The main routine to perform the presolve
    8389        """
    84         Vars = model._component[_VarBase]
    85         Con = model._component[Constraint]
    86         Obj = model._component[Objective]
     90        Vars = model.active_components(Var)
     91        Con = model.active_components(Constraint)
     92        Obj = model.active_components(Objective)
    8793        self.vnum=0
    8894        self.cnum=0
    8995        self.onum=0
     96        model.statistics.number_of_binary_variables = 0
     97        model.statistics.number_of_integer_variables = 0
     98        model.statistics.number_of_continuous_variables = 0
    9099        #
    91100        # Indicate that all variables are unused
     
    101110        for key in Obj.keys():
    102111            for ondx in Obj[key]._data:
     112                if not Obj[key]._data[ondx].active:
     113                    continue
    103114                try:
    104115                    self._identify_variables(Obj[key]._data[ondx].expr, model)
     
    111122            C = Con[key]
    112123            for cndx in C.keys():
     124                if not C._data[cndx].active:
     125                    continue
    113126                try:
    114127                    self._identify_variables(C._data[cndx].body, model)
     
    118131                model._con[self.cnum] = C._data[cndx]
    119132                self.cnum += 1
    120         model.vnum=self.vnum
    121         model.cnum=self.cnum
    122         model.onum=self.onum
     133        model.statistics.number_of_variables=self.vnum
     134        model.statistics.number_of_constraints=self.cnum
     135        model.statistics.number_of_objectives=self.onum
    123136        return model
    124137
  • coopr.pyomo/stable/2.1/coopr/pyomo/tests/unit/test_expr.py

    r1972 r2070  
    479479            return (model.b[i],0.0)
    480480
    481         def c6_rule(model):
     481        def c6a_rule(model):
    482482            return 0.0 <= model.c
    483         def c7_rule(model):
     483        def c6b_rule(model):
     484            return 0.0 < model.c
     485        def c7a_rule(model):
    484486            return model.c <= 1.0
     487        def c7b_rule(model):
     488            return model.c < 1.0
    485489        def c8_rule(model):
    486490            return model.c == 2.0
    487         def c9_rule(model):
     491        def c9a_rule(model):
    488492            return model.A+model.A <= model.c
    489         def c10_rule(model):
     493        def c9b_rule(model):
     494            return model.A+model.A < model.c
     495        def c10a_rule(model):
    490496            return model.c <= model.B+model.B
     497        def c10b_rule(model):
     498            return model.c < model.B+model.B
    491499        def c11_rule(model):
    492500            return model.c == model.A+model.B
     501        def c15a_rule(model):
     502            return model.A <= model.A*model.d
     503        def c15b_rule(model):
     504            return model.A < model.A*model.d
     505        def c16a_rule(model):
     506            return model.A*model.d <= model.B
     507        def c16b_rule(model):
     508            return model.A*model.d < model.B
    493509
    494510        def c12_rule(model):
    495511            return model.c == model.d
    496         def c13_rule(model):
     512        def c13a_rule(model):
    497513            return model.c <= model.d
    498         def c14_rule(model):
     514        def c13b_rule(model):
     515            return model.c < model.d
     516        def c14a_rule(model):
    499517            return model.c >= model.d
    500 
    501         def c20_rule(model):
    502             return model.A > model.c > model.B
    503         def c21_rule(model):
    504             return model.A > model.c < model.B
    505         def c22_rule(model):
    506             return model.A < model.c > model.B
    507         def c23_rule(model):
    508             return model.A < model.c < model.B
     518        def c14b_rule(model):
     519            return model.c > model.d
     520
     521        #def c20_rule(model):
     522            #return model.A > model.c > model.B
     523        #def c21_rule(model):
     524            #return model.A > model.c < model.B
     525        #def c22_rule(model):
     526            #return model.A < model.c > model.B
     527        #def c23_rule(model):
     528            #return model.A < model.c < model.B
    509529
    510530        def o2_rule(i,model):
     
    527547        model.c5 = Constraint(model.a,rule=c5_rule)
    528548
    529         model.c6 = Constraint(rule=c6_rule)
    530         model.c7 = Constraint(rule=c7_rule)
     549        model.c6a = Constraint(rule=c6a_rule)
     550        model.c6b = Constraint(rule=c6b_rule)
     551        model.c7a = Constraint(rule=c7a_rule)
     552        model.c7b = Constraint(rule=c7b_rule)
    531553        model.c8 = Constraint(rule=c8_rule)
    532         model.c9 = Constraint(rule=c9_rule)
    533         model.c10 = Constraint(rule=c10_rule)
     554        model.c9a = Constraint(rule=c9a_rule)
     555        model.c9b = Constraint(rule=c9b_rule)
     556        model.c10a = Constraint(rule=c10a_rule)
     557        model.c10b = Constraint(rule=c10b_rule)
    534558        model.c11 = Constraint(rule=c11_rule)
     559        model.c15a = Constraint(rule=c15a_rule)
     560        model.c15b = Constraint(rule=c15b_rule)
     561        model.c16a = Constraint(rule=c16a_rule)
     562        model.c16b = Constraint(rule=c16b_rule)
    535563
    536564        model.c12 = Constraint(rule=c12_rule)
    537         model.c13 = Constraint(rule=c13_rule)
    538         model.c14 = Constraint(rule=c14_rule)
     565        model.c13a = Constraint(rule=c13a_rule)
     566        model.c13b = Constraint(rule=c13b_rule)
     567        model.c14a = Constraint(rule=c14a_rule)
     568        model.c14b = Constraint(rule=c14b_rule)
    539569
    540570        #model.c20 = Constraint(rule=c20_rule)
     
    595625            #pass
    596626        try:
    597             model.a._construct(model,None)
     627            model.a.construct()
    598628            self.fail("Can't construct a parameter without data")
    599629        except ValueError:
     
    745775        model=Model()
    746776        model.a=Set(initialize=[1,2,3])
    747         model.b=Objective(model.a)
     777        model.x=Var()
     778        def b_rule(i,model):
     779            return model.x
     780        model.b=Objective(model.a, rule=b_rule)
    748781        instance=model.create()
    749782        self.failUnlessEqual(2 in instance.b,True)
     
    837870        model=Model()
    838871        model.o = Constraint(rule=rule1)
     872        instance=model.create()
    839873        try:
    840874            instance=model.create()
  • coopr.pyomo/stable/2.1/coopr/pyomo/tests/unit/test_model.py

    r1972 r2070  
    22# Unit Tests for Elements of a Model
    33#
    4 # TestSimpleVar                Class for testing single variables
    5 # TestArrayVar                Class for testing array of variables
    6 # TestSimpleObj                Class for testing single objective
    7 # TestArrayObj                Class for testing array of objective
    8 # TestSimpleCon                Class for testing single constraint
    9 # TestArrayCon                Class for testing array of constraint
    10 # TestModel             Class to test the Model class
     4# Test             Class to test the Model class
    115#
    126
     
    3428
    3529
    36 class TestSimpleVar(PyomoModel):
     30class Test(PyomoModel):
    3731
    3832    def setUp(self):
     
    4337
    4438    def tearDown(self):
    45         pass
    46 
    47     def test_fixed_attr(self):
    48         """Test fixed attribute"""
    49         self.model.x = Var()
    50         self.instance = self.model.create()
    51         self.instance.x.fixed = True
    52         self.failUnlessEqual(self.instance.x.fixed, True)
    53 
    54     def test_value_attr(self):
    55         """Test value attribute"""
    56         self.model.x = Var()
    57         self.instance = self.model.create()
    58         self.instance.x.value = 3.5
    59         self.failUnlessEqual(self.instance.x.value, 3.5)
    60 
    61     def test_initial_attr(self):
    62         """Test initial attribute"""
    63         self.model.x = Var()
    64         self.instance = self.model.create()
    65         self.instance.x.initial = 3.5
    66         self.failUnlessEqual(self.instance.x.initial, 3.5)
    67 
    68     def test_domain_attr(self):
    69         """Test domain attribute"""
    70         self.model.x = Var()
    71         self.instance = self.model.create()
    72         self.instance.x.domain = Integers
    73         self.failUnlessEqual(type(self.instance.x.domain), IntegerSet)
    74 
    75     def test_name_attr(self):
    76         """Test name attribute"""
    77         #
    78         # A user would never need to do this, but this
    79         # attribute is needed within Pyomo
    80         #
    81         self.model.x = Var()
    82         self.model.x.name = "foo"
    83         self.failUnlessEqual(self.model.x.name, "foo")
    84 
    85     def test_lb_attr1(self):
    86         """Test lb attribute"""
    87         self.model.x = Var()
    88         self.instance = self.model.create()
    89         self.instance.x.setlb(-1.0)
    90         self.failUnlessEqual(self.instance.x.lb(), -1.0)
    91 
    92     def test_lb_attr2(self):
    93         """Test lb attribute"""
    94         self.model.x = Var(within=NonNegativeReals, bounds=(-1,2))
    95         self.instance = self.model.create()
    96         self.failUnlessEqual(self.instance.x.lb(), 0.0)
    97         self.failUnlessEqual(self.instance.x.ub(), 2.0)
    98 
    99     def test_ub_attr1(self):
    100         """Test ub attribute"""
    101         self.model.x = Var()
    102         self.instance = self.model.create()
    103         self.instance.x.setub(1.0)
    104         self.failUnlessEqual(self.instance.x.ub(), 1.0)
    105 
    106     def test_ub_attr2(self):
    107         """Test ub attribute"""
    108         self.model.x = Var(within=NonPositiveReals, bounds=(-2,1))
    109         self.instance = self.model.create()
    110         self.failUnlessEqual(self.instance.x.lb(), -2.0)
    111         self.failUnlessEqual(self.instance.x.ub(), 0.0)
    112 
    113     def test_within_option(self):
    114         """Test within option"""
    115         self.model.x = Var(within=Integers)
    116         self.failUnlessEqual(type(self.model.x.domain), IntegerSet)
    117 
    118     def test_initialize_option(self):
    119         """Test initialize option"""
    120         self.model.x = Var(initialize=1.3)
    121         self.instance = self.model.create()
    122         self.failUnlessEqual(self.instance.x.initial, 1.3)
    123 
    124     def test_bounds_option1(self):
    125         """Test bounds option"""
    126         def x_bounds(model):
    127           return (-1.0,1.0)
    128         self.model.x = Var(bounds=x_bounds)
    129         self.instance = self.model.create()
    130         self.failUnlessEqual(self.instance.x.lb(), -1.0)
    131         self.failUnlessEqual(self.instance.x.ub(), 1.0)
    132 
    133     def test_bounds_option2(self):
    134         """Test bounds option"""
    135         self.model.x = Var(bounds=(-1.0,1.0))
    136         self.instance = self.model.create()
    137         self.failUnlessEqual(self.instance.x.lb(), -1.0)
    138         self.failUnlessEqual(self.instance.x.ub(), 1.0)
    139 
    140     def test_rule_option(self):
    141         """Test rule option"""
    142         def x_init(model):
    143           return 1.3
    144         self.model.x = Var(initialize=x_init)
    145         self.instance = self.model.create()
    146         self.failUnlessEqual(self.instance.x.value, None)
    147         self.failUnlessEqual(self.instance.x.initial, 1.3)
    148 
    149     def test_reset(self):
    150         """Test reset method"""
    151         self.model.x = Var(initialize=3)
    152         self.instance = self.model.create()
    153         self.failUnlessEqual(self.instance.x.initial,3)
    154         self.failUnlessEqual(self.instance.x.value,None)
    155         self.instance.x.reset()
    156         self.failUnlessEqual(self.instance.x.initial,3)
    157         self.failUnlessEqual(self.instance.x.initial,3)
    158 
    159     def test_dim(self):
    160         """Test dim method"""
    161         self.model.x = Var()
    162         self.instance = self.model.create()
    163         self.failUnlessEqual(self.instance.x.dim(),0)
    164 
    165     def test_keys(self):
    166         """Test keys method"""
    167         self.model.x = Var()
    168         self.instance = self.model.create()
    169         self.failUnlessEqual(self.instance.x.keys(),[None])
    170 
    171     def test_len(self):
    172         """Test len method"""
    173         self.model.x = Var()
    174         self.instance = self.model.create()
    175         self.failUnlessEqual(len(self.instance.x),1)
    176 
    177     def test_simplify(self):
    178         """Test simplify method"""
    179         self.model.x = Var()
    180         self.failUnlessEqual(type(self.model.x.simplify(self.model)),_VarElement)
    181 
    182     def test_value(self):
    183         """Check the value of the variable"""
    184         self.model.x = Var(initialize=3.3)
    185         self.instance = self.model.create()
    186         tmp = value(self.instance.x.initial)
    187         self.failUnlessEqual( type(tmp), float)
    188         self.failUnlessEqual( tmp, 3.3 )
    189         tmp = float(self.instance.x.initial)
    190         self.failUnlessEqual( type(tmp), float)
    191         self.failUnlessEqual( tmp, 3.3 )
    192         tmp = int(self.instance.x.initial)
    193         self.failUnlessEqual( type(tmp), int)
    194         self.failUnlessEqual( tmp, 3 )
    195 
    196 
    197 class TestArrayVar(TestSimpleVar):
    198 
    199     def setUp(self):
    200         #
    201         # Create Model
    202         #
    203         PyomoModel.setUp(self)
    204         self.model.A = Set(initialize=[1,2])
    205 
    206     def test_fixed_attr(self):
    207         """Test fixed attribute"""
    208         self.model.x = Var(self.model.A)
    209         self.model.y = Var(self.model.A)
    210         self.instance = self.model.create()
    211         self.instance.x.fixed = True
    212         #try:
    213           #self.instance.x.fixed
    214         #except AttributeError:
    215           #pass
    216         #else:
    217           #self.fail("test_fixed_attr")
    218         self.failUnlessEqual(self.instance.x[1].fixed, False)
    219         self.instance.y[1].fixed=True
    220         self.failUnlessEqual(self.instance.y[1].fixed, True)
    221 
    222     def test_value_attr(self):
    223         """Test value attribute"""
    224         self.model.x = Var(self.model.A)
    225         self.model.y = Var(self.model.A)
    226         self.instance = self.model.create()
    227         try:
    228             self.instance.x = 3.5
    229             self.fail("Expected ValueError")
    230         except ValueError:
    231             pass
    232         self.instance.y[1] = 3.5
    233         self.failUnlessEqual(self.instance.y[1], 3.5)
    234 
    235     #def test_initial_attr(self):
    236         #"""Test initial attribute"""
    237         #self.model.x = Var(self.model.A)
    238         #self.instance = self.model.create()
    239         #self.instance.x.initial = 3.5
    240         #self.failUnlessEqual(self.instance.x[1].initial, 3.5)
    241 
    242     #def test_lb_attr(self):
    243         #"""Test lb attribute"""
    244         #self.model.x = Var(self.model.A)
    245         #self.instance = self.model.create()
    246         #self.instance.x.setlb(-1.0)
    247         #self.failUnlessEqual(self.instance.x[1].lb(), -1.0)
    248 
    249     #def test_ub_attr(self):
    250         #"""Test ub attribute"""
    251         #self.model.x = Var(self.model.A)
    252         #self.instance = self.model.create()
    253         #self.instance.x.setub(1.0)
    254         #self.failUnlessEqual(self.instance.x[1].ub(), 1.0)
    255 
    256     def test_initialize_option(self):
    257         """Test initialize option"""
    258         self.model.x = Var(self.model.A,initialize={1:1.3,2:2.3})
    259         self.instance = self.model.create()
    260         self.failUnlessEqual(self.instance.x[1], 1.3)
    261         self.failUnlessEqual(self.instance.x[2], 2.3)
    262 
    263     def test_bounds_option1(self):
    264         """Test bounds option"""
    265         def x_bounds(i,model):
    266           return (-1.0,1.0)
    267         self.model.x = Var(self.model.A, bounds=x_bounds)
    268         self.instance = self.model.create()
    269         self.failUnlessEqual(self.instance.x[1].lb(), -1.0)
    270         self.failUnlessEqual(self.instance.x[1].ub(), 1.0)
    271 
    272     def test_bounds_option2(self):
    273         """Test bounds option"""
    274         self.model.x = Var(self.model.A, bounds=(-1.0,1.0))
    275         self.instance = self.model.create()
    276         self.failUnlessEqual(self.instance.x[1].lb(), -1.0)
    277         self.failUnlessEqual(self.instance.x[1].ub(), 1.0)
    278 
    279     def test_rule_option(self):
    280         """Test rule option"""
    281         def x_init(i,model):
    282           return 1.3
    283         self.model.x = Var(self.model.A, initialize=x_init)
    284         self.instance = self.model.create()
    285         self.failUnlessEqual(self.instance.x[1].initial, 1.3)
    286 
    287     def test_reset(self):
    288         """Test reset method"""
    289         self.model.x = Var(self.model.A,initialize=3)
    290         self.instance = self.model.create()
    291         self.failUnlessEqual(self.instance.x[1].initial,3)
    292         self.failUnlessEqual(self.instance.x[1].value,None)
    293         self.instance.x.reset()
    294         self.failUnlessEqual(self.instance.x[1].initial,3)
    295         self.failUnlessEqual(self.instance.x[1].initial,3)
    296 
    297     def test_dim(self):
    298         """Test dim method"""
    299         self.model.x = Var(self.model.A)
    300         self.instance = self.model.create()
    301         self.failUnlessEqual(self.instance.x.dim(),1)
    302 
    303     def test_keys(self):
    304         """Test keys method"""
    305         self.model.x = Var(self.model.A)
    306         self.instance = self.model.create()
    307         self.failUnlessEqual(self.instance.x.keys(),[1,2])
    308 
    309     def test_len(self):
    310         """Test len method"""
    311         self.model.x = Var(self.model.A)
    312         self.instance = self.model.create()
    313         self.failUnlessEqual(len(self.instance.x),2)
    314 
    315     def test_value(self):
    316         """Check the value of the variable"""
    317         self.model.x = Var(self.model.A,initialize=3.3)
    318         self.instance = self.model.create()
    319         tmp = value(self.instance.x[1].initial)
    320         self.failUnlessEqual( type(tmp), float)
    321         self.failUnlessEqual( tmp, 3.3 )
    322         tmp = float(self.instance.x[1].initial)
    323         self.failUnlessEqual( type(tmp), float)
    324         self.failUnlessEqual( tmp, 3.3 )
    325         tmp = int(self.instance.x[1].initial)
    326         self.failUnlessEqual( type(tmp), int)
    327         self.failUnlessEqual( tmp, 3 )
    328 
    329 
    330 class Test2DArrayVar(TestSimpleVar):
    331 
    332     def setUp(self):
    333         #
    334         # Create Model
    335         #
    336         PyomoModel.setUp(self)
    337         self.model.A = Set(initialize=[1,2])
    338 
    339     def test_fixed_attr(self):
    340         """Test fixed attribute"""
    341         self.model.x = Var(self.model.A,self.model.A)
    342         self.model.y = Var(self.model.A,self.model.A)
    343         self.instance = self.model.create()
    344         self.instance.x.fixed = True
    345         #try:
    346           #self.instance.x.fixed
    347         #except AttributeError:
    348           #pass
    349         #else:
    350           #self.fail("test_fixed_attr")
    351         self.failUnlessEqual(self.instance.x[1,2].fixed, False)
    352         self.instance.y[1,2].fixed=True
    353         self.failUnlessEqual(self.instance.y[1,2].fixed, True)
    354 
    355     def test_value_attr(self):
    356         """Test value attribute"""
    357         self.model.x = Var(self.model.A,self.model.A)
    358         self.model.y = Var(self.model.A,self.model.A)
    359         self.instance = self.model.create()
    360         try:
    361             self.instance.x = 3.5
    362             self.fail("Expected ValueError")
    363         except ValueError:
    364             pass
    365         self.instance.y[1,2] = 3.5
    366         self.failUnlessEqual(self.instance.y[1,2], 3.5)
    367 
    368     #def test_initial_attr(self):
    369         #"""Test initial attribute"""
    370         #self.model.x = Var(self.model.A,self.model.A)
    371         #self.instance = self.model.create()
    372         #self.instance.x.initial = 3.5
    373         #self.failUnlessEqual(self.instance.x[1,1].initial, 3.5)
    374 
    375     #def test_lb_attr(self):
    376         #"""Test lb attribute"""
    377         #self.model.x = Var(self.model.A,self.model.A)
    378         #self.instance = self.model.create()
    379         #self.instance.x.setlb(-1.0)
    380         #self.failUnlessEqual(self.instance.x[2,1].lb(), -1.0)
    381 
    382     #def test_ub_attr(self):
    383         #"""Test ub attribute"""
    384         #self.model.x = Var(self.model.A,self.model.A)
    385         #self.instance = self.model.create()
    386         #self.instance.x.setub(1.0)
    387         #self.failUnlessEqual(self.instance.x[2,1].ub(), 1.0)
    388 
    389     def test_initialize_option(self):
    390         """Test initialize option"""
    391         self.model.x = Var(self.model.A,self.model.A,initialize={(1,1):1.3,(2,2):2.3})
    392         self.instance = self.model.create()
    393         self.failUnlessEqual(self.instance.x[1,1], 1.3)
    394         self.failUnlessEqual(self.instance.x[2,2], 2.3)
    395         try:
    396             value(self.instance.x[1,2])
    397             self.fail("Expected KeyError")
    398         except KeyError:
    399             pass
    400 
    401     def test_bounds_option1(self):
    402         """Test bounds option"""
    403         def x_bounds(i,j,model):
    404           return (-1.0*(i+j),1.0*(i+j))
    405         self.model.x = Var(self.model.A, self.model.A, bounds=x_bounds)
    406         self.instance = self.model.create()
    407         self.failUnlessEqual(self.instance.x[1,1].lb(), -2.0)
    408         self.failUnlessEqual(self.instance.x[1,2].ub(), 3.0)
    409 
    410     def test_bounds_option2(self):
    411         """Test bounds option"""
    412         self.model.x = Var(self.model.A, self.model.A, bounds=(-1.0,1.0))
    413         self.instance = self.model.create()
    414         self.failUnlessEqual(self.instance.x[1,1].lb(), -1.0)
    415         self.failUnlessEqual(self.instance.x[1,1].ub(), 1.0)
    416 
    417     def test_rule_option(self):
    418         """Test rule option"""
    419         def x_init(i,j,model):
    420           return 1.3
    421         self.model.x = Var(self.model.A, self.model.A, initialize=x_init)
    422         self.instance = self.model.create()
    423         self.failUnlessEqual(self.instance.x[1,2].initial, 1.3)
    424 
    425     def test_reset(self):
    426         """Test reset method"""
    427         self.model.x = Var(self.model.A,self.model.A, initialize=3)
    428         self.instance = self.model.create()
    429         self.failUnlessEqual(self.instance.x[1,1].initial,3)
    430         self.failUnlessEqual(self.instance.x[1,1].value,None)
    431         self.instance.x.reset()
    432         self.failUnlessEqual(self.instance.x[1,1].initial,3)
    433         self.failUnlessEqual(self.instance.x[1,1].initial,3)
    434 
    435     def test_dim(self):
    436         """Test dim method"""
    437         self.model.x = Var(self.model.A,self.model.A)
    438         self.instance = self.model.create()
    439         self.failUnlessEqual(self.instance.x.dim(),2)
    440 
    441     def test_keys(self):
    442         """Test keys method"""
    443         self.model.x = Var(self.model.A,self.model.A)
    444         self.instance = self.model.create()
    445         ans = [(1,1),(1,2),(2,1),(2,2)]
    446         self.failUnlessEqual(self.instance.x.keys().sort(),ans.sort())
    447 
    448     def test_len(self):
    449         """Test len method"""
    450         self.model.x = Var(self.model.A,self.model.A)
    451         self.instance = self.model.create()
    452         self.failUnlessEqual(len(self.instance.x),4)
    453 
    454     def test_value(self):
    455         """Check the value of the variable"""
    456         self.model.x = Var(self.model.A,self.model.A,initialize=3.3)
    457         self.instance = self.model.create()
    458         tmp = value(self.instance.x[1,1].initial)
    459         self.failUnlessEqual( type(tmp), float)
    460         self.failUnlessEqual( tmp, 3.3 )
    461         tmp = float(self.instance.x[1,1].initial)
    462         self.failUnlessEqual( type(tmp), float)
    463         self.failUnlessEqual( tmp, 3.3 )
    464         tmp = int(self.instance.x[1,1].initial)
    465         self.failUnlessEqual( type(tmp), int)
    466         self.failUnlessEqual( tmp, 3 )
    467 
    468 
    469 class TestVarComplexArray(PyomoModel):
    470 
    471     def test_index1(self):
    472         self.model.A = Set(initialize=range(0,4))
    473         def B_index(model):
    474             for i in model.A:
    475                 if i%2 == 0:
    476                     yield i
    477         def B_init(i,j,model):
    478             if j:
    479                 return 2+i
    480             return -(2+i)
    481         self.model.B = Var(B_index, [True,False], initialize=B_init)
    482         self.instance = self.model.create()
    483         #self.instance.pprint()
    484         self.failUnlessEqual(set(self.instance.B.keys()),set([(0,True),(2,True),(0,   False),(2,False)]))
    485         self.failUnlessEqual(self.instance.B[0,True],2)
    486         self.failUnlessEqual(self.instance.B[0,False],-2)
    487         self.failUnlessEqual(self.instance.B[2,True],4)
    488         self.failUnlessEqual(self.instance.B[2,False],-4)
    489 
    490 
    491 class TestSimpleObj(PyomoModel):
    492 
    493     def setUp(self):
    494         #
    495         # Create Model
    496         #
    497         PyomoModel.setUp(self)
    498 
    499     def tearDown(self):
    500         pass
    501 
    502     def test_rule_option(self):
    503         """Test rule option"""
    504         def f(model):
    505           ans=0
    506           for i in model.x.keys():
    507             ans = ans + model.x[i]
    508           return ans
    509         self.model.x = Var(RangeSet(1,4),initialize=2)
    510         self.model.obj = Objective(rule=f)
    511         self.instance = self.model.create()
    512         try:
    513           self.failUnlessEqual(self.instance.obj(), 8)
    514         except ValueError:
    515           pass
    516         else:
    517           self.fail("test_rule_option")
    518         self.instance.x.reset()
    519         self.failUnlessEqual(self.instance.obj(), 8)
    520         self.failUnlessEqual(value(self.instance.obj), 8)
    521 
    522     def test_sense_option(self):
    523         """Test sense option"""
    524         def rule(model):
    525             return 1.0
    526         self.model.obj = Objective(sense=maximize, rule=rule)
    527         self.instance = self.model.create()
    528         self.failUnlessEqual(self.instance.obj.sense, maximize)
    529 
    530     def test_dim(self):
    531         """Test dim method"""
    532         def rule(model):
    533             return 1
    534         self.model.obj = Objective(rule=rule)
    535         self.instance = self.model.create()
    536         self.failUnlessEqual(self.instance.obj.dim(),0)
    537 
    538     def test_keys(self):
    539         """Test keys method"""
    540         def rule(model):
    541             return 1
    542         self.model.obj = Objective(rule=rule)
    543         self.instance = self.model.create()
    544         self.failUnlessEqual(self.instance.obj.keys(),[None])
    545 
    546     def test_len(self):
    547         """Test len method"""
    548         def rule(model):
    549             return 1.0
    550         self.model.obj = Objective(rule=rule)
    551         self.instance = self.model.create()
    552         self.failUnlessEqual(len(self.instance.obj),1)
    553         """Test rule option"""
    554         def f(model):
    555           ans=0
    556           for i in model.x.keys():
    557             ans = ans + model.x[i]
    558           return ans
    559         self.model.x = Var(RangeSet(1,4),initialize=2)
    560         self.model.obj = Objective(rule=f)
    561         self.instance = self.model.create()
    562         self.failUnlessEqual(len(self.instance.obj),1)
    563 
    564 
    565 class TestArrayObj(PyomoModel):
    566 
    567     def setUp(self):
    568         #
    569         # Create Model
    570         #
    571         PyomoModel.setUp(self)
    572         self.model.A = Set(initialize=[1,2])
    573 
    574     def tearDown(self):
    575         pass
    576 
    577     def test_rule_option(self):
    578         """Test rule option"""
    579         def f(i,model):
    580           ans=0
    581           for j in model.x.keys():
    582             ans = ans + model.x[j]
    583           ans *= i
    584           return ans
    585         self.model.x = Var(RangeSet(1,4),initialize=2)
    586         self.model.obj = Objective(self.model.A,rule=f)
    587         self.instance = self.model.create()
    588         try:
    589             self.instance.obj[1]()
    590             self.fail("Excepted ValueError due to uninitialized variables")
    591         except ValueError:
    592             pass
    593         self.instance.x.reset()
    594         self.failUnlessEqual(self.instance.obj[1](), 8)
    595         self.failUnlessEqual(self.instance.obj[2](), 16)
    596         self.failUnlessEqual(value(self.instance.obj[1]), 8)
    597         self.failUnlessEqual(value(self.instance.obj[2]), 16)
    598 
    599     def test_sense_option(self):
    600         """Test sense option"""
    601         self.model.obj = Objective(self.model.A,sense=maximize)
    602         self.instance = self.model.create()
    603         self.failUnlessEqual(self.instance.obj.sense, maximize)
    604 
    605     def test_dim(self):
    606         """Test dim method"""
    607         self.model.obj = Objective(self.model.A)
    608         self.instance = self.model.create()
    609         self.failUnlessEqual(self.instance.obj.dim(),1)
    610 
    611     def test_keys(self):
    612         """Test keys method"""
    613         self.model.obj = Objective(self.model.A)
    614         self.instance = self.model.create()
    615         self.failUnlessEqual(len(self.instance.obj.keys()),2)
    616 
    617     def test_len(self):
    618         """Test len method"""
    619         self.model.obj = Objective(self.model.A)
    620         self.instance = self.model.create()
    621         self.failUnlessEqual(len(self.instance.obj),0)
    622         """Test rule option"""
    623         def f(model):
    624           ans=0
    625           for i in model.x.keys():
    626             ans = ans + model.x[i]
    627           return ans
    628         self.model.x = Var(RangeSet(1,4),initialize=2)
    629         self.model.obj = Objective(rule=f)
    630         self.instance = self.model.create()
    631         self.failUnlessEqual(len(self.instance.obj),1)
    632 
    633 
    634 class Test2DArrayObj(PyomoModel):
    635 
    636     def setUp(self):
    637         #
    638         # Create Model
    639         #
    640         PyomoModel.setUp(self)
    641         self.model.A = Set(initialize=[1,2])
    642 
    643     def tearDown(self):
    644         pass
    645 
    646     def test_rule_option(self):
    647         """Test rule option"""
    648         def f(i,k,model):
    649           ans=0
    650           for j in model.x.keys():
    651             ans = ans + model.x[j]
    652           ans *= i
    653           return ans
    654         self.model.x = Var(RangeSet(1,4),initialize=2)
    655         self.model.obj = Objective(self.model.A,self.model.A, rule=f)
    656         self.instance = self.model.create()
    657         try:
    658             self.failUnlessEqual(self.instance.obj(),None)
    659             self.fail("Expected ValueError")
    660         except ValueError:
    661             pass
    662         self.instance.x.reset()
    663         self.failUnlessEqual(self.instance.obj[1,1](), 8)
    664         self.failUnlessEqual(self.instance.obj[2,1](), 16)
    665         self.failUnlessEqual(value(self.instance.obj[1,1]), 8)
    666         self.failUnlessEqual(value(self.instance.obj[2,1]), 16)
    667 
    668     def test_sense_option(self):
    669         """Test sense option"""
    670         self.model.obj = Objective(self.model.A,self.model.A,sense=maximize)
    671         self.instance = self.model.create()
    672         self.failUnlessEqual(self.instance.obj.sense, maximize)
    673 
    674     def test_dim(self):
    675         """Test dim method"""
    676         self.model.obj = Objective(self.model.A,self.model.A)
    677         self.instance = self.model.create()
    678         self.failUnlessEqual(self.instance.obj.dim(),2)
    679 
    680     def test_keys(self):
    681         """Test keys method"""
    682         self.model.obj = Objective(self.model.A,self.model.A)
    683         self.instance = self.model.create()
    684         self.failUnlessEqual(len(self.instance.obj.keys()),4)
    685 
    686     def test_len(self):
    687         """Test len method"""
    688         self.model.obj = Objective(self.model.A,self.model.A)
    689         self.instance = self.model.create()
    690         self.failUnlessEqual(len(self.instance.obj),0)
    691         """Test rule option"""
    692         def f(model):
    693           ans=0
    694           for i in model.x.keys():
    695             ans = ans + model.x[i]
    696           return ans
    697         self.model.x = Var(RangeSet(1,4),initialize=2)
    698         self.model.obj = Objective(rule=f)
    699         self.instance = self.model.create()
    700         self.failUnlessEqual(len(self.instance.obj),1)
    701 
    702 
    703 class TestSimpleCon(PyomoModel):
    704 
    705     def setUp(self):
    706         #
    707         # Create Model
    708         #
    709         PyomoModel.setUp(self)
    710 
    711     def tearDown(self):
    712         pass
    713 
    714     def test_rule1(self):
    715         """Test rule option"""
    716         def f(model):
    717           ans=0
    718           for i in model.x.keys():
    719             ans = ans + model.x[i]
    720           ans = ans >= 0
    721           ans = ans <= 1
    722           return ans
    723         self.model.x = Var(RangeSet(1,4),initialize=2)
    724         self.model.c = Constraint(rule=f)
    725         self.instance = self.model.create()
    726         try:
    727           self.failUnlessEqual(self.instance.c(), 8)
    728         except ValueError:
    729           pass
    730         else:
    731           self.fail("test_rule_option")
    732         self.instance.x.reset()
    733         self.failUnlessEqual(self.instance.c(), 8)
    734         self.failUnlessEqual(value(self.instance.c), 8)
    735 
    736     def test_rule2(self):
    737         """Test rule option"""
    738         def f(model):
    739           ans=0
    740           for i in model.x.keys():
    741             ans = ans + model.x[i]
    742           return (0,ans,1)
    743         self.model.x = Var(RangeSet(1,4),initialize=2)
    744         self.model.c = Constraint(rule=f)
    745         self.instance = self.model.create()
    746         try:
    747           self.failUnlessEqual(self.instance.c(), 8)
    748         except ValueError:
    749           pass
    750         else:
    751           self.fail("test_rule_option")
    752         self.instance.x.reset()
    753         self.failUnlessEqual(self.instance.c(), 8)
    754         self.failUnlessEqual(value(self.instance.c), 8)
    755 
    756     def test_rule3(self):
    757         """Test rule option"""
    758         def f(model):
    759           ans=0
    760           for i in model.x.keys():
    761             ans = ans + model.x[i]
    762           return (0,ans,None)
    763         self.model.x = Var(RangeSet(1,4),initialize=2)
    764         self.model.c = Constraint(rule=f)
    765         self.instance = self.model.create()
    766         try:
    767           self.failUnlessEqual(self.instance.c(), 8)
    768         except ValueError:
    769           pass
    770         else:
    771           self.fail("test_rule_option")
    772         self.instance.x.reset()
    773         self.failUnlessEqual(self.instance.c(), 8)
    774         self.failUnlessEqual(value(self.instance.c), 8)
    775 
    776     def test_rule4(self):
    777         """Test rule option"""
    778         def f(model):
    779           ans=0
    780           for i in model.x.keys():
    781             ans = ans + model.x[i]
    782           return (None,ans,1)
    783         self.model.x = Var(RangeSet(1,4),initialize=2)
    784         self.model.c = Constraint(rule=f)
    785         self.instance = self.model.create()
    786         try:
    787           self.failUnlessEqual(self.instance.c(), 8)
    788         except ValueError:
    789           pass
    790         else:
    791           self.fail("test_rule_option")
    792         self.instance.x.reset()
    793         self.failUnlessEqual(self.instance.c(), 8)
    794         self.failUnlessEqual(value(self.instance.c), 8)
    795 
    796     def test_rule5(self):
    797         """Test rule option"""
    798         def f(model):
    799           ans=0
    800           for i in model.x.keys():
    801             ans = ans + model.x[i]
    802           return (ans,1)
    803         self.model.x = Var(RangeSet(1,4),initialize=2)
    804         self.model.c = Constraint(rule=f)
    805         self.instance = self.model.create()
    806         try:
    807           self.failUnlessEqual(self.instance.c(), 8)
    808         except ValueError:
    809           pass
    810         else:
    811           self.fail("test_rule_option")
    812         self.instance.x.reset()
    813         self.failUnlessEqual(self.instance.c(), 8)
    814         self.failUnlessEqual(value(self.instance.c), 8)
    815 
    816     def test_dim(self):
    817         """Test dim method"""
    818         self.model.c = Constraint()
    819         self.instance = self.model.create()
    820         self.failUnlessEqual(self.instance.c.dim(),0)
    821 
    822     def test_keys(self):
    823         """Test keys method"""
    824         self.model.c = Constraint()
    825         self.instance = self.model.create()
    826         self.failUnlessEqual(self.instance.c.keys(),[])
    827 
    828     def test_len(self):
    829         """Test len method"""
    830         self.model.c = Constraint()
    831         self.instance = self.model.create()
    832         self.failUnlessEqual(len(self.instance.c),0)
    833         """Test rule option"""
    834         def f(model):
    835           ans=0
    836           for i in model.x.keys():
    837             ans = ans + model.x[i]
    838           ans = ans == 0
    839           return ans
    840         self.model.x = Var(RangeSet(1,4),initialize=2)
    841         self.model.c = Constraint(rule=f)
    842         self.instance = self.model.create()
    843         self.failUnlessEqual(len(self.instance.c),1)
    844 
    845 
    846 class TestArrayCon(PyomoModel):
    847 
    848     def setUp(self):
    849         #
    850         # Create Model
    851         #
    852         PyomoModel.setUp(self)
    853         self.model.A = Set(initialize=[1,2,3,4])
    854 
    855     def tearDown(self):
    856         pass
    857 
    858     def test_rule_option1(self):
    859         """Test rule option"""
    860         def f(i,model):
    861           ans=0
    862           for j in model.x.keys():
    863             ans = ans + model.x[j]
    864           ans *= i
    865           ans = ans < 0
    866           ans = ans > 0
    867           return ans
    868         self.model.x = Var(RangeSet(1,4),initialize=2)
    869         self.model.c = Constraint(self.model.A,rule=f)
    870         self.instance = self.model.create()
    871         try:
    872             self.instance.c[1]()
    873             self.fail("Expected ValueError")
    874         except ValueError:
    875             pass
    876         self.instance.x.reset()
    877         self.failUnlessEqual(self.instance.c[1](), 8)
    878         self.failUnlessEqual(self.instance.c[2](), 16)
    879         self.failUnlessEqual(value(self.instance.c[1]), 8)
    880         self.failUnlessEqual(value(self.instance.c[2]), 16)
    881         self.failUnlessEqual(len(self.instance.c), 4)
    882 
    883     def test_rule_option2(self):
    884         """Test rule option"""
    885         def f(i,model):
    886           if i%2 == 0:
    887                 return 0
    888           ans=0
    889           for j in model.x.keys():
    890             ans = ans + model.x[j]
    891           ans *= i
    892           ans = ans < 0
    893           ans = ans > 0
    894           return ans
    895         self.model.x = Var(RangeSet(1,4),initialize=2)
    896         self.model.c = Constraint(self.model.A,rule=f)
    897         self.instance = self.model.create()
    898         try:
    899             self.instance.c[1]()
    900             self.fail("Expected ValueError")
    901         except ValueError:
    902             pass
    903         self.instance.x.reset()
    904         self.failUnlessEqual(self.instance.c[1](), 8)
    905         self.failUnlessEqual(value(self.instance.c[1]), 8)
    906         self.failUnlessEqual(len(self.instance.c), 2)
    907 
    908     def test_rule_option3(self):
    909         """Test rule option"""
    910         def f(i,model):
    911           if i%2 == 0:
    912                 return None
    913           ans=0
    914           for j in model.x.keys():
    915             ans = ans + model.x[j]
    916           ans *= i
    917           ans = ans < 0
    918           ans = ans > 0
    919           return ans
    920         self.model.x = Var(RangeSet(1,4),initialize=2)
    921         self.model.c = Constraint(self.model.A,rule=f)
    922         self.instance = self.model.create()
    923         try:
    924             self.instance.c[1]()
    925             self.fail("Expected ValueError")
    926         except ValueError:
    927             pass
    928         self.instance.x.reset()
    929         self.failUnlessEqual(self.instance.c[1](), 8)
    930         self.failUnlessEqual(value(self.instance.c[1]), 8)
    931         self.failUnlessEqual(len(self.instance.c), 2)
    932 
    933     def test_rule_option4(self):
    934         """Test rule option"""
    935         def f(model):
    936           res={}
    937           for i in [0,1,2]:
    938                 ans=0
    939                 for j in model.x.keys():
    940                     ans = ans + model.x[j]
    941                 ans *= i
    942                 ans = ans < 0
    943                 ans = ans > 0
    944                 res[i]=ans
    945           return res
    946         self.model.x = Var(RangeSet(1,4),initialize=2)
    947         self.model.c = Constraint(self.model.A,rule=f)
    948         try:
    949             self.instance = self.model.create()
    950             self.fail("Expected IndexError")
    951         except IndexError:
    952             pass
    953 
    954     def test_dim(self):
    955         """Test dim method"""
    956         self.model.c = Constraint(self.model.A)
    957         self.instance = self.model.create()
    958         self.failUnlessEqual(self.instance.c.dim(),1)
    959 
    960     def test_keys(self):
    961         """Test keys method"""
    962         self.model.c = Constraint(self.model.A)
    963         self.instance = self.model.create()
    964         self.failUnlessEqual(len(self.instance.c.keys()),0)
    965 
    966     def test_len(self):
    967         """Test len method"""
    968         self.model.c = Constraint(self.model.A)
    969         self.instance = self.model.create()
    970         self.failUnlessEqual(len(self.instance.c),0)
    971         """Test rule option"""
    972         def f(model):
    973           ans=0
    974           for i in model.x.keys():
    975             ans = ans + model.x[i]
    976           ans = ans==2
    977           return ans
    978         self.model.x = Var(RangeSet(1,4),initialize=2)
    979         self.model.c = Constraint(rule=f)
    980         self.instance = self.model.create()
    981         self.failUnlessEqual(len(self.instance.c),1)
    982 
    983     def test_rule_error1(self):
    984         """Verify that errors in the rule dictionary are identified"""
    985         def f(model):
    986           res={}
    987           for i in model.A:
    988             if i%2 != 0:
    989                 ans=0
    990                 for j in model.x.keys():
    991                     ans = ans + model.x[j]
    992                 ans *= i
    993                 ans = ans < 0
    994                 ans = ans > 0
    995                 res[i]=ans
    996           return res
    997         self.model.x = Var(RangeSet(1,4),initialize=2)
    998         self.model.c = Constraint(self.model.A,rule=f)
    999         self.instance = self.model.create()
    1000         try:
    1001             self.instance.c[1]()
    1002             self.fail("Expected ValueError")
    1003         except ValueError:
    1004             pass
    1005         self.instance.x.reset()
    1006         self.failUnlessEqual(self.instance.c[1](), 8)
    1007         self.failUnlessEqual(value(self.instance.c[1]), 8)
    1008         self.failUnlessEqual(len(self.instance.c), 2)
    1009 
    1010 
    1011 
    1012 class Test2DArrayCon(PyomoModel):
    1013 
    1014     def setUp(self):
    1015         #
    1016         # Create Model
    1017         #
    1018         PyomoModel.setUp(self)
    1019         self.model.A = Set(initialize=[1,2])
    1020 
    1021     def tearDown(self):
    1022         pass
    1023 
    1024     def test_rule_option(self):
    1025         """Test rule option"""
    1026         def f(i,j,model):
    1027           ans=0
    1028           for j in model.x.keys():
    1029             ans = ans + model.x[j]
    1030           ans *= i
    1031           ans = ans < 0
    1032           ans = ans > 0
    1033           return ans
    1034         self.model.x = Var(RangeSet(1,4),initialize=2)
    1035         self.model.c = Constraint(self.model.A,self.model.A,rule=f)
    1036         self.instance = self.model.create()
    1037         try:
    1038             self.instance.c[1,1]()
    1039             self.fail("Expected ValueError")
    1040         except ValueError:
    1041             pass
    1042         self.instance.x.reset()
    1043         self.failUnlessEqual(self.instance.c[1,1](), 8)
    1044         self.failUnlessEqual(self.instance.c[2,1](), 16)
    1045         self.failUnlessEqual(value(self.instance.c[1,1]), 8)
    1046         self.failUnlessEqual(value(self.instance.c[2,1]), 16)
    1047 
    1048     def test_dim(self):
    1049         """Test dim method"""
    1050         self.model.c = Constraint(self.model.A,self.model.A)
    1051         self.instance = self.model.create()
    1052         self.failUnlessEqual(self.instance.c.dim(),2)
    1053 
    1054     def test_keys(self):
    1055         """Test keys method"""
    1056         self.model.c = Constraint(self.model.A,self.model.A)
    1057         self.instance = self.model.create()
    1058         self.failUnlessEqual(len(self.instance.c.keys()),0)
    1059 
    1060     def test_len(self):
    1061         """Test len method"""
    1062         self.model.c = Constraint(self.model.A,self.model.A)
    1063         self.instance = self.model.create()
    1064         self.failUnlessEqual(len(self.instance.c),0)
    1065         """Test rule option"""
    1066         def f(model):
    1067           ans=0
    1068           for i in model.x.keys():
    1069             ans = ans + model.x[i]
    1070           ans = ans==2
    1071           return ans
    1072         self.model.x = Var(RangeSet(1,4),initialize=2)
    1073         self.model.c = Constraint(rule=f)
    1074         self.instance = self.model.create()
    1075         self.failUnlessEqual(len(self.instance.c),1)
    1076 
    1077 
    1078 class TestModel(PyomoModel):
    1079 
    1080     def setUp(self):
    1081         #
    1082         # Create Model
    1083         #
    1084         PyomoModel.setUp(self)
    1085 
    1086     def tearDown(self):
    1087         #pass
    108839        if os.path.exists("unknown.lp"):
    108940           os.unlink("unknown.lp")
     41        pyutilib.services.TempfileManager.clear_tempfiles()
    109042
    109143    def test_clear_attribute(self):
     
    111264        self.model.x = Var(self.model.A, bounds=(-1,1))
    111365        def obj_rule(model):
    1114           expr = 0
    1115           for i in model.A:
    1116             expr += model.x[i]
    1117           return expr
     66            return summation(model.x)
    111867        self.model.obj = Objective(rule=obj_rule)
    111968        self.instance = self.model.create()
     
    112473        self.model.x = Var(self.model.A, bounds=(-1,1))
    112574        def obj_rule(model):
    1126           expr = 0
    1127           for i in model.A:
    1128             expr += model.x[i]
    1129           return expr
    1130         self.model.obj = Objective(rule=obj_rule)
    1131         def c_rule(model):
    1132           return (1, model.x[1]+model.x[2], 2)
     75            return summation(model.x)
     76        self.model.obj = Objective(rule=obj_rule)
     77        def c_rule(model):
     78            return (1, model.x[1]+model.x[2], 2)
    113379        self.model.c = Constraint(rule=c_rule)
    113480        self.instance = self.model.create()
    113581        self.instance.write()
     82
     83    def test_write3(self):
     84        """Test that the summation works correctly, even though param 'w' has a default value"""
     85        self.model.J = RangeSet(1,4)
     86        self.model.w=Param(self.model.J, default=4)
     87        self.model.x=Var(self.model.J)
     88        def obj_rule(instance):
     89            return summation(instance.x, instance.w)
     90        self.model.obj = Objective(rule=obj_rule)
     91        self.instance = self.model.create()
     92        self.failUnlessEqual(self.instance.obj[None].expr._nargs, 4)
    113693
    113794    def test_write_error(self):
     
    1144101
    1145102    def test_solve1(self):
    1146         self.model.A = RangeSet(1,4)
    1147         self.model.x = Var(self.model.A, bounds=(-1,1))
    1148         def obj_rule(model):
    1149           expr = 0
    1150           for i in model.A:
    1151             expr += model.x[i]
    1152           return expr
    1153         self.model.obj = Objective(rule=obj_rule)
    1154         def c_rule(model):
    1155           expr = 0
    1156           for i in model.A:
    1157             expr += i*model.x[i]
    1158           return (expr,0)
     103        if not pyutilib.services.registered_executable("glpsol"):
     104            return
     105        self.model.A = RangeSet(1,4)
     106        self.model.x = Var(self.model.A, bounds=(-1,1))
     107        def obj_rule(model):
     108            return summation(model.x)
     109        self.model.obj = Objective(rule=obj_rule)
     110        def c_rule(model):
     111            expr = 0
     112            for i in model.A:
     113                expr += i*model.x[i]
     114            return expr == 0
    1159115        self.model.c = Constraint(rule=c_rule)
    1160116        self.instance = self.model.create()
    1161117        #self.instance.pprint()
    1162         if not pyutilib.services.registered_executable("glpsol"):
    1163             return
    1164         else:   
    1165            opt = SolverFactory('glpk')
     118        opt = SolverFactory('glpk')
    1166119        solutions = opt.solve(self.instance, keepFiles=True)
    1167120        self.instance.load(solutions)
    1168121        self.instance.display(currdir+"solve1.out")
    1169122        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1.txt")
     123        #
     124        def d_rule(model):
     125            return model.x[1] > 0
     126        self.model.d = Constraint(rule=d_rule)
     127        self.model.d.deactivate()
     128        self.instance = self.model.create()
     129        solutions = opt.solve(self.instance, keepFiles=True)
     130        self.instance.load(solutions)
     131        self.instance.display(currdir+"solve1.out")
     132        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1.txt")
     133        #
     134        self.model.d.activate()
     135        self.instance = self.model.create()
     136        solutions = opt.solve(self.instance, keepFiles=True)
     137        self.instance.load(solutions)
     138        self.instance.display(currdir+"solve1.out")
     139        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1a.txt")
     140        #
     141        self.model.d.deactivate()
     142        def e_rule(i, model):
     143            return model.x[i] > 0
     144        self.model.e = Constraint(self.model.A, rule=e_rule)
     145        self.instance = self.model.create()
     146        for i in self.instance.A:
     147            self.instance.e[i].deactivate()
     148        solutions = opt.solve(self.instance, keepFiles=True)
     149        self.instance.load(solutions)
     150        self.instance.display(currdir+"solve1.out")
     151        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1b.txt")
     152
     153    def test_load1(self):
     154        """Testing loading of vector solutions"""
     155        self.model.A = RangeSet(1,4)
     156        self.model.x = Var(self.model.A, bounds=(-1,1))
     157        def obj_rule(model):
     158            return summation(model.x)
     159        self.model.obj = Objective(rule=obj_rule)
     160        def c_rule(model):
     161            expr = 0
     162            for i in model.A:
     163                expr += i*model.x[i]
     164            return expr == 0
     165        self.model.c = Constraint(rule=c_rule)
     166        self.instance = self.model.create()
     167        ans = [0.75]*4
     168        self.instance.load(ans)
     169        self.instance.display(currdir+"solve1.out")
     170        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1c.txt")
    1170171
    1171172    def Xtest_solve2(self):
     
    1175176        impacted this test...
    1176177        """
     178        if not pyutilib.services.registered_executable("glpsol"):
     179            return
    1177180        self.model.A = RangeSet(1,4)
    1178181        self.model.x = Var(self.model.A, bounds=(-1,1))
     
    1185188        self.instance = self.model.create()
    1186189        #self.instance.pprint()
    1187         if not pyutilib.services.registered_executable("glpsol"):
    1188             return
    1189         else:   
    1190            opt = solvers.GLPK(keepFiles=True)
     190        opt = solvers.GLPK(keepFiles=True)
    1191191        solutions = opt.solve(self.instance)
    1192192        solutions.write()
     
    1212212
    1213213    def test_solve4(self):
    1214         self.model.A = RangeSet(1,4)
    1215         self.model.x = Var(self.model.A, bounds=(-1,1))
    1216         def obj_rule(model):
    1217           expr = 0
    1218           for i in model.A:
    1219             expr += model.x[i]
    1220           return expr
     214        if not pyutilib.services.registered_executable("glpsol"):
     215            return
     216        self.model.A = RangeSet(1,4)
     217        self.model.x = Var(self.model.A, bounds=(-1,1))
     218        def obj_rule(model):
     219            return summation(model.x)
    1221220        self.model.obj = Objective(rule=obj_rule)
    1222221        def c_rule(model):
     
    1224223          for i in model.A:
    1225224            expr += i*model.x[i]
    1226           return (expr,0)
     225          return expr == 0
    1227226        self.model.c = Constraint(rule=c_rule)
    1228227        self.instance = self.model.create()
    1229228        #self.instance.pprint()
    1230         if not pyutilib.services.registered_executable("glpsol"):
    1231             return
    1232         else:   
    1233            opt = SolverFactory('glpk', keepFiles=True)
     229        opt = SolverFactory('glpk', keepFiles=True)
    1234230        solutions = opt.solve(self.instance)
    1235231        self.instance.load(solutions.solution(0))
     
    1237233        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1.txt")
    1238234
     235    def Xtest_solve5(self):
     236        """ A draft test for the option to select an objective """
     237        if not pyutilib.services.registered_executable("glpsol"):
     238            return
     239        self.model.A = RangeSet(1,4)
     240        self.model.x = Var(self.model.A, bounds=(-1,1))
     241        def obj1_rule(model):
     242          expr = 0
     243          for i in model.A:
     244            expr += model.x[i]
     245          return expr
     246        self.model.obj1 = Objective(rule=obj1_rule)
     247        def obj2_rule(model):
     248          expr = 0
     249          tmp=-1
     250          for i in model.A:
     251            expr += tmp*i*model.x[i]
     252            tmp *= -1
     253          return expr
     254        self.model.obj2 = Objective(rule=obj2_rule)
     255        self.instance = self.model.create()
     256        opt = SolverFactory('glpk', keepfiles=True)
     257        solutions = opt.solve(self.instance, objective='obj2')
     258        self.instance.load(solutions.solution())
     259        self.instance.display(currdir+"solve5.out")
     260        self.failUnlessFileEqualsBaseline(currdir+"solve5.out",currdir+"solve5a.txt")
     261
    1239262if __name__ == "__main__":
    1240263   unittest.main()
  • coopr.pyomo/stable/2.1/coopr/pyomo/tests/unit/test_param.py

    r1972 r2070  
    245245        #
    246246        self.model.Z = Set(initialize=[1,3])
    247         self.model.A = Param(self.model.Z, initialize={1:1.3},default=0.0)
     247        self.model.A = Param(self.model.Z, initialize={1:1.3}, default=0.0)
    248248        self.instance = self.model.create()
    249249
     
    256256        self.failUnlessEqual( self.instance.A[3], 4.3)
    257257
     258    def test_keys(self):
     259        """Check the use of keys"""
     260        self.failUnlessEqual( len(self.instance.A.keys()), 2)
     261
    258262    def test_len(self):
    259263        """Check the use of len"""
     
    332336        self.failUnlessEqual( self.instance.A[1], 1.3)
    333337        self.failUnlessEqual( self.instance.A[3], 1.3)
    334 
    335     def test_keys(self):
    336         """Check the use of keys"""
    337         self.failUnlessEqual( len(self.instance.A.keys()), 2)
    338338
    339339
     
    376376        self.failUnlessEqual(self.instance.B[2,False],-4)
    377377
     378    def test_dimen1(self):
     379        model=Model()
     380        model.A = Set(dimen=2, initialize=[(1,2),(3,4)])
     381        model.B = Set(dimen=3, initialize=[(1,1,1),(2,2,2),(3,3,3)])
     382        model.C = Set(dimen=1, initialize=[9,8,7,6,5])
     383        model.x = Param(model.A, model.B, model.C, initialize=-1)
     384        model.y = Param(model.B, initialize=(1,1))
     385        instance=model.create()
     386        self.failUnlessEqual( instance.x.dim(), 6)
     387        self.failUnlessEqual( instance.y.dim(), 3)
     388
    378389
    379390class TestIO(PyomoModel):
  • coopr.pyomo/stable/2.1/coopr/pyomo/tests/unit/test_set.py

    r1972 r2070  
    230230        """Check that set union works"""
    231231        self.instance.tmp = self.instance.A | self.instance.tmpset3
    232         self.instance.tmp._construct(self.instance)
     232        self.instance.tmp.construct()
    233233        self.failUnlessEqual( self.instance.tmp == self.instance.setunion, True)
    234234
     
    236236        """Check that set intersection works"""
    237237        self.instance.tmp = self.instance.A & self.instance.tmpset3
    238         self.instance.tmp._construct(self.instance)
     238        self.instance.tmp.construct()
    239239        self.failUnlessEqual( self.instance.tmp == self.instance.setintersection, True)
    240240
    241241    def test_xor(self):
    242242        """Check that set exclusive or works"""
    243         self.tmp = self.instance.A ^ self.instance.tmpset3
    244         self.tmp._construct(self.instance)
    245         self.failUnlessEqual( self.tmp == self.instance.setxor, True)
     243        self.instance.tmp = self.instance.A ^ self.instance.tmpset3
     244        self.instance.tmp.construct()
     245        self.failUnlessEqual( self.instance.tmp == self.instance.setxor, True)
    246246
    247247    def test_diff(self):
    248248        """Check that set difference works"""
    249         self.tmp = self.instance.A - self.instance.tmpset3
    250         self.tmp._construct(self.instance)
    251         self.failUnlessEqual( self.tmp == self.instance.setdiff, True)
     249        self.instance.tmp = self.instance.A - self.instance.tmpset3
     250        self.instance.tmp.construct()
     251        self.failUnlessEqual( self.instance.tmp == self.instance.setdiff, True)
    252252
    253253    def test_mul(self):
    254254        """Check that set cross-product works"""
    255255        self.instance.tmp = self.instance.A * self.instance.tmpset3
    256         self.instance.tmp._construct(self.instance)
     256        self.instance.tmp.construct()
    257257        self.failUnlessEqual( self.instance.tmp == self.instance.setmul, True)
    258258
     
    462462    def test_constructor1(self):
    463463        a=RangeSet(10)
    464         a._construct()
     464        a.construct()
    465465        tmp=[]
    466466        for i in a:
     
    472472    def test_constructor2(self):
    473473        a=RangeSet(1,10,2)
    474         a._construct()
     474        a.construct()
    475475        tmp=[]
    476476        for i in a:
     
    14141414        self.failUnlessEqual(self.instance.B[2,True].data(),set([2,3]))
    14151415
    1416     def test_dimen(self):
     1416    def test_dimen1(self):
    14171417        #
    14181418        # Create model instance
     
    14201420        self.model.A = Set(initialize=[1,2,3], dimen=1)
    14211421        self.instance = self.model.create()
    1422         try:
    1423           #self.model = Model()
     1422        #
     1423        try:
    14241424          self.model.A = Set(initialize=[4,5,6], dimen=2)
    14251425          self.instance = self.model.create()
     
    14281428        else:
    14291429          self.fail("test_dimen")
     1430        #
    14301431        self.model.A = Set(initialize=[(1,2), (2,3), (3,4)], dimen=2)
    14311432        self.instance = self.model.create()
     1433        #
    14321434        try:
    14331435          self.model.A = Set(initialize=[(1,2), (2,3), (3,4)], dimen=1)
    14341436          self.instance = self.model.create()
     1437        except ValueError:
     1438          pass
     1439        else:
     1440          self.fail("test_dimen")
     1441        #
     1442        def f(model):
     1443            return [(1,1), (2,2), (3,3)]
     1444        self.model.A = Set(initialize=f, dimen=2)
     1445        self.instance = self.model.create()
     1446        #
     1447        try:
     1448            self.model.A = Set(initialize=f, dimen=3)
     1449            self.instance = self.model.create()
    14351450        except ValueError:
    14361451          pass
     
    20762091        a = Set(initialize={})
    20772092        try:
    2078             a._construct()
     2093            a.construct()
    20792094            self.fail("test_construct - expected failure constructing with a dictionary")
    20802095        except ValueError:
     
    20832098        a = Set(initialize=init_fn)
    20842099        try:
    2085             a._construct()
     2100            a.construct()
    20862101            self.fail("test_construct - expected exception due to None model")
    20872102        except ValueError:
     
    21082123    def test_eq(self):
    21092124        a=Set(dimen=1,name="a",initialize=[1,2])
    2110         a._construct()
     2125        a.construct()
    21112126        b=Set(dimen=2)
    21122127        self.failUnlessEqual(a==b,False)
     
    21162131    def test_neq(self):
    21172132        a=Set(dimen=1,initialize=[1,2])
    2118         a._construct()
     2133        a.construct()
    21192134        b=Set(dimen=2)
    21202135        self.failUnlessEqual(a!=b,True)
     
    21242139    def test_contains(self):
    21252140        a=Set(initialize=[1,3,5,7])
    2126         a._construct()
     2141        a.construct()
    21272142        b=Set(initialize=[1,3])
    2128         b._construct()
     2143        b.construct()
    21292144        self.failUnlessEqual(b in a, True)
    21302145        self.failUnlessEqual(a in b, False)
     
    21552170            pass
    21562171        a=Set(initialize=[1,3,5,7])
    2157         a._construct()
     2172        a.construct()
    21582173        b=Set(initialize=[1,3])
    2159         b._construct()
     2174        b.construct()
    21602175        self.failUnlessEqual(Reals >= b, True)
    21612176        self.failUnlessEqual(Reals >= [1,3,7], True)
     
    21702185            pass
    21712186        a=Set(initialize=[1,3,5,7])
    2172         a._construct()
     2187        a.construct()
    21732188        try:
    21742189            a < Reals
     
    21772192            pass
    21782193        b=Set(initialize=[1,3,5])
    2179         b._construct()
     2194        b.construct()
    21802195        self.failUnlessEqual(a<a,False)
    21812196        self.failUnlessEqual(b<a,True)
    21822197        c=Set(initialize=[(1,2)])
    2183         c._construct()
     2198        c.construct()
    21842199        try:
    21852200            a<c
     
    21902205    def test_gt(self):
    21912206        a=Set(initialize=[1,3,5,7])
    2192         a._construct()
     2207        a.construct()
    21932208        c=Set(initialize=[(1,2)])
    2194         c._construct()
     2209        c.construct()
    21952210        try:
    21962211            a>c
     
    22022217        a=Set(initialize=[1,2,3])
    22032218        c=Set(initialize=[(1,2)])
    2204         c._construct()
     2219        c.construct()
    22052220        try:
    22062221            Reals | Integers
     
    22222237        a=Set(initialize=[1,2,3])
    22232238        c=Set(initialize=[(1,2)])
    2224         c._construct()
     2239        c.construct()
    22252240        try:
    22262241            Reals & Integers
     
    22422257        a=Set(initialize=[1,2,3])
    22432258        c=Set(initialize=[(1,2)])
    2244         c._construct()
     2259        c.construct()
    22452260        try:
    22462261            Reals ^ Integers
     
    22622277        a=Set(initialize=[1,2,3])
    22632278        c=Set(initialize=[(1,2)])
    2264         c._construct()
     2279        c.construct()
    22652280        try:
    22662281            Reals - Integers
     
    22822297        a=Set(initialize=[1,2,3])
    22832298        c=Set(initialize=[(1,2)])
    2284         c._construct()
     2299        c.construct()
    22852300        try:
    22862301            Reals * Integers
     
    23022317    def test_arrayset_construct(self):
    23032318        a=Set(initialize=[1,2,3])
    2304         a._construct()
     2319        a.construct()
    23052320        b=Set(a, initialize=tmp_constructor)
    23062321        try:
    2307             b._construct(None,{4:None})
     2322            b.construct({4:None})
    23082323            self.fail("test_arrayset_construct - expected KeyError")
    23092324        except KeyError:
    23102325            pass
    23112326        try:
    2312             b._construct()
     2327            b.construct()
    23132328            self.fail("test_arrayset_construct - expected ValueError")
    23142329        except ValueError:
     
    23182333          self.failUnlessEqual(i in a, True)
    23192334        try:
    2320             b._construct(self.model)
     2335            b.construct()
    23212336            self.fail("test_arrayset_construct - expected ValueError")
    23222337        except ValueError:
     
    23252340    def test_prodset(self):
    23262341        a=Set(initialize=[1,2])
    2327         a._construct()
     2342        a.construct()
    23282343        b=Set(initialize=[6,7])
    2329         b._construct()
     2344        b.construct()
    23302345        c=a*b
    2331         c._construct()
     2346        c.construct()
    23322347        self.failUnlessEqual((6,2) in c, False)
    23332348        c=coopr.pyomo.base.sets._ProductSet(a,b)
     
    23372352        c=coopr.pyomo.base.sets._ProductSet()
    23382353        c.virtual=True
    2339         c._construct()
     2354        c.construct()
    23402355        c=coopr.pyomo.base.sets._ProductSet(a,b,initialize={(1,7):None,(2,6):None})
    2341         c._construct()
     2356        c.construct()
    23422357        c=coopr.pyomo.base.sets._ProductSet(a,b,initialize=(1,7))
    2343         c._construct()
     2358        c.construct()
    23442359
    23452360def virt_constructor(y,model):
     
    23502365    def test_construct(self):
    23512366        a=Set(initialize=[1,2,3])
    2352         a._construct()
     2367        a.construct()
    23532368        b=Set(a, initialize=virt_constructor)
    2354         #b._construct()
     2369        #b.construct()
    23552370
    23562371if __name__ == "__main__":
  • coopr.pyomo/stable/2.1/coopr/pyomo/tests/unit/varpprint.txt

    r1972 r2070  
    3434
    35352 Objective Declarations
    36    o2 :         Size=3
     36   o2 :         Size=3  Index= a
    3737        b[1]
    3838        b[2]
     
    4040   o3 :         Size=0  Index= o3_index
    4141
    42 14 Constraint Declarations
     4224 Constraint Declarations
    4343   c1 :         Size=1
    44         None
    45                 identity( 1.0 )
    46                 identity( b[1] )
    47                 Inf
    48    c10 :        Size=1
    49         None
    50                 -Inf
    51                 identity( c )
     44                identity( 1.0 )
     45                <=
     46                identity( b[1] )
     47                <
     48                Inf
     49   c10a :       Size=1
     50                -Inf
     51                <
     52                identity( c )
     53                <=
     54                sum( B , B )
     55   c10b :       Size=1
     56                -Inf
     57                <
     58                identity( c )
     59                <
    5260                sum( B , B )
    5361   c11 :        Size=1
    54         None
    5562                sum( A , B )
    56                 identity( c )
     63                <=
     64                identity( c )
     65                <=
    5766                sum( A , B )
    5867   c12 :        Size=1
    59         None
    60                 identity( 0.0 )
     68                identity( 0.0 )
     69                <=
    6170                sum( c , -1 *  d )
    62                 identity( 0.0 )
    63    c13 :        Size=1
    64         None
    65                 identity( 0.0 )
     71                <=
     72                identity( 0.0 )
     73   c13a :       Size=1
     74                identity( 0.0 )
     75                <=
    6676                sum( d , -1 *  c )
    67                 Inf
    68    c14 :        Size=1
    69         None
    70                 identity( 0.0 )
     77                <
     78                Inf
     79   c13b :       Size=1
     80                identity( 0.0 )
     81                <
     82                sum( d , -1 *  c )
     83                <
     84                Inf
     85   c14a :       Size=1
     86                identity( 0.0 )
     87                <=
    7188                sum( c , -1 *  d )
    72                 Inf
     89                <
     90                Inf
     91   c14b :       Size=1
     92                identity( 0.0 )
     93                <
     94                sum( c , -1 *  d )
     95                <
     96                Inf
     97   c15a :       Size=1
     98                identity( A )
     99                <=
     100                prod( num=( A , d ) )
     101                <
     102                Inf
     103   c15b :       Size=1
     104                identity( A )
     105                <
     106                prod( num=( A , d ) )
     107                <
     108                Inf
     109   c16a :       Size=1
     110                -Inf
     111                <
     112                prod( num=( A , d ) )
     113                <=
     114                identity( B )
     115   c16b :       Size=1
     116                -Inf
     117                <
     118                prod( num=( A , d ) )
     119                <
     120                identity( B )
    73121   c2 :         Size=1
    74         None
    75                 -Inf
    76                 identity( b[1] )
     122                -Inf
     123                <
     124                identity( b[1] )
     125                <=
    77126                identity( 0.0 )
    78127   c3 :         Size=1
    79         None
    80                 identity( 0.0 )
    81                 identity( b[1] )
     128                identity( 0.0 )
     129                <=
     130                identity( b[1] )
     131                <=
    82132                identity( 1.0 )
    83133   c4 :         Size=1
    84         None
    85134                identity( 3.0 )
    86                 identity( b[1] )
     135                <=
     136                identity( b[1] )
     137                <=
    87138                identity( 3.0 )
    88    c5 :         Size=3
     139   c5 :         Size=3  Index= a
    89140        1
    90141                identity( 0.0 )
    91                 identity( b[1] )
     142                <=
     143                identity( b[1] )
     144                <=
    92145                identity( 0.0 )
    93146        2
    94147                identity( 0.0 )
     148                <=
    95149                identity( b[2] )
     150                <=
    96151                identity( 0.0 )
    97152        3
    98153                identity( 0.0 )
     154                <=
    99155                identity( b[3] )
    100                 identity( 0.0 )
    101    c6 :         Size=1
    102         None
    103                 identity( 0.0 )
    104                 identity( c )
    105                 Inf
    106    c7 :         Size=1
    107         None
    108                 -Inf
    109                 identity( c )
     156                <=
     157                identity( 0.0 )
     158   c6a :        Size=1
     159                identity( 0.0 )
     160                <=
     161                identity( c )
     162                <
     163                Inf
     164   c6b :        Size=1
     165                identity( 0.0 )
     166                <
     167                identity( c )
     168                <
     169                Inf
     170   c7a :        Size=1
     171                -Inf
     172                <
     173                identity( c )
     174                <=
     175                identity( 1.0 )
     176   c7b :        Size=1
     177                -Inf
     178                <
     179                identity( c )
     180                <
    110181                identity( 1.0 )
    111182   c8 :         Size=1
    112         None
    113183                identity( 2.0 )
    114                 identity( c )
     184                <=
     185                identity( c )
     186                <=
    115187                identity( 2.0 )
    116    c9 :         Size=1
    117         None
     188   c9a :        Size=1
    118189                sum( A , A )
    119                 identity( c )
    120                 Inf
    121 
    122 24 Declarations: a b c d e A B o2 o3_index o3 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14
     190                <=
     191                identity( c )
     192                <
     193                Inf
     194   c9b :        Size=1
     195                sum( A , A )
     196                <
     197                identity( c )
     198                <
     199                Inf
     200
     20134 Declarations: a b c d e A B o2 o3_index o3 c1 c2 c3 c4 c5 c6a c6b c7a c7b c8 c9a c9b c10a c10b c11 c15a c15b c16a c16b c12 c13a c13b c14a c14b
  • coopr.pyomo/stable/2.1/examples/pyomo/amplbook2/diet.py

    r1032 r2070  
    1010
    1111model = Model()
     12
    1213model.NUTR = Set()
     14
    1315model.FOOD = Set()
    1416
     
    1820
    1921def f_max_valid (value, j, model):
    20     return model.f_max[j] > model.f_min[j]
     22    return value > model.f_min[j]
    2123model.f_max = Param(model.FOOD, validate=f_max_valid)
    2224
    2325model.n_min = Param(model.NUTR, within=NonNegativeReals)
    2426
    25 def paramn_max (i, model):
    26     model.n_max[i] > model.n_min[i]
    27     return model.n_max[i]
    28 model.n_max = Param(model.NUTR, initialize=paramn_max)
    29 
    30 # ***********************************
     27def paramn_max(value, i, model):
     28    return value > model.n_min[i]
     29model.n_max = Param(model.NUTR, validate=paramn_max)
    3130
    3231model.amt = Param(model.NUTR, model.FOOD, within=NonNegativeReals)
     
    3736
    3837def Objective_rule(model):
    39     ans = 0
    40     for j in model.FOOD:
    41         ans = ans + model.cost[j] * model.Buy[j]
    42     return ans
     38    return summation(model.cost, model.Buy)
    4339model.totalcost = Objective(rule=Objective_rule)
    4440
     
    4743    for j in model.FOOD:
    4844      expr = expr + model.amt[i,j] * model.Buy[j]
    49     expr = expr > model.n_min[i]
    50     expr = expr < model.n_max[i]
    51     return expr
     45    return (model.n_min[i], expr, model.n_max[i])
    5246model.Diet = Constraint(model.NUTR, rule=Diet_rule)
    5347
  • coopr.pyomo/stable/2.1/examples/pyomo/amplbook2/dieti.py

    r1032 r2070  
    1010
    1111model = Model()
     12
    1213model.NUTR = Set()
     14
    1315model.FOOD = Set()
    1416
     
    1820
    1921def f_max_valid (value, j, model):
    20     return model.f_max[j] > model.f_min[j]
     22    return value > model.f_min[j]
    2123model.f_max = Param(model.FOOD, validate=f_max_valid)
    2224
    2325model.n_min = Param(model.NUTR, within=NonNegativeReals)
    2426
    25 def paramn_max (i, model):
    26     model.n_max[i] > model.n_min[i]
    27     return model.n_max[i]
    28 model.n_max = Param(model.NUTR, initialize=paramn_max)
    29 
    30 # ***********************************
     27def paramn_max (value, i, model):
     28    return value > model.n_min[i]
     29model.n_max = Param(model.NUTR, validate=paramn_max)
    3130
    3231model.amt = Param(model.NUTR, model.FOOD, within=NonNegativeReals)
     
    3736
    3837def Objective_rule(model):
    39     ans = 0
    40     for j in model.FOOD:
    41         ans = ans + model.cost[j] * model.Buy[j]
    42     return ans
     38    return summation(model.cost, model.Buy)
    4339model.totalcost = Objective(rule=Objective_rule)
    4440
  • coopr.pyomo/stable/2.1/examples/pyomo/amplbook2/econ2min.py

    r1032 r2070  
    1313# ***********************************
    1414
    15 model.PROD = Set()
     15model.PROD = Set(doc='products')
    1616
    17 model.ACT = Set()
     17model.ACT = Set(doc='activities')
    1818
    1919# ***********************************
    2020
    21 model.cost = Param(model.ACT, within=PositiveReals)
     21model.cost = Param(model.ACT, within=PositiveReals, doc='cost per unit of each activity')
    2222
    23 model.demand = Param(model.PROD, within=NonNegativeReals)
     23model.demand = Param(model.PROD, within=NonNegativeReals, doc='units of demand for each product')
    2424
    25 model.io = Param(model.PROD, model.ACT, within=NonNegativeReals)
     25model.io = Param(model.PROD, model.ACT, within=NonNegativeReals, doc='units of each product from 1 unit of each activity')
    2626
    27 model.level_min = Param(model.ACT, within=NonNegativeReals)
     27model.level_min = Param(model.ACT, within=NonNegativeReals, doc='min allowed level for each activity')
    2828
    29 model.level_max = Param(model.ACT, within=NonNegativeReals)
     29model.level_max = Param(model.ACT, within=NonNegativeReals, doc='max allowed level for each activity')
    3030
    3131# ***********************************
     
    3333def Level_bounds(i, model):
    3434  return (model.level_min[i], model.level_max[i])
    35 model.Level = Var(model.ACT, bounds=Level_bounds)
     35model.Level = Var(model.ACT, bounds=Level_bounds, doc='level for each activity')
    3636
    3737# ***********************************
    3838
    3939def Total_Cost_rule(model):
    40     expr=0
    41     for j in model.ACT:
    42       expr += model.cost[j]*model.Level[j]
    43     return expr
    44 model.Total_Cost = Objective(rule=Total_Cost_rule)
     40    return summation(model.cost, model.Level)
     41model.Total_Cost = Objective(rule=Total_Cost_rule, doc='minimize total cost')
    4542
    4643def Demand_rule(i, model):
     
    4845    for j in model.ACT:
    4946      expr += model.io[i,j] * model.Level[j]
    50     expr = expr > model.demand[i]
    51     return expr
    52 model.Demand = Constraint(model.PROD, rule=Demand_rule)
     47    return model.demand[i] < expr
     48model.Demand = Constraint(model.PROD, rule=Demand_rule, doc='total level for each activity exceeds demand')
    5349
  • coopr.pyomo/stable/2.1/examples/pyomo/amplbook2/econmin.py

    r1032 r2070  
    3232
    3333def Total_Cost_rule(model):
    34     expr=0
    35     for j in model.ACT:
    36       expr += model.cost[j]*model.Level[j]
    37     return expr
     34    return summation(model.cost, model.Level)
    3835model.Total_Cost = Objective(rule=Total_Cost_rule)
    3936
     
    4239    for j in model.ACT:
    4340      expr += model.io[i,j] * model.Level[j]
    44     expr = expr > model.demand[i]
    45     return expr
     41    return expr > model.demand[i]
    4642model.Demand = Constraint(model.PROD, rule=Demand_rule)
    4743
  • coopr.pyomo/stable/2.1/examples/pyomo/amplbook2/steel.py

    r1032 r2070  
    22# Imports
    33#
    4 import sys
    54from coopr.pyomo import *
    6 
    75
    86#
     
    1614model.rate = Param(model.PROD,within=PositiveReals)
    1715
    18 model.avail = Param(within=PositiveReals)
     16model.avail = Param(within=NonNegativeReals)
    1917
    2018model.profit = Param(model.PROD)
    21 model.market = Param(model.PROD, within=PositiveReals)
     19
     20model.market = Param(model.PROD, within=NonNegativeReals)
    2221
    2322def Make_bounds(i,model):
     
    2524model.Make = Var(model.PROD, bounds=Make_bounds)
    2625
    27 # Max profit
    2826def Objective_rule(model):
    29     ans = 0
    30     for p in model.PROD:
    31         ans = ans + model.profit[p] * model.Make[p]
    32     return ans
    33 #profit v totalprofit
    34 model.totalprofit = Objective(rule=Objective_rule, sense=maximize)
     27    return summation(model.profit, model.Make)
     28model.Total_Profit = Objective(rule=Objective_rule, sense=maximize)
    3529
    36 # Subj to time
    3730def Time_rule(model):
    3831    ans = 0
     
    4033      ans = ans + (1.0/model.rate[p]) * model.Make[p]
    4134    return ans < model.avail
    42 model.Time = Constraint(rule=Time_rule)
     35
     36def XTime_rule(model):
     37    return summation(model.Make, denom=(model.rate,) ) < model.avail
     38#model.Time = Constraint(rule=Time_rule)
  • coopr.pyomo/stable/2.1/examples/pyomo/amplbook2/steel3.py

    r1948 r2070  
    1414
    1515model.rate = Param(model.PROD, within=PositiveReals)
    16 #(ampl) param rate {PROD} > 0;
    1716
    1817model.avail = Param(within=NonNegativeReals)
     
    2827model.Make = Var(model.PROD, bounds=Make_bounds)
    2928
    30 # max profit
    31 
    3229def Objective_rule(model):
    33     ans = 0
    34     for p in model.PROD:
    35         ans = ans + model.profit[p] * model.Make[p]
    36     return ans
    37 #proft v totalprofit?
     30    return summation(model.profit, model.Make)
    3831model.totalprofit = Objective(rule=Objective_rule, sense=maximize)
    3932
    40 #Subj to time
    4133def Time_rule(model):
    42     ans = 0
    43     for p in model.PROD:
    44         ans = ans + (1.0/model.rate[p]) * model.Make[p]
    45     return ans < model.avail
     34    return summation(model.Make, denom=(model.rate)) < model.avail
    4635model.Time = Constraint(rule=Time_rule)
    4736
  • coopr.pyomo/stable/2.1/examples/pyomo/amplbook2/steel4.py

    r1032 r2070  
    22# Imports
    33#
    4 import sys
    54from coopr.pyomo import *
    65
     
    1211
    1312model.PROD = Set()
     13
    1414model.STAGE = Set()
    1515
    16 model.rate = Param(model.PROD,model.STAGE,within=PositiveReals)
     16model.rate = Param(model.PROD, model.STAGE, within=PositiveReals)
    1717
    18 model.avail = Param(model.STAGE, within=PositiveReals)
     18model.avail = Param(model.STAGE, within=NonNegativeReals)
    1919
    2020model.profit = Param(model.PROD)
    2121
    22 model.commit = Param(model.PROD, within=PositiveReals)
     22model.commit = Param(model.PROD, within=NonNegativeReals)
    2323
    24 model.market = Param(model.PROD, within=PositiveReals)
     24model.market = Param(model.PROD, within=NonNegativeReals)
    2525
    2626def Make_bounds(i,model):
     
    2929
    3030def Objective_rule (model):
    31     ans = 0
    32     for p in model.PROD:
    33         ans = ans + model.profit[p] * model.Make[p]
    34     return ans
    35 model.totalprofit = Objective(rule=Objective_rule, sense=maximize)
    36 
    37 #Subj to time
    38 
    39 #************************ new problem -
    40 #subject to Time {s in STAGE}:
    41 #def Time_rule(model):
    42 #    ans = 0
    43 #    for p in model.PROD:
    44 #        ans = ans + (1.0/model.rate[p] * model.Make[p])
    45 #        return ans < model.market
    46 #model.avail = Constraint(rule=Time_rule)
     31    return summation(model.profit, model.Make)
     32model.Total_Profit = Objective(rule=Objective_rule, sense=maximize)
    4733
    4834def Timelim_rule(s, model):
  • coopr.pyomo/stable/2.1/examples/pyomo/draft/bpack.py

    r1948 r2070  
    1 import sys
     1
    22from coopr.pyomo import *
    3 
    4 def range_set(lb,ub):
    5         ans = set()
    6         for i in xrange(lb,ub+1):
    7                 ans.add(i)
    8         return ans
    93
    104model = Model()
     
    1610# Set I
    1711#
    18 def I_rule(model):
    19         return range_set(1,model.N)
    20 model.I = Set(initialize = I_rule)
     12model.I = RangeSet(1,model.N)
    2113#
    2214# Variable b
     
    4032        ans = set()
    4133        i = 1
    42         N9 = model.N - 9
     34        N9 = model.N.value - 9
    4335        while i <= N9:
    4436                j = i
     
    5749# Set rhs_ind
    5850#
    59 def rhs_ind_rule(model):
    60         return range_set(1,model.N-9)
    61 model.rhs_ind = Set(initialize = rhs_ind_rule)
     51model.rhs_ind = RangeSet(1,model.N-9)
    6252#
    6353# Parameter rhs
  • coopr.pyomo/stable/2.1/examples/pyomo/draft/diet2.py

    r1948 r2070  
    55# Imports
    66#
    7 import sys
    87from coopr.pyomo import *
    98
  • coopr.pyomo/stable/2.1/examples/pyomo/p-median/README.txt

    r1675 r2070  
    22====================================
    33
    4 The goal of this problem is place facilities to meet customer demands.  This formulation randomly generates customer demands.
     4The goal of this problem is to place facilities to meet customer demands.
     5This formulation randomly generates customer demands.
    56
    67
     
    3031
    3132Files
    32   solver.py       - A Python file that contains a greedy heuristic
     33  solver1.py      - A Python file that contains a greedy heuristic
     34  solver2.py      - A Python file that contains a randomized heuristic
    3335  pmedian.py      - A Python model written with Pyomo objects
    3436  pmedian.dat     - A simple data file for this example
    3537
    3638Running Pyomo
    37   pyomo --preprocess=solver.py --solver=greedy pmedian.py pmedian.dat
     39  pyomo --preprocess=solver1.py --solver=greedy pmedian.py pmedian.dat
     40  pyomo --preprocess=solver2.py --solver=random pmedian.py pmedian.dat
    3841
  • coopr.pyomo/stable/2.1/examples/pyomo/p-median/pmedian.dat

    r1675 r2070  
    1 param N := 5;
     1param N := 10;
    22param M := 6;
    33param P := 3;
  • coopr.pyomo/stable/2.1/scripts/pyomo

    r1806 r2070  
    5252try:
    5353    coopr.pyomo.main_script.run()
    54 except ValueError, str:
    55     print str
    56 except IOError, str:
    57     print str
    58 except pyutilib.common.ApplicationError, str:
    59     print str
    60 except RuntimeError:
     54except SystemExit:
    6155    pass
    62 except:
    63    print "Encountered unhandled exception"
    64    traceback.print_exc()
     56#except ValueError, str:
     57    #print str
     58#except IOError, str:
     59    #print str
     60#except pyutilib.common.ApplicationError, str:
     61    #print str
     62#except RuntimeError:
     63    #pass
     64#except:
     65   #print "Encountered unhandled exception"
     66   #traceback.print_exc()
  • coopr.pyomo/stable/2.1/setup.py

    r1948 r2070  
    6161            'Programming Language :: Unix Shell',
    6262            'Topic :: Scientific/Engineering :: Mathematics',
    63             'Topic :: Software Development :: Libraries :: Python Modules'
     63            'Topic :: Software Development :: Libraries :: Python Modules',
     64            'Topic :: Scientific/Engineering'
    6465        ],
    6566      packages=packages,
Note: See TracChangeset for help on using the changeset viewer.