Beispiel #1
0
 def test_issue1062_issue1097(self):
     # Must not be used by any other tests
     assert "nanometer" not in ureg._units
     for i in range(5):
         ctx = Context.from_lines(["@context _", "cal = 4 J"])
         with ureg.context("sp", ctx):
             q = ureg.Quantity(1, "nm")
             q.to("J")
Beispiel #2
0
 def test_issue932(self):
     q = ureg.Quantity("1 kg")
     with self.assertRaises(DimensionalityError):
         q.to("joule")
     ureg.enable_contexts("energy", *(Context() for _ in range(20)))
     q.to("joule")
     ureg.disable_contexts()
     with self.assertRaises(DimensionalityError):
         q.to("joule")
Beispiel #3
0
def ureg(**defaults):

    if ureg_singleton.ureg is None:
        u = ureg_singleton.ureg = UnitRegistry()
    else:
        return ureg_singleton.ureg
    u.define('Msun = 1.99885e30kg')
    u.define("hubble = [hubbli]")
    u.define("scalefactor = [scalefactori]")
    u.define('gmass = 1e10 Msun/hubble')
    u.define('cmass = Msun/hubble')
    u.define('clength = kpc/hubble*scalefactor')
    u.define('glength = clength')
    u.define('cvelocity = scalefactor*km/s')
    u.define('gvelocity_a = (scalefactor**0.5)km/s')
    u.define('gvelocity_noa = km/s')
    c = Context('comoving', defaults={"hubble": None, "scalefactor": None})

    def f_1(u, v, hubble=None, scalefactor=None):
        m = v.to(u.clength).magnitude
        if hubble is not None and scalefactor is not None:
            return u.kpc * m * scalefactor / hubble
        else:
            raise Exception("hubble=%s, scalefactor=%s" %
                            (str(hubble), str(scalefactor)))

    def g_1(u, v, hubble=None, scalefactor=None):
        m = v.to(u.cmass).magnitude
        if hubble is not None:
            return u.Msun * m / hubble
        else:
            raise Exception("hubble=%s " % (str(hubble)))

    def f_2(u, v, hubble=None, scalefactor=None):
        m = v.to(u.kpc).magnitude
        if hubble is not None and scalefactor is not None:
            return u.clength / scalefactor * hubble
        else:
            raise Exception("hubble=%s, scalefactor=%s" %
                            (str(hubble), str(scalefactor)))

    c.add_transformation('[length] * [scalefactori] / [hubbli]', '[length]',
                         f_1)
    c.add_transformation('[length]', '[length] * [scalefactori] / [hubbli]',
                         f_2)
    c.add_transformation('[mass]  / [hubbli]', '[mass]', g_1)

    u.add_context(c)
    #if(len(defaults)>0):
    #    u.enable_contexts(c,**defaults)
    u.enable_contexts(c, hubble=.704)

    return u
Beispiel #4
0
def unit_entity_compatibility(unit_name, entity_name):
    """
    Determines a unit and an entity are compatible. Returns True if so,
    False otherwise

    This function assumes that the entity is among the relevant ones (power, electrical potential,
    current, length, energy)

    e.g. unit_entity_compatibility('meter', 'length') ---> True
         unit_entity_compatibility('meter', 'volt') ----> False

    Parameters
    ----------
    unit_name: str
        Unit name (e.g. ampere, volt_ampere...)
    entity_name: str
        Entity name (e.g. power, electrical potential, length...)

    Returns
    -------
    bool:
        True if the unit and the entity match, assuming the entity is among the
        relevant ones. False otherwise or if the entity is irrelevant
    """
    # Determine the reference unit for that entity
    ref_unit = ""
    for unit_info in unit_references:
        if unit_info['entity'] == entity_name:
            ref_unit = unit_info['unit_full_name']

    # If the entity is not part of the relevant ones,
    # return False
    if len(ref_unit) == 0:
        print("WARNING: Entity {} is irrelevant.".format(entity_name))
        return False

    return Unit(unit_name).is_compatible_with(Unit(ref_unit), Context())
Beispiel #5
0
# -*- coding: utf-8 -*-

"""Various units-related things

This module has a soft dependency on the pint units library.  Please
import this module only conditionally or only if you can accept a pint
dependency.
"""

from pint import (UnitRegistry, Context)
ureg = UnitRegistry()
ureg.define("micro- = 1e-6 = µ-")

# aid conversion between different radiance units
sp2 = Context("radiance")
sp2.add_transformation(
    "[length] * [mass] / [time] ** 3",
    "[mass] / [time] ** 2",
    lambda ureg, x: x / ureg.speed_of_light)
sp2.add_transformation(
    "[mass] / [time] ** 2",
    "[length] * [mass] / [time] ** 3",
    lambda ureg, x: x * ureg.speed_of_light)
ureg.add_context(sp2)

radiance_units = {
    "si": ureg.W / (ureg.m**2 * ureg.sr * ureg.Hz),
    "ir": ureg.mW / (ureg.m**2 * ureg.sr * (1 / ureg.cm))}
Beispiel #6
0
def set_nmr_context(larmor):
    """
    Set a NMR context relative to the given Larmor frequency.

    Parameters
    ----------
    larmor : |Quantity| or float
        The Larmor frequency of the current nucleus.
        If it is not a quantity it is assumed to be given in MHz.

    Examples
    --------

    First we set the NMR context,

    >>> from spectrochempy.core.units import ur, set_nmr_context
    >>>
    >>> set_nmr_context(104.3 * ur.MHz)

    then, we can use the context as follow

    >>> fhz = 10000 * ur.Hz
    >>> with ur.context('nmr'):
    ...     fppm = fhz.to('ppm')
    >>> print("{:~.3f}".format(fppm))
    95.877 ppm

    or in the opposite direction

    >>> with ur.context('nmr'):
    ...     fhz = fppm.to('kHz')
    >>> print("{:~.3f}".format(fhz))
    10.000 kHz

    Now we update the context :

    >>> with ur.context('nmr', larmor=100. * ur.MHz):
    ...     fppm = fhz.to('ppm')
    >>> print("{:~.3f}".format(fppm))
    100.000 ppm

    >>> set_nmr_context(75 * ur.MHz)
    >>> fhz = 10000 * ur.Hz
    >>> with ur.context('nmr'):
    ...     fppm = fhz.to('ppm')
    >>> print("{:~.3f}".format(fppm))
    133.333 ppm
    """

    if not isinstance(larmor, U_.Quantity):
        larmor = larmor * U_.MHz

    if "nmr" not in list(U_._contexts.keys()):
        c = Context("nmr", defaults={"larmor": larmor})

        c.add_transformation(
            "[]",
            "[frequency]",
            lambda U_, x, **kwargs: x * kwargs.get("larmor") / 1.0e6,
        )
        c.add_transformation(
            "[frequency]",
            "[]",
            lambda U_, x, **kwargs: x * 1.0e6 / kwargs.get("larmor"),
        )
        U_.add_context(c)

    else:

        c = U_._contexts["nmr"]
        c.defaults["larmor"] = larmor
Beispiel #7
0
# 
# All those contributions are dual-licensed under the MIT license for use
# in typhon, and the GNU General Public License version 3.

from pint import (UnitRegistry, Context)

__all__ = [
    'ureg',
    'radiance_units',
        ]

ureg = UnitRegistry()
ureg.define("micro- = 1e-6 = µ-")

# aid conversion between different radiance units
sp2 = Context("radiance")
# specrad per frequency → specrad per wavenumber
sp2.add_transformation(
    "[length] * [mass] / [time] ** 3",
    "[mass] / [time] ** 2",
    lambda ureg, x, **kwargs: x / ureg.speed_of_light)
# specrad per wavenumber → specrad per frequency
sp2.add_transformation(
    "[mass] / [time] ** 2",
    "[length] * [mass] / [time] ** 3",
    lambda ureg, x, **kwargs: x * ureg.speed_of_light)
#sp2.add_transformation(
#    "[mass] / ([length] * [time] ** 3)",
#    "[length] * [mass] / [time] ** 3",
#    lambda ureg, x, **kwargs: )
def _R_to_bt(ureg, R, srf):
Beispiel #8
0
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 29 11:15:57 2016

@author: Arno Rehn
"""

from pint import Context
from common import ureg

# Create and enable a THz-TDS context where we can convert times to lengths
# and vice-versa
thz_context = Context('terahertz')

thz_context.add_transformation('[time]', '[length]',
                               lambda ureg, x: ureg.speed_of_light * x / 2)
thz_context.add_transformation('[length]', '[time]',
                               lambda ureg, x: 2 * x / ureg.speed_of_light)

thz_context.add_transformation('', '[length]/[time]',
                               lambda ureg, x: ureg.speed_of_light * x / 2)
thz_context.add_transformation('[length]/[time]', '',
                               lambda ureg, x: 2 * x / ureg.speed_of_light)

ureg.add_context(thz_context)
ureg.enable_contexts('terahertz')
Beispiel #9
0
def set_nmr_context(larmor):
    """
    Set a NMR context relative to the given Larmor frequency

    Parameters
    ----------
    larmor : Quantity or float
        The Larmor frequency of the current nucleus.
        If it is not a quantity it is assumed to be given in MHz

    Examples
    --------

    First we set the NMR context,

    >>> set_nmr_context(104.3 * U_.MHz)

    then, we can use the context as follow :

    >>> fhz = 10000 * U_.Hz
    >>> with U_.context('nmr'):
    ...    fppm = fhz.to('ppm')
    >>> print("{:~.3f}".format(fppm))
    95.877 ppm

    or in the opposite direction

    >>> with U_.context('nmr'):
    ...    fhz = fppm.to('kHz')
    >>> print("{:~.3f}".format(fhz))
    10.000 kHz

    Now we update the context :

    >>> with U_.context('nmr', larmor=100. * U_.MHz):
    ...    fppm = fhz.to('ppm')
    >>> print("{:~.3f}".format(fppm))
    100.000 ppm

    >>> set_nmr_context(75 * U_.MHz)
    >>> fhz = 10000 * U_.Hz
    >>> with U_.context('nmr'):
    ...    fppm = fhz.to('ppm')
    >>> print("{:~.3f}".format(fppm))
    133.333 ppm
    """

    if not isinstance(larmor, U_.Quantity):
        larmor = larmor * U_.MHz

    if 'nmr' not in list(U_._contexts.keys()):
        c = Context('nmr', defaults={'larmor': larmor})

        c.add_transformation('[]', '[frequency]', lambda U_, x, **kwargs: x * kwargs.get('larmor') / 1.e6)
        c.add_transformation('[frequency]', '[]', lambda U_, x, **kwargs: x * 1.e6 / kwargs.get('larmor'))
        U_.add_context(c)

    else:

        c = U_._contexts['nmr']
        c.defaults['larmor'] = larmor
Beispiel #10
0
unit_registry.define("a = 1 * year = annum = yr")
unit_registry.define("h = hour")
unit_registry.define("d = day")
unit_registry.define("degreeC = degC")
unit_registry.define("degreeF = degF")
unit_registry.define(
    "kt = 1000 * t")  # since kt is used for "knot" in the defaults

unit_registry.define("ppt = [concentrations]")
unit_registry.define("ppb = 1000 * ppt")
unit_registry.define("ppm = 1000 * ppb")

# Contexts:

_c = Context("AR4GWP12")
_c.add_transformation(
    "[carbon]",
    "[nitrogen]",
    lambda unit_registry, x: 20 * unit_registry.N * x / unit_registry.C,
)
_c.add_transformation(
    "[nitrogen]",
    "[carbon]",
    lambda unit_registry, x: x * unit_registry.C / unit_registry.N / 20,
)
unit_registry.add_context(_c)

_ch4_context = Context("CH4_conversions")
_ch4_context.add_transformation(
    "[carbon]",