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 construct(self, values=None): """ Initialize set data """ if self._constructed: return timer = ConstructionTimer(self) self._constructed = True # # We call value() here for cases like Expressions, mutable # Params and the like # self._start_val = value(self._start) self._end_val = value(self._end) self._step_val = value(self._step) # # The set generates integer values if the starting value, # step and end value are all integers. Otherwise, the set # generates real values. # if type(self._start_val) is int and type(self._step) is int and type( self._end_val) is int: self.domain = Integers else: self.domain = Reals # # Compute the set length and upper bound # if self.filter is None and self.validate is None: # # Directly compute the number of elements in the set, from # which the upper-bound is computed. # self._len = int( math.floor( (self._end_val - self._start_val + self._step_val + 1e-7) // self._step_val)) ub = self._start_val + (self._len - 1) * self._step_val else: # # Iterate through the set to compute the upper bound # and number of elements. # ub = self._start_val ctr = 0 for i in self: ub = i ctr += 1 self._len = ctr # # Set the bounds information # self._bounds = (self._start_val, ub) timer.report()
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): if __debug__ and logger.isEnabledFor(logging.DEBUG): #pragma:nocover try: name = str(self.name) except: name = type(self) if logger.isEnabledFor(logging.DEBUG): logger.debug( "Constructing Alias, name=%s, " "from data=%s", name, str(data)) if self._constructed: return timer = ConstructionTimer(self) self._constructed = True timer.report()
def construct(self, values=None): """ Constructs a :py:class:`ContinuousSet` component """ timer = ConstructionTimer(self) OrderedSimpleSet.construct(self, values) for val in self.value: if type(val) is tuple: raise ValueError("ContinuousSet cannot contain tuples") if val.__class__ not in native_numeric_types: raise ValueError("ContinuousSet can only contain numeric " "values") if self._bounds is None: raise ValueError("ContinuousSet '%s' must have at least two values" " indicating the range over which a differential " "equation is to be discretized" % (self.name)) # If bounds were set using pyomo parameters, get their values lb = value(self._bounds[0]) ub = value(self._bounds[1]) self._bounds = (lb, ub) if self._bounds[0].__class__ not in native_numeric_types: raise ValueError("Bounds on ContinuousSet must be numeric values") if self._bounds[1].__class__ not in native_numeric_types: raise ValueError("Bounds on ContinuousSet must be numeric values") # TBD: If a user specifies bounds they will be added to the set # unless the user specified bounds have been overwritten during # OrderedSimpleSet construction. This can lead to some unintuitive # behavior when the ContinuousSet is both initialized with values and # bounds are specified. The current implementation is consistent # with how 'Set' treats this situation. if self._bounds[0] not in self.value: self.add(self._bounds[0]) self._sort() if self._bounds[1] not in self.value: self.add(self._bounds[1]) self._sort() if len(self) < 2: raise ValueError("ContinuousSet '%s' must have at least two values" " indicating the range over which a differential " "equation is to be discretized" % (self.name)) self._fe = sorted(self) 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 construct(self, data=None): """ Constructs this component, applying rule if it exists. """ if __debug__ and logger.isEnabledFor(logging.DEBUG): logger.debug("Constructing suffix %s", self.name) if self._constructed is True: return timer = ConstructionTimer(self) self._constructed = True if self._rule is not None: self.update_values(self._rule(self._parent())) timer.report()
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, data) ) if self._constructed: return timer = ConstructionTimer(self) self._constructed=True # # Construct _ConnectorData objects for all index values # if self.is_indexed(): self._initialize_members(self._index) else: self._data[None] = self self._initialize_members([None]) timer.report()
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 Action, name=" + self.name) # if self._constructed: #pragma:nocover return timer = ConstructionTimer(self) self._constructed = True # if not self.is_indexed(): # Scalar component self._rule(self._parent()) else: # Indexed component for index in self._index: apply_indexed_rule(self, self._rule, self._parent(), index) timer.report()
def construct(self, data=None): """Construct this component.""" if __debug__ and logger.isEnabledFor(logging.DEBUG): #pragma:nocover try: name = str(self.name) except: # Some Var components don't have a name yet, so just use # the type name = type(self) if logger.isEnabledFor(logging.DEBUG): logger.debug("Constructing Variable, name=%s, from data=%s" % (name, str(data))) if self._constructed: return timer = ConstructionTimer(self) self._constructed = True # # Construct _VarData objects for all index values # if not self.is_indexed(): self._data[None] = self self._initialize_members((None, )) elif self._dense: # This loop is optimized for speed with pypy. # Calling dict.update((...) for ...) is roughly # 30% slower self_weakref = weakref_ref(self) for ndx in self._index: cdata = self._ComponentDataClass( domain=self._domain_init_value, component=None) cdata._component = self_weakref self._data[ndx] = cdata #self._initialize_members((ndx,)) self._initialize_members(self._index) timer.report()
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): """ 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): """ Initialize this component. A parameter is constructed using the initial data or the data loaded from an external source. We first set all the values based on self._rule, and then allow the data dictionary to overwrite anything. Note that we allow an undefined Param value to be constructed. We throw an exception if a user tries to use an uninitialized Param. """ if __debug__ and logger.isEnabledFor(logging.DEBUG): #pragma:nocover logger.debug("Constructing Param, name=%s, from data=%s" % (self.name, str(data))) # if self._constructed: return timer = ConstructionTimer(self) # # If the default value is a simple type, we check it versus # the domain. # val = self._default_val if val is not None \ and type(val) in native_types \ and val not in self.domain: raise ValueError( "Default value (%s) is not valid for Param %s domain %s" % (str(val), self.name, self.domain.name)) # # Step #1: initialize data from rule value # if self._rule is not None: self._initialize_from(self._rule) # # Step #2: allow any user-specified (external) data to override # the initialization # if data is not None: try: for key, val in iteritems(data): self[key] = val except Exception: msg = sys.exc_info()[1] if type(data) is not dict: raise ValueError( "Attempting to initialize parameter=%s with data=%s.\n" "\tData type is not a dictionary, and a dictionary is " "expected." % (self.name, str(data))) else: raise RuntimeError( "Failed to set value for param=%s, index=%s, value=%s." "\n\tsource error message=%s" % (self.name, str(key), str(val), str(msg))) self._constructed = True # populate all other indices with default data # (avoids calling _set_contains on self._index at runtime) if self._dense_initialize: self.to_dense_data() timer.report()
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 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 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 \ = __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()