def gas_emissivity_mul2_eqn(b, t):
     X1 = (b.side_2.properties_in[t].temperature + b.side_2.properties_out[t].temperature)/2
     X2 = b.mbl_mul2
     X3 = b.side_2.properties_in[t].pressure
     X4 = b.side_2.properties_in[t].mole_frac_comp['CO2']
     X5 = b.side_2.properties_in[t].mole_frac_comp['H2O']
     X6 = b.side_2.properties_in[t].mole_frac_comp['O2']
     return b.gas_emissivity_mul2[t] == \
     -0.000116906 * X1 \
     +1.02113 * X2 \
     +4.81687e-07 * X3 \
     +0.922679 * X4 \
     -0.0708822 * X5 \
     -0.0368321 * X6 \
     +0.121843 * log(X1) \
     +0.0353343 * log(X2) \
     +0.0346181 * log(X3) \
     +0.0180859 * log(X5) \
     -0.256274 * exp(X2) \
     -0.674791 * exp(X4) \
     -0.724802 * sin(X2) \
     -0.0206726 * cos(X2) \
     -9.01012e-05 * cos(X3) \
     -3.09283e-05 * X1*X2 \
     -5.44339e-10 * X1*X3 \
     -0.000196134 * X1*X5 \
     +4.54838e-05 * X1*X6 \
     +7.57411e-07 * X2*X3 \
     +0.0395456 * X2*X4 \
     +0.726625 * X2*X5 \
     -0.034842 * X2*X6 \
     +4.00056e-06 * X3*X5 \
     +5.71519e-09 * (X1*X2)**2 \
     -1.27853 * (X2*X5)**2
Пример #2
0
def power_flow_through_branch(Vi,
                              Vj,
                              delta,
                              branch,
                              bus_type="from_bus",
                              power_type="Reactive"):
    if not (power_type == "Active" or power_type == "Reactive"):
        raise ValueError(
            'Power type must be "Active" (for p) or "Reactive" (for q)')

    if not (bus_type == "from_bus" or bus_type == "to_bus"):
        raise ValueError(
            'Bus type must be "from_bus" (for f) or "to_bus" (for t)')

    g = tx_calc.calculate_conductance(branch)
    b = tx_calc.calculate_susceptance(branch)

    if power_type == "Active":
        if bus_type == "from_bus":
            return Vi**2 * g - Vi * Vj * g * pe.cos(
                delta) - Vi * Vj * b * pe.sin(delta)
        else:
            return Vj**2 * g - Vi * Vj * g * pe.cos(
                delta) - Vi * Vj * b * pe.sin(delta)

    else:
        if bus_type == "from_bus":
            return -Vi**2 * b + Vi * Vj * b * pe.cos(
                delta) - Vi * Vj * g * pe.sin(delta)
        else:
            return -Vj**2 * b + Vi * Vj * b * pe.cos(
                delta) - Vi * Vj * g * pe.sin(delta)
Пример #3
0
def test_expr_hash_unary_expr(model):
    model.cons1 = aml.Constraint(model.I,
                                 rule=lambda m, i: aml.cos(m.x[i]) <= 0.5)

    hash_cons1 = expr_hash(model.cons1[2].expr)
    ex1 = aml.cos(model.x[2]) <= 0.5
    assert hash_cons1 == expr_hash(ex1)
Пример #4
0
def test_expr_equal(model):
    assert not expr_equal(1.2, 2.3)
    assert expr_equal(model.x[1], model.x[1])
    assert expr_equal(model.x[1] + 1.23, model.x[1] + 1.23)
    assert not expr_equal(model.x[1], model.y[1, 0])
    assert not expr_equal(model.x[1], 2)

    sum1 = sum(model.x[i] for i in model.I)
    sum2 = sum(model.x[i] for i in model.I)
    sum3 = sum((i + 1) * model.x[i] for i in model.I)
    sum4 = sum(i * model.x[i] for i in model.I)
    sum5 = sum((i + 1) * model.x[i] for i in model.I)
    sum6 = sum(model.y[i, 0] for i in model.I)

    assert expr_equal(sum1, sum2)
    assert not expr_equal(sum1, sum3)
    assert not expr_equal(sum1, sum4)
    assert expr_equal(sum3, sum5)
    assert not expr_equal(sum1, sum6)

    fun1 = aml.cos(sum1)
    fun2 = aml.cos(sum2)
    fun3 = aml.sin(sum1)

    assert expr_equal(fun1, fun2)
    assert not expr_equal(fun1, fun3)
    assert expr_equal(fun1 * fun3, fun2 * fun3)
    assert expr_equal(fun1 / fun3, fun2 / fun3)
Пример #5
0
def _relax_leaf_to_root_cos(node, values, aux_var_map, degree_map, parent_block, relaxation_side_map, counter):
    arg = values[0]
    degree = degree_map[arg]
    if degree == 0:
        res = pe.cos(arg)
        degree_map[res] = 0
        return res
    elif (id(arg), 'cos') in aux_var_map:
        _aux_var, relaxation = aux_var_map[id(arg), 'cos']
        relaxation_side = relaxation_side_map[node]
        if relaxation_side != relaxation.relaxation_side:
            relaxation.relaxation_side = RelaxationSide.BOTH
        degree_map[_aux_var] = 1
        return _aux_var
    else:
        _aux_var = _get_aux_var(parent_block, pe.cos(arg))
        arg = replace_sub_expression_with_aux_var(arg, parent_block)
        relaxation_side = relaxation_side_map[node]
        degree_map[_aux_var] = 1
        relaxation = PWCosRelaxation()
        relaxation.set_input(x=arg, aux_var=_aux_var, relaxation_side=relaxation_side)
        aux_var_map[id(arg), 'cos'] = (_aux_var, relaxation)
        setattr(parent_block.relaxations, 'rel'+str(counter), relaxation)
        counter.increment()
        return _aux_var
Пример #6
0
 def perimeter_if(b):
     if self.config.single_side_only:
         return (const.pi - 2 * b.alpha_tube) * b.radius_out + b.pitch \
             - 2 * b.radius_out * cos(b.alpha_tube)
     else:
         return 2 * ((const.pi - 2 * b.alpha_tube) * b.radius_out +
                     b.pitch - 2 * b.radius_out * cos(b.alpha_tube))
Пример #7
0
def get_pyomo_model():
    m = aml.ConcreteModel()

    m.x = aml.Var(initialize=10.0)
    m.z = aml.Var(initialize=-10.0)

    m.c0 = aml.Constraint(expr=aml.cos(m.x) >= 0)
    m.c1 = aml.Constraint(expr=aml.cos(m.z) >= 0)
    m.o = aml.Objective(expr=aml.cos(m.x))
    return m
Пример #8
0
 def perimeter_ss(b, t):
     if self.config.single_side_only:
         return (const.pi - 2 * b.alpha_slag[t]) \
             * (b.radius_out + b.slag_thickness[t]) + \
             b.pitch - 2 * (b.radius_out + b.slag_thickness[t]) \
             * cos(b.alpha_slag[t])
     else:
         return 2 * (
             (const.pi - 2 * b.alpha_slag[t]) *
             (b.radius_out + b.slag_thickness[t]) + b.pitch - 2 *
             (b.radius_out + b.slag_thickness[t]) *
             cos(b.alpha_slag[t]))
Пример #9
0
    def test_trig_fuctions(self):
        m = ConcreteModel()
        m.x = Var()

        e = differentiate(sin(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s(cos(m.x)))

        e = differentiate(cos(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s(-1.0*sin(m.x)))

        e = differentiate(tan(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s(1.+tan(m.x)**2.))

        e = differentiate(sinh(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s(cosh(m.x)))

        e = differentiate(cosh(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s(sinh(m.x)))

        e = differentiate(tanh(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s(1.0-tanh(m.x)**2.0))


        e = differentiate(asin(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s((1.0 + (-1.0)*m.x**2.)**-0.5))

        e = differentiate(acos(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s(-1.*(1.+ (-1.0)*m.x**2.)**-0.5))

        e = differentiate(atan(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s((1.+m.x**2.)**-1.))

        e = differentiate(asinh(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s((1.+m.x**2)**-.5))

        e = differentiate(acosh(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s((-1.+m.x**2.)**-.5))

        e = differentiate(atanh(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s((1.+(-1.0)*m.x**2.)**-1.))
Пример #10
0
    def test_cos(self):
        m = pe.Block(concrete=True)
        m.x = pe.Var(bounds=(0, math.pi))
        m.c = pe.Constraint(expr=pe.inequality(body=pe.cos(m.x), lower=-0.5, upper=0.5))
        fbbt(m)
        self.assertAlmostEqual(pe.value(m.x.lb), math.acos(0.5))
        self.assertAlmostEqual(pe.value(m.x.ub), math.acos(-0.5))

        m = pe.Block(concrete=True)
        m.x = pe.Var()
        m.c = pe.Constraint(expr=pe.inequality(body=pe.cos(m.x), lower=-0.5, upper=0.5))
        fbbt(m)
        self.assertEqual(m.x.lb, None)
        self.assertEqual(m.x.ub, None)
Пример #11
0
    def test_pow(self):
        m = aml.ConcreteModel()
        m.I = range(10)
        m.x = aml.Var(m.I)

        m.c0 = aml.Constraint(expr=aml.cos(m.x[0])**2.0 >= 1)
        m.c1 = aml.Constraint(expr=2**aml.sin(m.x[1]) >= 1)

        dag = problem_from_pyomo_model(m)

        c0 = dag.constraint('c0')
        root_c0 = c0.root_expr
        assert isinstance(root_c0, core.PowExpression)
        assert root_c0.num_children == 2
        assert isinstance(root_c0.children[0], core.CosExpression)
        assert isinstance(root_c0.children[1], core.Constant)
        assert root_c0.children[1].value == 2.0

        c1 = dag.constraint('c1')
        root_c1 = c1.root_expr
        assert isinstance(root_c1, core.PowExpression)
        assert root_c1.num_children == 2
        assert isinstance(root_c1.children[0], core.Constant)
        assert isinstance(root_c1.children[1], core.SinExpression)
        self._check_depth(root_c0)
        self._check_depth(root_c1)
Пример #12
0
    def test_convert(self):
        u = units
        m = ConcreteModel()
        m.dx = Var(units=u.m, initialize=0.10188943773836046)
        m.dy = Var(units=u.m, initialize=0.0)
        m.vx = Var(units=u.m/u.s, initialize=0.7071067769802851)
        m.vy = Var(units=u.m/u.s, initialize=0.7071067769802851)
        m.t = Var(units=u.min, bounds=(1e-5,10.0), initialize=0.0024015570927624456)
        m.theta = Var(bounds=(0, 0.49*3.14), initialize=0.7853981693583533, units=u.radians)
        m.a = Param(initialize=-32.2, units=u.ft/u.s**2)

        m.obj = Objective(expr = m.dx, sense=maximize)
        m.vx_con = Constraint(expr = m.vx == 1.0*u.m/u.s*cos(m.theta))
        m.vy_con = Constraint(expr = m.vy == 1.0*u.m/u.s*sin(m.theta))
        m.dx_con = Constraint(expr = m.dx == m.vx*u.convert(m.t, to_units=u.s))
        m.dy_con = Constraint(expr = m.dy == m.vy*u.convert(m.t, to_units=u.s)
                              + 0.5*(u.convert(m.a, to_units=u.m/u.s**2))*(u.convert(m.t, to_units=u.s))**2)
        m.ground = Constraint(expr = m.dy == 0)

        with self.assertRaises(UnitsError):
            u.convert(m.a, to_units=u.kg)

        self.assertAlmostEqual(value(m.obj), 0.10188943773836046, places=5)
        self.assertAlmostEqual(value(m.vx_con.body), 0.0, places=5)
        self.assertAlmostEqual(value(m.vy_con.body), 0.0, places=5)
        self.assertAlmostEqual(value(m.dx_con.body), 0.0, places=5)
        self.assertAlmostEqual(value(m.dy_con.body), 0.0, places=5)
        self.assertAlmostEqual(value(m.ground.body), 0.0, places=5)
Пример #13
0
 def test_updateSurrogateModel(self):
     # Set up necessary data objects and Params
     self.interface.replaceExternalFunctionsWithVariables()
     self.interface.createConstraints()
     # Set starter values on the model
     self.interface.model.x[0] = 2.0
     self.interface.model.z.set_values({0: 5.0, 1: 2.5, 2: -1.0})
     self.interface.data.basis_model_output[:] = 0
     self.interface.data.grad_basis_model_output[...] = 0
     self.interface.data.truth_model_output[:] = 0
     self.interface.data.grad_truth_model_output[...] = 0
     self.interface.data.value_of_ef_inputs[...] = 0
     self.interface.updateSurrogateModel()
     # The basis model here is 0, so all basis values should be 0
     for key, val in self.interface.data.basis_model_output.items():
         self.assertEqual(value(val), 0)
     for key, val in self.interface.data.grad_basis_model_output.items():
         self.assertEqual(value(val), 0)
     for key, val in self.interface.data.truth_model_output.items():
         self.assertEqual(value(val), 0.8414709848078965)
     # The truth gradients should equal the output of [cos(2-1), -cos(2-1)]
     truth_grads = []
     for key, val in self.interface.data.grad_truth_model_output.items():
         truth_grads.append(value(val))
     self.assertEqual(truth_grads, [cos(1), -cos(1)])
     # The inputs should be the values of x[0] and x[1]
     for key, val in self.interface.data.value_of_ef_inputs.items():
         self.assertEqual(value(self.interface.model.x[key[1]]), value(val))
     # Change the model values to something else and try again
     self.interface.model.x.set_values({0: 0, 1: 0})
     self.interface.updateSurrogateModel()
     # The basis values should still all be 0
     for key, val in self.interface.data.basis_model_output.items():
         self.assertEqual(value(val), 0)
     for key, val in self.interface.data.grad_basis_model_output.items():
         self.assertEqual(value(val), 0)
     # We still have not updated this value, so the value should be 0
     for key, val in self.interface.data.truth_model_output.items():
         self.assertEqual(value(val), 0)
     # The truth gradients should equal the output of [cos(0-0), -cos(0-0)]
     truth_grads = []
     for key, val in self.interface.data.grad_truth_model_output.items():
         truth_grads.append(value(val))
     self.assertEqual(truth_grads, [cos(0), -cos(0)])
     # The inputs should be the values of x[0] and x[1]
     for key, val in self.interface.data.value_of_ef_inputs.items():
         self.assertEqual(value(self.interface.model.x[key[1]]), value(val))
Пример #14
0
 def test_cos(self):
     m = pyo.ConcreteModel()
     m.x = pyo.Var(initialize=2.0)
     e = pyo.cos(m.x)
     derivs = reverse_ad(e)
     symbolic = reverse_sd(e)
     self.assertAlmostEqual(derivs[m.x], pyo.value(symbolic[m.x]), tol + 3)
     self.assertAlmostEqual(derivs[m.x], approx_deriv(e, m.x), tol)
Пример #15
0
def create_problem():
    m = aml.ConcreteModel()
    m.I = range(10)
    m.x = aml.Var(m.I, bounds=(-1, 2))
    m.obj = aml.Objective(expr=sum(m.x[i] for i in m.I))
    m.cons = aml.Constraint(
        m.I[1:], rule=lambda m, i: aml.cos(m.x[0]) * aml.sin(m.x[i]) >= 0)
    return problem_from_pyomo_model(m)
Пример #16
0
 def test_cos(self):
     m = pe.ConcreteModel()
     m.x = pe.Var(initialize=2.0)
     e = pe.cos(m.x)
     derivs = reverse_ad(e)
     symbolic = reverse_sd(e)
     self.assertAlmostEqual(derivs[m.x], pe.value(symbolic[m.x]), tol+3)
     self.assertAlmostEqual(derivs[m.x], approx_deriv(e, m.x), tol)
Пример #17
0
        def _eval(node):
            name = _tag_name(node)
            cs = list(node)

            if name == 'negate':
                assert len(cs) == 1
                return -_eval(cs[0])
            elif name == 'number':
                return float(node.attrib['value'])
            elif name == 'variable':
                c = float(node.attrib.get('coef', 1))
                return c * self._v(int(node.attrib['idx']))
            elif name == 'power':
                assert len(cs) == 2
                b = _eval(cs[0])
                e = _eval(cs[1])
                return b**e
            elif name == 'square':
                assert len(cs) == 1
                return _eval(cs[0])**2
            elif name == 'sqrt':
                assert len(cs) == 1
                return aml.sqrt(_eval(cs[0]))
            elif name == 'product':
                return reduce(op.mul, [_eval(c) for c in cs])
            elif name == 'divide':
                assert len(cs) == 2
                return _eval(cs[0]) / _eval(cs[1])
            elif name == 'times':
                assert len(cs) == 2
                return _eval(cs[0]) * _eval(cs[1])
            elif name == 'plus':
                assert len(cs) == 2
                return _eval(cs[0]) + _eval(cs[1])
            elif name == 'sum':
                return sum([_eval(c) for c in cs])
            elif name == 'minus':
                assert len(cs) == 2
                return _eval(cs[0]) - _eval(cs[1])
            elif name == 'abs':
                assert len(cs) == 1
                return abs(_eval(cs[0]))
            elif name == 'exp':
                assert len(cs) == 1
                return aml.exp(_eval(cs[0]))
            elif name == 'ln':
                assert len(cs) == 1
                return aml.log(_eval(cs[0]))
            elif name == 'sin':
                assert len(cs) == 1
                return aml.sin(_eval(cs[0]))
            elif name == 'cos':
                assert len(cs) == 1
                return aml.cos(_eval(cs[0]))
            elif name == 'log10':
                assert len(cs) == 1
                return aml.log10(_eval(cs[0]))
            raise RuntimeError('unhandled tag {}'.format(name))
Пример #18
0
    def test_problem(self):
        problem = self.get_problem(
            lambda m: aml.cos(m.x) * aml.sin(m.y) - m.x / (m.y * m.y + 1))

        h = IntervalHessianEvaluator(problem)
        h.eval_at_x(np.array([I(-1, 2), I(-1, 1)]))
        print(h.jacobian[0])
        print(h.hessian[0])
        assert False
Пример #19
0
    def test_assert_units_consistent_equivalent(self):
        u = units
        m = ConcreteModel()
        m.dx = Var(units=u.m, initialize=0.10188943773836046)
        m.dy = Var(units=u.m, initialize=0.0)
        m.vx = Var(units=u.m / u.s, initialize=0.7071067769802851)
        m.vy = Var(units=u.m / u.s, initialize=0.7071067769802851)
        m.t = Var(units=u.min,
                  bounds=(1e-5, 10.0),
                  initialize=0.0024015570927624456)
        m.theta = Var(bounds=(0, 0.49 * 3.14),
                      initialize=0.7853981693583533,
                      units=u.radians)
        m.a = Param(initialize=-32.2, units=u.ft / u.s**2)
        m.x_unitless = Var()

        m.obj = Objective(expr=m.dx, sense=maximize)
        m.vx_con = Constraint(expr=m.vx == 1.0 * u.m / u.s * cos(m.theta))
        m.vy_con = Constraint(expr=m.vy == 1.0 * u.m / u.s * sin(m.theta))
        m.dx_con = Constraint(expr=m.dx == m.vx * u.convert(m.t, to_units=u.s))
        m.dy_con = Constraint(
            expr=m.dy == m.vy * u.convert(m.t, to_units=u.s) + 0.5 *
            (u.convert(m.a, to_units=u.m / u.s**2)) *
            (u.convert(m.t, to_units=u.s))**2)
        m.ground = Constraint(expr=m.dy == 0)
        m.unitless_con = Constraint(expr=m.x_unitless == 5.0)

        assert_units_consistent(m)  # check model
        assert_units_consistent(m.dx)  # check var - this should never fail
        assert_units_consistent(
            m.x_unitless)  # check unitless var - this should never fail
        assert_units_consistent(m.vx_con)  # check constraint
        assert_units_consistent(m.unitless_con)  # check unitless constraint

        assert_units_equivalent(m.dx, m.dy)  # check var
        assert_units_equivalent(m.x_unitless,
                                u.dimensionless)  # check unitless var
        assert_units_equivalent(m.x_unitless, None)  # check unitless var
        assert_units_equivalent(m.vx_con.body, u.m / u.s)  # check constraint
        assert_units_equivalent(m.unitless_con.body,
                                u.dimensionless)  # check unitless constraint
        assert_units_equivalent(m.dx, m.dy)  # check var
        assert_units_equivalent(m.x_unitless,
                                u.dimensionless)  # check unitless var
        assert_units_equivalent(m.x_unitless, None)  # check unitless var
        assert_units_equivalent(m.vx_con.body, u.m / u.s)  # check constraint

        m.broken = Constraint(expr=m.dy == 42.0 * u.kg)
        with self.assertRaises(UnitsError):
            assert_units_consistent(m)
        assert_units_consistent(m.dx)
        assert_units_consistent(m.vx_con)
        with self.assertRaises(UnitsError):
            assert_units_consistent(m.broken)

        self.assertTrue(check_units_equivalent(m.dx, m.dy))
        self.assertFalse(check_units_equivalent(m.dx, m.vx))
Пример #20
0
 def _result_with_mono_bounds(self, visitor, g, mono_g, bounds_g):
     mono = ComponentMap()
     mono[g] = mono_g
     bounds = ComponentMap()
     bounds[g] = bounds_g
     expr = pe.cos(g)
     matched, result = visitor.visit_expression(expr, mono, bounds)
     assert matched
     return result
Пример #21
0
def create_rsv_acopf_model(model_data,
                           include_feasibility_slack=False,
                           pw_cost_model='delta'):
    model, md = _create_base_power_ac_model(
        model_data,
        include_feasibility_slack=include_feasibility_slack,
        pw_cost_model=pw_cost_model)
    bus_attrs = md.attributes(element_type='bus')
    branch_attrs = md.attributes(element_type='branch')
    bus_pairs = zip_items(branch_attrs['from_bus'], branch_attrs['to_bus'])
    unique_bus_pairs = list(
        OrderedDict((val, None) for idx, val in bus_pairs.items()).keys())

    # declare the rectangular voltages
    neg_v_max = map_items(op.neg, bus_attrs['v_max'])
    vr_init = {
        k: bus_attrs['vm'][k] * pe.cos(radians(bus_attrs['va'][k]))
        for k in bus_attrs['vm']
    }
    libbus.declare_var_vr(model,
                          bus_attrs['names'],
                          initialize=vr_init,
                          bounds=zip_items(neg_v_max, bus_attrs['v_max']))

    vj_init = {
        k: bus_attrs['vm'][k] * pe.sin(radians(bus_attrs['va'][k]))
        for k in bus_attrs['vm']
    }
    libbus.declare_var_vj(model,
                          bus_attrs['names'],
                          initialize=vj_init,
                          bounds=zip_items(neg_v_max, bus_attrs['v_max']))

    # fix the reference bus
    ref_bus = md.data['system']['reference_bus']
    ref_angle = md.data['system']['reference_bus_angle']
    if ref_angle != 0.0:
        libbus.declare_eq_ref_bus_nonzero(model, ref_angle, ref_bus)
    else:
        model.vj[ref_bus].fix(0.0)
        model.vr[ref_bus].setlb(bus_attrs['v_min'][ref_bus])

    # relate c, s, and vmsq to vm and va
    libbus.declare_eq_vmsq(model=model,
                           index_set=bus_attrs['names'],
                           coordinate_type=CoordinateType.RECTANGULAR)
    libbranch.declare_eq_c(model=model,
                           index_set=unique_bus_pairs,
                           coordinate_type=CoordinateType.RECTANGULAR)
    libbranch.declare_eq_s(model=model,
                           index_set=unique_bus_pairs,
                           coordinate_type=CoordinateType.RECTANGULAR)

    return model, md
Пример #22
0
    def setUpClass(cls):
        model = pe.ConcreteModel()
        cls.model = model
        model.x = pe.Var(bounds=(-2, 1))
        model.y = pe.Var(bounds=(-1, 1))
        model.w = pe.Var()

        model.f_x = pe.cos(model.x)*pe.sin(model.y) - model.x/(model.y**2 + 1)

        model.obj = pe.Objective(expr=model.w)
        model.abb = AlphaBBRelaxation()
        model.abb.build(aux_var=model.w, f_x_expr=model.f_x)
Пример #23
0
def NLP1(z0=[]):
    m = pyo.ConcreteModel()
    m.z1 = pyo.Var(initialize=z0[0])
    m.z2 = pyo.Var(initialize=z0[1])
    m.obj = pyo.Objective(expr=3 * pyo.sin(-2 * np.pi * m.z1) + 2 * m.z1 + 4 +
                          pyo.cos(2 * np.pi * m.z2) + m.z2)

    m.cons1 = pyo.Constraint(expr=(-1, m.z1, 1))
    m.cons2 = pyo.Constraint(expr=(-1, m.z2, 1))
    res = pyo.SolverFactory('ipopt').solve(m)

    return [m.z1(), m.z2(), m.obj()]
Пример #24
0
    def test_negation(self):
        m = aml.ConcreteModel()
        m.I = range(10)
        m.x = aml.Var(m.I)

        m.c = aml.Constraint(expr=-aml.cos(m.x[0]) >= 0)

        dag = problem_from_pyomo_model(m)

        constraint = dag.constraint('c')
        root = constraint.root_expr
        assert isinstance(root, core.NegationExpression)
        self._check_depth(root)
Пример #25
0
def problem():
    m = aml.ConcreteModel(name='test_relaxation')

    m.I = range(5)
    m.x = aml.Var(m.I, domain=aml.NonNegativeIntegers)

    m.obj = aml.Objective(expr=m.x[0])
    m.cons0 = aml.Constraint(expr=sum(m.x[i] for i in m.I) >= 0)
    m.cons1 = aml.Constraint(
        expr=-2.0 * aml.sin(m.x[0]) + aml.cos(m.x[1]) >= 0)
    m.cons2 = aml.Constraint(expr=m.x[1] * m.x[2] >= 0)

    return dag_from_pyomo_model(m)
Пример #26
0
    def pwl_cosine_rule(model, i, branch_name):
        branch = branches[branch_name]

        from_bus = branch['from_bus']
        to_bus = branch['to_bus']
        if i == 0:
            return model.cos_hat[branch_name] - (
                (pe.cos(upper_bound) - pe.cos(lower_bound)) /
                (upper_bound - lower_bound) *
                ((model.va[from_bus] - model.va[to_bus]) - lower_bound) +
                pe.cos(lower_bound)) >= 0
        else:
            if mode == "uniform":
                a = lower_bound + i * increment
                return 0 <= (-pe.sin(a) *
                             (model.va[from_bus] - model.va[to_bus] - a) +
                             pe.cos(a)) - model.cos_hat[branch_name]
            elif mode == "curvature":
                a = breakpoints[i]
                return 0 <= (-pe.sin(a) *
                             (model.va[from_bus] - model.va[to_bus] - a) +
                             pe.cos(a)) - model.cos_hat[branch_name]
            else:
                raise ValueError('Mode must be "uniform" or "curvature" ')
Пример #27
0
def declare_expr_c(model, index_set, coordinate_type=CoordinateType.POLAR):
    """
    Create expression for the nonlinear, nonconvex term based on cosine
    of the phase angle difference (polar) or bilinear voltages (rectangular)
    """
    m = model
    expr_set = decl.declare_set('_expr_c', model, index_set)
    m.c = pe.Expression(expr_set)

    if coordinate_type == CoordinateType.RECTANGULAR:
        for from_bus, to_bus in expr_set:
            m.c[(from_bus,to_bus)] = m.vr[from_bus]*m.vr[to_bus] + m.vj[from_bus]*m.vj[to_bus]
    elif coordinate_type == CoordinateType.POLAR:
        for from_bus, to_bus in expr_set:
            m.c[(from_bus,to_bus)] = m.vm[from_bus]*m.vm[to_bus]*pe.cos(m.va[from_bus]-m.va[to_bus])
Пример #28
0
 def test_unary_expressions(self):
     m = ConcreteModel()
     m.x = Var()
     m.y = Var()
     m.z = Var()
     m.a = Var()
     m.b = Var()
     m.c = Var()
     m.d = Var()
     m.c1 = Constraint(expr=0 <= sin(m.x))
     m.c2 = Constraint(expr=0 <= cos(m.y))
     m.c3 = Constraint(expr=0 <= tan(m.z))
     m.c4 = Constraint(expr=0 <= asin(m.a))
     m.c5 = Constraint(expr=0 <= acos(m.b))
     m.c6 = Constraint(expr=0 <= atan(m.c))
     m.c7 = Constraint(expr=0 <= sqrt(m.d))
     m.o = Objective(expr=m.x)
     self.assertTrue(satisfiable(m) is not False)
Пример #29
0
 def test_unary_expressions(self):
     m = ConcreteModel()
     m.x = Var()
     m.y = Var()
     m.z = Var()
     m.a = Var()
     m.b = Var()
     m.c = Var()
     m.d = Var()
     m.c1 = Constraint(expr=0 <= sin(m.x))
     m.c2 = Constraint(expr=0 <= cos(m.y))
     m.c3 = Constraint(expr=0 <= tan(m.z))
     m.c4 = Constraint(expr=0 <= asin(m.a))
     m.c5 = Constraint(expr=0 <= acos(m.b))
     m.c6 = Constraint(expr=0 <= atan(m.c))
     m.c7 = Constraint(expr=0 <= sqrt(m.d))
     m.o = Objective(expr=m.x)
     self.assertTrue(satisfiable(m) is not False)
Пример #30
0
    def test_product(self):
        m = aml.ConcreteModel()
        m.I = range(10)
        m.x = aml.Var(m.I)

        m.c = aml.Constraint(
            range(9),
            rule=lambda m, i: aml.sin(m.x[i]) * aml.cos(m.x[i + 1]) >= 0)

        dag = problem_from_pyomo_model(m)

        assert len(dag.constraints) == 9
        for constraint in dag.constraints:
            root = constraint.root_expr
            assert isinstance(root, core.ProductExpression)
            assert root.num_children == 2
            child1, child2 = root.children
            assert isinstance(child1, core.SinExpression)
            assert isinstance(child2, core.CosExpression)
            self._check_depth(root)
Пример #31
0
def declare_eq_c(model, index_set, coordinate_type=CoordinateType.POLAR):
    """
    Create a constraint relating c to the voltages
    """
    m = model
    con_set = decl.declare_set('_con_eq_c', model, index_set)
    m.eq_c = pe.Constraint(con_set)

    if coordinate_type == CoordinateType.POLAR:
        for from_bus, to_bus in con_set:
            m.eq_c[(from_bus,
                    to_bus)] = (m.c[(from_bus, to_bus)] == m.vm[from_bus] *
                                m.vm[to_bus] *
                                pe.cos(m.va[from_bus] - m.va[to_bus]))
    elif coordinate_type == CoordinateType.RECTANGULAR:
        for from_bus, to_bus in con_set:
            m.eq_c[(from_bus, to_bus)] = (m.c[(
                from_bus, to_bus)] == m.vr[from_bus] * m.m.vr[to_bus] +
                                          m.vj[from_bus] * m.vj[to_bus])
    else:
        raise ValueError('unexpected coordinate_type: {0}'.format(
            str(coordinate_type)))
Пример #32
0
def create_btheta_losses_dcopf_model(model_data, relaxation_type=RelaxationType.SOC, include_angle_diff_limits=False, include_feasibility_slack=False):
    md = model_data.clone_in_service()
    tx_utils.scale_ModelData_to_pu(md, inplace = True)

    gens = dict(md.elements(element_type='generator'))
    buses = dict(md.elements(element_type='bus'))
    branches = dict(md.elements(element_type='branch'))
    loads = dict(md.elements(element_type='load'))
    shunts = dict(md.elements(element_type='shunt'))

    gen_attrs = md.attributes(element_type='generator')
    bus_attrs = md.attributes(element_type='bus')
    branch_attrs = md.attributes(element_type='branch')
    load_attrs = md.attributes(element_type='load')
    shunt_attrs = md.attributes(element_type='shunt')

    inlet_branches_by_bus, outlet_branches_by_bus = \
        tx_utils.inlet_outlet_branches_by_bus(branches, buses)
    gens_by_bus = tx_utils.gens_by_bus(buses, gens)

    model = pe.ConcreteModel()

    ### declare (and fix) the loads at the buses
    bus_p_loads, _ = tx_utils.dict_of_bus_loads(buses, loads)

    libbus.declare_var_pl(model, bus_attrs['names'], initialize=bus_p_loads)
    model.pl.fix()

    ### declare the fixed shunts at the buses
    _, bus_gs_fixed_shunts = tx_utils.dict_of_bus_fixed_shunts(buses, shunts)

    ### declare the polar voltages
    va_bounds = {k: (-pi, pi) for k in bus_attrs['va']}
    libbus.declare_var_va(model, bus_attrs['names'], initialize=bus_attrs['va'],
                          bounds=va_bounds
                          )

    dva_initialize = {k: 0.0 for k in branch_attrs['names']}
    libbranch.declare_var_dva(model, branch_attrs['names'],
                              initialize=dva_initialize
                              )

    ### include the feasibility slack for the bus balances
    p_rhs_kwargs = {}
    penalty_expr = None
    if include_feasibility_slack:
        p_rhs_kwargs, penalty_expr = _include_feasibility_slack(model, bus_attrs, gen_attrs, bus_p_loads)

    ### fix the reference bus
    ref_bus = md.data['system']['reference_bus']
    ref_angle = md.data['system']['reference_bus_angle']
    model.va[ref_bus].fix(radians(ref_angle))

    ### declare the generator real power
    pg_init = {k: (gen_attrs['p_min'][k] + gen_attrs['p_max'][k]) / 2.0 for k in gen_attrs['pg']}
    libgen.declare_var_pg(model, gen_attrs['names'], initialize=pg_init,
                          bounds=zip_items(gen_attrs['p_min'], gen_attrs['p_max'])
                          )

    ### declare the current flows in the branches
    vr_init = {k: bus_attrs['vm'][k] * pe.cos(bus_attrs['va'][k]) for k in bus_attrs['vm']}
    vj_init = {k: bus_attrs['vm'][k] * pe.sin(bus_attrs['va'][k]) for k in bus_attrs['vm']}
    p_max = {k: branches[k]['rating_long_term'] for k in branches.keys()}
    pf_bounds = {k: (-p_max[k],p_max[k]) for k in branches.keys()}
    pf_init = dict()
    for branch_name, branch in branches.items():
        from_bus = branch['from_bus']
        to_bus = branch['to_bus']
        y_matrix = tx_calc.calculate_y_matrix_from_branch(branch)
        ifr_init = tx_calc.calculate_ifr(vr_init[from_bus], vj_init[from_bus], vr_init[to_bus],
                                         vj_init[to_bus], y_matrix)
        ifj_init = tx_calc.calculate_ifj(vr_init[from_bus], vj_init[from_bus], vr_init[to_bus],
                                         vj_init[to_bus], y_matrix)
        pf_init[branch_name] = tx_calc.calculate_p(ifr_init, ifj_init, vr_init[from_bus], vj_init[from_bus])
    pfl_bounds = {k: (0,p_max[k]**2) for k in branches.keys()}
    pfl_init = {k: 0 for k in branches.keys()}

    libbranch.declare_var_pf(model=model,
                             index_set=branch_attrs['names'],
                             initialize=pf_init,
                             bounds=pf_bounds
                             )

    libbranch.declare_var_pfl(model=model,
                              index_set=branch_attrs['names'],
                              initialize=pfl_init,
                              bounds=pfl_bounds
                             )

    ### declare the angle difference constraint
    libbranch.declare_eq_branch_dva(model=model,
                                    index_set=branch_attrs['names'],
                                    branches=branches
                                    )

    ### declare the branch power flow approximation constraints
    libbranch.declare_eq_branch_power_btheta_approx(model=model,
                                                    index_set=branch_attrs['names'],
                                                    branches=branches,
                                                    approximation_type=ApproximationType.BTHETA_LOSSES
                                                    )

    ### declare the branch power loss approximation constraints
    libbranch.declare_eq_branch_loss_btheta_approx(model=model,
                                                    index_set=branch_attrs['names'],
                                                    branches=branches,
                                                    relaxation_type=relaxation_type
                                                    )

    ### declare the p balance
    libbus.declare_eq_p_balance_dc_approx(model=model,
                                          index_set=bus_attrs['names'],
                                          bus_p_loads=bus_p_loads,
                                          gens_by_bus=gens_by_bus,
                                          bus_gs_fixed_shunts=bus_gs_fixed_shunts,
                                          inlet_branches_by_bus=inlet_branches_by_bus,
                                          outlet_branches_by_bus=outlet_branches_by_bus,
                                          approximation_type=ApproximationType.BTHETA_LOSSES,
                                          **p_rhs_kwargs
                                          )

    ### declare the real power flow limits
    libbranch.declare_ineq_p_branch_thermal_lbub(model=model,
                                                 index_set=branch_attrs['names'],
                                                 branches=branches,
                                                 p_thermal_limits=p_max,
                                                 approximation_type=ApproximationType.BTHETA
                                                 )

    ### declare angle difference limits on interconnected buses
    if include_angle_diff_limits:
        libbranch.declare_ineq_angle_diff_branch_lbub(model=model,
                                                      index_set=branch_attrs['names'],
                                                      branches=branches,
                                                      coordinate_type=CoordinateType.POLAR
                                                      )

    ### declare the generator cost objective
    libgen.declare_expression_pgqg_operating_cost(model=model,
                                                  index_set=gen_attrs['names'],
                                                  p_costs=gen_attrs['p_cost']
                                                  )

    obj_expr = sum(model.pg_operating_cost[gen_name] for gen_name in model.pg_operating_cost)
    if include_feasibility_slack:
        obj_expr += penalty_expr

    model.obj = pe.Objective(expr=obj_expr)

    return model, md