How to use chempy - 10 common examples

To help you get started, we’ve selected a few chempy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github bjodah / chempy / chempy / util / table.py View on Github external
lines = []
    for ri, rxn in enumerate(rsys.rxns):
        rxn_ref = rxn.ref
        if isinstance(rxn.param, RadiolyticBase):
            if unit_registry is not None:
                kunit = get_derived_unit(unit_registry, 'radiolytic_yield')
                k = k_fmt % to_unitless(rxn.param.args[0], kunit)
                k_unit_str = (kunit.dimensionality.latex.strip('$') if tex
                              else kunit.dimensionality)
        else:
            if unit_registry is not None:
                kunit = (get_derived_unit(unit_registry,
                                          'concentration')**(1-rxn.order()) /
                         get_derived_unit(unit_registry, 'time'))
                try:
                    k = k_fmt % to_unitless(rxn.param, kunit)
                    k_unit_str = (kunit.dimensionality.latex.strip('$') if tex
                                  else kunit.dimensionality)
                except Exception:
                    k, k_unit_str = rxn.param.equation_as_string(k_fmt, tex)
            else:
                k_unit_str = '-'
                if isinstance(k_fmt, str):
                    k = k_fmt % rxn.param
                else:
                    k = k_fmt(rxn.param)
        latex_kw = dict(with_param=False, with_name=False)
        if tex:
            latex_kw['substances'] = rsys.substances
            latex_kw['Reaction_around_arrow'] = ('}}' + coldelim + '\\ensuremath{{',
                                                 '}}' + coldelim + '\\ensuremath{{')
        else:
github bjodah / chempy / chempy / kinetics / ode.py View on Github external
def dedim_tcp(t, c, p, param_unit=lambda k, v: default_unit_in_registry(v, unit_registry)):
        _t = to_unitless(t, unit_time)
        _c = to_unitless(c, unit_conc)
        _p, pu = {}, {}
        for k, v in p.items():
            pu[k] = param_unit(k, v)
            _p[k] = to_unitless(v, pu[k])
        return (_t, _c, _p), dict(unit_time=unit_time, unit_conc=unit_conc, param_units=pu)
github bjodah / chempy / chempy / kinetics / analysis.py View on Github external
from pyodesys.results import Result
    if isinstance(xyp, Result):
        xyp = xyp.odesys.to_arrays(xyp.xout, xyp.yout, xyp.params, reshape=False)
    if varied is None:
        varied = xyp[0]
    if xyp[1].shape[-2] != varied.size:
        raise ValueError("Size mismatch between varied and yout")
    if substance_keys is None:
        substance_keys = rsys.substances.keys()
    if axes is None:
        _fig, axes = plt.subplots(len(substance_keys))
    rates = rate_exprs_cb(*xyp)
    if unit_registry is not None:
        time_unit = get_derived_unit(unit_registry, 'time')
        conc_unit = get_derived_unit(unit_registry, 'concentration')
        rates = to_unitless(rates*conc_unit/time_unit, u.molar/u.second)

    eqk1, eqk2, eqs = _combine_rxns_to_eq(rsys) if combine_equilibria else ([], [], [])

    for sk, ax in zip(substance_keys, axes):
        data, tot = _dominant_reaction_effects(sk, rsys, rates, linthreshy, eqk1, eqk2, eqs)
        factor = 1/xyp[1][:, rsys.as_substance_index(sk)] if relative else 1
        if total:
            ax.plot(varied, factor*tot, c='k', label='Total', linewidth=2, ls=':')
        for y, rxn in sorted(data, key=lambda args: args[0][-1], reverse=True):
            ax.plot(varied, factor*y,
                    label=r'$\mathrm{%s}$' % rxn.latex(rsys.substances))

        if rsys.substances[sk].latex_name is None:
            ttl = rsys.substances[sk].name
            ttl_template = '%s'
        else:
github bjodah / chempy / chempy / util / parsing.py View on Github external
try:
        import numpy
    except ImportError:
        def _numpy_not_installed_raise(*args, **kwargs):
            raise ImportError("numpy not installed, no such method")

        class numpy:
            array = staticmethod(_numpy_not_installed_raise)
            log = staticmethod(_numpy_not_installed_raise)
            exp = staticmethod(_numpy_not_installed_raise)

    _update(numpy, keys='array log exp'.split())  # could of course add more
    _update(rates)
    _update(chempy)
    for df in [default_units, default_constants]:
        if df is not None:
            globals_.update(df.as_dict())
    return globals_
github bjodah / chempy / chempy / kinetics / ode.py View on Github external
if backend.__name__ != 'sympy':
            warnings.warn("Backend != SymPy, provide your own transform function.")

        def transform(arg):
            expr = backend.logcombine(arg, force=True)
            v, w = map(backend.Wild, 'v w'.split())
            expr = expr.replace(backend.log(w**v), v*backend.log(w))
            return expr

    args = [symbols[key] for key in conditions]
    seen = [False]*len(args)
    rates = {}
    for k, v in rsys.rates(symbols).items():
        expr = transform(v)
        if expr == 0:
            rate = 0 * u.molar/u.second
        else:
            rate = backend.lambdify(args, expr)(*conditions.values())
            to_unitless(rate, u.molar/u.second)
        rates[k] = rate
        seen = [b or a in expr.free_symbols for b, a in zip(seen, args)]
    not_seen = [a for s, a in zip(seen, args) if not s]
    for k in conditions:
        if k not in odesys.param_names and k not in odesys.names and k not in ignore:
            raise KeyError("Unknown param: %s" % k)
    return {'not_seen': not_seen, 'rates': rates}
github bjodah / chempy / chempy / kinetics / analysis.py View on Github external
"""
    from pyodesys.results import Result
    if isinstance(xyp, Result):
        xyp = xyp.odesys.to_arrays(xyp.xout, xyp.yout, xyp.params, reshape=False)
    if varied is None:
        varied = xyp[0]
    if xyp[1].shape[-2] != varied.size:
        raise ValueError("Size mismatch between varied and yout")
    if substance_keys is None:
        substance_keys = rsys.substances.keys()
    if axes is None:
        _fig, axes = plt.subplots(len(substance_keys))
    rates = rate_exprs_cb(*xyp)
    if unit_registry is not None:
        time_unit = get_derived_unit(unit_registry, 'time')
        conc_unit = get_derived_unit(unit_registry, 'concentration')
        rates = to_unitless(rates*conc_unit/time_unit, u.molar/u.second)

    eqk1, eqk2, eqs = _combine_rxns_to_eq(rsys) if combine_equilibria else ([], [], [])

    for sk, ax in zip(substance_keys, axes):
        data, tot = _dominant_reaction_effects(sk, rsys, rates, linthreshy, eqk1, eqk2, eqs)
        factor = 1/xyp[1][:, rsys.as_substance_index(sk)] if relative else 1
        if total:
            ax.plot(varied, factor*tot, c='k', label='Total', linewidth=2, ls=':')
        for y, rxn in sorted(data, key=lambda args: args[0][-1], reverse=True):
            ax.plot(varied, factor*y,
                    label=r'$\mathrm{%s}$' % rxn.latex(rsys.substances))

        if rsys.substances[sk].latex_name is None:
            ttl = rsys.substances[sk].name
github bjodah / chempy / chempy / kinetics / ode.py View on Github external
def _get_derived_unit(reg, key):
    try:
        return get_derived_unit(reg, key)
    except KeyError:
        return get_derived_unit(reg, '_'.join(key.split('_')[:-1]))
github bjodah / chempy / chempy / kinetics / ode.py View on Github external
def _mk_dedim(unit_registry):
    unit_time = get_derived_unit(unit_registry, 'time')
    unit_conc = get_derived_unit(unit_registry, 'concentration')

    def dedim_tcp(t, c, p, param_unit=lambda k, v: default_unit_in_registry(v, unit_registry)):
        _t = to_unitless(t, unit_time)
        _c = to_unitless(c, unit_conc)
        _p, pu = {}, {}
        for k, v in p.items():
            pu[k] = param_unit(k, v)
            _p[k] = to_unitless(v, pu[k])
        return (_t, _c, _p), dict(unit_time=unit_time, unit_conc=unit_conc, param_units=pu)

    return locals()
github bjodah / chempy / chempy / util / table.py View on Github external
return '\\ensuremath{' + s + '}'
        else:
            return s

    lines = []
    for ri, rxn in enumerate(rsys.rxns):
        rxn_ref = rxn.ref
        if isinstance(rxn.param, RadiolyticBase):
            if unit_registry is not None:
                kunit = get_derived_unit(unit_registry, 'radiolytic_yield')
                k = k_fmt % to_unitless(rxn.param.args[0], kunit)
                k_unit_str = (kunit.dimensionality.latex.strip('$') if tex
                              else kunit.dimensionality)
        else:
            if unit_registry is not None:
                kunit = (get_derived_unit(unit_registry,
                                          'concentration')**(1-rxn.order()) /
                         get_derived_unit(unit_registry, 'time'))
                try:
                    k = k_fmt % to_unitless(rxn.param, kunit)
                    k_unit_str = (kunit.dimensionality.latex.strip('$') if tex
                                  else kunit.dimensionality)
                except Exception:
                    k, k_unit_str = rxn.param.equation_as_string(k_fmt, tex)
            else:
                k_unit_str = '-'
                if isinstance(k_fmt, str):
                    k = k_fmt % rxn.param
                else:
                    k = k_fmt(rxn.param)
        latex_kw = dict(with_param=False, with_name=False)
        if tex:
github bjodah / chempy / chempy / util / table.py View on Github external
if s.startswith('doi:'):
                    return _doi(s[4:])
            return s

    def _wrap(s):
        if tex:
            return '\\ensuremath{' + s + '}'
        else:
            return s

    lines = []
    for ri, rxn in enumerate(rsys.rxns):
        rxn_ref = rxn.ref
        if isinstance(rxn.param, RadiolyticBase):
            if unit_registry is not None:
                kunit = get_derived_unit(unit_registry, 'radiolytic_yield')
                k = k_fmt % to_unitless(rxn.param.args[0], kunit)
                k_unit_str = (kunit.dimensionality.latex.strip('$') if tex
                              else kunit.dimensionality)
        else:
            if unit_registry is not None:
                kunit = (get_derived_unit(unit_registry,
                                          'concentration')**(1-rxn.order()) /
                         get_derived_unit(unit_registry, 'time'))
                try:
                    k = k_fmt % to_unitless(rxn.param, kunit)
                    k_unit_str = (kunit.dimensionality.latex.strip('$') if tex
                                  else kunit.dimensionality)
                except Exception:
                    k, k_unit_str = rxn.param.equation_as_string(k_fmt, tex)
            else:
                k_unit_str = '-'