How to use the chempy.units.to_unitless function in chempy

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 / util / _expr.py View on Github external
"""
        from ..units import default_unit_in_registry, to_unitless, unitless_in_registry
        new_units = []
        if self.args is None:
            unitless_args = None
        else:
            unitless_args = []
            units = [None if isinstance(arg, Expr) else default_unit_in_registry(arg, unit_registry) for arg
                     in self.all_args(variables, backend=backend, evaluate=False)]
            for arg, unit in zip(self.all_args(variables, backend=backend, evaluate=False), units):
                if isinstance(arg, Expr):
                    if unit is not None:
                        raise ValueError()
                    _unit, _dedim = arg.dedimensionalisation(unit_registry, variables, backend=backend)
                else:
                    _unit, _dedim = unit, to_unitless(arg, unit)
                new_units.append(_unit)
                unitless_args.append(_dedim)
        instance = self.__class__(unitless_args, self.unique_keys)
        if self.argument_defaults is not None:
            instance.argument_defaults = tuple(unitless_in_registry(arg, unit_registry)
                                               for arg in self.argument_defaults)

        return new_units, instance
github bjodah / chempy / chempy / util / stoich.py View on Github external
-------
    1-dimensional array of effective rate coefficients.

    """
    from chempy import ReactionSystem
    # Sanity check:
    rxn_keys = set.union(*(rxn.keys() for rxn in rxns))
    for key in yields.keys():
        if key not in rxn_keys:
            raise ValueError("Substance key: %s not in reactions" % key)
    rsys = ReactionSystem(rxns, rxn_keys)
    A = rsys.net_stoichs(yields.keys())
    b = list(yields.values())
    unit = unit_of(b[0])
    x, residuals, rank, s = np.linalg.lstsq(
        np.asarray(A.T, dtype=np.float64), to_unitless(b, unit), rcond=2e-16*max(A.shape))
    if len(residuals) > 0:
        if np.any(residuals > atol):
            raise ValueError("atol not satisfied")
    return x*unit
github bjodah / chempy / chempy / util / _julia.py View on Github external
p[pk], unit_conc**(1-r.order())/unit_time
        )
        if not r.inact_reac:
            r_str = '{}, {}'.format(parmap[pk], r.string(substances=substmap, with_param=False,
                                                         Reaction_arrow='-->', Reaction_coeff_space=''))
        else:
            all_keys = r.keys()
            reac_stoichs = r.all_reac_stoich(all_keys)
            act_stoichs = r.active_reac_stoich(all_keys)
            rate = '*'.join([parmap[pk]] + [('%s^%d' % (substmap[k], v)) if v > 1 else substmap[k]
                                            for k, v in zip(all_keys, act_stoichs) if v > 0])
            r2 = Reaction(dict([(k, v) for k, v in zip(all_keys, reac_stoichs) if v]), r.prod)
            r_str = '{}, {}'.format(rate, r2.string(substances=substmap, with_param=False,
                                                    Reaction_arrow='\u21D2', Reaction_coeff_space=''))
    elif isinstance(r.param, RadiolyticBase):
        ratcoeff = to_unitless(
            p[pk]*variables['doserate']*variables['density'],
            unit_conc/unit_time
        )
        assert not r.reac and not r.inact_reac and not r.inact_prod
        (prod, n), = r.prod.items()
        assert n == 1
        r_str = ('{}, 0 \u21D2 {}' if ratcoeff > 0 else '{}, {} \u21D2 0').format(
            parmap[pk], substmap[prod])
    else:
        raise NotImplementedError("Whats that?")
    return r_str, pk, abs(ratcoeff)
github bjodah / chempy / chempy / util / bkh.py View on Github external
def _C(k):
        return to_unitless(c0[k], output_conc_unit)
    if p_units is None:
github bjodah / chempy / chempy / util / regression.py View on Github external
vcv_beta : array_like
    kw_data : dict
        Keyword arguments to ``plot`` for x, y data
    kw_fit : dict
        Keyword arguments to ``plot`` for fitted data
    fit_label_cb: callable:
        signature (beta, variance_beta, r2) -> str
    ax : matplotlib.axes.Axes
        Alternatively ``True`` or ``None``
    x_unit : unit
    y_unit : unit
    nsigma : int
        Multiplier for errorbars when plotting.

    """
    x_ul = to_unitless(x, x_unit)
    y_ul = to_unitless(y, y_unit)
    if ax is True:
        import matplotlib.pyplot as plt
        ax = plt.subplot(1, 1, 1)
    kw_data, kw_fit = kw_data or {}, kw_fit or {}
    if fit_label_cb is not None and 'label' not in kw_fit:
        kw_fit['label'] = fit_label_cb(beta, vcv_beta, r2)

    if yerr is None:
        ax.plot(x_ul, y_ul, **kw_data)
    else:
        ax.errorbar(x_ul, y_ul, yerr=to_unitless(yerr*nsigma, y_unit), **kw_data)

    xlim = [np.min(x_ul), np.max(x_ul)]
    if 'marker' not in kw_fit:
        kw_fit['marker'] = 'None'
github bjodah / chempy / chempy / util / bkh.py View on Github external
def update_data(attrname, old, new):
        _c0 = defaultdict(lambda: 0*output_conc_unit)
        for k, w in c0_widgets.items():
            _c0[k] = w.value * output_conc_unit
        _params = {}
        for (k, w), u in zip(param_widgets.items(), p_units):
            _params[k] = w.value if u is None else w.value * u
        _result = integrate(tout, _c0, _params)
        for idx, k in enumerate(rsys.substances):
            sources[idx].data = {
                'tout': to_unitless(_result.xout, output_time_unit),
                k: to_unitless(_result.yout[:, idx], output_conc_unit)
            }
github bjodah / chempy / chempy / util / regression.py View on Github external
def least_squares_units(x, y, w=1):
    """ Units-aware least-squares (w or w/o weights) fit to data series.

    Parameters
    ----------
    x : array_like
    y : array_like
    w : array_like, optional

    """
    x_unit, y_unit = unit_of(x), unit_of(y)
    integer_one = 1
    explicit_errors = w is not integer_one
    if explicit_errors:
        if unit_of(w) == y_unit**-2:
            _w = to_unitless(w, y_unit**-2)
        elif unit_of(w) == unit_of(1):
            _w = w
        else:
            raise ValueError("Incompatible units in y and w")
    else:
        _w = 1
    _x = to_unitless(x, x_unit)
    _y = to_unitless(y, y_unit)
    beta, vcv, r2 = least_squares(_x, _y, _w)
    beta_tup = _beta_tup(beta, x_unit, y_unit)
    return beta_tup, vcv, float(r2)