Changeset 3285


Ignore:
Timestamp:
Dec 3, 2010 10:55:43 PM (10 years ago)
Author:
wehart
Message:

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

........

r3188 | jwatson | 2010-10-29 08:09:35 -0600 (Fri, 29 Oct 2010) | 3 lines


Eliminating initial domain check when constructing numeric constants and the default domain (Reals) is specified.

........

r3203 | jwatson | 2010-10-29 14:46:18 -0600 (Fri, 29 Oct 2010) | 3 lines


Fixing bugs in has_discrete_variables() method of PyomoModel?.

........

r3211 | jdsiiro | 2010-11-01 14:49:11 -0600 (Mon, 01 Nov 2010) | 4 lines


bugfixes for Blocks:

  • avoid infinite loop when adding a block to a model
  • support pretty printing of user-defined components

........

r3212 | jdsiiro | 2010-11-02 15:17:13 -0600 (Tue, 02 Nov 2010) | 5 lines


  • cleaning up the management of Block._parent_block and Component.model attributes. Adding & removing blocks now updates the model attribute on all children
  • renaming Block._setattr_exec -> Block._add_component

........

r3213 | jdsiiro | 2010-11-03 10:47:06 -0600 (Wed, 03 Nov 2010) | 2 lines


Bugfix to the PyomoLogHandler? for python 2.4 compatibility

........

r3214 | jdsiiro | 2010-11-03 15:20:47 -0600 (Wed, 03 Nov 2010) | 3 lines


There is no point logging a warning when the problem is encountered
generating a logging.info message: log the warning at the info level.

........

r3215 | wehart | 2010-11-04 23:05:17 -0600 (Thu, 04 Nov 2010) | 3 lines


Adding a simple knapsack example to illustrate the difference between
a concrete and abstract model.

........

r3216 | jwatson | 2010-11-05 09:39:19 -0600 (Fri, 05 Nov 2010) | 3 lines


Fixing error diagnostic when indexing a variable with a bad index.

........

r3219 | jwatson | 2010-11-05 16:01:23 -0600 (Fri, 05 Nov 2010) | 3 lines


Supressing a validation test with NumericConstant?. If the user specifies a value, we are (now) assuming it is actually a numeric value - otherwise, the domain check significantly inflates the run-time associated with expression tree creation. This needs to be revisited in the Coopr 2.5 re-write.

........

r3226 | wehart | 2010-11-06 21:32:59 -0600 (Sat, 06 Nov 2010) | 2 lines


Setting up example, which was never converted.

........

r3233 | wehart | 2010-11-12 15:56:28 -0700 (Fri, 12 Nov 2010) | 4 lines


Migrating OS-specific functionality into coopr.os


Adding coopr.os to the dev.ini config file.

........

r3242 | wehart | 2010-11-13 01:28:57 -0700 (Sat, 13 Nov 2010) | 4 lines


Type fix.


Updating error message.

........

r3244 | wehart | 2010-11-13 10:44:26 -0700 (Sat, 13 Nov 2010) | 2 lines


Skipping OSiL writer when not defined.

........

r3246 | wehart | 2010-11-13 10:54:15 -0700 (Sat, 13 Nov 2010) | 2 lines


bug fix.

........

r3247 | wehart | 2010-11-13 11:14:01 -0700 (Sat, 13 Nov 2010) | 2 lines


Bug fix.

........

r3248 | jwatson | 2010-11-17 13:51:47 -0700 (Wed, 17 Nov 2010) | 3 lines


Interim fixes to output of quadratic terms in LP writer - more to do, but at least the basic examples now work.

........

r3254 | jwatson | 2010-11-19 13:19:19 -0700 (Fri, 19 Nov 2010) | 3 lines


Fixed bug in LP writer involving quadratic terms involving two distinct variables. Added two new quadratic examples.

........

r3257 | jwatson | 2010-11-19 13:59:35 -0700 (Fri, 19 Nov 2010) | 3 lines


Fixing diagnostic error message when attempting to solve quadratic programs with GLPK - code for generating message was not syntatically legal.

........

r3268 | jwatson | 2010-12-01 15:08:28 -0700 (Wed, 01 Dec 2010) | 3 lines


Fixing issues with the Piecewise construct when breakpoints and slopes are generated via rules. Works now (on a sample of size 1 - the newly added example5.py) for non-indexed rules, likely broken for indexed breakpoint/slope rules.

........

r3272 | jwatson | 2010-12-02 13:53:51 -0700 (Thu, 02 Dec 2010) | 3 lines


Adding omitted pprint() method for SOS constraints - identified while debugging a piecewise issue.

........

r3274 | jwatson | 2010-12-02 16:32:29 -0700 (Thu, 02 Dec 2010) | 3 lines


Adding example of Piecewise construct using breakpoint and slope rules, as opposed to explicit/direct lists.

........

r3276 | jwatson | 2010-12-03 14:06:40 -0700 (Fri, 03 Dec 2010) | 3 lines


Some progress toward functional indexed Piecewise components.

........

Location:
coopr.pyomo/stable
Files:
1 deleted
14 edited
7 copied

Legend:

Unmodified
Added
Removed
  • coopr.pyomo/stable

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

    r2359 r3285  
    3636    for entrypoint in pkg_resources.iter_entry_points('coopr.pyomo'):
    3737        plugin_class = entrypoint.load()
    38 except:
    39     pass
     38except Exception, err:
     39    print "Error loading coopr.pyomo entry points:",str(err)
    4040
  • coopr.pyomo/stable/coopr/pyomo/base/PyomoModel.py

    r3182 r3285  
    2424
    2525from coopr.opt import ProblemFormat, ResultsFormat, guess_format
    26 from coopr.pyomo.base.var import _VarValue, VarStatus
     26from coopr.pyomo.base.var import _VarValue, VarStatus, Var
    2727from coopr.pyomo.base.constraint import ConstraintData
     28from coopr.pyomo.base.set_types import *
    2829import coopr.opt
    2930from PyomoModelData import ModelData
     
    101102
    102103       variables = self.active_components(Var)
    103        for variable_name, variable in vars.values():
     104       for variable_name, variable in variables.items():
    104105          if isinstance(variable.domain, IntegerSet) or isinstance(variable.domain, BooleanSet):
    105106             return True
     
    423424        problem_writer = coopr.opt.WriterFactory(format)
    424425        if problem_writer is None:
    425             msg = "Cannot write model in format '%s'': no model writer "      \
     426            msg = "Cannot write model in format '%s': no model writer "      \
    426427                  'registered for that format'
    427428            raise ValueError, msg % str(format)
  • coopr.pyomo/stable/coopr/pyomo/base/block.py

    r3114 r3285  
    6464        self.name=kwargs.get('name', 'unknown')
    6565        self._defer_construction=True
     66        # By default, a Block is a top-level (i.e. Model) block
     67        self.model = self
    6668        self._parent_block = None
    6769        #
     
    162164        Cleanup the pre-existing model attribute
    163165        """
    164         if name in self._declarations:
    165             self.__dict__[name]=None
    166             del self._component[ self._declarations[name].type() ][name]
    167             del self._declarations[name]
    168 
    169     def _setattr_exec(self, name, val):
     166        val = self._declarations.get(name, None)
     167        if val is None:
     168            return
     169
     170        if isinstance(val, Block):
     171            val.__dict__['_parent_block'] = None
     172            val.model = val
     173        else:
     174            val.model = None
     175           
     176        self.__dict__[name]=None # Any idea why we don't DEL here?
     177        del self._component[ val.type() ][name]
     178        del self._declarations[name]
     179
     180    def _add_component(self, name, val):
    170181        self._clear_attribute(name)
    171182        val.name=name
     
    179190        # immediate parent.
    180191
    181         # Don't let '_parent_block' attributes trigger recursion
     192        # Update the (new) child block's _parent_block. 
    182193        if isinstance(val, Block):
    183             self.__dict__["_parent_block"] = self
    184         else:
    185             curr = self
    186             while curr is not None:
    187                 val.model = curr
    188                 curr = self._parent_block
    189         # self is the top level model if self.model is None; otherwise,
    190         # self.model is the top level model
    191         if self.model is not None:
    192             self.__dict__["model"] = self.model
    193         else:
    194             self.__dict__["model"] = self
    195 
    196 #         # Need to break infinite loop of attribute setting
    197 #         if isinstance(val, Block) and name != "_parent_block":
    198 #             val._parent_block = self
    199 #         else:
    200 #             curr = self
    201 #             while not curr is None:
    202 #                val.model=curr
    203 #                curr = self._parent_block
    204 
     194            if val._parent_block is not None:
     195                # Nothing really wrong here, but until we are more
     196                # careful about checking that this actually works,
     197                # complain loudly.
     198                raise Exception, "Reassigning a block attached to a model"
     199            # NB: use __dict__ directly to prevent infinite recursion
     200            val.__dict__['_parent_block'] = self
     201
     202        # Update the new component's model pointer
     203        val.model = self.model
     204       
    205205        frame = sys._getframe(2)
    206206        locals_ = frame.f_locals
     
    215215        # Set Model Declaration
    216216        #
    217         if name != "_component" and isinstance(val, Component):
     217        if name == "model":
     218            if val is not None and not isinstance(val, Block):
     219                raise ValueError, "Cannot set Block.model to a non-Block " \
     220                      "object (%s)" % ( val )
     221            self.__dict__["model"] = val
     222            # Update all child components.  NB: use __dict__.get because
     223            # Component.__init__() assigns "self.model = None" before
     224            # Block.__init__ defines the _declarations map.
     225            for subcomp in self.__dict__.get("_declarations", {}).itervalues():
     226                subcomp.model = val
     227        elif name != "_component" and isinstance(val, Component):
    218228            #
    219229            # If this is a component type, then simply set it
    220230            #
    221             self._setattr_exec(name,val)
     231            self._add_component(name,val)
    222232        else:
    223233            #
     
    258268            if not item in items:
    259269                items.append(item)
     270
     271        # Currently, model components are not actually being registered
     272        # with the IModelComponent extension point (1 Nov 2010), so as a
     273        # workaround, we will loop through the components and add any
     274        # new components that actually have defined members.
     275        extra_items = []
     276        for item, members in self._component.iteritems():
     277            if item not in items and len(members):
     278                extra_items.append(item)
     279        # extra items get added alphabetically (so output is consistent)
     280        items.extend(sorted(extra_items))
     281
    260282        for item in items:
    261283            if not item in self._component:
     
    268290            print >>ostream, len(keys), item.__name__+" Declarations"
    269291            for key in keys:
    270                 self._component[item][key].pprint(ostream)
     292                self._component[item][key].pprint(ostream=ostream)
    271293            print >>ostream, ""
    272294        #
  • coopr.pyomo/stable/coopr/pyomo/base/constraint.py

    r3182 r3285  
    703703        """ Return the sets used to index the sets indexing the variables """
    704704        return self._index
     705
     706    def pprint(self, ostream=None):
     707        if ostream is None:
     708           ostream = sys.stdout
     709        print >>ostream, "  ",self.name,":",
     710        print >>ostream, "Type="+str(self._sosLevel)
     711        print >>ostream, "\tVariable: "+self._sosVars.name
     712        print >>ostream, "\tIndices: ",
     713        for i in self._sosSet.value:
     714           print >>ostream, str(i)+" ",
     715        print >>ostream, ""
  • coopr.pyomo/stable/coopr/pyomo/base/numvalue.py

    r3182 r3285  
    7777
    7878    #
    79     # kwargs are a nice programmer convenience, but their manipulation is very expensive in a highly used base class.
     79    # kwargs are a nice programmer convenience, but their manipulation appears too expensive in a highly used base class.
    8080    #
    81     def __init__(self, name='unknown', value=None, domain=None):
     81    # the validate_value argument only applies to the value supplied in the constructor, and does not prevent
     82    # subsequent value assignments from being checked.
     83    #
     84    def __init__(self, name='unknown', value=None, domain=None, validate_value=True):
    8285
    8386        self.name = name
     
    9396        # occurrences. similarly, we are avoiding the
    9497        # invocation of _valid_value.
    95         if (value is not None) and (self.domain is not None) and (value not in self.domain):
     98        if (value is not None) and (validate_value is True) and (self.domain is not None) and (value not in self.domain):
    9699           raise ValueError, "Numeric value `"+str(value)+"` is not in domain "+str(self.domain)           
    97100
     
    302305        if domain is None:
    303306           domain = Reals
    304         NumericValue.__init__(self, name=name, domain=domain, value=value)
     307        # NOTE: we in general don't perform domain validation of numeric constants,
     308        #       especially because the user/caller has specified the value, and
     309        #       typically does not specify the domain. the domain might be useful
     310        #       with meta-level symbolic expression analysis, but even there the
     311        #       above default of a real domain is questionable.
     312        NumericValue.__init__(self, name=name, domain=domain, value=value, validate_value=False)
    305313
    306314    def fixed_value(self):
  • coopr.pyomo/stable/coopr/pyomo/base/var.py

    r3182 r3285  
    6767
    6868        self.fixed = False
    69 
    7069        self.status = VarStatus.undefined
    7170
     
    308307        except KeyError: # thrown if the supplied index is hashable, but not defined.
    309308            msg = "Unknown index '%s' in variable %s;" % (str(ndx), self.name)
    310             if (isinstance(ndx, (tuple, list)) and len(ndx) != self.dim()) or \
    311                    (ndx != self.dim()):
     309            if (isinstance(ndx, (tuple, list)) and len(ndx) != self.dim()):
    312310                msg += "    Expecting %i-dimensional indices" % self.dim()
    313311            else:
     
    681679    model.C2.eval(7.0)
    682680
    683     Breakpoints refer to the value on the domain that separate the
     681    Breakpoints refer to the values on the domain that separate the
    684682    domain into distinct intervals. All intervals are assumed to be
    685683    closed on the lower bound and open on the upper bound, with the
     
    702700    would be modeled as:
    703701
    704     breakpoints = [0,1]
     702    breakpoints = [0, 1]
    705703    slopes = [2, 0, -1]
    706704    offset = 3
     
    743741
    744742        # We can either get explicit breakpoints and slopes, or rules
    745         # defining them
     743        # defining them.
    746744        self._breakpoints = kwargs.pop('breakpoints', None)
    747745        self._slopes = kwargs.pop('slopes', None)
     
    755753        self._forcesos2 = kwargs.pop('forcesos2', False)
    756754
    757         # Domain variable
     755        # The corresponding domain variable.
    758756        self.variable = kwargs.pop('value', None)
    759757
    760         # y-intercept
     758        # The y-intercept of the entire piecewise construct.
    761759        self.offset = kwargs.pop('offset', 0)
    762760
     
    767765        # Error checking
    768766
    769         # Make sure a domain variable was passed
     767        # Make sure a domain variable was passed.
    770768        if self.variable is None:
    771769            raise TypeError, "Specify a Variable object for the 'value' " \
     
    829827        Construct the breakpoint and slope expressions
    830828        """
    831         # Construct the break points
     829
     830        if pyomo.debug("verbose"):
     831           print "Constructing Piecewise component, name="+self.name+", from args="+`args`
     832
     833        # NOTE: the _breakvals and _slopevals attributes can be either lists (if the
     834        #       component is not indexed) or list of lists (if the component is indexed).
     835
     836        # Construct the breakpoints
    832837        self._breakvals = list()
    833838        if self._breakpoints is not None:
     
    838843        else:
    839844            # Get breakpoints from a rule
    840             if self._breakpoint_component._ndim == 0:
     845            if (self._breakpoint_component is None) or (self._breakpoint_component._ndim == 0):
    841846                # Rule isn't indexed
    842847                exp = self._breakpoint_rule((self.model,))
     848                if not isinstance(exp, (list, tuple)):
     849                   raise TypeError, "A breakpoint rule is expected to return a list or a tuple - returned type was "+str(type(exp))
    843850                if exp is not None:
    844                     self._breakvals.append(exp)
     851                    self._breakvals = exp
    845852            else:
    846853                # Rule is indexed
     
    867874        else:
    868875            # Get slopes from a rule
    869             if self._slope_component._ndim == 0:
     876            if (self._slope_component is None) or (self._slope_component._ndim == 0):
    870877                # Rule isn't indexed
    871878                exp = self._slope_rule((self.model,))
     879                if not isinstance(exp, (list, tuple)):
     880                   raise TypeError, "A slope rule is expected to return a list or a tuple - returned type was "+str(type(exp))
    872881                if exp is not None:
    873                     self._slopevals.append(exp)
     882                    self._slopevals = exp
    874883            else:
    875884                # Rule is indexed
     
    887896                        self._slopevals.append(exp)
    888897
    889         # If N breakpoints are specified, then there can be N-1 or N+1
    890         # slopes
    891         if abs(len(self._slopevals) - len(self._breakvals)) != 1:
    892             msg = "Error constructing Piecewise object '%(name)s'; "          \
    893                   "%(breaks)i breakpoints and %(slopes)i slopes were "        \
    894                   "specified.\n\tGiven %(breaks)i breakpoints, there should " \
    895                   "be %(breaks)i-1 or %(breaks)i+1 slopes."
    896             raise ValueError, msg % {
    897               "breaks" : len(self._breakvals),
    898               "slopes" : len(self._slopevals),
    899               "name"   : self.name
    900             }
    901 
    902         # If they have specified an unbounded problem, add "None" to both
    903         # ends of self._breakvals
    904         if len(self._breakvals) < len(self._slopevals):
    905             self._breakvals.insert(0, None)
    906             self._breakvals.append(None)
     898        if pyomo.debug("verbose"):
     899           if (self._slope_component is None) or (self._slope_component._ndim == 0):
     900              print "Slopes="+str(self._slopevals)
     901           else:
     902              i = 0
     903              for index in self._slope_component._index:
     904                 print "Slope["+str(index)+"]="+str(self._slopevals[i])
     905                 i += 1
     906
     907           if (self._breakpoint_component is None) or (self._breakpoint_component._ndim == 0):
     908              print "Breakpoints="+str(self._slopevals)
     909           else:
     910              i = 0
     911              for index in self._breakpoint_component._index:
     912                 print "Breakpoint["+str(index)+"]="+str(self._breakvals[i])
     913                 i += 1
     914
     915        # If N breakpoints are specified, then there can be N-1 or N+1 slopes.
     916        if (self._breakpoint_component is None) or (self._breakpoint_component._ndim == 0):
     917           if abs(len(self._slopevals) - len(self._breakvals)) != 1:
     918               msg = "Error constructing Piecewise object '%(name)s'; "          \
     919                     "%(breaks)i breakpoints and %(slopes)i slopes were "        \
     920                     "specified.\n\tGiven %(breaks)i breakpoints, there should " \
     921                     "be %(breaks)i-1 or %(breaks)i+1 slopes."
     922               raise ValueError, msg % {
     923                 "breaks" : len(self._breakvals),
     924                 "slopes" : len(self._slopevals),
     925                 "name"   : self.name
     926               }
     927        else:
     928           for i in range(0,len(self._breakvals)):
     929              if abs(len(self._slopevals[i]) - len(self._breakvals[i])) != 1:
     930                  msg = "Error constructing Piecewise object '%(name)s'; "          \
     931                        "%(breaks)i breakpoints and %(slopes)i slopes were "        \
     932                        "specified.\n\tGiven %(breaks)i breakpoints, there should " \
     933                        "be %(breaks)i-1 or %(breaks)i+1 slopes."
     934                  raise ValueError, msg % {
     935                    "breaks" : len(self._breakvals[i]),
     936                    "slopes" : len(self._slopevals[i]),
     937                    "name"   : self.name
     938                  }
     939
     940        # If a user specified an unbounded problem, add "None" to both ends of self._breakvals.
     941        if (self._breakpoint_component is None) or (self._breakpoint_component._ndim == 0):
     942           if len(self._breakvals) < len(self._slopevals):
     943              self._breakvals.insert(0, None)
     944              self._breakvals.append(None)
     945        else:
     946           for i in range(0,len(self._breakvals)):
     947              if len(self._breakvals[i]) < len(self._slopevals[i]):
     948                 self._breakvals[i].insert(0, None)
     949                 self._breakvals[i].append(None)             
    907950
    908951        self._generate_constraints()
     
    10131056            return rule
    10141057
    1015 
    10161058        # Bound model.value if domain is bounded
    10171059        if (self._breakvals[0] is not None):
     
    10321074            # constraints We first find the interval containing zero
    10331075
    1034             # Handle the case where the domain has no lower bound
     1076            # Handle the case where the domain has no lower bound.
    10351077            if self._breakvals[0] is None:
    10361078                start = 1
  • coopr.pyomo/stable/coopr/pyomo/expr/canonical_repn.py

    r3182 r3285  
    6969        item = 'unknown object'
    7070        name = ''
    71         Logger.warning("Argument 'context' not passed")
     71        Logger.info("Argument 'context' not passed")
    7272
    7373    if ( key is not None ):
  • coopr.pyomo/stable/coopr/pyomo/io/__init__.py

    r2745 r3285  
    1111import ampl
    1212import cpxlp
    13 import osil
    1413#import problem_utils
  • coopr.pyomo/stable/coopr/pyomo/io/cpxlp.py

    r3182 r3285  
    238238        #
    239239        if 2 in x:
    240             quadterms = list()
    241             keys = sorted( x[2].keys() )
    242             for id in keys:
    243                 coef = x[2][id]
    244 
     240
     241            print >>OUTPUT, "+ ["
     242
     243            for id in sorted(x[2].keys()):
     244
     245                coefficient = x[2][id]
    245246                sign = '+'
    246                 if coef < 0: sign = '-'
     247                if coefficient < 0:
     248                   sign = '-'
     249                   coefficient = math.fabs(coefficient)
     250
    247251                if is_objective:
    248                     coef *= 2
     252                    coefficient *= 2
    249253                # times 2 because LP format requires /2 for all the quadratic
    250254                # terms /of the objective only/.  Discovered the last bit thru
     
    252256                # Ref: ILog CPlex 8.0 User's Manual, p197.
    253257
    254                 coef = str( math.fabs(coef) ) + ' '
    255 
    256                 quad = list()
     258                print >>OUTPUT, sign, coefficient,
     259
     260                term_variables = []
    257261                for var in id:
    258262                    label = x[-1][var].label
    259263                    if not label:
    260                         self._no_label_error( x[-1][var] )
    261 
    262                     name = convert_name( label ) # like X(3,1),
    263                     quad.append( name )
    264 
    265                 term = ' ^2' # same var (e.g. X**2) ...
    266                 if ( 2 == len(quad) ):  # ... unless we've 2 vars
    267                     term = ' * ' + quad[1] # different vars (e.g. X*Y)
    268                 term = sign + coef + quad[0] + term
    269                 quadterms.append( term )
    270 
    271             quad_output = '+ [ %s ]' % ' '.join( quadterms )
     264                        self._no_label_error(x[-1][var])
     265
     266                    name = convert_name(label) # like X(3,1),
     267                    term_variables.append(name)
     268
     269                if len(term_variables) == 2:
     270                   print >>OUTPUT, term_variables[0],"*",term_variables[1],
     271                else:
     272                   print >>OUTPUT, term_variables[0],"^ 2",
     273               
     274            print >>OUTPUT, ""
     275
     276            print >>OUTPUT, "]",
    272277            if is_objective:
    273                 quad_output += ' / 2'
    274             # divide by 2 because LP format requires /2 for all the quadratic
    275             # terms.  Weird.  Ref: ILog CPlex 8.0 User's Manual, p197
    276 
    277             output.append( quad_output )
     278                print >>OUTPUT, ' / 2'
     279                # divide by 2 because LP format requires /2 for all the quadratic
     280                # terms.  Weird.  Ref: ILog CPlex 8.0 User's Manual, p197
     281            else:
     282               print >>OUTPUT, ""
     283
    278284
    279285        #
     
    460466                    if not supports_quadratic:
    461467                        msg  = 'Solver unable to handle quadratic '           \
    462                                "expressions.  Objective at issue: '%s%%s'"
    463                         if key is None: msg %= (obj.name, '')
    464                         else:           msg %= (obj.name, '[%s]' % key )
    465 
     468                               "objective expressions.  Objective at issue: %s%s."
     469                        if key is None:
     470                           msg %= (obj.name, " ")
     471                        else:
     472                           msg %= (obj.name, '[%s]' % key )
    466473                        raise ValueError, msg
    467474
  • coopr.pyomo/stable/coopr/pyomo/tests/NL/CUTE/gigomez1_cute.py

    r2882 r3285  
    3333
    3434from coopr.pyomo import *
    35 model = Model()
     35model = ConcreteModel()
    3636
    37 var x{1..2} := 2.0;
    38 var z:=2.0;
     37model.x = Var([1,2], initialize=2.0)
     38model.z = Var(initialize=2.0)
    3939
    40 model.f = Objective(rule=f,sense=minimize)
    41 minimize f:
    42         z;
    43 subject to cons1:
    44         z+5.0*x[1]-x[2] >= 0;
    45 subject to cons2:
    46         z-4*x[2]-x[1]^2-x[2]^2 >= 0;
    47 subject to cons3:
    48         z-5*x[1]-x[2] >= 0;
     40model.f = Objective(expr=model.z)
    4941
    50 solve;
    51 display f;
    52 display x;
    53 display z;
     42model.cons1 = Constraint(expr=model.z+5.0*model.x[1]-model.x[2] >= 0)
     43model.cons2 = Constraint(expr=model.z-4.0*model.x[2]-model.x[1]**2-model.x[2]**2 >= 0)
     44model.cons3 = Constraint(expr=model.z-5.0*model.x[1]-model.x[2] >= 0)
    5445
  • coopr.pyomo/stable/coopr/pyomo/tests/unit/test_expr.py

    r2865 r3285  
    212212
    213213    def test_vals(self):
    214         try:
    215             NumericConstant(value='a')
    216             self.fail("Cannot initialize a constant with a non-numeric value")
    217         except ValueError:
    218             pass
     214        # the following aspect of this test is being removed due to the check seminatics
     215        # of a numeric constant requiring far too much run-time, especially when involved
     216        # in expression tree construction. if the user specifies a constant, we're assuming
     217        # it is correct.
     218#        try:
     219#            NumericConstant(value='a')
     220#            self.fail("Cannot initialize a constant with a non-numeric value")
     221#        except ValueError:
     222#            pass
    219223        a = NumericConstant(value=1.1)
    220224        b = float(a)
  • coopr.pyomo/stable/coopr/pyomo/tests/unit/test_model.py

    r2749 r3285  
    9292
    9393    def test_write_osil1 ( self ):
     94        if not 'osil' in coopr.opt.WriterFactory().services():
     95            self.skipTest('No OSiL writer is available.')
    9496        base = '%s/test_write_osil1' % currdir
    9597        fout, fbase = (base + '.out', base + '.txt')
  • coopr.pyomo/stable/scripts/pyomo

    r2770 r3285  
    7070        filename = record.pathname  # file path
    7171        lineno   = record.lineno
    72         function = record.funcName
    7372        msg      = record.getMessage()
     73        try:
     74            function = record.funcName
     75        except AttributeError:
     76            function = '(unknown)'
    7477
    7578        filename = filename.replace( self.basepath, '[coopr base]' )
Note: See TracChangeset for help on using the changeset viewer.