Exemple #1
0
    def __init__(
        self,
        n_scenario,
        input_values,
        output_values=None,
        to_fix=None,
        to_deactivate=None,
        to_reset=None,
    ):
        """
        Parameters
        ----------
        n_scenario: Integer
            The number of different values we expect for each input variable
        input_values: ComponentMap
            Maps each input variable to a list of values of length n_scenario
        output_values: ComponentMap
            Maps each output variable to a list of values of length n_scenario
        to_fix: List
            to_fix argument for base class
        to_deactivate: List
            to_deactivate argument for base class
        to_reset: List
            to_reset argument for base class. This list is extended with
            input variables.

        """
        # Should this object be aware of the user's block/model?
        # My answer for now is no.
        self.input_values = input_values
        output = ComponentMap() if output_values is None else output_values
        self.output_values = output
        self.n_scenario = n_scenario
        self.initial_state_values = None
        self._ip = -1  # Index pointer for iteration

        if to_reset is None:
            # Input values will be set repeatedly by iterating over this
            # object. Output values will presumably be altered by some
            # solve within this context. We would like to reset these to
            # their original values to make this functionality less
            # intrusive.
            to_reset = list(input_values) + list(output)
        else:
            to_reset.extend(var for var in input_values)
            to_reset.extend(var for var in output)

        super(ParamSweeper, self).__init__(
            to_fix=to_fix,
            to_deactivate=to_deactivate,
            to_reset=to_reset,
        )
Exemple #2
0
def to_cnf(expr, bool_varlist=None, bool_var_to_special_atoms=None):
    """Converts a Pyomo logical constraint to CNF form.

    Note: the atoms AtMostExpression, AtLeastExpression, and ExactlyExpression
    require special treatment if they are not the root node, or if their children are not atoms,
    e.g. atmost(2, Y1, Y1 | Y2, Y2, Y3)

    As a result, the model may need to be augmented with
    additional boolean indicator variables and logical propositions.
    This function will raise ValueError if a BooleanVarList is
    not provided on which to store the augmented variables,
    and augmented variables are needed.

    This function will return a list of CNF logical constraints, including:
    - CNF of original statement, including possible substitutions
    - Additional CNF statements (for enforcing equivalence to augmented variables)

    In addition, the function will have side effects:
    - augmented variables are added to the passed bool_varlist
    - mapping from augmented variables to equivalent special atoms (see note above)
      with only literals as logical arguments

    """
    if type(expr) in special_boolean_atom_types:
        # If root node is one of the special atoms, recursively convert its
        # children nodes to CNF.
        return _convert_children_to_literals(expr, bool_varlist,
                                             bool_var_to_special_atoms)

    # If root node is not an expression, just return it.
    if type(expr) in native_types or not expr.is_expression_type():
        return [expr]

    # While performing conversion to sympy, substitute new boolean variables for
    # non-root special atoms.
    pyomo_sympy_map = _PyomoSympyLogicalBimap()
    bool_var_to_special_atoms = ComponentMap(
    ) if bool_var_to_special_atoms is None else bool_var_to_special_atoms
    visitor = _Pyomo2SympyVisitor(pyomo_sympy_map, bool_varlist)
    sympy_expr = visitor.walk_expression(expr)

    new_statements = []
    # If visitor encountered any special atoms in non-root node, ensure that their children are literals:
    for indicator_var, special_atom in visitor.special_atom_map.items():
        atom_cnf = _convert_children_to_literals(special_atom, bool_varlist,
                                                 bool_var_to_special_atoms)
        bool_var_to_special_atoms[indicator_var] = atom_cnf[0]
        new_statements.extend(atom_cnf[1:])

    cnf_form = sympy.to_cnf(sympy_expr)
    return [_sympy2pyomo_expression(cnf_form, pyomo_sympy_map)
            ] + new_statements  # additional statements
Exemple #3
0
 def get_active_partitions(self):
     ans = ComponentMap()
     for var, pts in self._partitions.items():
         val = pyo.value(var)
         lower = var.lb
         upper = var.ub
         for p in pts:
             if val >= p and p > lower:
                 lower = p
             if val <= p and p < upper:
                 upper = p
         ans[var] = lower, upper
     return ans
Exemple #4
0
 def _apply_to(self, instance, **kwds):
     self._generate_debug_messages = is_debug_set(logger)
     self.used_args = ComponentMap()  # If everything was sure to go well,
     # this could be a dictionary. But if
     # someone messes up and gives us a Var
     # as a key in bigMargs, I need the error
     # not to be when I try to put it into
     # this map!
     try:
         self._apply_to_impl(instance, **kwds)
     finally:
         # same for our bookkeeping about what we used from bigM arg dict
         self.used_args.clear()
Exemple #5
0
    def maximum_matching(self, variables=None, constraints=None):
        """
        Returns a maximal matching between the constraints and variables,
        in terms of a map from constraints to variables.
        """
        variables, constraints = self._validate_input(variables, constraints)
        matrix = self._extract_submatrix(variables, constraints)

        matching = maximum_matching(matrix.tocoo())
        # Matching maps row (constraint) indices to column (variable) indices

        return ComponentMap((constraints[i], variables[j])
                for i, j in matching.items())
Exemple #6
0
    def block_triangularize(self, variables=None, constraints=None):
        """
        Returns two ComponentMaps. A map from variables to their blocks
        in a block triangularization of the incidence matrix, and a
        map from constraints to their blocks in a block triangularization
        of the incidence matrix.
        """
        variables, constraints = self._validate_input(variables, constraints)
        matrix = self._extract_submatrix(variables, constraints)

        row_block_map, col_block_map = block_triangularize(matrix.tocoo())
        # Cache maps in case we want to get diagonal blocks quickly in the
        # future.
        self.row_block_map = row_block_map
        self.col_block_map = col_block_map
        con_block_map = ComponentMap((constraints[i], idx)
                for i, idx in row_block_map.items())
        var_block_map = ComponentMap((variables[j], idx)
                for j, idx in col_block_map.items())
        # Switch the order of the maps here to match the method call.
        # Hopefully this does not get too confusing...
        return var_block_map, con_block_map
Exemple #7
0
    def test_eq(self):
        cmap1 = ComponentMap()
        self.assertNotEqual(cmap1, set())
        self.assertFalse(cmap1 == set())
        self.assertNotEqual(cmap1, list())
        self.assertFalse(cmap1 == list())
        self.assertNotEqual(cmap1, tuple())
        self.assertFalse(cmap1 == tuple())
        self.assertEqual(cmap1, dict())
        self.assertTrue(cmap1 == dict())

        cmap1.update(self._components)
        self.assertNotEqual(cmap1, set())
        self.assertFalse(cmap1 == set())
        self.assertNotEqual(cmap1, list())
        self.assertFalse(cmap1 == list())
        self.assertNotEqual(cmap1, tuple())
        self.assertFalse(cmap1 == tuple())
        self.assertNotEqual(cmap1, dict())
        self.assertFalse(cmap1 == dict())

        self.assertTrue(cmap1 == cmap1)
        self.assertEqual(cmap1, cmap1)

        cmap2 = ComponentMap(self._components)
        self.assertTrue(cmap2 == cmap1)
        self.assertFalse(cmap2 != cmap1)
        self.assertEqual(cmap2, cmap1)
        self.assertTrue(cmap1 == cmap2)
        self.assertFalse(cmap1 != cmap2)
        self.assertEqual(cmap1, cmap2)

        del cmap2[self._components[0][0]]
        self.assertFalse(cmap2 == cmap1)
        self.assertTrue(cmap2 != cmap1)
        self.assertNotEqual(cmap2, cmap1)
        self.assertFalse(cmap1 == cmap2)
        self.assertTrue(cmap1 != cmap2)
        self.assertNotEqual(cmap1, cmap2)
Exemple #8
0
 def _set_input(self,
                relaxation_side=RelaxationSide.BOTH,
                persistent_solvers=None,
                use_linear_relaxation=True,
                large_eval_tol=math.inf):
     self._partitions = ComponentMap()
     self._saved_partitions = list()
     BaseRelaxationData._set_input(
         self,
         relaxation_side=relaxation_side,
         persistent_solvers=persistent_solvers,
         use_linear_relaxation=use_linear_relaxation,
         large_eval_tol=large_eval_tol)
Exemple #9
0
    def __init__(self, scaling_factor, varconlist=[], nominal_index=()):
        """
        Args:
            scaling_factor: A Pyomo scaling_factor Suffix that will hold all
                            the scaling factors calculated
            varconlist: A list of variable, constraint tuples. These variables
                        and constraints should be indexed by the same sets,
                        so they may need to be references-to-slices along some
                        common sets.
            nominal_index: The index of variables and constraints to access
                           when a calculation needs to be performed using
                           data objects.
        """
        self.scaling_factor = scaling_factor
        self.nominal_index = nominal_index
        if nominal_index is None or nominal_index == ():
            self.dim = 0
        else:
            try:
                self.dim = len(nominal_index)
            except TypeError:
                self.dim = 1

        varlist = []
        conlist = []
        for var, con in varconlist:
            varlist.append(var)
            conlist.append(con)
        self.varlist = varlist
        self.conlist = conlist

        data_getter = self.get_representative_data_object
        var_con_data_list = [(data_getter(var), data_getter(con))
                             for var, con in varconlist]
        con_var_data_list = [(data_getter(con), data_getter(var))
                             for var, con in varconlist]
        self.var2con = ComponentMap(var_con_data_list)
        self.con2var = ComponentMap(con_var_data_list)
Exemple #10
0
    def __init__(self, **kwds):
        if 'type' not in kwds:
            kwds['type'] = 'gurobi_direct'
        super(GurobiDirect, self).__init__(**kwds)
        self._pyomo_var_to_solver_var_map = ComponentMap()
        self._solver_var_to_pyomo_var_map = ComponentMap()
        self._pyomo_con_to_solver_con_map = dict()
        self._solver_con_to_pyomo_con_map = ComponentMap()
        self._needs_updated = True  # flag that indicates if solver_model.update() needs called before getting variable and constraint attributes
        self._callback = None
        self._callback_func = None

        self._python_api_exists = gurobipy_available
        self._range_constraints = set()

        self._max_obj_degree = 2
        self._max_constraint_degree = 2

        # Note: Undefined capabilites default to None
        self._capabilities.linear = True
        self._capabilities.quadratic_objective = True
        self._capabilities.quadratic_constraint = True
        self._capabilities.integer = True
        self._capabilities.sos1 = True
        self._capabilities.sos2 = True

        # fix for compatibility with pre-5.0 Gurobi
        #
        # Note: Unfortunately, this will trigger the immediate import
        #    of the gurobipy module
        if gurobipy_available and GurobiDirect._version_major < 5:
            self._max_constraint_degree = 1
            self._capabilities.quadratic_constraint = False

        # remove the instance-level definition of the gurobi version:
        # because the version comes from an imported module, only one
        # version of gurobi is supported (and stored as a class attribute)
        del self._version
Exemple #11
0
    def _set_instance(self, model, kwds={}):
        self._range_constraints = set()
        DirectOrPersistentSolver._set_instance(self, model, kwds)
        self._pyomo_con_to_solver_con_map = dict()
        self._solver_con_to_pyomo_con_map = ComponentMap()
        self._pyomo_var_to_solver_var_map = ComponentMap()
        self._solver_var_to_pyomo_var_map = ComponentMap()
        try:
            if model.name is not None:
                self._solver_model = self._gurobipy.Model(model.name)
            else:
                self._solver_model = self._gurobipy.Model()
        except Exception:
            e = sys.exc_info()[1]
            msg = ("Unable to create Gurobi model. "
                   "Have you installed the Python "
                   "bindings for Gurobi?\n\n\t" +
                   "Error message: {0}".format(e))
            raise Exception(msg)

        self._add_block(model)

        for var, n_ref in self._referenced_variables.items():
            if n_ref != 0:
                if var.fixed:
                    if not self._output_fixed_variable_bounds:
                        raise ValueError(
                            "Encountered a fixed variable (%s) inside "
                            "an active objective or constraint "
                            "expression on model %s, which is usually "
                            "indicative of a preprocessing error. Use "
                            "the IO-option 'output_fixed_variable_bounds=True' "
                            "to suppress this error and fix the variable "
                            "by overwriting its bounds in the Gurobi instance."
                            % (
                                var.name,
                                self._pyomo_model.name,
                            ))
Exemple #12
0
def _bt_prep(model, solver, objective_bound=None):
    """
    Prepare the model for bounds tightening.
    Gather the variable values to load back in after bounds tightening.
    Deactivate any active objectives.
    If objective_ub is not None, then add a constraint forcing the objective to be less than objective_ub

    Parameters
    ----------
    model : pyo.ConcreteModel or pyo.Block
        The model object that will be used for bounds tightening.
    objective_bound : float
        The objective value for the current best upper bound incumbent

    Returns
    -------
    initial_var_values: ComponentMap
    deactivated_objectives: list
    """
    if isinstance(solver, PersistentSolver):
        solver.set_instance(model)

    initial_var_values = ComponentMap()
    for v in model.component_data_objects(ctype=pyo.Var, active=None, sort=True, descend_into=True):
        initial_var_values[v] = v.value

    deactivated_objectives = list()
    for obj in model.component_data_objects(pyo.Objective, active=True, sort=True, descend_into=True):
        deactivated_objectives.append(obj)
        obj.deactivate()

    # add inequality bound on objective functions if required
    # obj.expr <= objective_ub
    if objective_bound is not None and math.isfinite(objective_bound):
        if len(deactivated_objectives) != 1:
            e = 'BoundsTightener: When providing objective_ub,' + \
                ' the model must have one and only one objective function.'
            logger.error(e)
            raise ValueError(e)
        original_obj = deactivated_objectives[0]
        if original_obj.sense == minimize:
            model.__objective_ineq = \
                pyo.Constraint(expr=original_obj.expr <= objective_bound)
        else:
            assert original_obj.sense == maximize
            model.__objective_ineq = pyo.Constraint(expr=original_obj.expr >= objective_bound)
        if isinstance(solver, PersistentSolver):
            solver.add_constraint(model.__objective_ineq)

    return initial_var_values, deactivated_objectives
Exemple #13
0
    def generate_cuid_string_map(block,
                                 ctype=None,
                                 descend_into=True,
                                 repr_version=2):
        def _record_indexed_object_cuid_strings_v1(obj, cuid_str):
            _unknown = lambda x: '?' + str(x)
            for idx, data in obj.items():
                if idx.__class__ is tuple and len(idx) > 1:
                    cuid_strings[data] = cuid_str + ':' + ','.join(
                        ComponentUID._repr_v1_map.get(x.__class__, _unknown)(x)
                        for x in idx)
                else:
                    cuid_strings[data] \
                        = cuid_str + ':' + ComponentUID._repr_v1_map.get(
                            idx.__class__, _unknown)(idx)

        def _record_indexed_object_cuid_strings_v2(obj, cuid_str):
            for idx, data in obj.items():
                cuid_strings[data] = cuid_str + _index_repr(idx)

        _record_indexed_object_cuid_strings = {
            1: _record_indexed_object_cuid_strings_v1,
            2: _record_indexed_object_cuid_strings_v2,
        }[repr_version]
        _record_name = {
            1: str,
            2: _name_repr,
        }[repr_version]

        model = block.model()
        cuid_strings = ComponentMap()
        cuid_strings[block] = ComponentUID(block).get_repr(repr_version)
        for blk in block.block_data_objects(descend_into=descend_into):
            if blk not in cuid_strings:
                blk_comp = blk.parent_component()
                cuid_str = _record_name(blk_comp.local_name)
                blk_pblk = blk_comp.parent_block()
                if blk_pblk is not model:
                    cuid_str = cuid_strings[blk_pblk] + '.' + cuid_str
                cuid_strings[blk_comp] = cuid_str
                if blk_comp.is_indexed():
                    _record_indexed_object_cuid_strings(blk_comp, cuid_str)
            for obj in blk.component_objects(ctype=ctype, descend_into=False):
                cuid_str = _record_name(obj.local_name)
                if blk is not model:
                    cuid_str = cuid_strings[blk] + '.' + cuid_str
                cuid_strings[obj] = cuid_str
                if obj.is_indexed():
                    _record_indexed_object_cuid_strings(obj, cuid_str)
        return cuid_strings
Exemple #14
0
    def _set_instance(self, model, kwds={}):
        self._range_constraints = set()
        DirectOrPersistentSolver._set_instance(self, model, kwds)
        self._pyomo_con_to_solver_con_map = dict()
        self._solver_con_to_pyomo_con_map = ComponentMap()
        self._pyomo_cone_to_solver_cone_map = dict()
        self._solver_cone_to_pyomo_cone_map = ComponentMap()
        self._pyomo_var_to_solver_var_map = ComponentMap()
        self._solver_var_to_pyomo_var_map = ComponentMap()
        self._whichsol = getattr(
            self._mosek.soltype, kwds.pop('soltype', 'bas'))

        try:
            self._solver_model = self._mosek_env.Task(0, 0)
        except Exception:
            e = sys.exc_info()[1]
            msg = ("Unable to create Mosek Task. "
                   "Have you installed the Python "
                   "bindings for Mosek?\n\n\t" +
                   "Error message: {0}".format(e))
            raise Exception(msg)

        self._add_block(model)
Exemple #15
0
    def test_update_contset_indexed_component_vars_multiple(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.t2 = ContinuousSet(initialize=[1, 2, 3])
        m.s = Set(initialize=[1, 2, 3])
        m.s2 = Set(initialize=[(1, 1), (2, 2)])
        m.v1 = Var(m.s, m.t, initialize=3)
        m.v2 = Var(m.s,
                   m.t,
                   m.t2,
                   bounds=(4, 10),
                   initialize={
                       (1, 0, 1): 22,
                       (2, 10, 2): 22
                   })

        def _init(m, i, j, k):
            return i

        m.v3 = Var(m.t, m.s2, bounds=(-5, 5), initialize=_init)
        m.v4 = Var(m.s, m.t2, initialize=7, dense=True)
        m.v5 = Var(m.s2)

        expansion_map = ComponentMap()

        generate_finite_elements(m.t, 5)
        update_contset_indexed_component(m.v1, expansion_map)
        update_contset_indexed_component(m.v2, expansion_map)
        update_contset_indexed_component(m.v3, expansion_map)
        update_contset_indexed_component(m.v4, expansion_map)
        update_contset_indexed_component(m.v5, expansion_map)

        self.assertTrue(len(m.v1) == 18)
        self.assertTrue(len(m.v2) == 54)
        self.assertTrue(len(m.v3) == 12)
        self.assertTrue(len(m.v4) == 9)

        self.assertTrue(value(m.v1[1, 4]) == 3)
        self.assertTrue(m.v1[2, 2].ub is None)
        self.assertTrue(m.v1[3, 8].lb is None)

        self.assertTrue(value(m.v2[1, 0, 1]) == 22)
        self.assertTrue(m.v2[1, 2, 1].value is None)
        self.assertTrue(m.v2[2, 4, 3].lb == 4)
        self.assertTrue(m.v2[3, 8, 1].ub == 10)

        self.assertTrue(value(m.v3[2, 2, 2]) == 2)
        self.assertTrue(m.v3[4, 1, 1].lb == -5)
        self.assertTrue(m.v3[8, 2, 2].ub == 5)
        self.assertTrue(value(m.v3[6, 1, 1]) == 6)
Exemple #16
0
    def test_perturb_indexed_parameters_with_scalar(self):
        model = make_indexed_model()
        param_list = [model.eta]
        ptb_list = [10.0]

        sens = SensitivityInterface(model, clone_model=False)
        sens.setup_sensitivity(param_list)
        sens.perturb_parameters(ptb_list)
        instance = sens.model_instance
        block = sens.block

        param_var_map = ComponentMap(
            (param, var) for var, param, _, _ in sens.block._sens_data_list)
        param_con_map = ComponentMap(
            (param, block.paramConst[i + 1])
            for i, (_, param, _, _) in enumerate(sens.block._sens_data_list))
        for param, ptb in zip(param_list, ptb_list):
            for idx in param:
                obj = param[idx]
                var = param_var_map[obj]
                con = param_con_map[obj]
                self.assertEqual(instance.sens_state_value_1[var], ptb)
                self.assertEqual(instance.DeltaP[con], obj.value - ptb)
Exemple #17
0
 def test_getsetdelitem(self):
     cmap = ComponentMap()
     for c, val in self._components:
         self.assertTrue(c not in cmap)
     for c, val in self._components:
         cmap[c] = val
         self.assertEqual(cmap[c], val)
         self.assertEqual(cmap.get(c), val)
         del cmap[c]
         with self.assertRaises(KeyError):
             cmap[c]
         with self.assertRaises(KeyError):
             del cmap[c]
         self.assertEqual(cmap.get(c), None)
Exemple #18
0
    def __next__(self):
        self._ip += 1

        i = self._ip
        n_scenario = self.n_scenario
        input_values = self.input_values
        output_values = self.output_values

        if i >= n_scenario:
            self._ip = -1
            raise StopIteration()

        else:
            inputs = ComponentMap()
            for var, values in input_values.items():
                val = values[i]
                var.set_value(val)
                inputs[var] = val

            outputs = ComponentMap([(var, values[i])
                                    for var, values in output_values.items()])

            return inputs, outputs
Exemple #19
0
def _reverse_diff_helper(expr, numeric=True):
    val_dict = ComponentMap()
    der_dict = ComponentMap()
    expr_list = list()

    visitorA = _LeafToRootVisitor(val_dict,
                                  der_dict,
                                  expr_list,
                                  numeric=numeric)
    visitorA.dfs_postorder_stack(expr)

    der_dict[expr] = 1
    for e in reversed(expr_list):
        if e.__class__ in _diff_map:
            _diff_map[e.__class__](e, val_dict, der_dict)
        elif e.is_named_expression_type():
            _diff_GeneralExpression(e, val_dict, der_dict)
        else:
            raise DifferentiationException(
                'Unsupported expression type for differentiation: {0}'.format(
                    type(e)))

    return der_dict
Exemple #20
0
def determine_valid_values(block, discr_var_to_constrs_map, config):
    """Calculate valid values for each effectively discrete variable.

    We need the set of possible values for the effectively discrete variable in
    order to do the reformulations.

    Right now, we select a naive approach where we look for variables in the
    discreteness-inducing constraints. We then adjust their values and see if
    things are stil feasible. Based on their coefficient values, we can infer a
    set of allowable values for the effectively discrete variable.

    Args:
        block: The model or a disjunct on the model.

    """
    possible_values = ComponentMap()

    for eff_discr_var, constrs in discr_var_to_constrs_map.items():
        # get the superset of possible values by looking through the
        # constraints
        for constr in constrs:
            repn = generate_standard_repn(constr.body)
            var_coef = sum(coef for i, coef in enumerate(repn.linear_coefs)
                           if repn.linear_vars[i] is eff_discr_var)
            const = -(repn.constant - constr.upper) / var_coef
            possible_vals = set((const, ))
            for i, var in enumerate(repn.linear_vars):
                if var is eff_discr_var:
                    continue
                coef = -repn.linear_coefs[i] / var_coef
                if var.is_binary():
                    var_values = (0, coef)
                elif var.is_integer():
                    var_values = [v * coef for v in range(var.lb, var.ub + 1)]
                else:
                    raise ValueError(
                        '%s has unacceptable variable domain: %s' %
                        (var.name, var.domain))
                possible_vals = set(
                    (v1 + v2 for v1 in possible_vals for v2 in var_values))
            old_possible_vals = possible_values.get(eff_discr_var, None)
            if old_possible_vals is not None:
                possible_values[
                    eff_discr_var] = old_possible_vals & possible_vals
            else:
                possible_values[eff_discr_var] = possible_vals

    possible_values = prune_possible_values(block, possible_values, config)

    return possible_values
Exemple #21
0
def obbt_disjunct(orig_model, idx, solver):
    model = orig_model.clone()

    # Fix the disjunct to be active
    disjunct = model._disjuncts_to_process[idx]
    disjunct.indicator_var.fix(1)

    for obj in model.component_data_objects(Objective, active=True):
        obj.deactivate()

    # Deactivate nonlinear constraints
    for constr in model.component_data_objects(Constraint,
                                               active=True,
                                               descend_into=(Block, Disjunct)):
        if constr.body.polynomial_degree() not in linear_degrees:
            constr.deactivate()

    # Only look at the variables participating in active constraints within the scope
    relevant_var_set = ComponentSet()
    for constr in disjunct.component_data_objects(Constraint, active=True):
        relevant_var_set.update(
            identify_variables(constr.body, include_fixed=False))

    TransformationFactory('gdp.bigm').apply_to(model)

    model._var_bounding_obj = Objective(expr=1, sense=minimize)

    for var in relevant_var_set:
        model._var_bounding_obj.set_value(expr=var)
        var_lb = solve_bounding_problem(model, solver)
        if var_lb is None:
            return None  # bounding problem infeasible
        model._var_bounding_obj.set_value(expr=-var)
        var_ub = solve_bounding_problem(model, solver)
        if var_ub is None:
            return None  # bounding problem infeasible
        else:
            var_ub = -var_ub  # sign correction

        var.setlb(var_lb)
        var.setub(var_ub)

    # Maps original variable --> (new computed LB, new computed UB)
    var_bnds = ComponentMap(
        ((orig_var, (clone_var.lb if clone_var.has_lb() else -inf,
                     clone_var.ub if clone_var.has_ub() else inf))
         for orig_var, clone_var in zip(orig_model._disj_bnds_linear_vars,
                                        model._disj_bnds_linear_vars)
         if clone_var in relevant_var_set))
    return var_bnds
Exemple #22
0
 def __init__(self, model=None):
     """
     """
     # If the user gives us a model or an NLP, we assume they want us
     # to cache the incidence matrix for fast analysis of submatrices
     # later on.
     # WARNING: This cache will become invalid if the user alters their
     #          model.
     self.cached = IncidenceMatrixType.NONE
     if isinstance(model, PyomoNLP):
         nlp = model
         self.cached = IncidenceMatrixType.NUMERIC
         self.variables = nlp.get_pyomo_variables()
         self.constraints = nlp.get_pyomo_constraints()
         self.var_index_map = ComponentMap(
                 (var, idx) for idx, var in enumerate(self.variables))
         self.con_index_map = ComponentMap(
                 (con, idx) for idx, con in enumerate(self.constraints))
         self.incidence_matrix = nlp.evaluate_jacobian_eq()
     elif isinstance(model, Block):
         self.cached = IncidenceMatrixType.STRUCTURAL
         self.variables = list(model.component_data_objects(Var))
         self.constraints = list(model.component_data_objects(Constraint))
         self.var_index_map = ComponentMap(
                 (var, i) for i, var in enumerate(self.variables))
         self.con_index_map = ComponentMap(
                 (con, i) for i, con in enumerate(self.constraints))
         self.incidence_matrix = get_structural_incidence_matrix(
                 self.variables,
                 self.constraints,
                 )
     elif model is not None:
         raise TypeError(
             "Unsupported type for incidence matrix. Expected "
             "%s or %s but got %s."
             % (PyomoNLP, Block, type(model))
             )
Exemple #23
0
 def _set_instance(self, model, kwds={}):
     self._range_constraints = set()
     super(MOSEKDirect, self)._set_instance(model, kwds)
     self._pyomo_cone_to_solver_cone_map = dict()
     self._solver_cone_to_pyomo_cone_map = ComponentMap()
     self._whichsol = getattr(self._mosek.soltype,
                              kwds.pop('soltype', 'bas'))
     try:
         self._solver_model = self._mosek.Env().Task()
     except:
         err_msg = sys.exc_info()[1]
         logger.error("MOSEK task creation failed. " +
                      "Reason: {}".format(err_msg))
         raise
     self._add_block(model)
Exemple #24
0
    def __init__(self, component=None):
        #
        # These lines represent in-lining of the
        # following constructors:
        #   - ComponentData
        #   - NumericValue
        self._component = weakref_ref(component) if (component is not None) \
                          else None

        self.vars = {}
        self._arcs = []
        self._sources = []
        self._dests = []
        self._rules = {}
        self._splitfracs = ComponentMap()
Exemple #25
0
def calc_jacobians(solve_data, config):
    """Generates a map of jacobians for the variables in the model.

    This function generates a map of jacobians corresponding to the variables in the
    model and adds this ComponentMap to solve_data.

    Args:
        solve_data (MindtPySolveData): data container that holds solve-instance data.
        config (ConfigBlock): the specific configurations for MindtPy.
    """
    # Map nonlinear_constraint --> Map(
    #     variable --> jacobian of constraint wrt. variable)
    solve_data.jacobians = ComponentMap()
    if config.differentiate_mode == 'reverse_symbolic':
        mode = differentiate.Modes.reverse_symbolic
    elif config.differentiate_mode == 'sympy':
        mode = differentiate.Modes.sympy
    for c in solve_data.mip.MindtPy_utils.nonlinear_constraint_list:
        vars_in_constr = list(EXPR.identify_variables(c.body))
        jac_list = differentiate(
            c.body, wrt_list=vars_in_constr, mode=mode)
        solve_data.jacobians[c] = ComponentMap(
            (var, jac_wrt_var)
            for var, jac_wrt_var in zip(vars_in_constr, jac_list))
Exemple #26
0
 def _apply_to(self, instance, **kwds):
     assert not NAME_BUFFER
     self.used_args = ComponentMap()  # If everything was sure to go well,
     # this could be a dictionary. But if
     # someone messes up and gives us a Var
     # as a key in bigMargs, I need the error
     # not to be when I try to put it into
     # this map!
     try:
         self._apply_to_impl(instance, **kwds)
     finally:
         # Clear the global name buffer now that we are done
         NAME_BUFFER.clear()
         # same for our bookkeeping about what we used from bigM arg dict
         self.used_args.clear()
Exemple #27
0
 def test_remove_ef_from_expr(self):
     # These data objects are normally initialized by
     # replaceExternalFunctionsWithVariables
     self.interface.data.all_variables = ComponentSet()
     self.interface.data.truth_models = ComponentMap()
     self.interface.data.ef_outputs = VarList()
     self.interface.data.basis_expressions = ComponentMap()
     # The objective function has no EF.
     # Therefore, remove_ef_from_expr should do nothing
     component = self.interface.model.obj
     self.interface._remove_ef_from_expr(component)
     self.assertEqual(
         str(self.interface.model.obj.expr),
         '(z[0] - 1.0)**2 + (z[0] - z[1])**2 + (z[2] - 1.0)**2 + (x[0] - 1.0)**4 + (x[1] - 1.0)**6'
     )
     # The first contraint has one EF.
     # Therefore, remove_ef_from_expr should do something
     component = self.interface.model.c1
     str_expr = str(component.expr)
     self.interface._remove_ef_from_expr(component)
     self.assertNotEqual(str_expr, str(component.expr))
     self.assertEqual(
         str(component.expr),
         'x[0]*z[0]**2 + trf_data.ef_outputs[1]  ==  2.8284271247461903')
Exemple #28
0
    def test_square_ill_posed_model(self):
        N = 1
        m = make_gas_expansion_model(N)
        m.P[0].fix()
        m.rho[0].fix()
        m.T[0].fix()

        variables = [
            v for v in m.component_data_objects(pyo.Var) if not v.fixed
        ]
        constraints = list(m.component_data_objects(pyo.Constraint))
        imat = get_structural_incidence_matrix(variables, constraints)

        var_idx_map = ComponentMap((v, i) for i, v in enumerate(variables))
        con_idx_map = ComponentMap((c, i) for i, c in enumerate(constraints))

        N, M = imat.shape
        self.assertEqual(N, M)

        row_partition, col_partition = dulmage_mendelsohn(imat)

        # Only unmatched constraint is ideal_gas[0]
        unmatched_rows = [con_idx_map[m.ideal_gas[0]]]
        self.assertEqual(row_partition[0], unmatched_rows)
        # No other constraints can possibly be unmatched.
        self.assertEqual(row_partition[1], [])
        # The potentially unmatched variables have four constraints
        # between them
        matched_con_set = set(con_idx_map[con] for con in constraints
                              if con is not m.ideal_gas[0])
        self.assertEqual(set(row_partition[2]), matched_con_set)

        # All variables are potentially unmatched
        potentially_unmatched_set = set(range(len(variables)))
        potentially_unmatched = col_partition[0] + col_partition[1]
        self.assertEqual(set(potentially_unmatched), potentially_unmatched_set)
Exemple #29
0
    def __init__(self, model=None):
        """
        This class holds the basic UI setup, but doesn't depend on Qt. It
        shouldn't really be used except for testing when Qt is not available.

        Args:
            model: The Pyomo model to view
        """
        super(UIDataNoUi, self).__init__()
        self._model = None
        self._begin_update = False
        self.value_cache = ComponentMap()
        self.begin_update()
        self.model = model
        self.end_update()
Exemple #30
0
 def test_setdefault(self):
     cmap = ComponentMap()
     for c,_ in self._components:
         with self.assertRaises(KeyError):
             cmap[c]
         self.assertTrue(c not in cmap)
         cmap.setdefault(c, []).append(1)
         self.assertEqual(cmap[c], [1])
         del cmap[c]
         with self.assertRaises(KeyError):
             cmap[c]
         self.assertTrue(c not in cmap)
         cmap[c] = []
         cmap.setdefault(c, []).append(1)
         self.assertEqual(cmap[c], [1])