Ignore:
Timestamp:
07/04/10 22:17:02 (4 years ago)
Author:
khunter
Message:

On the road to Coopr with Python 2.4

One more NFC that should have been committed two patches ago,

File:
1 edited

Legend:

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

    r2765 r2767  
    4343    """ 
    4444 
    45     pyutilib.component.core.alias("Model", "Model objects can be used as a component of other models.") 
     45    pyutilib.component.core.alias("Model", 'Model objects can be used as a '  \ 
     46                                  'component of other models.') 
    4647 
    4748    preprocessor_ep = pyutilib.component.core.ExtensionPoint(IPyomoPresolver) 
     
    175176            for tset in val._index_set: 
    176177                if tset.name == "_unknown_": 
    177                     self._construct_temporary_set(tset,val.name+"_index_"+str(ctr)) 
    178                 ctr+=1 
    179             val._index = self._construct_temporary_set(val._index_set,val.name+"_index") 
     178                    self._construct_temporary_set( 
     179                      tset, 
     180                      val.name+"_index_"+str(ctr) 
     181                    ) 
     182                ctr += 1 
     183            val._index = self._construct_temporary_set( 
     184              val._index_set, 
     185              val.name+"_index" 
     186            ) 
    180187        if isinstance(val._index,_SetContainer) and \ 
    181188            val._index.name == "_unknown_": 
     
    240247                self._setattr_exec(name,val) 
    241248                return 
    242         # 
    243         # Try to set the value.  This may fail if the attribute does not already 
     249 
     250        # Try to set the value. This may fail if the attribute does not already 
    244251        # exist in this model, if the set_value function is not defined, or if 
    245         # a bad value is provided.  In the latter case, a ValueError will be thrown, which 
    246         # we raise.  Otherwise, this is an object that we need to set directly. 
    247         # 
     252        # a bad value is provided. In the latter case, a ValueError will be 
     253        # thrown, which # we raise. Otherwise, this is an object that we need 
     254        # to set directly. 
    248255        try: 
    249256            self.__dict__[name].set_value(val) 
     
    340347        elif type(arg) is coopr.opt.SolverResults: 
    341348           # if the solver status not one of either OK or Warning, then error. 
    342            if (arg.solver.status != coopr.opt.SolverStatus.ok) and (arg.solver.status != coopr.opt.SolverStatus.warning): 
    343               raise ValueError, "Cannot load a SolverResults object with bad status: "+str(arg.solver.status) 
    344            # but if there is a warning, print out a warning, as someone should probably take a look! 
     349           if (arg.solver.status != coopr.opt.SolverStatus.ok) and \ 
     350              (arg.solver.status != coopr.opt.SolverStatus.warning): 
     351               msg = 'Cannot load a SolverResults object with bad status: %s' 
     352               raise ValueError, msg % str( arg.solver.status ) 
     353 
     354           # but if there is a warning, print out a warning, as someone should 
     355           # probably take a look! 
    345356           if (arg.solver.status == coopr.opt.SolverStatus.warning): 
    346               print "WARNING - Loading a SolverResults object with a warning status" 
     357               print 'WARNING - Loading a SolverResults object with a '       \ 
     358                     'warning status' 
     359 
    347360           if len(arg.solution) > 0: 
    348361              self._load_solution(arg.solution(0),symbol_map=arg.symbol_map) 
     
    357370           return True 
    358371        else: 
    359            raise ValueError, "Cannot load model with object of type "+str(type(arg)) 
     372            msg = "Cannot load model with object of type '%s'" 
     373            raise ValueError, msg % str( type(arg) ) 
    360374 
    361375 
     
    363377        """ Store model information into a SolverResults object """ 
    364378        results.problem.name = self.name 
    365         results.problem.number_of_variables = self.statistics.number_of_variables 
    366         results.problem.number_of_binary_variables = self.statistics.number_of_binary_variables 
    367         results.problem.number_of_integer_variables = self.statistics.number_of_integer_variables 
    368         results.problem.number_of_continuous_variables = self.statistics.number_of_continuous_variables 
    369         results.problem.number_of_constraints = self.statistics.number_of_constraints 
    370         results.problem.number_of_objectives = self.statistics.number_of_objectives 
     379 
     380        stat_keys = ( 
     381          'number_of_variables', 
     382          'number_of_binary_variables', 
     383          'number_of_integer_variables', 
     384          'number_of_continuous_variables', 
     385          'number_of_constraints', 
     386          'number_of_objectives' 
     387        ) 
     388 
     389        for key in stat_keys: 
     390            results.problem.__dict__[key] = self.statistics.__dict__[key] 
     391 
    371392 
    372393    def _tuplize(self, data, setobj): 
     
    392413        for namespace in namespaces: 
    393414            if not namespace is None and not namespace in modeldata._data: 
    394                 raise IOError, "Cannot access undefined namespace: '%s'" % namespace 
     415                msg = "Cannot access undefined namespace: '%s'" 
     416                raise IOError, msg % namespace 
    395417        #print "HERE _load_model_data",self._declarations 
    396418        for declaration in self._declarations: 
     
    400422            if tmp in modeldata._default.keys(): 
    401423                if declaration.type() is Set: 
    402                     declaration.default = self._tuplize(modeldata._default[tmp],declaration) 
     424                    declaration.default = self._tuplize(modeldata._default[tmp], 
     425                                                        declaration) 
    403426                else: 
    404427                    declaration.default = modeldata._default[tmp] 
     
    408431                #print "HERE", declaration.name, namespace, modeldata._data 
    409432                if tmp in modeldata._data.get(namespace,{}).keys(): 
    410                     #print "HERE", declaration.name, str(declaration.dimen),modeldata._data[namespace][tmp] 
     433                    #print "HERE", declaration.name, str(declaration.dimen), \ 
     434                    #modeldata._data[namespace][tmp] 
    411435                    if declaration.type() is Set: 
    412                         data = self._tuplize(modeldata._data[namespace][tmp],declaration) 
     436                        data = self._tuplize(modeldata._data[namespace][tmp], 
     437                                             declaration) 
    413438                    else: 
    414439                        data = modeldata._data[namespace][tmp] 
     
    416441                if not data is None: 
    417442                    break 
    418             if pyomo.debug("generate"):           #pragma:nocover 
    419                 print "About to generate '"+declaration.name+"' with data: "+str(data) 
     443            if pyomo.debug("generate"):                         #pragma:nocover 
     444                msg = "About to generate '%s' with data: %s" 
     445                print msg % ( declaration.name, str(data) ) 
    420446                self.pprint() 
    421447 
     
    424450                pass 
    425451            except Exception, err: 
    426                 print "Error constructing declaration "+str(declaration.name)+" from data="+str(data) 
    427                 print "ERROR: "+str(err) 
    428                 raise err 
     452                msg = "%s\nError constructing declaration '%s' from data=%s" 
     453                raise err, msg % ( str(declaration.name), str(data), str(err) ) 
    429454 
    430455    def _load_solution(self, soln, symbol_map=None): 
     
    435460        if type(soln) in (list, tuple): 
    436461            if len(soln) != len(self._var): 
    437                 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)) 
     462                msg = 'Attempting to load a list/tuple solution into a '      \ 
     463                      'model, but its length is %d while the model has %d '   \ 
     464                      'variables' % (len(soln), len(self._var)) 
     465                raise ValueError, msg % ( len(soln), len(self._var) ) 
    438466            for i in range(len(soln)): 
    439467                self._var[i].value = soln[i] 
     
    443471        # 
    444472        for name, entry in soln.variable.items(): 
    445           # 
    446           # NOTE: the following is a hack, to handle the ONE_VAR_CONSTANT variable 
    447           #       that is necessary for the objective constant-offset terms. 
    448           #       probably should create a dummy variable in the model map at the same 
    449           #       time the objective expression is being constructed. 
    450           # 
     473 
     474            # NOTE: the following is a hack, to handle the ONE_VAR_CONSTANT 
     475            #    variable that is necessary for the objective constant-offset 
     476            #    terms.  Probably should create a dummy variable in the model 
     477            #    map at the same time the objective expression is being 
     478            #    constructed. 
     479 
    451480          if name != "ONE_VAR_CONSTANT": 
    452              # translate the name first if there is a variable map associated with the input solution. 
     481             # translate the name first if there is a variable map associated 
     482             # with the input solution. 
    453483             if symbol_map is not None: 
    454484                name = symbol_map[name] 
    455485             if name not in self._name_varmap: 
    456                 names="" 
    457                 raise KeyError, "Variable name '"+name+"' is not in model "+self.name+".  Valid variable names: "+str(self._name_varmap.keys()) 
     486                msg = "Variable name '%s' is not in model '%s'.  Valid "      \ 
     487                      'variable names: %s' 
     488                raise KeyError, msg % ( 
     489                          name, self.name, str(self._name_varmap.keys()) ) 
     490 
    458491             if not isinstance(self._name_varmap[name],_VarValue): 
    459                 raise TypeError, "Variable '"+name+"' in model '"+self.name+"' is type "+str(type(self._name_varmap[name])) 
     492                 msg = "Variable '%s' in model '%s' is type %s" 
     493                 raise TypeError, msg % ( 
     494                     name, self.name, str(type(self._name_varmap[name])) ) 
     495 
    460496             if self._name_varmap[name].fixed is True: 
    461                 raise TypeError, "Variable '"+name+"' in model '"+self.name+"' is currently fixed - new value is not expected in solution" 
     497                 msg = "Variable '%s' in model '%s' is currently fixed - new" \ 
     498                       ' value is not expected in solution' 
     499                 raise TypeError, msg % ( name, self.name ) 
    462500 
    463501             var_value = self._name_varmap[name] 
     
    489527 
    490528             if _name not in self._name_conmap: 
    491                 names="" 
    492                 raise KeyError, "Constraint name '"+name+"' is not in model "+self.name+".  Valid constraint names: "+str(self._name_conmap.keys()) 
     529                msg = "Constraint name '%s' is not in model '%s'.  Valid "    \ 
     530                      'constraint names: %s' 
     531                raise KeyError, msg % ( 
     532                              name, self.name, str(self._name_conmap.keys()) ) 
     533 
    493534             if not isinstance(self._name_conmap[_name],ConstraintData): 
    494                 raise TypeError, "Constraint '"+name+"' in model '"+self.name+"' is type "+str(type(self._name_conmap[_name])) 
     535                 msg = "Constraint '%s' in model '%s' is type %s" 
     536                 raise TypeError, msg % ( 
     537                        name, self.name, str(type(self._name_conmap[_name])) ) 
    495538 
    496539             constraint_data = self._name_conmap[_name] 
     
    514557        problem_writer = coopr.opt.WriterFactory(format) 
    515558        if problem_writer is None: 
    516            raise ValueError, "Cannot write model in format \"" + str(format) + "\": no model writer registered for that format" 
     559            msg = "Cannot write model in format '%s'': no model writer "      \ 
     560                  'registered for that format' 
     561            raise ValueError, msg % str(format) 
     562 
    517563        (fname, symbol_map) = problem_writer(self, filename) 
    518564        if pyomo.debug("verbose"): 
    519            print "Writing model "+self.name+" to file '"+str(fname)+"'  with format "+str(format) 
     565            msg = "Writing model '%s' to file '%s' with format %s" 
     566            print msg % ( self.name, str(fname), str(format) ) 
     567 
    520568        return fname, symbol_map 
    521569 
     
    10111059class ConcreteModel(Model): 
    10121060    """ 
    1013     A concrete optimization model that does not defer construction of components. 
     1061    A concrete optimization model that does not defer construction of 
     1062    components. 
    10141063    """ 
    10151064 
     
    10181067        self._defer_construction=False 
    10191068 
    1020     pyutilib.component.core.alias("ConcreteModel", "Model with concrete expressions, which can be used as a component of other models.") 
     1069    pyutilib.component.core.alias("ConcreteModel", 'Model with concrete '     \ 
     1070              'expressions, which can be used as a component of other models.') 
Note: See TracChangeset for help on using the changeset viewer.