def __iter__(self): if not self._constructed: raise RuntimeError( "Cannot iterate over abstract RangeSet '%s' before it has " "been constructed (initialized)." % (self.name, )) if self.filter is None and self.validate is None: # # Iterate through all set elements # for i in xrange(self._len): yield self._start_val + i * self._step_val else: # # Iterate through all set elements and filter # and/or validate the element values. # for i in xrange( int((self._end_val - self._start_val + self._step_val + 1e-7) // self._step_val)): val = self._start_val + i * self._step_val if not self.filter is None and not apply_indexed_rule( self, self.filter, self._parent(), val): continue if not self.validate is None and not apply_indexed_rule( self, self.validate, self._parent(), val): continue yield val
def construct(self, data=None): """ Apply the rule to construct values in this set """ if __debug__ and logger.isEnabledFor(logging.DEBUG): #pragma:nocover logger.debug("Constructing Action, name="+self.name) # if self._constructed: #pragma:nocover return self._constructed=True # if None in self._index: # Scalar component self._rule(self._parent()) else: # Indexed component for index in self._index: apply_indexed_rule(self, self._rule, self._parent(), index)
def construct(self, data=None): if __debug__ and logger.isEnabledFor(logging.DEBUG): #pragma:nocover logger.debug("Constructing Connector, name=%s, from data=%s", self.name, str(data)) if self._constructed: return self._constructed=True # # Construct _ConnectorValue objects for all index values # rule = self._rule is not None extend = self._extends is not None init = self._initialize is not None if self.is_indexed(): for ndx in self._index: self._add_indexed_member(ndx) tmp = self[ndx] if self._implicit: for key in self._implicit: self.add(None,key) if extend: for key, val in self._extends.vars: tmp.add(val,key) if init: for key, val in iteritems(self._initialize): tmp.add(val,key) if rule: items = apply_indexed_rule( self, self._rule, self._parent(), ndx) for key, val in iteritems(items): tmp.add(val,key) else: # if the dimension is a scalar (i.e., we're dealing # with a _ConObject), and the _data is already initialized. if self._implicit: for key in self._implicit: self.add(None,key) if extend: for key, val in self._extends.vars: self.add(val,key) if init: for key, val in iteritems(dict(self._initialize)): self.add(val,key) if rule: items = apply_indexed_rule( self, self._rule, self._parent(), ()) for key, val in iteritems(items): self.add(val,key)
def construct(self, data=None): if __debug__ and logger.isEnabledFor(logging.DEBUG): logger.debug("Constructing disjunction %s" % (self.name)) if self._constructed: return timer = ConstructionTimer(self) self._constructed=True _self_parent = self.parent_block() if not self.is_indexed(): if self._init_rule is not None: expr = self._init_rule(_self_parent) elif self._init_expr is not None: expr = self._init_expr else: timer.report() return if expr is None: raise ValueError( _rule_returned_none_error % (self.name,) ) if expr is Disjunction.Skip: timer.report() return self._data[None] = self self._setitem_when_not_present( None, expr ) elif self._init_expr is not None: raise IndexError( "Disjunction '%s': Cannot initialize multiple indices " "of a disjunction with a single disjunction list" % (self.name,) ) elif self._init_rule is not None: _init_rule = self._init_rule for ndx in self._index: try: expr = apply_indexed_rule(self, _init_rule, _self_parent, ndx) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for " "disjunction %s with index %s:\n%s: %s" % (self.name, str(ndx), type(err).__name__, err)) raise if expr is None: _name = "%s[%s]" % (self.name, str(idx)) raise ValueError( _rule_returned_none_error % (_name,) ) if expr is Disjunction.Skip: continue self._setitem_when_not_present(ndx, expr) timer.report()
def construct(self, data=None): """Initialize the Arc""" if __debug__ and logger.isEnabledFor(logging.DEBUG): logger.debug("Constructing Arc %s" % self.name) if self._constructed: return timer = ConstructionTimer(self) self._constructed = True if self._rule is None and self._init_vals is None: # No construction rule or values specified return elif self._rule is not None and self._init_vals is not None: raise ValueError( "Cannot specify rule along with source/destination/ports " "keywords for arc '%s'" % self.name) self_parent = self._parent() if not self.is_indexed(): if self._rule is None: tmp = self._init_vals tmp["directed"] = self._init_directed else: try: tmp = self._rule(self_parent) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating values for " "arc %s:\n%s: %s" % (self.name, type(err).__name__, err)) raise tmp = _iterable_to_dict(tmp, self._init_directed, self.name) self._setitem_when_not_present(None, tmp) else: if self._init_vals is not None: raise IndexError( "Arc '%s': Cannot initialize multiple indices " "of an arc with single ports" % self.name) for idx in self._index: try: tmp = apply_indexed_rule(self, self._rule, self_parent, idx) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating values for " "arc %s with index %s:\n%s: %s" % (self.name, str(idx), type(err).__name__, err)) raise tmp = _iterable_to_dict(tmp, self._init_directed, self.name) self._setitem_when_not_present(idx, tmp) timer.report()
def _update_expression(expre): """ This method will construct any additional indices in a expression resulting from the discretization """ _rule=expre._init_rule _parent=expre._parent() for i in expre.index_set(): if i not in expre: # Code taken from the construct() method of Expression expre.add(i,apply_indexed_rule(expre,_rule,_parent,i))
def _update_constraint(con): """ This method will construct any additional indices in a constraint resulting from the discretization. """ _rule=con.rule _parent=con._parent() for i in con.index_set(): if i not in con: # Code taken from the construct() method of Constraint con.add(i,apply_indexed_rule(con,_rule,_parent,i))
def construct(self, data=None): if __debug__ and logger.isEnabledFor(logging.DEBUG): #pragma:nocover logger.debug("Constructing %s '%s', from data=%s", self.__class__.__name__, self.name, str(data)) if self._constructed: #pragma:nocover return timer = ConstructionTimer(self) # _self_rule = self._rule self._rule = None super(Complementarity, self).construct() self._rule = _self_rule # if _self_rule is None and self._expr is None: # No construction rule or expression specified. return # if not self.is_indexed(): # # Scalar component # if _self_rule is None: self.add(None, self._expr) else: try: tmp = _self_rule(self.parent_block()) self.add(None, tmp) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for " "complementarity %s:\n%s: %s" % ( self.name, type(err).__name__, err ) ) raise else: if not self._expr is None: raise IndexError( "Cannot initialize multiple indices of a Complementarity " "component with a single expression") _self_parent = self._parent() for idx in self._index: try: tmp = apply_indexed_rule( self, _self_rule, _self_parent, idx ) self.add(idx, tmp) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for " "complementarity %s with index %s:\n%s: %s" % ( self.name, idx, type(err).__name__, err ) ) raise timer.report()
def construct(self, data=None): """ Apply the rule to construct values in this set """ if __debug__ and logger.isEnabledFor(logging.DEBUG): logger.debug( "Constructing Expression, name=%s, from data=%s" % (self.name, str(data))) if self._constructed: return timer = ConstructionTimer(self) self._constructed = True _init_expr = self._init_expr _init_rule = self._init_rule # # We no longer need these # self._init_expr = None # Utilities like DAE assume this stays around #self._init_rule = None if not self.is_indexed(): self._data[None] = self # # Construct and initialize members # if _init_rule is not None: # construct and initialize with a rule if self.is_indexed(): for key in self._index: self.add(key, apply_indexed_rule( self, _init_rule, self._parent(), key)) else: self.add(None, _init_rule(self._parent())) else: # construct and initialize with a value if _init_expr.__class__ is dict: for key in self._index: if key not in _init_expr: continue self.add(key, _init_expr[key]) else: for key in self._index: self.add(key, _init_expr) timer.report()
def _initialize_members(self, initSet): for idx in initSet: tmp = self[idx] for key in self._implicit: tmp.add(None, key) if self._extends: for key, val in iteritems(self._extends.vars): tmp.add(val, key, self._extends.rule_for(key)) if self._initialize: self._add_from_container(tmp, self._initialize) if self._rule: items = apply_indexed_rule( self, self._rule, self._parent(), idx) self._add_from_container(tmp, items)
def _initialize_members(self, initSet): for idx in initSet: tmp = self[idx] for key in self._implicit: tmp.add(None,key) if self._extends: for key, val in iteritems(self._extends.vars): tmp.add(val,key) for key, val in iteritems(self._initialize): tmp.add(val,key) if self._rule: items = apply_indexed_rule( self, self._rule, self._parent(), idx) for key, val in iteritems(items): tmp.add(val,key)
def _initialize_members(self, init_set): if self._init_xor[0] == _Initializer.value: # POD data val = self._init_xor[1] for key in init_set: self._data[key].xor = val elif self._init_xor[0] == _Initializer.deferred_value: # Param data val = bool(value( self._init_xor[1] )) for key in init_set: self._data[key].xor = val elif self._init_xor[0] == _Initializer.function: # rule fcn = self._init_xor[1] for key in init_set: self._data[key].xor = bool(value(apply_indexed_rule( self, fcn, self._parent(), key))) elif self._init_xor[0] == _Initializer.dict_like: # dict-like thing val = self._init_xor[1] for key in init_set: self._data[key].xor = bool(value(val[key]))
def construct(self, data=None): """ Construct the expression(s) for this complementarity condition. """ generate_debug_messages = __debug__ and logger.isEnabledFor(logging.DEBUG) if generate_debug_messages: #pragma:nocover logger.debug("Constructing complementarity list %s", self.name) if self._constructed: #pragma:nocover return timer = ConstructionTimer(self) _self_rule = self._rule self._constructed=True if _self_rule is None: return # _generator = None _self_parent = self._parent() if inspect.isgeneratorfunction(_self_rule): _generator = _self_rule(_self_parent) elif inspect.isgenerator(_self_rule): _generator = _self_rule if _generator is None: while True: val = self._nconditions + 1 if generate_debug_messages: #pragma:nocover logger.debug(" Constructing complementarity index "+str(val)) expr = apply_indexed_rule( self, _self_rule, _self_parent, val ) if expr is None: raise ValueError( "Complementarity rule returned None " "instead of ComplementarityList.End" ) if (expr.__class__ is tuple and expr == ComplementarityList.End): return self.add(expr) else: for expr in _generator: if expr is None: raise ValueError( "Complementarity generator returned None " "instead of ComplementarityList.End" ) if (expr.__class__ is tuple and expr == ComplementarityList.End): return self.add(expr) timer.report()
def construct(self, data=None): """ Apply the rule to construct values in this set """ if __debug__ and logger.isEnabledFor(logging.DEBUG): #pragma:nocover logger.debug("Constructing Check, name="+self.name) # if self._constructed: #pragma:nocover return self._constructed=True # if None in self._index: # Scalar component res = self._rule(self._parent()) if not res: raise ValueError("BuildCheck %r identified error" % self.name) else: # Indexed component for index in self._index: res = apply_indexed_rule(self, self._rule, self._parent(), index) if not res: raise ValueError("BuildCheck %r identified error with index %r" % (self.name, str(index)))
def construct(self, data=None): """ Apply the rule to construct values in this set """ if __debug__ and logger.isEnabledFor(logging.DEBUG): #pragma:nocover logger.debug("Constructing Check, name="+self.name) # if self._constructed: #pragma:nocover return timer = ConstructionTimer(self) self._constructed=True # if not self.is_indexed(): # Scalar component res = self._rule(self._parent()) if not res: raise ValueError("BuildCheck %r identified error" % self.name) else: # Indexed component for index in self._index: res = apply_indexed_rule(self, self._rule, self._parent(), index) if not res: raise ValueError("BuildCheck %r identified error with index %r" % (self.name, str(index))) timer.report()
def _update_block(blk): """ This method will construct any additional indices in a block resulting from the discretization of a ContinuousSet. """ # Code taken from the construct() method of Block missing_idx = set(blk._index)-set(iterkeys(blk._data)) for idx in list(missing_idx): _block = blk[idx] obj = apply_indexed_rule( None, blk._rule, _block, idx, blk._options ) if isinstance(obj, _BlockData) and obj is not _block: # If the user returns a block, use their block instead # of the empty one we just created. for c in list(obj.component_objects(descend_into=False)): obj.del_component(c) _block.add_component(c.local_name, c) # transfer over any other attributes that are not components for name, val in iteritems(obj.__dict__): if not hasattr(_block, name) and not hasattr(blk, name): super(_BlockData, _block).__setattr__(name, val)
def construct(self, data=None): """ Construct the expression(s) for this objective. """ generate_debug_messages = \ __debug__ and logger.isEnabledFor(logging.DEBUG) if generate_debug_messages: logger.debug( "Constructing objective %s" % (self.name)) if self._constructed: return self._constructed=True assert self._init_expr is None _init_rule = self.rule _init_sense = self._init_sense # # We no longer need these # self._init_expr = None self._init_sense = None # Utilities like DAE assume this stays around #self.rule = None if _init_rule is None: return _generator = None _self_parent = self._parent() if inspect.isgeneratorfunction(_init_rule): _generator = _init_rule(_self_parent) elif inspect.isgenerator(_init_rule): _generator = _init_rule if _generator is None: while True: val = self._nobjectives + 1 if generate_debug_messages: logger.debug( " Constructing objective index "+str(val)) expr = apply_indexed_rule(self, _init_rule, _self_parent, val) if expr is None: raise ValueError( "Objective rule returned None " "instead of ObjectiveList.End") if (expr.__class__ is tuple) and \ (expr == ObjectiveList.End): return self.add(expr, sense=_init_sense) else: for expr in _generator: if expr is None: raise ValueError( "Objective generator returned None " "instead of ObjectiveList.End") if (expr.__class__ is tuple) and \ (expr == ObjectiveList.End): return self.add(expr, sense=_init_sense)
def construct(self, data=None): """ Construct the expression(s) for this constraint. """ if __debug__ and logger.isEnabledFor(logging.DEBUG): logger.debug("Constructing constraint %s" % (self.name)) if self._constructed: return timer = ConstructionTimer(self) self._constructed=True _init_expr = self._init_expr _init_rule = self.rule # # We no longer need these # self._init_expr = None # Utilities like DAE assume this stays around #self.rule = None if (_init_rule is None) and \ (_init_expr is None): # No construction role or expression specified. return _self_parent = self._parent() if not self.is_indexed(): # # Scalar component # if _init_rule is None: tmp = _init_expr else: try: tmp = _init_rule(_self_parent) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for " "constraint %s:\n%s: %s" % (self.name, type(err).__name__, err)) raise self._setitem_when_not_present(None, tmp) else: if _init_expr is not None: raise IndexError( "Constraint '%s': Cannot initialize multiple indices " "of a constraint with a single expression" % (self.name,) ) for ndx in self._index: try: tmp = apply_indexed_rule(self, _init_rule, _self_parent, ndx) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for " "constraint %s with index %s:\n%s: %s" % (self.name, str(ndx), type(err).__name__, err)) raise self._setitem_when_not_present(ndx, tmp) timer.report()
def construct(self, data=None): """ Construct the expression(s) for this logical constraint. """ generate_debug_messages = is_debug_set(logger) if generate_debug_messages: logger.debug("Constructing logical constraint list %s" % self.name) if self._constructed: return self._constructed = True assert self._init_expr is None _init_rule = self.rule # # We no longer need these # self._init_expr = None # Utilities like DAE assume this stays around # self.rule = None if _init_rule is None: return _generator = None _self_parent = self._parent() if inspect.isgeneratorfunction(_init_rule): _generator = _init_rule(_self_parent) elif inspect.isgenerator(_init_rule): _generator = _init_rule if _generator is None: while True: val = len(self._index) + 1 if generate_debug_messages: logger.debug( " Constructing logical constraint index " + str(val)) expr = apply_indexed_rule(self, _init_rule, _self_parent, val) if expr is None: raise ValueError( "LogicalConstraintList '%s': rule returned None " "instead of LogicalConstraintList.End" % (self.name,)) if (expr.__class__ is tuple) and \ (expr == LogicalConstraintList.End): return self.add(expr) else: for expr in _generator: if expr is None: raise ValueError( "LogicalConstraintList '%s': generator returned None " "instead of LogicalConstraintList.End" % (self.name,)) if (expr.__class__ is tuple) and \ (expr == LogicalConstraintList.End): return self.add(expr)
def construct(self, data=None): """ Construct the expression(s) for this objective. """ if __debug__ and logger.isEnabledFor(logging.DEBUG): logger.debug( "Constructing objective %s" % (self.name)) if self._constructed: return self._constructed = True _init_expr = self._init_expr _init_sense = self._init_sense _init_rule = self.rule # # We no longer need these # self._init_expr = None self._init_sense = None # Utilities like DAE assume this stays around #self.rule = None if (_init_rule is None) and \ (_init_expr is None): # No construction rule or expression specified. return _self_parent = self._parent() if not self.is_indexed(): # # Scalar component # if _init_rule is None: tmp = _init_expr else: try: tmp = _init_rule(_self_parent) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for " "objective %s:\n%s: %s" % (self.name, type(err).__name__, err)) raise if tmp is None: raise ValueError( "Objective rule returned None instead of " "Objective.Skip") assert None not in self._data cdata = self._check_skip_add(None, tmp, objdata=self) if cdata is not None: # this happens as a side-effect of set_value on # SimpleObjective (normally _check_skip_add does not # add anything to the _data dict but it does call # set_value on the objdata object we pass in) assert None in self._data cdata.set_sense(_init_sense) else: assert None not in self._data else: if not _init_expr is None: raise IndexError( "Cannot initialize multiple indices of an " "objective with a single expression") for ndx in self._index: try: tmp = apply_indexed_rule(self, _init_rule, _self_parent, ndx) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for" " objective %s with index %s:\n%s: %s" % (self.name, str(ndx), type(err).__name__, err)) raise if tmp is None: raise ValueError( "Objective rule returned None instead of " "Objective.Skip for index %s" % (str(ndx))) cdata = self._check_skip_add(ndx, tmp) if cdata is not None: cdata.set_sense(_init_sense) self._data[ndx] = cdata
def _getitem_when_not_present(self, index): """ Returns the default component data value """ # # Local values # val = self._default_val if val is Param.NoValue: # We should allow the creation of mutable params without # a default value, as long as *solving* a model without # reasonable values produces an informative error. if self._mutable: # Note: _ParamData defaults to Param.NoValue if self.is_indexed(): ans = self._data[index] = _ParamData(self) else: ans = self._data[index] = self ans._index = index return ans if self.is_indexed(): idx_str = '%s[%s]' % ( self.name, index, ) else: idx_str = '%s' % (self.name, ) raise ValueError( "Error retrieving immutable Param value (%s):\n\tThe Param " "value is undefined and no default value is specified." % (idx_str, )) _default_type = type(val) _check_value_domain = True if _default_type in native_types: # # The set_default() method validates the domain of native types, so # we can skip the check on the value domain. # _check_value_domain = False elif _default_type is types.FunctionType: val = apply_indexed_rule(self, val, self.parent_block(), index) elif hasattr(val, '__getitem__') and (not isinstance(val, NumericValue) or val.is_indexed()): # Things that look like Dictionaries should be allowable. This # includes other IndexedComponent objects. val = val[index] else: # this is something simple like a non-indexed component pass # # If the user wants to validate values, we need to validate the # default value as well. For Mutable Params, this is easy: # _setitem_impl will inject the value into _data and # then call validate. # if self._mutable: return self._setitem_when_not_present(index, val) # # For immutable params, we never inject the default into the data # dictionary. This will break validation, as the validation rule is # allowed to assume the data is already present (actually, it will # die on infinite recursion, as Param.__getitem__() will re-call # _getitem_when_not_present). # # So, we will do something very inefficient: if we are # validating, we will inject the value into the dictionary, # call validate, and remove it. # if _check_value_domain or self._validate: try: self._data[index] = val self._validate_value(index, val, _check_value_domain) finally: del self._data[index] return val
def _initialize_members(self, init_set): """Initialize variable data for all indices in a set.""" # # Initialize domains # if self._domain_init_rule is not None: # # Initialize domains with a rule # if self.is_indexed(): for ndx in init_set: self._data[ndx].domain = apply_indexed_rule( self, self._domain_init_rule, self._parent(), ndx) else: self.domain = self._domain_init_rule(self._parent()) else: # # Initialize domains with a value # if self.is_indexed(): for ndx in init_set: self._data[ndx].domain = self._domain_init_value else: self.domain = self._domain_init_value # # Initialize values # if self._value_init_value is not None: # # Initialize values with a value # if self._value_init_value.__class__ is dict: for key in init_set: # # Skip indices that are not in the dictionary. This arises when # initializing VarList objects with a dictionary. # if not key in self._value_init_value: continue val = self._value_init_value[key] vardata = self._data[key] vardata.set_value(val) else: val = value(self._value_init_value) for key in init_set: vardata = self._data[key] vardata.set_value(val) elif self._value_init_rule is not None: # # Initialize values with a rule # if self.is_indexed(): for key in init_set: vardata = self._data[key] val = apply_indexed_rule(self, self._value_init_rule, self._parent(), key) val = value(val) vardata.set_value(val) else: val = self._value_init_rule(self._parent()) val = value(val) self.set_value(val) # # Initialize bounds # if self._bounds_init_rule is not None: # # Initialize bounds with a rule # if self.is_indexed(): for key in init_set: vardata = self._data[key] (lb, ub) = apply_indexed_rule(self, self._bounds_init_rule, self._parent(), key) vardata.setlb(lb) vardata.setub(ub) else: (lb, ub) = self._bounds_init_rule(self._parent()) self.setlb(lb) self.setub(ub) elif self._bounds_init_value is not None: # # Initialize bounds with a value # (lb, ub) = self._bounds_init_value for key in init_set: vardata = self._data[key] vardata.setlb(lb) vardata.setub(ub)
def construct(self, data=None): """ Construct the expression(s) for this constraint. """ generate_debug_messages = \ __debug__ and logger.isEnabledFor(logging.DEBUG) if generate_debug_messages: logger.debug("Constructing constraint list %s" % (self.cname(True))) if self._constructed: return self._constructed=True assert self._init_expr is None _init_rule = self.rule # # We no longer need these # self._init_expr = None # Utilities like DAE assume this stays around #self.rule = None if _init_rule is None: return _generator = None _self_parent = self._parent() if inspect.isgeneratorfunction(_init_rule): _generator = _init_rule(_self_parent) elif inspect.isgenerator(_init_rule): _generator = _init_rule if _generator is None: while True: val = self._nconstraints + 1 if generate_debug_messages: logger.debug( " Constructing constraint index "+str(val)) expr = apply_indexed_rule(self, _init_rule, _self_parent, val) if expr is None: raise ValueError( "Constraint rule returned None " "instead of ConstraintList.End") if (expr.__class__ is tuple) and \ (expr == ConstraintList.End): return self.add(expr) else: for expr in _generator: if expr is None: raise ValueError( "Constraint generator returned None " "instead of ConstraintList.End") if (expr.__class__ is tuple) and \ (expr == ConstraintList.End): return self.add(expr)
def _default(self, idx): """ Returns the default component data value """ # # Local values # val = self._default_val _default_type = type(val) # if not self._constructed: if idx is None: idx_str = '%s' % (self.local_name,) else: idx_str = '%s[%s]' % (self.local_name, idx,) raise ValueError( "Error retrieving Param value (%s): This parameter has " "not been constructed" % ( idx_str,) ) if val is None: # If the Param is mutable, then it is OK to create a Param # implicitly ... the error will be tossed later when someone # attempts to evaluate the value of the Param if self._mutable: if self.is_indexed(): self._data[idx] = _ParamData(self, val) #self._raw_setitem(idx, _ParamData(self, val), True) else: self._raw_setitem(idx, val) return self[idx] if self.is_indexed(): idx_str = '%s[%s]' % (self.name, idx,) else: idx_str = '%s' % (self.name,) raise ValueError( "Error retrieving Param value (%s):\nThe Param value is " "undefined and no default value is specified" % ( idx_str,) ) # # Get the value of the default for this index # _check_value_domain = True if _default_type in native_types: # # The set_default() method validates the domain of native types, so # we can skip the check on the value domain. # _check_value_domain = False elif _default_type is types.FunctionType: val = apply_indexed_rule(self, val, self.parent_block(), idx) elif hasattr(val, '__getitem__') and not isinstance(val, NumericValue): val = val[idx] else: pass if _check_value_domain: # # Get the value of a numeric value # if val.__class__ not in native_types: if isinstance(val, NumericValue): val = val() # # Check the domain # if val not in self.domain: raise ValueError( "Invalid default parameter value: %s[%s] = '%s';" " value type=%s.\n\tValue not in parameter domain %s" % (self.name, idx, val, type(val), self.domain.name) ) # # Set the parameter # if self._mutable: if self.is_indexed(): self._data[idx] = _ParamData(self, val) #self._raw_setitem(idx, _ParamData(self, val), True) else: self._raw_setitem(idx, val) return self[idx] else: # # This is kludgy: If the user wants to validate the Param # values, we need to validate the default value as well. # For Mutable Params, this is easy: setitem will inject the # value into _data and then call validate. For immutable # params, we never inject the default into the data # dictionary. This will break validation, as the validation # rule is allowed to assume the data is already present # (actually, it will die on infinite recursion, as # Param.__getitem__() will re-call _default). # # So, we will do something very inefficient: if we are # validating, we will inject the value into the dictionary, # call validate, and remove it. # if self._validate: try: self._data[idx] = val self._validateitem(idx, val) finally: del self._data[idx] return val
def _default(self, idx): """ Returns the default component data value """ # # Local values # val = self._default_val _default_type = type(val) # if not self._constructed: if idx is None: idx_str = '%s' % (self.name, ) else: idx_str = '%s[%s]' % ( self.name, idx, ) raise ValueError( "Error retrieving Param value (%s): This parameter has " "not been constructed" % (idx_str, )) if val is None: if self.is_indexed(): idx_str = '%s[%s]' % ( self.cname(True), idx, ) else: idx_str = '%s' % (self.cname(True), ) raise ValueError( "Error retrieving Param value (%s): The Param value is " "undefined and no default value is specified" % (idx_str, )) # # Get the value of the default for this index # _check_value_domain = True if _default_type in native_types: # # The set_default() method validates the domain of native types, so # we can skip the check on the value domain. # _check_value_domain = False elif _default_type is types.FunctionType: val = apply_indexed_rule(self, val, self.parent_block(), idx) elif hasattr(val, '__getitem__') and not isinstance(val, NumericValue): val = val[idx] else: pass if _check_value_domain: # # Get the value of a numeric value # if val.__class__ not in native_types: if isinstance(val, NumericValue): val = val() # # Check the domain # if val not in self.domain: raise ValueError( "Invalid default parameter value: %s[%s] = '%s';" " value type=%s.\n\tValue not in parameter domain %s" % (self.cname(True), idx, val, type(val), self.domain.name)) # # Set the parameter # if self._mutable: if idx is None: self._raw_setitem(idx, val) else: self._data[idx] = _ParamData(self, val) #self._raw_setitem(idx, _ParamData(self, val), True) return self[idx] else: # # This is kludgy: If the user wants to validate the Param # values, we need to validate the default value as well. # For Mutable Params, this is easy: setitem will inject the # value into _data and then call validate. For immutable # params, we never inject the default into the data # dictionary. This will break validation, as the validation # rule is allowed to assume the data is already present # (actually, it will die on infinite recursion, as # Param.__getitem__() will re-call _default). # # So, we will do something very inefficient: if we are # validating, we will inject the value into the dictionary, # call validate, and remove it. # if self._validate: try: self._data[idx] = val self._validateitem(idx, val) finally: del self._data[idx] return val
def _initialize_from(self, _init): """ Initialize data from a rule or data """ _init_type = type(_init) _isDict = _init_type is dict if _isDict or _init_type in native_types: # # We skip the other tests if we have a dictionary or constant # value, as these are the most common cases. # pass elif _init_type is types.FunctionType: # # Initializing from a function # if not self.is_indexed(): # # A scalar value has a single value. # We call __setitem__, which does checks on the value. # self[None] = _init(self.parent_block()) return else: # # An indexed parameter, where we call the function for each # index. # self_parent = self.parent_block() # try: # # Create an iterator for the indices. We assume that # it returns flattened tuples. Otherwise, # the validation process is far too expensive. # _iter = self._index.__iter__() idx = next(_iter) # # If a function returns a dict (or # dict-like thing), then we initialize the Param object # by reseting _init and _isDict # # Note that this logic allows the user to call a # function without an index # val = apply_indexed_rule(self, _init, self_parent, idx) # # The following is a simplification of the main # _initialize_from logic. The idea is that if the # function returns a scalar-like thing, use it to # initialize this index and re-call the function for # the next value. However, if the function returns # somethign that is dict-like, then use the dict to # initialize everything and do not re-vall the # initialize function. # # Note: while scalar components are technically # "dict-like", we will treat them as scalars and # re-call the initialize function. # _dict_like = False if type(val) is dict: _dict_like = True elif isinstance(val, IndexedComponent): _dict_like = val.is_indexed() elif hasattr(val, '__getitem__') \ and not isinstance(val, NumericValue): try: for x in _init: _init.__getitem__(x) _dict_like = True except: pass if _dict_like: _init = val _isDict = True else: # # At this point, we know the value is specific to # this index (i.e., not likely to be a dict-like # thing), and that the index is valid; so, it is # safe to use _raw_setitem (which will perform all # the domain / validation checking) # self._raw_setitem(idx, val) # # Now iterate over the rest of the index set. # for idx in _iter: self._raw_setitem( idx, apply_indexed_rule( self, _init, self_parent, idx ) ) return except StopIteration: # # The index set was empty... # The parameter is indexed by an empty set, or an empty set tuple. # Rare, but it has happened. # return elif isinstance(_init, NumericValue): # # Reduce NumericValues to scalars. This allows us to treat # scalar components as numbers and not # as indexed components with a index set of [None] # _init = _init() elif isinstance(_init, IndexedComponent): # # Ideally, we want to reduce IndexedComponents to # a dict, but without "densifying" it. However, since # there is no way to (easily) get the default value, we # will take the "less surprising" route of letting the # source become dense, so that we get the expected copy. # # TODO: Establish use-cases where we can use default values # for sparsity. # _init_keys_len = sum(1 for _ in _init.keys()) sparse_src = len(_init) != _init_keys_len tmp = dict( _init.iteritems() ) if sparse_src and len(_init) == _init_keys_len: logger.warning(""" Initializing Param %s using a sparse mutable indexed component (%s). This has resulted in the conversion of the source to dense form. """ % (self.name, _init.name)) _init = tmp _isDict = True # # If the _init is not a native dictionary, but it # behaves like one (that is, it could be converted to a # dict with "dict((key,_init[key]) for key in _init)"), # then we will treat it as such # # TODO: Establish a use-case for this. This iteration is # expensive. # if not _isDict and hasattr(_init, '__getitem__'): try: _isDict = True for x in _init: _init.__getitem__(x) except: _isDict = False # # Now, we either have a scalar or a dictionary # if _isDict: # # Because this is a user-specified dictionary, we # must use the normal (expensive) __setitem__ route # so that the individual indices are validated. # for key in _init: self[key] = _init[key] else: try: # # A constant is being supplied as a default to # a parameter. This happens for indexed parameters, # particularly when dealing with mutable parameters. # # We look at the first iteration index separately to # to validate the value against the domain once. # _iter = self._index.__iter__() idx = next(_iter) self._raw_setitem(idx, _init) # # Note: the following is safe for both indexed and # non-indexed parameters: for non-indexed, the first # idx (above) will be None, and the for-loop below # will NOT be called. # if self._mutable: _init = self[idx].value for idx in _iter: self._raw_setitem( idx, _ParamData(self,_init) ) else: _init = self[idx] for idx in _iter: self._raw_setitem(idx, _init) except StopIteration: # # The index set was empty... # The parameter is indexed by an empty set, or an empty set tuple. # Rare, but it has happened. # pass
def _getitem_when_not_present(self, index): """ Returns the default component data value """ # # Local values # val = self._default_val if val is _NotValid: # We should allow the creation of mutable params without # a default value, as long as *solving* a model without # reasonable values produces an informative error. if self._mutable: # Note: _ParamData defaults to _NotValid ans = self._data[index] = _ParamData(self) return ans if self.is_indexed(): idx_str = '%s[%s]' % (self.name, index,) else: idx_str = '%s' % (self.name,) raise ValueError( "Error retrieving immutable Param value (%s):\n\tThe Param " "value is undefined and no default value is specified." % ( idx_str,) ) _default_type = type(val) _check_value_domain = True if _default_type in native_types: # # The set_default() method validates the domain of native types, so # we can skip the check on the value domain. # _check_value_domain = False elif _default_type is types.FunctionType: val = apply_indexed_rule(self, val, self.parent_block(), index) elif hasattr(val, '__getitem__') and ( not isinstance(val, NumericValue) or val.is_indexed() ): # Things that look like Dictionaries should be allowable. This # includes other IndexedComponent objects. val = val[index] else: # this is something simple like a non-indexed component pass # # If the user wants to validate values, we need to validate the # default value as well. For Mutable Params, this is easy: # _setitem_impl will inject the value into _data and # then call validate. # if self._mutable: return self._setitem_when_not_present(index, val) # # For immutable params, we never inject the default into the data # dictionary. This will break validation, as the validation rule is # allowed to assume the data is already present (actually, it will # die on infinite recursion, as Param.__getitem__() will re-call # _getitem_when_not_present). # # So, we will do something very inefficient: if we are # validating, we will inject the value into the dictionary, # call validate, and remove it. # if _check_value_domain or self._validate: try: self._data[index] = val self._validate_value(index, val, _check_value_domain) finally: del self._data[index] return val
def _initialize_from(self, _init): """ Initialize data from a rule or data """ _init_type = type(_init) _isDict = _init_type is dict if _isDict or _init_type in native_types: # # We skip the other tests if we have a dictionary or constant # value, as these are the most common cases. # pass elif _init_type is types.FunctionType: # # Initializing from a function # if not self.is_indexed(): # # A scalar value has a single value. # We call __setitem__, which does checks on the value. # self[None] = _init(self.parent_block()) return else: # # An indexed parameter, where we call the function for each # index. # self_parent = self.parent_block() # try: # # Create an iterator for the indices. We assume that # it returns flattened tuples. Otherwise, # the validation process is far too expensive. # _iter = self._index.__iter__() idx = next(_iter) # # If a function returns a dict (or # dict-like thing), then we initialize the Param object # by reseting _init and _isDict # # Note that this logic allows the user to call a # function without an index # val = apply_indexed_rule(self, _init, self_parent, idx) # # The following is a simplification of the main # _initialize_from logic. The idea is that if the # function returns a scalar-like thing, use it to # initialize this index and re-call the function for # the next value. However, if the function returns # somethign that is dict-like, then use the dict to # initialize everything and do not re-vall the # initialize function. # # Note: while scalar components are technically # "dict-like", we will treat them as scalars and # re-call the initialize function. # _dict_like = False if type(val) is dict: _dict_like = True elif isinstance(val, IndexedComponent): _dict_like = val.is_indexed() elif hasattr(val, '__getitem__') \ and not isinstance(val, NumericValue): try: for x in _init: _init.__getitem__(x) _dict_like = True except: pass if _dict_like: _init = val _isDict = True else: # # At this point, we know the value is specific to # this index (i.e., not likely to be a dict-like # thing), and that the index is valid; so, it is # safe to use _raw_setitem (which will perform all # the domain / validation checking) # self._raw_setitem(idx, val) # # Now iterate over the rest of the index set. # for idx in _iter: self._raw_setitem( idx, apply_indexed_rule(self, _init, self_parent, idx)) return except StopIteration: # # The index set was empty... # The parameter is indexed by an empty set, or an empty set tuple. # Rare, but it has happened. # return elif isinstance(_init, NumericValue): # # Reduce NumericValues to scalars. This allows us to treat # scalar components as numbers and not # as indexed components with a index set of [None] # _init = _init() elif isinstance(_init, IndexedComponent): # # Ideally, we want to reduce IndexedComponents to # a dict, but without "densifying" it. However, since # there is no way to (easily) get the default value, we # will take the "less surprising" route of letting the # source become dense, so that we get the expected copy. # # TODO: Establish use-cases where we can use default values # for sparsity. # _init_keys_len = sum(1 for _ in _init.keys()) sparse_src = len(_init) != _init_keys_len tmp = dict(_init.iteritems()) if sparse_src and len(_init) == _init_keys_len: logger.warning(""" Initializing Param %s using a sparse mutable indexed component (%s). This has resulted in the conversion of the source to dense form. """ % (self.cname(True), _init.name)) _init = tmp _isDict = True # # If the _init is not a native dictionary, but it # behaves like one (that is, it could be converted to a # dict with "dict((key,_init[key]) for key in _init)"), # then we will treat it as such # # TODO: Establish a use-case for this. This iteration is # expensive. # if not _isDict and hasattr(_init, '__getitem__'): try: _isDict = True for x in _init: _init.__getitem__(x) except: _isDict = False # # Now, we either have a scalar or a dictionary # if _isDict: # # Because this is a user-specified dictionary, we # must use the normal (expensive) __setitem__ route # so that the individual indices are validated. # for key in _init: self[key] = _init[key] else: try: # # A constant is being supplied as a default to # a parameter. This happens for indexed parameters, # particularly when dealing with mutable parameters. # # We look at the first iteration index separately to # to validate the value against the domain once. # _iter = self._index.__iter__() idx = next(_iter) self._raw_setitem(idx, _init) # # Note: the following is safe for both indexed and # non-indexed parameters: for non-indexed, the first # idx (above) will be None, and the for-loop below # will NOT be called. # if self._mutable: _init = self[idx].value for idx in _iter: self._raw_setitem(idx, _ParamData(self, _init)) else: _init = self[idx] for idx in _iter: self._raw_setitem(idx, _init) except StopIteration: # # The index set was empty... # The parameter is indexed by an empty set, or an empty set tuple. # Rare, but it has happened. # pass
def construct(self, data=None): """ Construct this component """ assert data is None # because I don't know why it's an argument generate_debug_messages \ = __debug__ and logger.isEnabledFor(logging.DEBUG) if self._constructed is True: #pragma:nocover return if generate_debug_messages: #pragma:nocover logger.debug("Constructing SOSConstraint %s",self.name) timer = ConstructionTimer(self) self._constructed = True if self._rule is None: if self._sosSet is None and self.is_indexed(): if generate_debug_messages: #pragma:nocover logger.debug(" Cannot construct "+self.name+". No rule is defined and no SOS sets are defined.") else: if not self.is_indexed(): if self._sosSet is None: if getattr(self._sosVars.index_set(), 'ordered', False): _sosSet = {None: list(self._sosVars.index_set())} else: _sosSet = {None: set(self._sosVars.index_set())} else: _sosSet = {None: self._sosSet} else: _sosSet = self._sosSet for index, sosSet in six.iteritems(_sosSet): if generate_debug_messages: #pragma:nocover logger.debug(" Constructing "+self.name+" index "+str(index)) if self._sosLevel == 2: # # Check that the sets are ordered. # ordered=False if type(sosSet) is list or sosSet is UnindexedComponent_set or len(sosSet) == 1: ordered=True if hasattr(sosSet, 'ordered') and sosSet.ordered: ordered=True if type(sosSet) is _IndexedOrderedSetData: ordered=True if not ordered: raise ValueError("Cannot define a SOS over an unordered index.") variables = [self._sosVars[idx] for idx in sosSet] if self._sosWeights is not None: weights = [self._sosWeights[idx] for idx in sosSet] else: weights = None self.add(index, variables, weights) else: _self_rule = self._rule _self_parent = self._parent() for index in self._index: try: tmp = apply_indexed_rule(self, _self_rule, _self_parent, index) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for " "sos constraint %s with index %s:\n%s: %s" % ( self.name, str(index), type(err).__name__, err ) ) raise if tmp is None: raise ValueError("SOSConstraint rule returned None instead of SOSConstraint.Skip for index %s" % str(index)) if type(tmp) is tuple: if tmp is SOSConstraint.Skip: continue # tmp is a tuple of variables, weights self.add(index, tmp[0], tmp[1]) else: # tmp is a list of variables self.add(index, tmp) timer.report()
def _initialize_members(self, init_set): """Initialize variable data for all indices in a set.""" # # Initialize domains # if self._domain_init_rule is not None: # # Initialize domains with a rule # if self.is_indexed(): for ndx in init_set: self._data[ndx].domain = apply_indexed_rule(self, self._domain_init_rule, self._parent(), ndx) else: self.domain = self._domain_init_rule(self._parent()) else: # # Initialize domains with a value # if self.is_indexed(): for ndx in init_set: self._data[ndx].domain = self._domain_init_value else: self.domain = self._domain_init_value # # Initialize values # if self._value_init_value is not None: # # Initialize values with a value # if self._value_init_value.__class__ is dict: for key in init_set: # # Skip indices that are not in the dictionary. This arises when # initializing VarList objects with a dictionary. # if not key in self._value_init_value: continue val = self._value_init_value[key] vardata = self._data[key] vardata.set_value(val) else: val = value(self._value_init_value) for key in init_set: vardata = self._data[key] vardata.set_value(val) elif self._value_init_rule is not None: # # Initialize values with a rule # if self.is_indexed(): for key in init_set: vardata = self._data[key] val = apply_indexed_rule( self, self._value_init_rule, self._parent(), key ) val = value(val) vardata.set_value(val) else: val = self._value_init_rule(self._parent()) val = value(val) self.set_value(val) # # Initialize bounds # if self._bounds_init_rule is not None: # # Initialize bounds with a rule # if self.is_indexed(): for key in init_set: vardata = self._data[key] (lb, ub) = apply_indexed_rule( self, self._bounds_init_rule, self._parent(), key ) vardata.setlb(lb) vardata.setub(ub) else: (lb, ub) = self._bounds_init_rule(self._parent()) self.setlb(lb) self.setub(ub) elif self._bounds_init_value is not None: # # Initialize bounds with a value # (lb, ub) = self._bounds_init_value for key in init_set: vardata = self._data[key] vardata.setlb(lb) vardata.setub(ub)
def _initialize_members(self, init_set): """Initialize variable data for all indices in a set.""" # # Initialize domains # if self._domain_init_rule is not None: # # Initialize domains with a rule # if self.is_indexed(): for ndx in init_set: self._data[ndx].domain = \ apply_indexed_rule(self, self._domain_init_rule, self._parent(), ndx) else: self.domain = self._domain_init_rule(self._parent()) else: if self.is_indexed(): # Optimization: It is assumed self._domain_init_value # is used when the _GeneralVarData objects # are created. This avoids an unnecessary # loop over init_set, which can significantly # speed up construction of variables with large # index sets. pass else: # the above optimization does not apply for # singleton objects (trying to do so breaks # some of the pickle tests) self.domain = self._domain_init_value # # Initialize values # if self._value_init_rule is not None: # # Initialize values with a rule # if self.is_indexed(): for key in init_set: vardata = self._data[key] val = apply_indexed_rule(self, self._value_init_rule, self._parent(), key) val = value(val) vardata.set_value(val) else: val = self._value_init_rule(self._parent()) val = value(val) self.set_value(val) elif self._value_init_value is not None: # # Initialize values with a value # if self._value_init_value.__class__ is dict: for key in init_set: # Skip indices that are not in the # dictionary. This arises when # initializing VarList objects with a # dictionary. if not key in self._value_init_value: continue val = self._value_init_value[key] vardata = self._data[key] vardata.set_value(val) else: val = value(self._value_init_value) for key in init_set: vardata = self._data[key] vardata.set_value(val) # # Initialize bounds # if self._bounds_init_rule is not None: # # Initialize bounds with a rule # if self.is_indexed(): for key in init_set: vardata = self._data[key] (lb, ub) = apply_indexed_rule(self, self._bounds_init_rule, self._parent(), key) vardata.setlb(lb) vardata.setub(ub) else: (lb, ub) = self._bounds_init_rule(self._parent()) self.setlb(lb) self.setub(ub) elif self._bounds_init_value is not None: # # Initialize bounds with a value # (lb, ub) = self._bounds_init_value for key in init_set: vardata = self._data[key] vardata.setlb(lb) vardata.setub(ub)
def _initialize_members(self, init_set): """Initialize variable data for all indices in a set.""" # TODO: determine if there is any advantage to supporting init_set. # Preliminary tests indicate that there isn't a significant speed # difference to using the set form (used in dense vector # construction). Getting rid of it could simplify _setitem and # this method. # # Initialize domains # if self._domain_init_rule is not None: # # Initialize domains with a rule # if self.is_indexed(): for ndx in init_set: self._data[ndx].domain = \ apply_indexed_rule(self, self._domain_init_rule, self._parent(), ndx) else: self.domain = self._domain_init_rule(self._parent()) else: if self.is_indexed(): # Optimization: It is assumed self._domain_init_value # is used when the _GeneralVarData objects # are created. This avoids an unnecessary # loop over init_set, which can significantly # speed up construction of variables with large # index sets. pass else: # the above optimization does not apply for # singleton objects (trying to do so breaks # some of the pickle tests) self.domain = self._domain_init_value # # Initialize values # if self._value_init_rule is not None: # # Initialize values with a rule # if self.is_indexed(): for key in init_set: vardata = self._data[key] val = apply_indexed_rule(self, self._value_init_rule, self._parent(), key) val = value(val) vardata.set_value(val) else: val = self._value_init_rule(self._parent()) val = value(val) self.set_value(val) elif self._value_init_value is not None: # # Initialize values with a value # if self._value_init_value.__class__ is dict: for key in init_set: # Skip indices that are not in the # dictionary. This arises when # initializing VarList objects with a # dictionary. if not key in self._value_init_value: continue val = self._value_init_value[key] vardata = self._data[key] vardata.set_value(val) else: val = value(self._value_init_value) for key in init_set: vardata = self._data[key] vardata.set_value(val) # # Initialize bounds # if self._bounds_init_rule is not None: # # Initialize bounds with a rule # if self.is_indexed(): for key in init_set: vardata = self._data[key] (lb, ub) = apply_indexed_rule(self, self._bounds_init_rule, self._parent(), key) vardata.setlb(lb) vardata.setub(ub) else: (lb, ub) = self._bounds_init_rule(self._parent()) self.setlb(lb) self.setub(ub) elif self._bounds_init_value is not None: # # Initialize bounds with a value # (lb, ub) = self._bounds_init_value for key in init_set: vardata = self._data[key] vardata.setlb(lb) vardata.setub(ub)
def construct(self, data=None): """ Apply the rule to construct values in this set """ if __debug__ and logger.isEnabledFor(logging.DEBUG): logger.debug( "Constructing Expression, name=%s, from data=%s" % (self.cname(True), str(data))) if self._constructed: return self._constructed = True _init_expr = self._init_expr _init_rule = self._init_rule # # We no longer need these # self._init_expr = None self._init_rule = None # # Construct _GeneralExpressionData objects for all index values # if not self.is_indexed(): self._data[None] = self self._data.update( (key, _GeneralExpressionData(None, component=self)) for key in self._index) # # Initialize members # if _init_expr is not None: # # Initialize values with a value # if _init_expr.__class__ is dict: for key in self._index: # Skip indices that are not in the dictionary if not key in _init_expr: continue self.add(key, _init_expr[key]) #self._data[key].set_value(_init_expr[key]) else: for key in self._index: self.add(key, _init_expr) #self._data[key].set_value(_init_expr) elif _init_rule is not None: # # Initialize values with a rule # if self.is_indexed(): for key in self._index: self.add(key, apply_indexed_rule(self, _init_rule, self._parent(), key)) else: self.add(None, _init_rule(self._parent()))
def construct(self, data=None): """ Construct the expression(s) for this constraint. """ if __debug__ and logger.isEnabledFor(logging.DEBUG): logger.debug("Constructing constraint %s" % (self.name)) if self._constructed: return self._constructed = True _init_expr = self._init_expr _init_rule = self.rule # # We no longer need these # self._init_expr = None # Utilities like DAE assume this stays around #self.rule = None if (_init_rule is None) and \ (_init_expr is None): # No construction role or expression specified. return _self_parent = self._parent() if not self.is_indexed(): # # Scalar component # if _init_rule is None: tmp = _init_expr else: try: tmp = _init_rule(_self_parent) except Exception: err = sys.exc_info()[1] logger.error("Rule failed when generating expression for " "constraint %s:\n%s: %s" % (self.name, type(err).__name__, err)) raise if tmp is None: raise ValueError(_rule_returned_none_error % (self.name, )) assert None not in self._data cdata = self._check_skip_add(None, tmp, condata=self) if cdata is not None: # this happens as a side-effect of set_value on # SimpleConstraint (normally _check_skip_add does not # add anything to the _data dict but it does call # set_value on the condata object we pass in) assert None in self._data else: assert None not in self._data else: if not _init_expr is None: raise IndexError( "Constraint '%s': Cannot initialize multiple indices " "of a constraint with a single expression" % (self.name, )) for ndx in self._index: try: tmp = apply_indexed_rule(self, _init_rule, _self_parent, ndx) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for " "constraint %s with index %s:\n%s: %s" % (self.name, str(ndx), type(err).__name__, err)) raise if tmp is None: raise ValueError(_rule_returned_none_error % ('%s[%s]' % (self.name, str(ndx)), )) cdata = self._check_skip_add(ndx, tmp) if cdata is not None: self._data[ndx] = cdata
def construct(self, data=None): """ Construct the expression(s) for this objective. """ if __debug__ and logger.isEnabledFor(logging.DEBUG): logger.debug("Constructing objective %s" % (self.name)) if self._constructed: return timer = ConstructionTimer(self) self._constructed = True _init_expr = self._init_expr _init_sense = self._init_sense _init_rule = self.rule # # We no longer need these # self._init_expr = None self._init_sense = None # Utilities like DAE assume this stays around #self.rule = None if (_init_rule is None) and \ (_init_expr is None): # No construction rule or expression specified. return _self_parent = self._parent() if not self.is_indexed(): # # Scalar component # if _init_rule is None: tmp = _init_expr else: try: tmp = _init_rule(_self_parent) except Exception: err = sys.exc_info()[1] logger.error("Rule failed when generating expression for " "objective %s:\n%s: %s" % (self.name, type(err).__name__, err)) raise if self._setitem_when_not_present(None, tmp) is not None: self.set_sense(_init_sense) else: if _init_expr is not None: raise IndexError("Cannot initialize multiple indices of an " "objective with a single expression") for ndx in self._index: try: tmp = apply_indexed_rule(self, _init_rule, _self_parent, ndx) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for" " objective %s with index %s:\n%s: %s" % (self.name, str(ndx), type(err).__name__, err)) raise ans = self._setitem_when_not_present(ndx, tmp) if ans is not None: ans.set_sense(_init_sense) timer.report()
def construct(self, data=None): """ Construct the expression(s) for this logical constraint. """ if is_debug_set(logger): logger.debug("Constructing logical constraint %s" % self.name) if self._constructed: return timer = ConstructionTimer(self) self._constructed = True _init_expr = self._init_expr _init_rule = self.rule # # We no longer need these # self._init_expr = None # Utilities like DAE assume this stays around # self.rule = None if (_init_rule is None) and \ (_init_expr is None): # No construction role or expression specified. return _self_parent = self._parent() if not self.is_indexed(): # # Scalar component # if _init_rule is None: tmp = _init_expr else: try: tmp = _init_rule(_self_parent) except Exception: err = sys.exc_info()[1] logger.error("Rule failed when generating expression for " "logical constraint %s:\n%s: %s" % (self.name, type(err).__name__, err)) raise self._setitem_when_not_present(None, tmp) else: if _init_expr is not None: raise IndexError( "LogicalConstraint '%s': Cannot initialize multiple indices " "of a logical constraint with a single expression" % (self.name, )) for ndx in self._index: try: tmp = apply_indexed_rule(self, _init_rule, _self_parent, ndx) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for " "logical constraint %s with index %s:\n%s: %s" % (self.name, str(ndx), type(err).__name__, err)) raise self._setitem_when_not_present(ndx, tmp) timer.report()
def construct(self, data=None): """ Construct this component """ assert data is None # because I don't know why it's an argument generate_debug_messages = is_debug_set(logger) if self._constructed is True: #pragma:nocover return if generate_debug_messages: #pragma:nocover logger.debug("Constructing SOSConstraint %s", self.name) timer = ConstructionTimer(self) self._constructed = True if self._rule is None: if self._sosSet is None and self.is_indexed(): if generate_debug_messages: #pragma:nocover logger.debug( " Cannot construct " + self.name + ". No rule is defined and no SOS sets are defined.") else: if not self.is_indexed(): if self._sosSet is None: if getattr(self._sosVars.index_set(), 'isordered', lambda *x: False)(): _sosSet = {None: list(self._sosVars.index_set())} else: _sosSet = {None: set(self._sosVars.index_set())} else: _sosSet = {None: self._sosSet} else: _sosSet = self._sosSet for index, sosSet in six.iteritems(_sosSet): if generate_debug_messages: #pragma:nocover logger.debug(" Constructing " + self.name + " index " + str(index)) if self._sosLevel == 2: # # Check that the sets are ordered. # ordered = False if type( sosSet ) is list or sosSet is UnindexedComponent_set or len( sosSet) == 1: ordered = True if hasattr(sosSet, 'isordered') and sosSet.isordered(): ordered = True if not ordered: raise ValueError( "Cannot define a SOS over an unordered index.") variables = [self._sosVars[idx] for idx in sosSet] if self._sosWeights is not None: weights = [self._sosWeights[idx] for idx in sosSet] else: weights = None self.add(index, variables, weights) else: _self_rule = self._rule _self_parent = self._parent() for index in self._index: try: tmp = apply_indexed_rule(self, _self_rule, _self_parent, index) except Exception: err = sys.exc_info()[1] logger.error( "Rule failed when generating expression for " "sos constraint %s with index %s:\n%s: %s" % (self.name, str(index), type(err).__name__, err)) raise if tmp is None: raise ValueError( "SOSConstraint rule returned None instead of SOSConstraint.Skip for index %s" % str(index)) if type(tmp) is tuple: if tmp is SOSConstraint.Skip: continue # tmp is a tuple of variables, weights self.add(index, tmp[0], tmp[1]) else: # tmp is a list of variables self.add(index, tmp) timer.report()