예제 #1
0
    def setUp(self):
        self.m = ConcreteModel()
        self.m.z = Var(range(3), domain=Reals, initialize=2.)
        self.m.x = Var(range(2), initialize=2.)
        self.m.x[1] = 1.0

        def blackbox(a, b):
            return sin(a - b)

        def grad_blackbox(args, fixed):
            a, b = args[:2]
            return [cos(a - b), -cos(a - b)]

        self.m.bb = ExternalFunction(blackbox, grad_blackbox)

        self.m.obj = Objective(expr=(self.m.z[0] - 1.0)**2 +
                               (self.m.z[0] - self.m.z[1])**2 +
                               (self.m.z[2] - 1.0)**2 +
                               (self.m.x[0] - 1.0)**4 + (self.m.x[1] - 1.0)**6)
        self.m.c1 = Constraint(expr=(self.m.x[0] * self.m.z[0]**2 +
                                     self.m.bb(self.m.x[0], self.m.x[1]) == 2 *
                                     sqrt(2.0)))
        self.m.c2 = Constraint(expr=self.m.z[2]**4 * self.m.z[1]**2 +
                               self.m.z[1] == 8 + sqrt(2.0))
        self.config = _trf_config()
        self.ext_fcn_surrogate_map_rule = lambda comp, ef: 0
        self.interface = TRFInterface(self.m,
                                      [self.m.z[0], self.m.z[1], self.m.z[2]],
                                      self.ext_fcn_surrogate_map_rule,
                                      self.config)
예제 #2
0
    def log_fug_phase_comp_Tdew(blk, p, j, pp):
        pobj = blk.params.get_phase(p)
        ctype = pobj._cubic_type
        cname = pobj.config.equation_of_state_options["type"].name

        if pobj.is_liquid_phase():
            x = blk._mole_frac_tdew
            xidx = pp
        elif pobj.is_vapor_phase():
            x = blk.mole_frac_comp
            xidx = ()
        else:
            raise BurntToast("{} non-vapor or liquid phase called for bubble "
                             "temperature calculation. This should never "
                             "happen, so please contact the IDAES developers "
                             "with this bug.".format(blk.name))

        def a(k):
            cobj = blk.params.get_component(k)
            fw = getattr(blk, cname + "_fw")[k]
            return (
                EoS_param[ctype]['omegaA'] *
                ((Cubic.gas_constant(blk) * cobj.temperature_crit)**2 /
                 cobj.pressure_crit) *
                ((1 + fw *
                  (1 - sqrt(blk.temperature_dew[pp] / cobj.temperature_crit)))
                 **2))

        kappa = getattr(blk.params, cname + "_kappa")
        am = sum(
            sum(x[xidx, i] * x[xidx, j] * sqrt(a(i) * a(j)) * (1 - kappa[i, j])
                for j in blk.component_list) for i in blk.component_list)

        b = getattr(blk, cname + "_b")
        bm = sum(x[xidx, i] * b[i] for i in blk.component_list)

        A = am * blk.pressure / (Cubic.gas_constant(blk) *
                                 blk.temperature_dew[pp])**2
        B = bm * blk.pressure / (Cubic.gas_constant(blk) *
                                 blk.temperature_dew[pp])

        delta = (2 * sqrt(a(j)) / am * sum(x[xidx, i] * sqrt(a(i)) *
                                           (1 - kappa[j, i])
                                           for i in blk.component_list))

        f = getattr(blk, "_" + cname + "_ext_func_param")
        if pobj.is_vapor_phase():
            proc = getattr(blk, "_" + cname + "_proc_Z_vap")
        elif pobj.is_liquid_phase():
            proc = getattr(blk, "_" + cname + "_proc_Z_liq")

        Z = proc(f, A, B)

        if pobj.is_vapor_phase():
            mole_frac = blk.mole_frac_comp[j]
        else:
            mole_frac = blk._mole_frac_tdew[pp[0], pp[1], j]

        return (_log_fug_coeff_method(A, b[j], bm, B, delta, Z, ctype) +
                log(mole_frac) + log(blk.pressure / blk.pressure._units))
예제 #3
0
    def setUp(self):
        # Borrowed this test model from the trust region tests
        m = ConcreteModel()
        m.z = Var(range(3), domain=Reals, initialize=2.)
        m.x = Var(range(4), initialize=2.)
        m.x[1] = 1.0
        m.x[2] = 0.0
        m.x[3] = None

        m.b1 = Block()
        m.b1.e1 = Expression(expr=m.x[0] + m.x[1])
        m.b1.e2 = Expression(expr=m.x[0]/m.x[2])
        m.b1.e3 = Expression(expr=m.x[3]*m.x[1])
        m.b1.e4 = Expression(expr=log(m.x[2]))
        m.b1.e5 = Expression(expr=log(m.x[2] - 2))

        def blackbox(a,b):
            return sin(a-b)
        self.bb = ExternalFunction(blackbox)

        m.obj = Objective(
            expr=(m.z[0]-1.0)**2 + (m.z[0]-m.z[1])**2 + (m.z[2]-1.0)**2 \
                + (m.x[0]-1.0)**4 + (m.x[1]-1.0)**6 # + m.bb(m.x[0],m.x[1])
            )
        m.c1 = Constraint(expr=m.x[0] * m.z[0]**2 + self.bb(m.x[0],m.x[1]) == 2*sqrt(2.0))
        m.c2 = Constraint(expr=m.z[2]**4 * m.z[1]**2 + m.z[1] == 8+sqrt(2.0))
        m.c3 = Constraint(expr=m.x[1] == 3)
        m.c4 = Constraint(expr=0 == 3/m.x[2])
        m.c5 = Constraint(expr=0 == log(m.x[2]))
        m.c6 = Constraint(expr=0 == log(m.x[2]-4))
        m.c7 = Constraint(expr=0 == log(m.x[3]))
        m.p1 = Param(mutable=True, initialize=1)
        m.c8 = Constraint(expr = m.x[1] <= 1/m.p1)
        m.p1 = 0
        self.m = m.clone()
예제 #4
0
 def test_nested_disjunctions_max_binary(self):
     m = models.makeNestedNonlinearModel()
     SolverFactory('gdpopt').solve(m, strategy='LOA', mip_solver=mip_solver,
                                   nlp_solver=nlp_solver,
                                   init_strategy='max_binary')
     self.assertAlmostEqual(value(m.x), sqrt(2)/2)
     self.assertAlmostEqual(value(m.y), sqrt(2)/2)
예제 #5
0
 def rule_heat_below_pinch(blk, p):
     return (blk.QAc[p] == sum(
         blk.Theta[i] * (0.5 * ((blk.Tout[i] - blk.T_[p] + DTmin) + sqrt(
             (blk.Tout[i] - blk.T_[p] + DTmin)**2 + eps)) - 0.5 *
                         ((blk.Tin[i] - blk.T_[p] + DTmin) + sqrt(
                             (blk.Tin[i] - blk.T_[p] + DTmin)**2 + eps)))
         for i in heatingdict.keys()))
예제 #6
0
    def setUp(self):

        self.m = ConcreteModel()
        self.m.z = Var(range(3), domain=Reals, initialize=2.)
        self.m.x = Var(range(2), initialize=2.)
        self.m.x[1] = 1.0

        def blackbox(a, b):
            return sin(a - b)

        def grad_blackbox(args, fixed):
            a, b = args[:2]
            return [cos(a - b), -cos(a - b)]

        self.m.bb = ExternalFunction(blackbox, grad_blackbox)

        self.m.obj = Objective(expr=(self.m.z[0] - 1.0)**2 +
                               (self.m.z[0] - self.m.z[1])**2 +
                               (self.m.z[2] - 1.0)**2 +
                               (self.m.x[0] - 1.0)**4 + (self.m.x[1] - 1.0)**6)
        self.m.c1 = Constraint(expr=(self.m.x[0] * self.m.z[0]**2 +
                                     self.m.bb(self.m.x[0], self.m.x[1]) == 2 *
                                     sqrt(2.0)))
        self.m.c2 = Constraint(expr=self.m.z[2]**4 * self.m.z[1]**2 +
                               self.m.z[1] == 8 + sqrt(2.0))
        self.decision_variables = [self.m.z[0], self.m.z[1], self.m.z[2]]
예제 #7
0
 def rule_heat_above_pinch(blk, p):
     return (blk.QAh[p] == sum(
         blk.Theta[i] * (0.5 * ((blk.Tin[i] - blk.T_[p]) + sqrt(
             (blk.Tin[i] - blk.T_[p])**2 + eps)) - 0.5 *
                         ((blk.Tout[i] - blk.T_[p]) + sqrt(
                             (blk.Tout[i] - blk.T_[p])**2 + eps)))
         for i in coolingdict.keys()))
예제 #8
0
    def test_fix_then_solve(self):
        # This is a test of the expected use case. We have a (square)
        # subsystem that we can solve easily after fixing and deactivating
        # certain variables and constraints.

        m = _make_simple_model()
        ipopt = pyo.SolverFactory("ipopt")

        # Initialize to avoid converging infeasible due to bad pivots
        m.v1.set_value(1.0)
        m.v2.set_value(1.0)
        m.v3.set_value(1.0)
        m.v4.set_value(2.0)

        with TemporarySubsystemManager(to_fix=[m.v3, m.v4],
                                       to_deactivate=[m.con1]):
            # Solve the subsystem with m.v1, m.v2 unfixed and
            # m.con2, m.con3 inactive.
            ipopt.solve(m)

        # Have solved model to expected values
        self.assertAlmostEqual(m.v1.value, pyo.sqrt(7.0), delta=1e-8)
        self.assertAlmostEqual(m.v2.value,
                               pyo.sqrt(4.0 - pyo.sqrt(7.0)),
                               delta=1e-8)
예제 #9
0
    def test_solve_subsystem(self):
        # This is a test of this function's intended use. We extract a
        # subsystem then solve it without altering the rest of the model.
        m = _make_simple_model()
        ipopt = pyo.SolverFactory("ipopt")

        m.v5 = pyo.Var(initialize=1.0)
        m.c4 = pyo.Constraint(expr=m.v5 == 5.0)

        cons = [m.con2, m.con3]
        vars = [m.v1, m.v2]
        block = create_subsystem_block(cons, vars)

        m.v3.fix(1.0)
        m.v4.fix(2.0)

        # Initialize to avoid converging infeasible due to bad pivots
        m.v1.set_value(1.0)
        m.v2.set_value(1.0)
        ipopt.solve(block)

        # Have solved model to expected values
        self.assertAlmostEqual(m.v1.value, pyo.sqrt(7.0), delta=1e-8)
        self.assertAlmostEqual(m.v2.value, pyo.sqrt(4.0-pyo.sqrt(7.0)),
                delta=1e-8)

        # Rest of model has not changed
        self.assertEqual(m.v5.value, 1.0)
예제 #10
0
def add_data_match_obj(model, df_meta, bin_stdev):
    @model.Expression(model.data_param.index_set())
    def err_abs(b, tag):
        return df_meta[tag]["reference"][0] - model.data_param[tag]

    @model.Expression(model.data_param.index_set())
    def err_rel(b, tag):
        return model.err_abs[tag] / model.data_param[tag]

    @model.Expression(model.data_param.index_set())
    def err_pct(b, tag):
        return model.err_rel[tag] * 100

    @model.Expression(model.data_param.index_set())
    def err_stdev(b, tag):
        return model.err_abs[tag] / bin_stdev[model.data_bin][tag]

    model.obj_weight = pyo.Param(model.data_param.index_set(),
                                 initialize=1,
                                 mutable=True)

    n = len(model.data_param.index_set())
    model.obj_datarec = pyo.Objective(expr=pyo.sqrt(
        sum(model.obj_weight[t] * (model.err_stdev[t])**2
            for t in model.data_param) / n))
    model.obj_expr = pyo.Expression(expr=pyo.sqrt(
        sum(model.obj_weight[t] * (model.err_stdev[t])**2
            for t in model.data_param) / n))
예제 #11
0
 def rule_delta(m, p, i):
     # See pg. 145 in Properties of Gases and Liquids
     a = getattr(m, cname + "_a")
     am = getattr(m, cname + "_am")
     kappa = getattr(m.params, cname + "_kappa")
     return (2 * sqrt(a[i]) / am[p] *
             sum(m.mole_frac_phase_comp[p, j] * sqrt(a[j]) *
                 (1 - kappa[i, j]) for j in b.components_in_phase(p)))
예제 #12
0
    def test_with_solve(self):
        m = _make_simple_model()
        ipopt = pyo.SolverFactory("ipopt")

        n_scenario = 2
        input_values = ComponentMap([
            (m.v3, [1.3, 2.3]),
            (m.v4, [1.4, 2.4]),
            ])

        _v1_val_1 = pyo.sqrt(3*1.4+1.3)
        _v1_val_2 = pyo.sqrt(3*2.4+2.3)
        _v2_val_1 = pyo.sqrt(2*1.4 - _v1_val_1)
        _v2_val_2 = pyo.sqrt(2*2.4 - _v1_val_2)
        output_values = ComponentMap([
            (m.v1, [_v1_val_1, _v1_val_2]),
            (m.v2, [_v2_val_1, _v2_val_2]),
            ])

        to_fix = [m.v3, m.v4]
        to_deactivate = [m.con1]
        to_reset = [m.v1, m.v2]

        # Initialize values so we don't fail due to bad initialization
        m.v1.set_value(1.0)
        m.v2.set_value(1.0)

        with ParamSweeper(n_scenario, input_values, output_values,
                to_fix=to_fix,
                to_deactivate=to_deactivate,
                to_reset=to_reset,
                ) as sweeper:
            self.assertFalse(m.v1.fixed)
            self.assertFalse(m.v2.fixed)
            self.assertTrue(m.v3.fixed)
            self.assertTrue(m.v4.fixed)
            self.assertFalse(m.con1.active)
            self.assertTrue(m.con2.active)
            self.assertTrue(m.con3.active)
            for i, (inputs, outputs) in enumerate(sweeper):
                ipopt.solve(m)

                for var, val in inputs.items():
                    # These values should not have been altered.
                    # I believe exact equality should be appropriate here.
                    self.assertEqual(var.value, val)
                    self.assertEqual(var.value, input_values[var][i])

                for var, val in outputs.items():
                    self.assertAlmostEqual(var.value, val, delta=1e-8)
                    self.assertAlmostEqual(var.value, output_values[var][i],
                            delta=1e-8)

        # Values have been reset after exit.
        self.assertIs(m.v1.value, 1.0)
        self.assertIs(m.v2.value, 1.0)
        self.assertIs(m.v3.value, None)
        self.assertIs(m.v4.value, None)
예제 #13
0
 def rule_delta_eq(m, p1, p2, p3, i):
     # See pg. 145 in Properties of Gases and Liquids
     a = getattr(m, "_" + cname + "_a_eq")
     am = getattr(m, "_" + cname + "_am_eq")
     kappa = getattr(m.params, cname + "_kappa")
     return (
         2 * sqrt(a[p1, p2, i]) / am[p1, p2, p3] *
         sum(m.mole_frac_phase_comp[p3, j] * sqrt(a[p1, p2, j]) *
             (1 - kappa[i, j]) for j in m.components_in_phase(p3)))
예제 #14
0
 def Theta_(blk, i):
     if i in heatingdict.keys():
         return (Q[i] / (0.5 * ((blk.Tout[i] - blk.Tin[i] +
                                 (EpsT)) + sqrt((blk.Tout[i] - blk.Tin[i] -
                                                 (EpsT))**2 + eps))))
     else:
         return (Q[i] /
                 (-0.5 * ((-(blk.Tout[i] - blk.Tin[i]) - (-EpsT)) + sqrt((
                     (-EpsT) - (blk.Tout[i] - blk.Tin[i]))**2 + eps))))
예제 #15
0
def get_pyomo_model():
    m = aml.ConcreteModel()

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

    m.c0 = aml.Constraint(expr=aml.sqrt(m.x) >= 0)
    m.c1 = aml.Constraint(expr=aml.sqrt(m.y) >= 0)
    m.c2 = aml.Constraint(expr=aml.sqrt(m.z) >= 0)
    m.o = aml.Objective(expr=aml.sqrt(m.x))
    return m
예제 #16
0
def get_pyomo_model():
    m = aml.ConcreteModel()

    N = 4
    NP = 100
    PI_2 = 2.0 * math.atan(1.0)
    X = [1.0, 0.0, 0.0, 0.5]
    Y = [0.0, 1.0, -1.0, 0.0]

    m.I = range(N)

    m.v1 = aml.Var(initialize=-40.0)
    m.w1 = aml.Var(initialize=5.0)
    m.d = aml.Var(bounds=(1e-8, None), initialize=1.0)
    m.a = aml.Var(bounds=(1.0, None), initialize=2.0)
    m.t = aml.Var(bounds=(0.0, 6.2831852), initialize=1.5)
    m.r = aml.Var(bounds=(0.39, None), initialize=0.75)
    m.f = aml.Var()
    m.s1 = aml.Var(bounds=(-0.99, 0.99))
    m.s2 = aml.Var(bounds=(-0.99, 0.99))

    def eq_1(m, i):
        return ((m.v1 + m.a * m.d * aml.cos(m.t) - X[i])**2 +
                (m.w1 + m.a * m.d * aml.sin(m.t) - Y[i])**2 -
                (m.d + m.r)**2 <= 0)

    m.eq_1 = aml.Constraint(m.I, rule=eq_1)

    def eq_2(m, i):
        return (m.v1 - X[i])**2 + (m.w1 - Y[i])**2 - (m.a * m.d +
                                                      m.r)**2 >= 0.0

    m.eq_2 = aml.Constraint(m.I, rule=eq_2)

    m.add_1 = aml.Constraint(
        expr=(m.s1 == -((m.a + m.d)**2 - (m.a * m.d + m.r)**2 +
                        (m.d + m.r)**2) / (2 * (m.d + m.r) * m.a * m.d)))

    m.add_2 = aml.Constraint(
        expr=(m.s2 == ((m.a + m.d)**2 + (m.a * m.d + m.r)**2 -
                       (m.d + m.r)**2) / (2 * (m.a * m.d + m.r) * m.a * m.d)))

    m.obj = aml.Objective(
        expr=((m.d + m.r) * (m.d + m.r) *
              (PI_2 - aml.atan(m.s1 / (aml.sqrt(1 - m.s1 * m.s1)))) -
              (m.a * m.d + m.r) * (m.a * m.d + m.r) *
              (PI_2 - aml.atan(m.s2 / (aml.sqrt(1 - m.s2 * m.s2)))) +
              (m.d + m.r) * m.a * m.d *
              aml.sin((PI_2 - aml.atan(m.s1 / (aml.sqrt(1 - m.s1 * m.s1)))))))
    return m
예제 #17
0
 def test_nested_disjunctions_set_covering(self):
     # This test triggers the InfeasibleConstraintException in
     # deactivate_trivial_constraints in one of the subproblem solves during
     # initialization. This makes sure we get the correct answer anyway, as
     # there is a feasible solution.
     m = models.makeNestedNonlinearModel()
     SolverFactory('gdpopt').solve(m, strategy='LOA', mip_solver=mip_solver,
                                   nlp_solver=nlp_solver,
                                   init_strategy='set_covering')
     self.assertAlmostEqual(value(m.x), sqrt(2)/2)
     self.assertAlmostEqual(value(m.y), sqrt(2)/2)
     self.assertTrue(value(m.disj.disjuncts[1].indicator_var))
     self.assertFalse(value(m.disj.disjuncts[0].indicator_var))
     self.assertTrue(value(m.d1.indicator_var))
     self.assertFalse(value(m.d2.indicator_var))
예제 #18
0
    def __init__(self, *args, **kwargs):
        """Create the problem."""
        kwargs.setdefault('name', 'SimpleMINLP4')
        super(SimpleMINLP4, self).__init__(*args, **kwargs)
        m = self

        m.x = Var(domain=Reals, bounds=(1, 20), initialize=5.29)
        m.y = Var(domain=Integers, bounds=(1, 20), initialize=3)

        m.c1 = Constraint(expr=0.3 * (m.x - 8)**2 + 0.04 *
                          (m.y - 6)**4 + 0.1 * exp(2 * m.x) *
                          ((m.y)**(-4)) <= 56)
        m.c2 = Constraint(expr=1 / m.x + 1 / m.y - sqrt(m.x) * sqrt(m.y) <= -1)
        m.c3 = Constraint(expr=2 * m.x - 5 * m.y <= -1)

        m.obj = Objective(expr=-6 * m.x - m.y, sense=minimize)
예제 #19
0
def rule_am_default(m, cname, a, p, pp=()):
    k = getattr(m.params, cname + "_kappa")
    return sum(
        sum(m.mole_frac_phase_comp[p, i] * m.mole_frac_phase_comp[p, j] *
            sqrt(a[pp, i] * a[pp, j]) * (1 - k[i, j])
            for j in m.components_in_phase(p))
        for i in m.components_in_phase(p))
예제 #20
0
    def entr_mol_phase_comp(blk, p, j):
        pobj = blk.params.get_phase(p)
        if not (pobj.is_vapor_phase() or pobj.is_liquid_phase()):
            raise PropertyNotSupportedError(_invalid_phase_msg(blk.name, p))

        cname = pobj._cubic_type.name
        bm = getattr(blk, cname + "_bm")[p]
        B = getattr(blk, cname + "_B")[p]
        dadT = getattr(blk, cname + "_dadT")[p]
        Z = blk.compress_fact_phase[p]

        EoS_u = EoS_param[pobj._cubic_type]['u']
        EoS_w = EoS_param[pobj._cubic_type]['w']
        EoS_p = sqrt(EoS_u**2 - 4 * EoS_w)

        # See pg. 102 in Properties of Gases and Liquids
        return (((Cubic.gas_constant(blk) * safe_log(
            (Z - B) / Z, eps=1e-6) * bm * EoS_p + Cubic.gas_constant(blk) *
                  safe_log(Z * blk.params.pressure_ref /
                           (blk.mole_frac_phase_comp[p, j] * blk.pressure),
                           eps=1e-6) * bm * EoS_p + dadT * safe_log(
                               (2 * Z + B * (EoS_u + EoS_p)) /
                               (2 * Z + B * (EoS_u - EoS_p)),
                               eps=1e-6)) / (bm * EoS_p)) +
                get_method(blk, "entr_mol_ig_comp", j)(blk, cobj(blk, j),
                                                       blk.temperature))
예제 #21
0
    def enth_mol_phase(blk, p):
        pobj = blk.params.get_phase(p)
        if not (pobj.is_vapor_phase() or pobj.is_liquid_phase()):
            raise PropertyNotSupportedError(_invalid_phase_msg(blk.name, p))

        cname = pobj._cubic_type.name
        am = getattr(blk, cname + "_am")[p]
        bm = getattr(blk, cname + "_bm")[p]
        B = getattr(blk, cname + "_B")[p]
        dadT = getattr(blk, cname + "_dadT")[p]
        Z = blk.compress_fact_phase[p]

        EoS_u = EoS_param[pobj._cubic_type]['u']
        EoS_w = EoS_param[pobj._cubic_type]['w']
        EoS_p = sqrt(EoS_u**2 - 4 * EoS_w)

        # Derived from equation on pg. 120 in Properties of Gases and Liquids
        return (((blk.temperature * dadT - am) * safe_log(
            (2 * Z + B * (EoS_u + EoS_p)) / (2 * Z + B * (EoS_u - EoS_p)),
            eps=1e-6) + Cubic.gas_constant(blk) * blk.temperature *
                 (Z - 1) * bm * EoS_p) / (bm * EoS_p) +
                sum(blk.mole_frac_phase_comp[p, j] *
                    get_method(blk, "enth_mol_ig_comp", j)
                    (blk, cobj(blk, j), blk.temperature)
                    for j in blk.components_in_phase(p)))
예제 #22
0
    def return_expression(blk, phase):
        pobj = blk.params.get_phase(phase)

        theta_ij = {}
        o = dict()
        for (i, j) in enumerate(blk.component_list, 1):
            o[i] = j

        for i in range(1, len(blk.component_list)):
            for j in range(i + 1, len(blk.component_list) + 1):
                theta_ij[o[i], o[j]] = (
                    (1 +
                     2*sqrt(visc_d_comp(blk, pobj, o[i]) /
                            visc_d_comp(blk, pobj, o[j])) *
                     (blk.mw_comp[o[j]]/blk.mw_comp[o[i]])**0.25 +
                     visc_d_comp(blk, pobj, o[i]) /
                     visc_d_comp(blk, pobj, o[j]) *
                     (blk.mw_comp[o[j]]/blk.mw_comp[o[i]])**0.5) /
                    (8 + 8*blk.mw_comp[o[i]]/blk.mw_comp[o[j]])**0.5)

                theta_ij[o[j], o[i]] = (
                    visc_d_comp(blk, pobj, o[j])/visc_d_comp(blk, pobj, o[i]) *
                    blk.mw_comp[o[i]]/blk.mw_comp[o[j]] *
                    theta_ij[o[i], o[j]])

        for i in blk.component_list:
            for j in blk.component_list:
                if i == j:
                    theta_ij[i, j] = 1

        return sum(blk.mole_frac_comp[i]*visc_d_comp(blk, pobj, i) /
                   sum(blk.mole_frac_comp[j]*theta_ij[i, j]
                       for j in blk.component_list)
                   for i in blk.component_list)
예제 #23
0
def below_threshold(x, i, t, mean=True):
    """Compute the CDF of the lognormal distribution at x using an approximation of
    the error function:

    .. math::

        erf(x) \approx \tanh(\sqrt \pi \log x)

    Parameters
    ----------
    x : numeric
       threshold income
    i : numeric
       mean income (per capita)
    t : numeric or Pyomo variable
       theil coefficient
    mean : bool, default: True
       treat income as mean income
    """
    # see
    # https://math.stackexchange.com/questions/321569/approximating-the-error-function-erf-by-analytical-functions
    sigma2 = 2 * t  # t is var
    # f(var), adjust for mean income vs. median
    mu = math.log(i)
    if mean:
        mu -= sigma2 / 2
    # f(var), argument for error function
    arg = (math.log(x) - mu) / mo.sqrt(2 * sigma2)
    # coefficient for erf approximation
    k = math.pi**0.5 * math.log(2)
    # definition of cdf with tanh(kx) approximating erf(x)
    return 0.5 + 0.5 * mo.tanh(k * arg)
예제 #24
0
    def enth_mol_phase(blk, p):
        pobj = blk.params.get_phase(p)

        cname = pobj._cubic_type.name
        am = getattr(blk, cname + "_am")[p]
        bm = getattr(blk, cname + "_bm")[p]
        B = getattr(blk, cname + "_B")[p]
        dam_dT = getattr(blk, cname + "_dam_dT")[p]
        Z = blk.compress_fact_phase[p]
        R = Cubic.gas_constant(blk)
        T = blk.temperature

        EoS_u = EoS_param[pobj._cubic_type]['u']
        EoS_w = EoS_param[pobj._cubic_type]['w']
        EoS_p = sqrt(EoS_u**2 - 4 * EoS_w)

        enth_ideal = sum(blk.mole_frac_phase_comp[p, j] *
                         get_method(blk, "enth_mol_ig_comp", j)
                         (blk, cobj(blk, j), blk.temperature)
                         for j in blk.components_in_phase(p))

        # Derived from equation on pg. 120 in Properties of Gases and Liquids
        enth_departure = (R * T * (Z - 1) + (T * dam_dT - am) /
                          (bm * EoS_p) * safe_log(
                              (2 * Z + B * (EoS_u + EoS_p)) /
                              (2 * Z + B * (EoS_u - EoS_p)),
                              eps=eps_SL))
        return enth_ideal + enth_departure
예제 #25
0
 def hpool_eqn(b, t):
     return (1e-4*b.hpool[t]*sqrt(pyunits.convert(
                 b.control_volume.properties_in[0].mw,
                 to_units=pyunits.g/pyunits.mol)) *
             (-log10(b.reduced_pressure[t]))**(0.55) ==
             1e-4*55.0*b.reduced_pressure[t]**0.12 *
             b.heat_flux_conv[t]**0.67)
예제 #26
0
    def entr_mol_phase(blk, p):
        pobj = blk.params.get_phase(p)

        cname = pobj._cubic_type.name
        bm = getattr(blk, cname + "_bm")[p]
        B = getattr(blk, cname + "_B")[p]
        dam_dT = getattr(blk, cname + "_dam_dT")[p]
        Z = blk.compress_fact_phase[p]

        EoS_u = EoS_param[pobj._cubic_type]['u']
        EoS_w = EoS_param[pobj._cubic_type]['w']
        EoS_p = sqrt(EoS_u**2 - 4 * EoS_w)

        R = Cubic.gas_constant(blk)

        entr_ideal_gas = -R * safe_log(blk.pressure / blk.params.pressure_ref,
                                       eps=eps_SL)
        for j in blk.components_in_phase(p):
            entr_j = get_method(blk, "entr_mol_ig_comp", j)(blk, cobj(blk, j),
                                                            blk.temperature)
            xj = blk.mole_frac_phase_comp[p, j]
            log_xj = blk.log_mole_frac_phase_comp[p, j]

            entr_ideal_gas += xj * (entr_j - R * log_xj)

        # See pg. 102 in Properties of Gases and Liquids
        # or pg. 208 of Sandler, 4th Ed.
        entr_departure = (R * safe_log(
            (Z - B), eps=eps_SL) + dam_dT / (bm * EoS_p) * safe_log(
                (2 * Z + B * (EoS_u + EoS_p)) / (2 * Z + B * (EoS_u - EoS_p)),
                eps=eps_SL))

        return entr_ideal_gas + entr_departure
예제 #27
0
 def steam_entering_velocity(b, t):
     # 1.414 = 44.72/sqrt(1000) for SI if comparing to Liese (2014)
     # b.delta_enth_isentropic[t] = -(hin - hiesn), the mw converts
     # enthalpy to a mass basis
     return 1.414 * sqrt(
         -(1 - b.blade_reaction) * b.delta_enth_isentropic[t] /
         b.control_volume.properties_in[t].mw * self.eff_nozzle)
예제 #28
0
    def test_sqrt_function(self):
        m = ConcreteModel()
        m.x = Var()

        e = differentiate(sqrt(m.x), wrt=m.x)
        self.assertTrue(e.is_expression_type())
        self.assertEqual(s(e), s(0.5 * m.x**-0.5))
예제 #29
0
 def rule_tc(b, p):
     L0 = self.config.parameters.tc_L0
     L1 = self.config.parameters.tc_L1
     return (sqrt(1.0 / tau) / sum(L0[i] * tau**i for i in L0) *
             exp(delta[p] * sum(
                 (tau - 1)**i * sum(L1[i, j] * (delta[p] - 1)**j
                                    for j in range(0, 6))
                 for i in range(0, 5))))
예제 #30
0
 def rule_mu(b, p):
     H0 = self.config.parameters.visc_H0
     H1 = self.config.parameters.visc_H1
     return (1e-4 * sqrt(1.0 / tau) / sum(H0[i] * tau**i for i in H0) *
             exp(delta[p] * sum(
                 (tau - 1)**i * sum(H1[i, j] * (delta[p] - 1)**j
                                    for j in range(0, 7))
                 for i in range(0, 6))))
예제 #31
0
    def test_substitute_casadi_intrinsic2(self):

        m = self.m
        m.y = Var()
        t = IndexTemplate(m.t)

        e = sin(m.dv[t]) + log(m.v[t]) + sqrt(m.y) + m.v[t] + t
        templatemap = {}

        e3 = substitute_pyomo2casadi(e, templatemap)
        self.assertIs(e3.arg(0)._fcn, casadi.sin)
        self.assertIs(e3.arg(1)._fcn, casadi.log)
        self.assertIs(e3.arg(2)._fcn, casadi.sqrt)

        m.del_component('y')
예제 #32
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)
예제 #33
0
파일: test_fbbt.py 프로젝트: mskarha/pyomo
    def test_sqrt(self):
        m = pe.ConcreteModel()
        m.x = pe.Var()
        m.y = pe.Var()
        m.c = pe.Constraint(expr=pe.sqrt(m.x) == m.y)

        fbbt(m)
        self.assertEqual(m.x.lb, 0)
        self.assertEqual(m.x.ub, None)
        self.assertEqual(m.y.lb, 0)
        self.assertEqual(m.y.ub, None)

        m.x.setlb(None)
        m.x.setub(None)
        m.y.setlb(-5)
        m.y.setub(-1)
        with self.assertRaises(InfeasibleConstraintException):
            fbbt(m)

        m.x.setlb(None)
        m.x.setub(None)
        m.y.setub(0)
        m.y.setlb(None)
        fbbt(m)
        self.assertAlmostEqual(m.x.lb, 0)
        self.assertAlmostEqual(m.x.ub, 0)

        m.x.setlb(None)
        m.x.setub(None)
        m.y.setub(2)
        m.y.setlb(1)
        fbbt(m)
        self.assertAlmostEqual(m.x.lb, 1)
        self.assertAlmostEqual(m.x.ub, 4)

        m.x.setlb(None)
        m.x.setub(0)
        m.y.setlb(None)
        m.y.setub(None)
        fbbt(m)
        self.assertAlmostEqual(m.y.lb, 0)
        self.assertAlmostEqual(m.y.ub, 0)