Exemplo n.º 1
0
def test_get_odesys_3():
    M = u.molar
    s = u.second
    mol = u.mol
    m = u.metre
    substances = list(map(Substance, 'H2O H+ OH-'.split()))
    dissociation = Reaction({'H2O': 1}, {'H+': 1, 'OH-': 1}, 2.47e-5/s)
    recombination = Reaction({'H+': 1, 'OH-': 1}, {'H2O': 1}, 1.37e11/M/s)
    rsys = ReactionSystem([dissociation, recombination], substances)
    odesys = get_odesys(
        rsys, include_params=True, unit_registry=SI_base_registry,
        output_conc_unit=M)[0]
    c0 = {'H2O': 55.4*M, 'H+': 1e-7*M, 'OH-': 1e-4*mol/m**3}
    x, y, p = odesys.to_arrays(-42*u.second,
                               rsys.as_per_substance_array(c0, unit=M), ())
    fout = odesys.f_cb(x, y, p)

    time_unit = get_derived_unit(SI_base_registry, 'time')
    conc_unit = get_derived_unit(SI_base_registry, 'concentration')

    r1 = to_unitless(55.4*2.47e-5*M/s, conc_unit/time_unit)
    r2 = to_unitless(1e-14*1.37e11*M/s, conc_unit/time_unit)
    assert np.all(abs(fout[:, 0] - r2 + r1)) < 1e-10
    assert np.all(abs(fout[:, 1] - r1 + r2)) < 1e-10
    assert np.all(abs(fout[:, 2] - r1 + r2)) < 1e-10
Exemplo n.º 2
0
def test_MassAction__expression():
    class GibbsExpr(Expr):
        parameter_keys = ("temperature", )
        argument_names = tuple("dS_over_R dCp_over_R dH_over_R Tref".split())

        def __call__(self, variables, backend=patched_numpy, **kwargs):
            am = dict(
                zip(
                    self.argument_names,
                    map(simplified, self.all_args(variables, backend=backend)),
                ))
            (T, ) = self.all_params(variables, backend=backend)
            return (backend.exp(am["dS_over_R"]) *
                    (T / am["Tref"])**am["dCp_over_R"] *
                    backend.exp(-am["dH_over_R"] / T))

    GeNH3 = GibbsExpr(
        dict(
            dS_over_R=18.8 * u.cal / u.K / u.mol /
            default_constants.molar_gas_constant,  # NOQA
            dCp_over_R=52 * u.cal / u.K / u.mol /
            default_constants.molar_gas_constant,  # NOQA
            dH_over_R=-0.87e3 * u.cal / u.mol /
            default_constants.molar_gas_constant,  # NOQA
            Tref=298.15 * u.K,  # NOQA
        ))
    reac_prod = {"NH3": 1, "H2O": 1}, {"NH4+": 1, "OH-": 1}
    Equilibrium(*reac_prod, GeNH3).check_consistent_units(throw=True)
    Equilibrium(*reac_prod[::-1], 1 / GeNH3).check_consistent_units(throw=True)

    Ea = 40e3 * u.J / u.mol
    R = default_constants.molar_gas_constant
    A, Ea_over_R = 1.2e11 / u.molar**2 / u.second, Ea / R
    arrh = Arrhenius([A, Ea_over_R])
    ama = MassAction(arrh)

    ma_mul_expr = ama * GeNH3
    ma_div_expr = ama / GeNH3
    expr_mul_ma = GeNH3 * ama
    expr_div_ma = GeNH3 / ama
    assert all(
        isinstance(expr, MassAction)
        for expr in [ma_mul_expr, ma_div_expr, expr_mul_ma, expr_div_ma])

    Reaction(*reac_prod, ama).check_consistent_units(throw=True)
    Reaction(*reac_prod[::-1],
             42 * ma_div_expr).check_consistent_units(throw=True)
    Reaction(*reac_prod[::-1],
             42 / u.M / u.s / GeNH3).check_consistent_units(throw=True)

    varbls = {"temperature": 298.15 * u.K}
    r_ama, r_GeNH3 = ama.rate_coeff(varbls), GeNH3(varbls)
    assert allclose(ma_mul_expr.rate_coeff(varbls), r_ama * r_GeNH3)
    assert allclose(ma_div_expr.rate_coeff(varbls), r_ama / r_GeNH3)
    assert allclose(expr_mul_ma.rate_coeff(varbls), r_GeNH3 * r_ama)
    assert allclose(expr_div_ma.rate_coeff(varbls), r_GeNH3 / r_ama)
def get_rsys():
    r1 = Reaction({'A'}, {'B'},
                  MassAction([4. / 100], unique_keys=['k1']),
                  name='R1: A cons.')
    r2 = Reaction({'B', 'C'}, {'A', 'C'},
                  MassAction([1e4], unique_keys=['k2']),
                  name='R2: A reform.')
    r3 = Reaction({'B': 2}, {'B', 'C'},
                  MassAction([3e7], unique_keys=['k3']),
                  name='R3: C form.')
    return ReactionSystem([r1, r2, r3])
Exemplo n.º 4
0
def get_rsys():
    r1 = Reaction(
        {"A"}, {"B"}, MassAction([4.0 / 100], unique_keys=["k1"]), name="R1: A cons."
    )
    r2 = Reaction(
        {"B", "C"},
        {"A", "C"},
        MassAction([1e4], unique_keys=["k2"]),
        name="R2: A reform.",
    )
    r3 = Reaction(
        {"B": 2}, {"B", "C"}, MassAction([3e7], unique_keys=["k3"]), name="R3: C form."
    )
    return ReactionSystem([r1, r2, r3])
Exemplo n.º 5
0
def test_EyringMassAction():
    args = kB_h_times_exp_dS_R, dH_over_R, c0 = 1.2e11 / 273.15, 40e3 / 8, 1
    ama = MassAction(Eyring(args, ("Sfreq", "Hact")))
    rxn1 = Reaction({"A": 2, "B": 1}, {"C": 1}, ama, {"B": 1})
    T_ = "temperature"

    def ref(v):
        return (v.get("Sfreq", 1.2e11 / 273.15) * v[T_] *
                math.exp(-v.get("Hact", 40e3 / 8) / v[T_]) * v["B"] *
                v["A"]**2)

    for params in [(11.0, 13.0, 17.0, 311.2), (12, 8, 5, 270)]:
        var = dict(zip(["A", "B", "C", T_], params))
        ref_val = ref(var)
        assert abs((ama(var, reaction=rxn1) - ref_val) / ref_val) < 1e-14

    with pytest.raises(ValueError):
        MassAction(Eyring([1, 1, 1, 1, 1]))

    # assert ama.as_mass_action({T_: 273.15}).args[0] == 1.2e11*math.exp(-40e3/8/273.15)

    ama2 = MassAction(
        Eyring4([1.2e11 / 273, 40e3 / 8, 1.2, 1e3],
                ("Sfreq", "Hact", "Sref", "Href")))
    rxn2 = Reaction({"C": 1}, {"A": 2, "B": 2}, ama2)
    var2 = {"C": 29, "temperature": 273}

    def ref2(var):
        return (var["C"] * var.get("temperature", 273) *
                var.get("Sfreq", 1.2e11 / 273) / var.get("Sref", 1.2) *
                math.exp((var.get("Href", 1e3) - var.get("Hact", 5e3)) /
                         var.get("temperature", 273)))

    r2 = ref2(var2)
    assert abs((ama2(var2, reaction=rxn2) - r2) / r2) < 1e-14

    rsys = ReactionSystem([rxn1, rxn2])
    var3 = {
        "A": 11,
        "B": 13,
        "C": 17,
        "temperature": 298,
        "Sfreq": 1.2e11 / 298
    }
    rates = rsys.rates(var3)
    rf3 = ref(var3)
    rb3 = ref2(var3)
    ref_rates = {"A": 2 * (rb3 - rf3), "B": 2 * (rb3 - rf3), "C": rf3 - rb3}
    for k, v in ref_rates.items():
        assert abs((rates[k] - v) / v) < 1e-14
Exemplo n.º 6
0
def test_EyringMassAction():
    args = kB_h_times_exp_dS_R, dH_over_R, c0 = 1.2e11 / 273.15, 40e3 / 8, 1
    ama = MassAction(Eyring(args, ('Sfreq', 'Hact')))
    rxn1 = Reaction({'A': 2, 'B': 1}, {'C': 1}, ama, {'B': 1})
    T_ = 'temperature'

    def ref(v):
        return v.get('Sfreq', 1.2e11 / 273.15) * v[T_] * math.exp(
            -v.get('Hact', 40e3 / 8) / v[T_]) * v['B'] * v['A']**2

    for params in [(11., 13., 17., 311.2), (12, 8, 5, 270)]:
        var = dict(zip(['A', 'B', 'C', T_], params))
        ref_val = ref(var)
        assert abs((ama(var, reaction=rxn1) - ref_val) / ref_val) < 1e-14

    with pytest.raises(ValueError):
        MassAction(Eyring([1, 1, 1, 1, 1]))

    # assert ama.as_mass_action({T_: 273.15}).args[0] == 1.2e11*math.exp(-40e3/8/273.15)

    ama2 = MassAction(
        Eyring4([1.2e11 / 273, 40e3 / 8, 1.2, 1e3],
                ('Sfreq', 'Hact', 'Sref', 'Href')))
    rxn2 = Reaction({'C': 1}, {'A': 2, 'B': 2}, ama2)
    var2 = {'C': 29, 'temperature': 273}

    def ref2(var):
        return var['C'] * var.get('temperature', 273) * var.get(
            'Sfreq', 1.2e11 / 273) / var.get('Sref', 1.2) * math.exp(
                (var.get('Href', 1e3) - var.get('Hact', 5e3)) /
                var.get('temperature', 273))

    r2 = ref2(var2)
    assert abs((ama2(var2, reaction=rxn2) - r2) / r2) < 1e-14

    rsys = ReactionSystem([rxn1, rxn2])
    var3 = {
        'A': 11,
        'B': 13,
        'C': 17,
        'temperature': 298,
        'Sfreq': 1.2e11 / 298
    }
    rates = rsys.rates(var3)
    rf3 = ref(var3)
    rb3 = ref2(var3)
    ref_rates = {'A': 2 * (rb3 - rf3), 'B': 2 * (rb3 - rf3), 'C': rf3 - rb3}
    for k, v in ref_rates.items():
        assert abs((rates[k] - v) / v) < 1e-14
Exemplo n.º 7
0
def test_TPolyInLog10MassAction():
    r = TPolyInLog10MassAction([1, 2, 0.3, .2, .03, .004])
    Reaction({'A': 2, 'B': 1}, {'C': 1}, r, {'B': 1})
    res = r({'A': 11, 'B': 13, 'temperature': 298.15})
    _T = math.log10(298.15) - 2
    ref = .3 + .2 * _T + 0.03 * _T**2 + 0.004 * _T**3
    assert abs(res - ref * 13 * 11**2) < 1e-15
Exemplo n.º 8
0
def test_get_ode__Radiolytic__substitutions__units():
    rad = Radiolytic([2.4e-7 * u.mol / u.joule])
    rxn = Reaction({'A': 4, 'B': 1}, {'C': 3, 'D': 2}, rad)
    rsys = ReactionSystem([rxn], 'A B C D')
    g_dm3 = u.gram / u.decimetre**3
    kg_dm3 = u.kg / u.decimetre**3
    substance_rho = Density(
        [1 * kg_dm3, -1 * g_dm3 / u.kelvin, 273.15 * u.kelvin])
    odesys = get_odesys(rsys,
                        include_params=True,
                        unit_registry=SI_base_registry,
                        substitutions={'density': substance_rho})[0]
    conc = {
        'A': 3 * u.molar,
        'B': 5 * u.molar,
        'C': 11 * u.molar,
        'D': 13 * u.molar
    }
    x, y, p = odesys.to_arrays(-37 * u.second, conc, {
        'doserate': 0.4 * u.gray / u.second,
        'temperature': 298.15 * u.kelvin
    })
    fout = odesys.f_cb(x, y, p)
    r = 2.4e-7 * 0.4 * 0.975 * 1e3  # mol/m3/s
    ref = [-4 * r, -r, 3 * r, 2 * r]
    assert np.all(abs((fout - ref) / ref) < 1e-14)
Exemplo n.º 9
0
def test_TPiecewise():
    expr0 = ShiftedTPoly(
        [273.15 * u.K, 10 / u.molar / u.s, 0.1 / u.molar / u.s / u.K])
    expr1 = ShiftedTPoly([
        298.15 * u.K,
        12.5 / u.molar / u.s,
        0 / u.molar / u.s / u.K,
        2 / u.molar / u.s / u.K**2,
    ])
    pwma = MassAction(
        TPiecewise([273.15 * u.K, expr0, 298.15 * u.K, expr1, 373.15 * u.K]))
    r = Reaction({"e-(aq)": 2}, {"H2": 1, "OH-": 2}, inact_reac={"H2O": 2})
    res0 = pwma({
        "temperature": 293.15 * u.K,
        "e-(aq)": 1e-13 * u.molar
    },
                reaction=r)
    ref0 = 12 * 1e-26 * u.molar / u.s
    assert allclose(res0, ref0)
    assert not allclose(res0, 2 * ref0)

    res1 = pwma({
        "temperature": 300.15 * u.K,
        "e-(aq)": 2e-13 * u.molar
    },
                reaction=r)
    ref1 = 20.5 * 4e-26 * u.molar / u.s
    assert allclose(res1, ref1)
    assert not allclose(res1, ref1 / 2)
Exemplo n.º 10
0
def test_mk_Radiolytic():
    R1 = mk_Radiolytic()
    R2 = mk_Radiolytic()
    assert R1 is R2

    RABG = mk_Radiolytic("alpha", "beta", "gamma")
    rxn = Reaction({}, {"H": 2}, RABG([3, 5, 7], "ya yb yg".split()))
    rat = rxn.rate({
        "doserate_alpha": 11,
        "doserate_beta": 13,
        "doserate_gamma": 17,
        "density": 0.7,
    })
    assert abs(rat["H"] - 0.7 * 2 * (3 * 11 + 5 * 13 + 7 * 17)) < 1e-13
    assert RABG.parameter_keys == (
        "density",
        "doserate_alpha",
        "doserate_beta",
        "doserate_gamma",
    )
    assert RABG.argument_names == tuple("radiolytic_yield_%s" % k
                                        for k in "alpha beta gamma".split())
    assert rxn.param.unique_keys == ("ya", "yb", "yg")
    rat2 = rxn.rate({
        "doserate_alpha": 11,
        "doserate_beta": 13,
        "doserate_gamma": 17,
        "density": 0.7,
        "ya": 23,
        "yb": 29,
        "yg": 31,
    })
    assert abs(rat2["H"] - 0.7 * 2 * (23 * 11 + 29 * 13 + 31 * 17)) < 1e-13
Exemplo n.º 11
0
def test_create_odesys__ShiftedTPoly():
    rxn = Reaction({'A': 1, 'B': 1}, {'C': 3, 'D': 2}, 'k_bi', {'A': 3})
    rsys = ReactionSystem([rxn], 'A B C D')

    _k0, _k1, T0C = 10, 2, 273.15
    rate = MassAction(ShiftedTPoly([T0C*u.K, _k0/u.molar/u.s, _k1/u.molar/u.s/u.K]))
    T_C = 25
    T = (T0C+T_C)*u.kelvin
    p1 = rate.rate_coeff({'temperature': T})
    assert allclose(p1, (_k0 + _k1*T_C)/u.molar/u.s)

    odesys, odesys_extra = create_odesys(rsys)
    ics = {'A': 3*u.molar, 'B': 5*u.molar, 'C': 11*u.molar, 'D': 13*u.molar}
    pars = dict(k_bi=p1)
    validation = odesys_extra['validate'](dict(ics, **pars))
    assert set(map(str, validation['not_seen'])) == {'C', 'D'}

    dedim_ctx = _mk_dedim(SI_base_registry)
    (t, c, _p), dedim_extra = dedim_ctx['dedim_tcp'](-37*u.s, [ics[k] for k in odesys.names], pars)
    fout = odesys.f_cb(t, c, [_p[pk] for pk in odesys.param_names])
    r = 3*5*(_k0 + _k1*25)*1000  # mol/m3/s
    ref = [-4*r, -r, 3*r, 2*r]
    assert np.all(abs((fout - ref)/ref) < 1e-14)

    odesys.integrate(t, c, _p)
Exemplo n.º 12
0
def test_mk_Radiolytic():
    R1 = mk_Radiolytic()
    R2 = mk_Radiolytic()
    assert R1 is R2

    RABG = mk_Radiolytic('alpha', 'beta', 'gamma')
    rxn = Reaction({}, {'H': 2}, RABG([3, 5, 7], 'ya yb yg'.split()))
    rat = rxn.rate({
        'doserate_alpha': 11,
        'doserate_beta': 13,
        'doserate_gamma': 17,
        'density': .7
    })
    assert abs(rat['H'] - .7 * 2 * (3 * 11 + 5 * 13 + 7 * 17)) < 1e-13
    assert RABG.parameter_keys == ('density', 'doserate_alpha',
                                   'doserate_beta', 'doserate_gamma')
    assert RABG.argument_names == tuple('radiolytic_yield_%s' % k
                                        for k in 'alpha beta gamma'.split())
    assert rxn.param.unique_keys == ('ya', 'yb', 'yg')
    rat2 = rxn.rate({
        'doserate_alpha': 11,
        'doserate_beta': 13,
        'doserate_gamma': 17,
        'density': .7,
        'ya': 23,
        'yb': 29,
        'yg': 31
    })
    assert abs(rat2['H'] - .7 * 2 * (23 * 11 + 29 * 13 + 31 * 17)) < 1e-13
Exemplo n.º 13
0
def test_get_odesys__with_units():
    a = Substance('A')
    b = Substance('B')
    molar = u.molar
    second = u.second
    r = Reaction({'A': 2}, {'B': 1}, param=1e-3/molar/second)
    rsys = ReactionSystem([r], [a, b])
    odesys = get_odesys(rsys, include_params=True,
                        unit_registry=SI_base_registry)[0]
    c0 = {
        'A': 13*u.mol / u.metre**3,
        'B': .2 * u.molar
    }
    conc_unit = get_derived_unit(SI_base_registry, 'concentration')
    t = np.linspace(0, 10)*u.hour
    xout, yout, info = odesys.integrate(
        t, rsys.as_per_substance_array(c0, unit=conc_unit),
        atol=1e-10, rtol=1e-12)

    t_unitless = to_unitless(xout, u.second)
    Aref = dimerization_irrev(t_unitless, 1e-6, 13.0)
    # Aref = 1/(1/13 + 2*1e-6*t_unitless)
    yref = np.zeros((xout.size, 2))
    yref[:, 0] = Aref
    yref[:, 1] = 200 + (13-Aref)/2
    assert allclose(yout, yref*conc_unit)
Exemplo n.º 14
0
def test_decompose_yields_2():
    from chempy import Reaction
    yields = {'B': 3.0, 'C': 24.0}
    rxns = [
        Reaction({'A': 1}, {
            'B': 1,
            'C': 1
        }, inact_reac={'A': 1}),
        Reaction({'A': 1}, {'C': 3})
    ]
    k = decompose_yields(yields, rxns)
    k_ref = [3, 7]

    rtol = 1e-12
    for a, b in zip(k, k_ref):
        assert abs(a - b) < abs(a * rtol)
Exemplo n.º 15
0
def test_get_odesys__Expr_as_param__unique_as_param():
    def _eyring_pe_coupled(args, T, S, backend=math, **kwargs):
        freq, = args
        return freq*T/S

    EyringPreExpCoupled = Expr.from_callback(_eyring_pe_coupled, argument_names=('freq',),
                                             parameter_keys=('temperature', 'S_u'))

    def _k(args, T, backend=math, **kwargs):
        A, H, S = args
        return A*backend.exp(-(H - T*S)/(8.314511*T))

    EyringMA = MassAction.from_callback(_k, parameter_keys=('temperature',),
                                        argument_names=('Aa', 'Ha', 'Sa'))
    kb_h = 2.08e10
    rxn = Reaction({'A'}, {'B'}, EyringMA(unique_keys=('A_u', 'H_u', 'S_u')))
    rsys = ReactionSystem([rxn], ['A', 'B'])
    odesys2, extra2 = get_odesys(rsys, include_params=False,
                                 substitutions={'A_u': EyringPreExpCoupled(kb_h)})
    y0 = defaultdict(float, {'A': 7.0})
    rt = 293.15
    xout2, yout2, info2 = odesys2.integrate(5, y0, {'H_u': 107e3, 'S_u': 150, 'temperature': rt},
                                            integrator='cvode', atol=1e-12, rtol=1e-10, nsteps=1000)
    kref2 = kb_h*rt*np.exp(-(107e3 - rt*150)/(8.314511*rt))/150
    ref2 = y0['A']*np.exp(-kref2*xout2)
    assert np.allclose(yout2[:, 0], ref2)
    assert np.allclose(yout2[:, 1], y0['A'] - ref2)
Exemplo n.º 16
0
def test_ArrheniusMassAction__units(R_from_constants):
    import numpy as np

    Ea = 40e3 * u.J / u.mol
    R = (default_constants.molar_gas_constant if R_from_constants else
         (8.3145 * u.J / u.mol / u.K))
    A, Ea_over_R = 1.2e11 / u.molar**2 / u.second, Ea / R
    ref1 = A * np.exp(-to_unitless(Ea_over_R / (290 * u.K)))
    arrh = Arrhenius([A, Ea_over_R])
    assert allclose(arrh({"temperature": 290 * u.K}), ref1)
    ama = MassAction(arrh)
    r = Reaction({"A": 2, "B": 1}, {"C": 1}, ama, {"B": 1})
    T_ = "temperature"

    def ref(v):
        return (1.2e11 / u.molar**2 / u.second *
                math.exp(-Ea_over_R.simplified / v[T_]) * v["B"] * v["A"]**2)

    ma = r.rate_expr()

    for params in [
        (11.0 * u.molar, 13.0 * u.molar, 17.0 * u.molar, 311.2 * u.kelvin),
        (12 * u.molar, 8 * u.molar, 5 * u.molar, 270 * u.kelvin),
    ]:
        var = dict(zip(["A", "B", "C", T_], params))
        ref_val = ref(var)
        assert abs((ma(var, reaction=r) - ref_val) / ref_val) < 1e-14
Exemplo n.º 17
0
def test_RTPolyMassAction__units():
    Mps = u.molar/u.second
    kunit = 1/u.molar**2/u.second
    p = MassAction(ShiftedRTPoly([273.15*u.K, 7*kunit, .2*kunit*u.K, .03*kunit*u.K**2, .004*kunit*u.K**3]))
    r = Reaction({'A': 2, 'B': 1}, {'C': 1}, None, {'B': 1})
    res = p({'A': 11*u.molar, 'B': 13*u.molar, 'temperature': 298.15*u.K}, reaction=r)
    ref = 7 + .2/25 + 0.03 / 25**2 + 0.004 / 25**3
    assert abs(res - ref*13*11**2*Mps) < 1e-15
Exemplo n.º 18
0
def test_ShiftedTPoly_MassAction():
    rate = MassAction(ShiftedTPoly([100, 2, 5, 7]))
    assert rate.args[0].args == [100, 2, 5, 7]
    r = Reaction({"A": 2, "B": 1}, {"P": 1}, rate)
    res = r.rate_expr()({"A": 11, "B": 13, "temperature": 273.15}, reaction=r)
    x = 273.15 - 100
    ref = 11 * 11 * 13 * (2 + 5 * x + 7 * x**2)
    assert abs((res - ref) / ref) < 1e-14
Exemplo n.º 19
0
def test_Log10PiecewiseRTPolyMassAction():
    p1 = RTPoly([12.281, -3.768e2, -6.673e4, -1.075e7])
    p2 = RTPoly([-47.532, 4.92, -1.036, 0.0])
    ratex = MassAction(10**TPiecewise([293.15, p1, 423.15, p2, 623.15]))
    r = Reaction({"e-(aq)": 2}, {"H2": 1, "OH-": 2}, ratex, {"H2O": 2})
    res = ratex({"e-(aq)": 1e-13, "temperature": 293.15}, reaction=r)
    ref = 6.20e9 * 1e-26
    assert abs((res - ref) / ref) < 6e-3
Exemplo n.º 20
0
def test_Log10TPolyMassAction__units():
    Mps = u.molar/u.second
    kunit = 1/u.molar**2/u.second
    p = MassAction(Constant(kunit)*10**ShiftedTPoly([273.15*u.K, .7, .02/u.K, .003/u.K**2, .0004/u.K**3]))
    r = Reaction({'A': 2, 'B': 1}, {'C': 1}, p, {'B': 1})
    res = p({'A': 11*u.molar, 'B': 13*u.molar, 'temperature': 298.15*u.K}, reaction=r)
    ref = 10**(.7 + .02*25 + 0.003 * 25**2 + 0.0004 * 25**3)
    assert abs(res - ref*13*11**2*Mps) < 1e-15
Exemplo n.º 21
0
def test_TPolyMassAction__2():
    rate = TPolyMassAction([100, 2, 5, 7])
    assert rate.args == [100, 2, 5, 7]
    Reaction({'A': 2, 'B': 1}, {'P': 1}, rate)
    res = rate({'A': 11, 'B': 13, 'temperature': 273.15})
    x = 273.15 - 100
    ref = 11 * 11 * 13 * (2 + 5 * x + 7 * x**2)
    assert abs((res - ref) / ref) < 1e-14
Exemplo n.º 22
0
def test_MassAction():
    ma = MassAction([3.14], ['my_rate'])
    Reaction({'A': 2, 'B': 1}, {'C': 1}, ma, {'B': 1})
    assert abs(ma({'A': 11, 'B': 13, 'C': 17}) - 3.14*13*11**2) < 1e-14
    assert abs(ma({'A': 11, 'B': 13, 'C': 17, 'my_rate': 2.72}) - 2.72*13*11**2) < 1e-12
    ma2 = ma.as_mass_action({})
    assert ma == ma2
    assert abs(ma2({'A': 11, 'B': 13, 'C': 17}) - 3.14*13*11**2) < 1e-14
Exemplo n.º 23
0
def test_PiecewiseTPolyMassAction__units():
    tp1 = TPoly([10/u.molar**2/u.second, 0.1/u.molar**2/u.second/u.kelvin])
    tp2 = ShiftedTPoly([273.15*u.kelvin, 37.315/u.molar**2/u.second, -0.1/u.molar**2/u.second/u.kelvin])
    pwp = MassAction(TPiecewise([0*u.kelvin, tp1, 273.15*u.kelvin, tp2, float('inf')*u.kelvin]))
    r = Reaction({'A': 2, 'B': 1}, {'C': 1}, pwp, {'B': 1})
    res1 = pwp({'A': 11*u.molar, 'B': 13*u.molar, 'temperature': 198.15*u.kelvin}, reaction=r)
    ref1 = 11*11*13*29.815 * u.molar/u.second
    assert abs((res1-ref1)/ref1) < 1e-14
Exemplo n.º 24
0
def test_MassAction__subclass_from_callback():
    def rate_coeff(variables, all_args, backend):
        return all_args[0]*backend.exp(all_args[1]/variables['temperature'])
    CustomMassAction = MassAction.subclass_from_callback(
        rate_coeff, cls_attrs=dict(parameter_keys=('temperature',), nargs=2))
    k1 = CustomMassAction([2.1e10, -5132.2], rxn=Reaction({'H2': 2, 'O2': 1}, {'H2O': 2}))
    res = k1({'temperature': 273.15, 'H2': 7, 'O2': 13})
    ref = 7*7*13*2.1e10*math.exp(-5132.2/273.15)
    assert abs((res-ref)/ref) < 1e-14
Exemplo n.º 25
0
def test_MassAction__subclass_from_callback__units():
    def rate_coeff(variables, all_args, backend):
        return all_args[0]*backend.exp(all_args[1]/variables['temperature'])
    CustomMassAction = MassAction.subclass_from_callback(
        rate_coeff, cls_attrs=dict(parameter_keys=('temperature',), nargs=2))
    k1 = CustomMassAction([2.1e10/u.molar**2/u.second, -5132.2*u.kelvin], rxn=Reaction({'H2': 2, 'O2': 1}, {'H2O': 2}))
    res = k1({'temperature': 491.67*u.rankine, 'H2': 7000*u.mol/u.metre**3, 'O2': 13*u.molar}, backend=Backend())
    ref = 7*7*13*2.1e10*math.exp(-5132.2/273.15) * u.molar/u.second
    assert allclose(res, ref)
Exemplo n.º 26
0
def test_TPolyInLog10MassAction():
    p = MassAction(ShiftedLog10TPoly([2, 0.3, .2, .03, .004]))
    r = Reaction({'A': 2, 'B': 1}, {'C': 1}, p, {'B': 1})
    lgT = Log10('temperature')
    lgTref = Log10('Tref')
    res = p({'A': 11, 'B': 13, 'temperature': 298.15,
             'log10_temperature': lgT, 'log10_Tref': lgTref}, reaction=r)
    _T = math.log10(298.15) - 2
    ref = .3 + .2*_T + 0.03 * _T**2 + 0.004 * _T**3
    assert abs(res - ref*13*11**2) < 1e-15
Exemplo n.º 27
0
def test_get_ode__TPoly():
    rate = MassAction(ShiftedTPoly([273.15*u.K, 10/u.molar/u.s, 2/u.molar/u.s/u.K]))
    rxn = Reaction({'A': 1, 'B': 1}, {'C': 3, 'D': 2}, rate, {'A': 3})
    rsys = ReactionSystem([rxn], 'A B C D')
    odesys = get_odesys(rsys, unit_registry=SI_base_registry)[0]
    conc = {'A': 3*u.molar, 'B': 5*u.molar, 'C': 11*u.molar, 'D': 13*u.molar}
    x, y, p = odesys.to_arrays(-37*u.second, conc, {'temperature': 298.15*u.kelvin})
    fout = odesys.f_cb(x, y, p)
    r = 3*5*(10+2*25)*1000  # mol/m3/s
    ref = [-4*r, -r, 3*r, 2*r]
    assert np.all(abs((fout - ref)/ref) < 1e-14)
Exemplo n.º 28
0
def test_get_ode__Radiolytic():
    rad = Radiolytic([2.4e-7])
    rxn = Reaction({'A': 4, 'B': 1}, {'C': 3, 'D': 2}, rad)
    rsys = ReactionSystem([rxn], 'A B C D')
    odesys = get_odesys(rsys, include_params=True)[0]
    c = {'A': 3, 'B': 5, 'C': 11, 'D': 13}
    x, y, p = odesys.to_arrays(-37, c, {'doserate': 0.4, 'density': 0.998})
    fout = odesys.f_cb(x, y, p)
    r = 2.4e-7*0.4*0.998
    ref = [-4*r, -r, 3*r, 2*r]
    assert np.all(abs((fout - ref)/ref) < 1e-14)
Exemplo n.º 29
0
def test_get_ode__ArrheniusParam():
    rxn = Reaction({'A': 1}, {'B': 1}, None)
    rxn.param = ArrheniusParam(1e10, 40e3)
    rsys = ReactionSystem([rxn], 'A B')
    odesys = get_odesys(rsys, include_params=True)[0]
    conc = {'A': 3, 'B': 5}
    x, y, p = odesys.to_arrays(-37, conc, {'temperature': 200})
    fout = odesys.f_cb(x, y, p)
    ref = 3*1e10*np.exp(-40e3/8.314472/200)
    assert np.all(abs((fout[:, 0] + ref)/ref) < 1e-14)
    assert np.all(abs((fout[:, 1] - ref)/ref) < 1e-14)
Exemplo n.º 30
0
def test_TPolyInLog10MassAction__units():
    Mps = u.molar/u.second
    kunit = 1/u.molar**2/u.second
    p = MassAction(Constant(kunit)*ShiftedLog10TPoly([2, 0.3, .2, .03, .004]))
    lgT = Log10('temperature'/Constant(u.K))
    r = Reaction({'A': 2, 'B': 1}, {'C': 1}, p, {'B': 1})
    res = p({'A': 11*u.molar, 'B': 13*u.molar, 'temperature': 298.15*u.K,
             'log10_temperature': lgT}, backend=Backend(), reaction=r)
    _T = math.log10(298.15) - 2
    ref = (.3 + .2*_T + 0.03 * _T**2 + 0.004 * _T**3) * 13 * 11**2 * Mps
    assert abs(res - ref) < 1e-15*Mps