コード例 #1
0
 def _apply_to(self, instance, **kwds):
     self._deterministic = kwds.get('deterministic', False)
     #
     # Process options
     #
     submodel = self._preprocess('bilevel.linear_mpec', instance, **kwds)
     instance.reclassify_component_type(submodel, Block)
     #
     # Create a block with optimality conditions
     #
     setattr(instance, self._submodel + '_kkt',
             self._add_optimality_conditions(instance, submodel))
     instance._transformation_data[
         'bilevel.linear_mpec'].submodel_cuid = ComponentUID(submodel)
     instance._transformation_data[
         'bilevel.linear_mpec'].block_cuid = ComponentUID(
             getattr(instance, self._submodel + '_kkt'))
     #-------------------------------------------------------------------------------
     #
     # Disable the original submodel and
     #
     #instance.reclassify_component_type(submodel, SubModel)
     #submodel.deactivate()
     # TODO: Cache the list of components that were deactivated
     for (name, data) in submodel.component_map(active=True).items():
         if not isinstance(data, Var) and not isinstance(data, Set):
             data.deactivate()
コード例 #2
0
ファイル: embeddedsp.py プロジェクト: yuanzy97/pyomo
    def pyro_sample_sp(self, size, **kwds):
        assert size > 0
        model = self.reference_model.clone()

        scenario_tree_model = \
            self._create_scenario_tree_model(size)
        factory = ScenarioTreeInstanceFactory(
            model=self.reference_model, scenario_tree=scenario_tree_model)
        options = \
            ScenarioTreeManagerClientPyro.register_options()
        for key in kwds:
            options[key] = kwds[key]
        manager = ScenarioTreeManagerClientPyro(options, factory=factory)
        try:
            init = manager.initialize(async_call=True)
            pcuids = ComponentMap()
            for param in self.stochastic_data:
                pcuids[param] = ComponentUID(param)
            init.complete()
            for scenario in manager.scenario_tree.scenarios:
                data = []
                for param, dist in self.stochastic_data.items():
                    data.append((pcuids[param], dist.sample()))
                manager.invoke_function(
                    "_update_data",
                    thisfile,
                    invocation_type=InvocationType.OnScenario(scenario.name),
                    function_args=(data, ),
                    oneway_call=True)
            manager.reference_model = model
        except:
            manager.close()
            raise
        return manager
コード例 #3
0
 def _apply_to(self, instance, **kwds):
     options = kwds.pop('options', {})
     #
     # Find the free variables
     #
     free_vars = {}
     id_list = []
     for vdata in instance.component_data_objects(
             Var, active=True, sort=SortComponents.deterministic):
         id_list.append(id(vdata))
         free_vars[id(vdata)] = vdata
     #
     # Iterate over the Complementarity components
     #
     cobjs = []
     for bdata in instance.block_data_objects(
             active=True, sort=SortComponents.deterministic):
         for cobj in bdata.component_objects(Complementarity,
                                             active=True,
                                             descend_into=False):
             cobjs.append(cobj)
             for index in sorted(iterkeys(cobj)):
                 _cdata = cobj[index]
                 if not _cdata.active:
                     continue
                 #
                 # Apply a variant of the standard form logic
                 #
                 self.to_common_form(_cdata, free_vars)
     #
     tdata = instance._transformation_data['mpec.nl']
     tdata.compl_cuids = []
     for cobj in cobjs:
         tdata.compl_cuids.append(ComponentUID(cobj))
         cobj.parent_block().reclassify_component_type(cobj, Block)
コード例 #4
0
 def _preprocess(self, tname, instance, **kwds):
     options = kwds.pop('options', {})
     sub = options.get('submodel', None)
     #
     # Iterate over the model collecting variable data,
     # until the submodel is found.
     #
     var = {}
     submodel = None
     for (name, data) in instance.component_map(active=True).items():
         if isinstance(data, Var):
             var[name] = data
         elif isinstance(data, SubModel):
             if sub is None or sub == name:
                 sub = name
                 submodel = data
                 break
     if submodel is None:
         raise RuntimeError("Missing submodel: " + str(sub))
     #
     instance._transformation_data[tname].submodel = [name]
     #
     # Fix variables
     #
     if submodel._fixed:
         fixed = [i.name for i in submodel._fixed]
         unfixed = []
         for v in var:
             if not v in fixed:
                 unfixed.append((v, getattr(submodel._parent(),
                                            v).is_indexed()))
     elif submodel._var:
         # NOTE: This argument is undocumented
         _var = set(submodel._var)
         unfixed = [(v, getattr(submodel._parent(), v).is_indexed())
                    for v in _var]
         fixed = []
         for v in var:
             if not v in _var:
                 fixed.append(v)
     else:
         #
         # By default, we assume that variables are fixed if they are not part of the
         # local model.
         #
         fixed = [v for v in var]
         unfixed = []
         for (name, data) in submodel.component_map(active=True).items():
             if isinstance(data, Var):
                 unfixed.append((data.cname(), data.is_indexed()))
     #
     self._submodel = sub
     self._upper_vars = var
     self._fixed_upper_vars = fixed
     self._unfixed_upper_vars = unfixed
     instance._transformation_data[tname].fixed = [
         ComponentUID(var[v]) for v in fixed
     ]
     return submodel
コード例 #5
0
ファイル: mpec1.py プロジェクト: jialuw96/pyomo
 def _apply_to(self, instance, **kwds):
     options = kwds.pop('options', {})
     bound = kwds.pop('mpec_bound', 0.0)
     #
     # Create a mutable parameter that defines the value of the upper bound
     # on the constraints
     #
     bound = options.get('mpec_bound', bound)
     instance.mpec_bound = Param(mutable=True, initialize=bound)
     #
     # Setup transformation data
     #
     tdata = instance._transformation_data['mpec.simple_nonlinear']
     tdata.compl_cuids = []
     #
     # Iterate over the model finding Complementarity components
     #
     for complementarity in instance.component_objects(
             Complementarity,
             active=True,
             descend_into=(Block, Disjunct),
             sort=SortComponents.deterministic):
         block = complementarity.parent_block()
         for index in sorted(complementarity.keys()):
             _data = complementarity[index]
             if not _data.active:
                 continue
             _data.to_standard_form()
             #
             _type = getattr(_data.c, "_complementarity_type", 0)
             if _type == 1:
                 #
                 # Constraint expression is bounded below, so we can replace
                 # constraint c with a constraint that ensures that either
                 # constraint c is active or variable v is at its lower bound.
                 #
                 _data.ccon = Constraint(
                     expr=(_data.c.body - _data.c.lower) *
                     _data.v <= instance.mpec_bound)
                 del _data.c._complementarity_type
             elif _type == 3:
                 #
                 # Variable v is bounded above and below.  We can define
                 #
                 _data.ccon_l = Constraint(
                     expr=(_data.v - _data.v.bounds[0]) *
                     _data.c.body <= instance.mpec_bound)
                 _data.ccon_u = Constraint(
                     expr=(_data.v - _data.v.bounds[1]) *
                     _data.c.body <= instance.mpec_bound)
                 del _data.c._complementarity_type
             elif _type == 2:  #pragma:nocover
                 raise ValueError(
                     "to_standard_form does not generate _type 2 expressions"
                 )
         tdata.compl_cuids.append(ComponentUID(complementarity))
         block.reclassify_component_type(complementarity, Block)
コード例 #6
0
ファイル: transform.py プロジェクト: astrojuanlu/pyomo
 def _preprocess(self, tname, instance, **kwds):
     options = kwds.pop('options', {})
     sub = options.get('submodel', None)
     #
     # Iterate over the model collecting variable data,
     # until the submodel is found.
     #
     var = {}
     submodel = None
     for (name, data) in instance.component_map(active=True).items():
         if isinstance(data, Var):
             var[name] = data
         elif isinstance(data, SubModel):
             if sub is None or sub == name:
                 sub = name
                 submodel = data
                 break
     if submodel is None:
         raise RuntimeError("Missing submodel: " + str(sub))
     #
     instance._transformation_data[tname].submodel = [name]
     #
     # Fix variables
     #
     if submodel._fixed:
         fixed = [i.name for i in submodel._fixed]
         unfixed = []
         for v in var:
             if not v in fixed:
                 unfixed.append((v, getattr(submodel._parent(),
                                            v).is_indexed()))
     elif submodel._var:
         _var = set(submodel._var)
         unfixed = [(v, getattr(submodel._parent(), v).is_indexed())
                    for v in _var]
         fixed = []
         for v in var:
             if not v in _var:
                 fixed.append(v)
     else:
         raise RuntimeError(
             "Must specify either 'fixed' or 'var' option for SubModel")
     #
     self._submodel = sub
     self._upper_vars = var
     self._fixed_upper_vars = fixed
     self._unfixed_upper_vars = unfixed
     instance._transformation_data[tname].fixed = [
         ComponentUID(var[v]) for v in fixed
     ]
     return submodel
コード例 #7
0
 def _apply_to(self, instance, **kwds):
     self._deterministic = kwds.get('deterministic', False)
     #
     # Process options
     #
     submodel = self._preprocess('bilevel.linear_mpec', instance, **kwds)
     instance.reclassify_component_type(submodel, Block)
     #
     # Create a block with optimality conditions
     #
     setattr(instance, self._submodel + '_kkt',
             self._add_optimality_conditions(instance, submodel))
     instance._transformation_data[
         'bilevel.linear_mpec'].submodel_cuid = ComponentUID(submodel)
     instance._transformation_data[
         'bilevel.linear_mpec'].block_cuid = ComponentUID(
             getattr(instance, self._submodel + '_kkt'))
     #-------------------------------------------------------------------------------
     #
     # Disable the original submodel and
     # execute the preprocessor
     #
     instance.reclassify_component_type(submodel, SubModel)
     submodel.deactivate()
コード例 #8
0
 def _apply_to(self, instance, **kwds):
     #
     # Find the free variables
     #
     free_vars = {}
     id_list = []
     # [ESJ 07/12/2019] Look on the whole model in case instance is a Block or a Disjunct
     for vdata in instance.model().component_data_objects(
             Var,
             active=True,
             sort=SortComponents.deterministic,
             descend_into=(Block, Disjunct)):
         id_list.append(id(vdata))
         free_vars[id(vdata)] = vdata
     #
     # Iterate over the Complementarity components
     #
     cobjs = []
     for cobj in instance.component_objects(
             Complementarity,
             active=True,
             descend_into=(Block, Disjunct),
             sort=SortComponents.deterministic):
         cobjs.append(cobj)
         for index in sorted(cobj.keys()):
             _cdata = cobj[index]
             if not _cdata.active:
                 continue
             #
             # Apply a variant of the standard form logic
             #
             self.to_common_form(_cdata, free_vars)
             #
     tdata = instance._transformation_data['mpec.nl']
     tdata.compl_cuids = []
     for cobj in cobjs:
         tdata.compl_cuids.append(ComponentUID(cobj))
         cobj.parent_block().reclassify_component_type(cobj, Block)
コード例 #9
0
    def _apply_to(self, instance, **kwds):
        #
        # Setup transformation data
        #
        tdata = instance._transformation_data['mpec.simple_disjunction']
        tdata.compl_cuids = []
        #
        # Iterate over the model finding Complementarity components
        #
        for complementarity in instance.component_objects(Complementarity, active=True,
                                                          descend_into=(Block, Disjunct),
                                                          sort=SortComponents.deterministic):
            block = complementarity.parent_block()

            for index in sorted(complementarity.keys()):
                _data = complementarity[index]
                if not _data.active:
                    continue
                #
                _e1 = _data._canonical_expression(_data._args[0])
                _e2 = _data._canonical_expression(_data._args[1])
                if len(_e1)==3 and len(_e2) == 3 and (_e1[0] is None) + (_e1[2] is None) + (_e2[0] is None) + (_e2[2] is None) != 2:
                    raise RuntimeError("Complementarity condition %s must have exactly two finite bounds" % _data.name)
                if len(_e1) == 3 and _e1[0] is None and _e1[2] is None:
                    #
                    # Swap _e1 and _e2.  The ensures that 
                    # only e2 will be an unconstrained expression
                    #
                    _e1, _e2 = _e2, _e1
                if _e2[0] is None and _e2[2] is None:
                    if len(_e1) == 2:
                        _data.c = Constraint(expr=_e1)
                    else:
                        _data.expr1 = Disjunct()
                        _data.expr1.c0 = Constraint(expr= _e1[0] == _e1[1])
                        _data.expr1.c1 = Constraint(expr= _e2[1] >= 0)
                        #
                        _data.expr2 = Disjunct()
                        _data.expr2.c0 = Constraint(expr= _e1[1] == _e1[2])
                        _data.expr2.c1 = Constraint(expr= _e2[1] <= 0)
                        #
                        _data.expr3 = Disjunct()
                        _data.expr3.c0 = Constraint(expr= inequality(_e1[0], _e1[1], _e1[2]))
                        _data.expr3.c1 = Constraint(expr= _e2[1] == 0)
                        _data.complements = Disjunction(expr=(_data.expr1, _data.expr2, _data.expr3))
                else:
                    if _e1[0] is None:
                        tmp1 = _e1[2] - _e1[1]
                    else:
                        tmp1 = _e1[1] - _e1[0]
                    if _e2[0] is None:
                        tmp2 = _e2[2] - _e2[1]
                    else:
                        tmp2 = _e2[1] - _e2[0]
                    _data.expr1 = Disjunct()
                    _data.expr1.c0 = Constraint(expr= tmp1 >= 0)
                    _data.expr1.c1 = Constraint(expr= tmp2 == 0)
                    #
                    _data.expr2 = Disjunct()
                    _data.expr2.c0 = Constraint(expr= tmp1 == 0)
                    _data.expr2.c1 = Constraint(expr= tmp2 >= 0)
                    #
                    _data.complements = Disjunction(expr=(_data.expr1, _data.expr2))
            tdata.compl_cuids.append( ComponentUID(complementarity) )
            block.reclassify_component_type(complementarity, Block)