Exemple #1
0
def test_custom_units(ureg, custom_ureg, sync_xdb):
    """dask _meta is a np.ndarray, but dask payload is a Quantity"""
    import pint

    a = xarray.DataArray(custom_ureg.Quantity([1], "test_unit"))
    assert str(a.data.units) == "test_unit"

    sync_xdb_custom = XarrayMongoDB(
        sync_xdb.meta.database,
        collection=sync_xdb.meta.name.split(".")[0],
        ureg=custom_ureg,
        embed_threshold_bytes=0,
    )

    _id, _ = sync_xdb_custom.put(a)
    b = sync_xdb_custom.get(_id)

    assert str(b.data.units) == "test_unit"
    xarray.testing.assert_identical(a, b)

    with pytest.raises(pint.UndefinedUnitError):
        sync_xdb.get(_id)

    pint.set_application_registry(custom_ureg)
    try:
        c = sync_xdb.get(_id)
        assert str(c.data.units) == "test_unit"
        xarray.testing.assert_identical(a, c)
    finally:
        pint.set_application_registry(ureg)
Exemple #2
0
def custom_units(ureg, ureg_custom, xdb):
    """dask _meta is a np.ndarray, but dask payload is a Quantity
    """
    import pint

    a = xarray.DataArray(ureg_custom.Quantity(1, "test_unit"))
    assert str(a.data.units) == "test_unit"

    xdb_custom = XarrayMongoDB(
        xdb.meta.database, collection=xdb.meta.name.split(".")[0], ureg=ureg_custom
    )

    _id, future = xdb_custom.put(a)
    future.compute()
    b = xdb_custom.get(_id)

    assert str(b.data.compute().units) == "test_unit"
    xarray.testing.assert_identical(a, b)

    with pytest.raises(pint.UndefinedUnitError):
        xdb.get(_id)

    pint.set_application_registry(ureg_custom)
    try:
        c = xdb.get(_id)
        assert str(c.data.compute().units) == "test_unit"
        xarray.testing.assert_identical(a, c)
    finally:
        pint.set_application_registry(ureg)
Exemple #3
0
 def setUp(self):
     super().setUp()
     self.ureg_bak = get_application_registry()
     self.ureg = UnitRegistry(None)
     self.ureg.define("foo = []")
     self.ureg.define("bar = foo / 2")
     set_application_registry(self.ureg)
     assert get_application_registry() is self.ureg
Exemple #4
0
def ureg_custom_global():
    import pint

    ureg = pint.UnitRegistry()
    ureg.define("test_unit = 123 kg")
    prev = pint._APP_REGISTRY
    pint.set_application_registry(ureg)
    yield ureg
    pint.set_application_registry(prev)
Exemple #5
0
def test_update_saved_registries():
    ureg1 = get_application_registry()
    ureg2 = get_application_registry()

    new = UnitRegistry()
    new.define("foo = []")
    set_application_registry(new)

    assert ureg1.Unit("foo") == ureg2.Unit("foo")
Exemple #6
0
    def test_pickle(self):
        import pickle
        set_application_registry(self.ureg)
        def pickle_test(q):
            pq = pickle.loads(pickle.dumps(q))
            np.testing.assert_array_equal(q.magnitude, pq.magnitude)
            self.assertEqual(q.units, pq.units)

        pickle_test([10,20]*self.ureg.m)
def class_tiny_app_registry():
    ureg_bak = pint.get_application_registry()
    ureg = pint.UnitRegistry(None)
    ureg.define("foo = []")
    ureg.define("bar = foo / 2")
    pint.set_application_registry(ureg)
    assert pint.get_application_registry() is ureg
    yield ureg
    pint.set_application_registry(ureg_bak)
Exemple #8
0
 def test_unit(self, protocol):
     set_application_registry(self.ureg1)
     u1 = Unit("bar")
     set_application_registry(self.ureg2)
     u2 = Unit("bar")
     u3 = pickle.loads(pickle.dumps(u1, protocol))
     assert u1.dimensionality == {"[dim1]": 1}
     assert u2.dimensionality == {"[dim2]": 1}
     assert u3.dimensionality == {"[dim2]": 1}
Exemple #9
0
 def test_quantity_2args(self, protocol):
     set_application_registry(self.ureg1)
     q1 = Quantity(1, "foo")
     set_application_registry(self.ureg2)
     q2 = Quantity(1, "foo")
     q3 = pickle.loads(pickle.dumps(q1, protocol))
     assert q1.dimensionality == {"[dim1]": 1}
     assert q2.dimensionality == {"[dim2]": 1}
     assert q3.dimensionality == {"[dim2]": 1}
     assert q1.to("bar").magnitude == 2
     assert q2.to("bar").magnitude == 3
     assert q3.to("bar").magnitude == 3
Exemple #10
0
def custom_ureg_global():
    import pint

    ureg = pint.UnitRegistry()
    ureg.define("test_unit = 123 kg")
    prev = pint.get_application_registry()
    try:
        # pint.__version__ > 0.18
        prev = prev.get()
    except AttributeError:
        pass
    pint.set_application_registry(ureg)
    yield ureg
    pint.set_application_registry(prev)
Exemple #11
0
def getUnitRegistry(length="meter",
                    time="second",
                    substance="item",
                    volume=None,
                    other=()):
    """Return a pint.UnitRegistry made compatible with ecell4.

    Parameters
    ----------
    length : str, optional
        A default unit for '[length]'. 'meter' is its default.
    time : str, optional
        A default unit for '[time]'. 'second' is its default.
    substance : str, optional
        A default unit for '[substance]' (the number of molecules). 'item' is its default.
    volume : str, optional
        A default unit for '[volume]'. Its default is None, thus '[length]**3'.
    other : tuple, optional
        A list of user-defined default units other than the above.

    Returns
    -------
    ureg : pint.UnitRegistry

    """
    ureg = pint.UnitRegistry()
    ureg.define('item = mole / avogadro_number')
    assert ureg.Quantity(1, 'item').check('[substance]')

    try:
        ureg.molar
    # except UndefinedUnitError:
    except AttributeError:
        # https://github.com/hgrecco/pint/blob/master/pint/default_en.txt#L75-L77
        ureg.define('[concentration] = [substance] / [volume]')
        ureg.define('molar = mol / (1e-3 * m ** 3) = M')

    base_units = [
        unit for unit in (length, time, substance, volume) if unit is not None
    ]
    base_units.extend(other)
    _ = ureg.System.from_lines(["@system local using international"] +
                               base_units, ureg.get_base_units)
    ureg.default_system = 'local'

    wrap_quantity(ureg.Quantity)

    pint.set_application_registry(ureg)  # for pickling
    return ureg
    def test_measurement_3args(self):
        set_application_registry(self.ureg1)
        m1 = Measurement(10, 1, "foo")
        set_application_registry(self.ureg2)
        m2 = Measurement(10, 1, "foo")
        m3 = pickle.loads(pickle.dumps(m1))

        assert m1.dimensionality == {"[dim1]": 1}
        assert m2.dimensionality == {"[dim2]": 1}
        self.assertEqual(m1.to("bar").value.magnitude, 20)
        self.assertEqual(m2.to("bar").value.magnitude, 30)
        self.assertEqual(m3.to("bar").value.magnitude, 30)
        self.assertEqual(m1.to("bar").error.magnitude, 2)
        self.assertEqual(m2.to("bar").error.magnitude, 3)
        self.assertEqual(m3.to("bar").error.magnitude, 3)
Exemple #13
0
    def test_measurement_3args(self, protocol):
        set_application_registry(self.ureg1)
        m1 = Measurement(10, 1, "foo")
        set_application_registry(self.ureg2)
        m2 = Measurement(10, 1, "foo")
        m3 = pickle.loads(pickle.dumps(m1, protocol))

        assert m1.dimensionality == {"[dim1]": 1}
        assert m2.dimensionality == {"[dim2]": 1}
        assert m1.to("bar").value.magnitude == 20
        assert m2.to("bar").value.magnitude == 30
        assert m3.to("bar").value.magnitude == 30
        assert m1.to("bar").error.magnitude == 2
        assert m2.to("bar").error.magnitude == 3
        assert m3.to("bar").error.magnitude == 3
Exemple #14
0
def custom_registry(isolate_application_registry):
    ureg = UnitRegistry(None)
    ureg.define("foo = []")
    ureg.define("bar = foo / 2")
    set_application_registry(ureg)
"""
evaluator
A physical property evaluation toolkit from the Open Forcefield Consortium.
"""

import warnings

import pint

from ._version import get_versions
from .plugins import register_default_plugins, register_external_plugins

unit = pint.UnitRegistry()
unit.default_format = "~"
pint.set_application_registry(unit)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    pint.Quantity([])

# Load the default plugins
register_default_plugins()
# Load in any found external plugins.
register_external_plugins()

# Handle versioneer
versions = get_versions()
__version__ = versions["version"]
__git_revision__ = versions["full-revisionid"]
del get_versions, versions
Exemple #16
0
from pint import UnitRegistry, set_application_registry

__author__ = 'Anubhav Jain <*****@*****.**>, Saurabh Bajaj <*****@*****.**>'

ureg = UnitRegistry()
Q_ = ureg.Quantity
set_application_registry(ureg)
Exemple #17
0
 def tearDown(self):
     set_application_registry(self.ureg_bak)
Exemple #18
0
Example scripts are available at https://github.com/PrincetonUniversity/PsyNeuLink/tree/master/Scripts

If you have trouble installing PsyNeuLink, run into any bugs, or have suggestions for development,
please contact [email protected].
"""

import logging as _logging

import numpy as _numpy
import pint as _pint

# pint requires a package-specific unit registry, and to use it as
# needed in psyneulink, it has to come before imports. This is the
# reason for skipping E402 below
_unit_registry = _pint.get_application_registry()
_pint.set_application_registry(_unit_registry)
_unit_registry.precision = 8  # TODO: remove when floating point issues resolved

# starred imports to allow user imports from top level
from . import core  # noqa: E402
from . import library  # noqa: E402

from ._version import get_versions  # noqa: E402
from .core import *  # noqa: E402
from .library import *  # noqa: E402

_pnl_global_names = [
    'primary_registries',
    'System',
    'Process',
    '_unit_registry',
Exemple #19
0
from functools import wraps

import numpy as np

from .. import ditParams


try:

    import pint

    ureg = pint.UnitRegistry()
    ureg.define('nat = {} * bit'.format(np.log2(np.e)))
    ureg.define('dit = {} * bit'.format(np.log2(10)))
    pint.set_application_registry(ureg)


    def unitful(f):
        """
        Add units to the functions return value.

        Parameters
        ----------
        f : func
            The function to wrap.

        Returns
        -------
        wrapper : func
            A function which optionally adds units to return values.
Exemple #20
0
    U_.define("absolute_transmittance = 1.")
    U_.define("absorbance = 1. = a.u.")
    U_.define("Kubelka_Munk = 1. = K.M.")

    U_.define("ppm = 1. = ppm")

    U_.define(UnitDefinition("percent", "pct", (), ScaleConverter(1 / 100.0)))
    U_.define(
        UnitDefinition("weight_percent", "wt_pct", (),
                       ScaleConverter(1 / 100.0)))

    U_.default_format = "~P"
    Q_ = U_.Quantity
    Q_.default_format = "~P"

    set_application_registry(U_)
    del UnitRegistry  # to avoid importing it

else:
    warn("Unit registry was already set up. Bypassed the new loading")

U_.enable_contexts("spectroscopy", "boltzmann", "chemistry")


# Context for NMR
# ------------------------------------------------------------------
def set_nmr_context(larmor):
    """
    Set a NMR context relative to the given Larmor frequency.

    Parameters
Exemple #21
0
def ureg():
    ureg = pint.UnitRegistry()
    pint.set_application_registry(ureg)
    return ureg
Exemple #22
0
    (pd.refDensity * pd.refGravity * pd.refLength**3).to_base_units() /
    (pd.refViscosity * pd.refDiffusivity).to_base_units()).magnitude

# In[37]:

#print the timescale
s2myr = (1. * ur.megayear).to_base_units().magnitude
if uw.mpi.size == 1:
    print('Dimensionless time to Myr conversion is {}'.format(
        Kt.to_base_units().magnitude / s2myr))

# In[38]:

#*************CHECKPOINT-BLOCK**************#

pint.set_application_registry(ur)  #https://github.com/hgrecco/pint/issues/146

#if this is a restart, attempt to read in saved dicts.
if cp.restart and md.restartParams:
    #try:
    with open(os.path.join(cp.loadpath, 'pd.pkl'), 'rb') as fp:
        pd = pickle.load(fp)
    with open(os.path.join(cp.loadpath, 'md.pkl'), 'rb') as fp:
        md = pickle.load(fp)

    #and check if additional command line args are also being provided
    utils.easy_args(sysArgs, pd)
    utils.easy_args(sysArgs, md)

    #create dimensionless versions of the parameter dictionaries
    npd = params.build_nondim_dict(pd, sca)
Exemple #23
0
 def tearDown(self):
     super(TestCustomApplicationRegistry, self).tearDown()
     set_application_registry(self.ureg_bak)
Exemple #24
0
 def tearDown(self):
     super().tearDown()
     set_application_registry(self.ureg_bak)
Exemple #25
0
>>> v
<Quantity(10.0, 'millimeter / second')>
"""
__test__ = {"Q": Q_.__doc__}  # enable doctest checking.

U_ = WELDX_UNIT_REGISTRY.Unit
U_.__name__ = "U_"
U_.__module__ = "pint.unit"  # skipcq: PYL-W0212
U_.__doc__ = """For details on working with quantities and units, please see the
`pint documentation <https://pint.readthedocs.io/>`_
"""

# set default units
_DEFAULT_LEN_UNIT = WELDX_UNIT_REGISTRY.millimeters
_DEFAULT_ANG_UNIT = WELDX_UNIT_REGISTRY.rad

# set default unit registry for pint-xarray
pint.set_application_registry(WELDX_UNIT_REGISTRY)
pint_xarray.unit_registry = WELDX_UNIT_REGISTRY

__all__ = (
    "META_ATTR",
    "USER_ATTR",
    "WELDX_PATH",
    "WELDX_QUANTITY",
    "WELDX_UNIT_REGISTRY",
    "Q_",
    "U_",
    "UNITS_KEY",
)