Esempio n. 1
0
def test_osil_read():
    filename = current_dir / 'osil' / 'example1.xml'
    problem = read_osil(str(filename))
    variables = list(model_variables(problem))
    constraints = list(model_constraints(problem))
    objectives = list(model_objectives(problem))
    assert len(variables) == 35
    assert len(constraints) == 18
    assert len(objectives) == 1

    m = problem

    e9_body_expected = m.x33 - (m.x32*pe.log(m.x22)/(1.0-m.x32))
    e9_body_actual = m.e9.body
    assert sympyify_expression(e9_body_expected - e9_body_actual)[1] == 0

    e11_body_expected = m.x35 - ((m.x33 - m.x34*(m.x32+1.0))/(m.x32+3.0)/(1.0-m.x32)**2/m.x34)
    e11_body_actual = m.e11.body
    assert sympyify_expression(e11_body_expected - e11_body_actual)[1] == 0

    e14_body_expected = m.x26 - m.x22 * m.x28
    e14_body_actual = m.e14.body
    assert sympyify_expression(e14_body_expected - e14_body_actual)[1] == 0

    e15_body_expected = m.x27 - m.x22 * m.x29
    e15_body_actual = m.e15.body
    assert sympyify_expression(e15_body_expected - e15_body_actual)[1] == 0
Esempio n. 2
0
 def test_multivariate2(self):
     m = pe.ConcreteModel()
     m.x = pe.Var(bounds=(-1, 1))
     m.y = pe.Var(bounds=(-1, 1))
     m.aux = pe.Var()
     m.rel = coramin.relaxations.MultivariateRelaxation()
     m.rel.build(aux_var=m.aux,
                 shape=coramin.utils.FunctionShape.CONCAVE,
                 f_x_expr=(-m.x**2 - m.y**2),
                 use_linear_relaxation=True)
     m2 = pe.ConcreteModel()
     m2.x = pe.Var(bounds=(-1, 1))
     m2.y = pe.Var(bounds=(-1, 1))
     m2.aux = pe.Var()
     new_rel = copy_relaxation_with_local_data(m.rel, {id(m.x): m2.x,
                                                 id(m.y): m2.y,
                                                 id(m.aux): m2.aux})
     self.assertEqual(m.rel.use_linear_relaxation, new_rel.use_linear_relaxation)
     self.assertEqual(m.rel.relaxation_side, new_rel.relaxation_side)
     rhs_vars = ComponentSet(new_rel.get_rhs_vars())
     self.assertIn(m2.x, rhs_vars)
     self.assertIn(m2.y, rhs_vars)
     self.assertEqual(len(rhs_vars), 2)
     self.assertIs(m2.aux, new_rel.get_aux_var())
     self.assertEqual(m.rel._function_shape, new_rel._function_shape)
     self.assertIsInstance(new_rel, coramin.relaxations.MultivariateRelaxationData)
     self.assertEqual(sympyify_expression(-m2.x**2 - m2.y**2 - new_rel.get_rhs_expr())[1], 0)
Esempio n. 3
0
 def test_sqrt(self):
     m = pe.ConcreteModel()
     m.x = pe.Var()
     m.z = pe.Var()
     m.c = pe.Constraint(expr=m.z + pe.sqrt(2*pe.log(m.x)) <= 1)
     coramin.relaxations.relax(m, in_place=True, use_fbbt=False)
     rels = list(coramin.relaxations.relaxation_data_objects(m, descend_into=True, active=True, sort=True))
     self.assertEqual(len(rels), 2)
     rel0 = m.relaxations.rel0  # log
     rel1 = m.relaxations.rel1  # sqrt
     self.assertEqual(sympyify_expression(rel0.get_rhs_expr() - pe.log(m.x))[1], 0)
     self.assertEqual(sympyify_expression(rel1.get_rhs_expr() - m.aux_vars[3]**0.5)[1], 0)
     self.assertEqual(sympyify_expression(m.aux_cons[1].body - m.aux_vars[3] + 2 * m.aux_vars[1])[1], 0)
     self.assertEqual(sympyify_expression(m.aux_cons[2].body - m.z - m.aux_vars[2])[1], 0)
     self.assertEqual(m.aux_cons[1].lower, 0)
     self.assertEqual(m.aux_cons[2].lower, None)
     self.assertEqual(m.aux_cons[2].upper, 1)
     self.assertIs(rel0.get_aux_var(), m.aux_vars[1])
     self.assertIs(rel1.get_aux_var(), m.aux_vars[2])
     self.assertEqual(rel0.relaxation_side, coramin.utils.RelaxationSide.UNDER)
     self.assertEqual(rel1.relaxation_side, coramin.utils.RelaxationSide.UNDER)
Esempio n. 4
0
def model_is_valid(model):
    '''
    Possibilities:
    Deterministic model has a single objective
    Deterministic model has no objective
    Deterministic model has multiple objectives
    :param model: the deterministic model
    :return: True if it satisfies certain properties, else False.
    '''
    objectives = list(model.component_data_objects(Objective))
    for o in objectives:
        o.deactivate()
    if len(objectives) == 1:
        '''
        Ensure objective is a minimization. If not, change the sense.
        '''
        obj = objectives[0]

        if obj.sense is not minimize:
            sympy_obj = sympyify_expression(-obj.expr)
            # Use sympy to distribute the negation so the method for determining first/second stage costs is valid
            min_obj = Objective(expr=sympy2pyomo_expression(
                sympy_obj[1].simplify(), sympy_obj[0]))
            model.del_component(obj)
            model.add_component(
                unique_component_name(model, obj.name + '_min'), min_obj)
        return True

    elif len(objectives) > 1:
        '''
        User should deactivate all Objectives in the model except the one represented by the output of 
        first_stage_objective + second_stage_objective
        '''
        return False
    else:
        '''
        No Objective objects provided as part of the model, please provide an Objective to your model so that
        PyROS can infer first- and second-stage objective.
        '''
        return False
Esempio n. 5
0
def differentiate(expr, wrt=None, wrt_list=None):
    """Return derivative of expression.

    This function returns an expression or list of expression objects
    corresponding to the derivative of the passed expression 'expr' with
    respect to a variable 'wrt' or list of variables 'wrt_list'

    Args:
        expr (Expression): Pyomo expression
        wrt (Var): Pyomo variable
        wrt_list (list): list of Pyomo variables

    Returns:
        Expression or list of Expression objects

    """
    if not sympy_available:
        raise RuntimeError(
            "The sympy module is not available.\n\t"
            "Cannot perform automatic symbolic differentiation.")
    if not ((wrt is None) ^ (wrt_list is None)):
        raise ValueError(
            "differentiate(): Must specify exactly one of wrt and wrt_list")
    import sympy
    #
    # Convert the Pyomo expression to a sympy expression
    #
    objectMap, sympy_expr = sympyify_expression(expr)
    #
    # The partial_derivs dict holds intermediate sympy expressions that
    # we can re-use.  We will prepopulate it with None for all vars that
    # appear in the expression (so that we can detect wrt combinations
    # that are, by definition, 0)
    #
    partial_derivs = {x: None for x in objectMap.sympyVars()}
    #
    # Setup the WRT list
    #
    if wrt is not None:
        wrt_list = [wrt]
    else:
        # Copy the list because we will normalize things in place below
        wrt_list = list(wrt_list)
    #
    # Convert WRT vars into sympy vars
    #
    ans = [None] * len(wrt_list)
    for i, target in enumerate(wrt_list):
        if target.__class__ is not tuple:
            target = (target, )
        wrt_list[i] = tuple(objectMap.getSympySymbol(x) for x in target)
        for x in wrt_list[i]:
            if x not in partial_derivs:
                ans[i] = 0.
                break
    #
    # We assume that users will not request duplicate derivatives.  We
    # will only cache up to the next-to last partial, and if a user
    # requests the exact same derivative twice, then we will just
    # re-calculate it.
    #
    last_partial_idx = max(len(x) for x in wrt_list) - 1
    #
    # Calculate all the derivatives
    #
    for i, target in enumerate(wrt_list):
        if ans[i] is not None:
            continue
        part = sympy_expr
        for j, wrt_var in enumerate(target):
            if j == last_partial_idx:
                part = sympy.diff(part, wrt_var)
            else:
                partial_target = target[:j + 1]
                if partial_target in partial_derivs:
                    part = partial_derivs[partial_target]
                else:
                    part = sympy.diff(part, wrt_var)
                    partial_derivs[partial_target] = part
        ans[i] = sympy2pyomo_expression(part, objectMap)
    #
    # Return the answer
    #
    return ans if wrt is None else ans[0]