예제 #1
0
 def test_pickle_crash_measurement(self, protocol):
     ureg = UnitRegistry(None)
     ureg.define("foo = []")
     m = ureg.Quantity(123, "foo").plus_minus(10)
     b = pickle.dumps(m, protocol)
     with pytest.raises(UndefinedUnitError):
         pickle.loads(b)
예제 #2
0
파일: units.py 프로젝트: Acellera/htmd
def convert(fromunit, tounit, value, fstep=1, timestep=4):
    """ Converts values between units

    Parameters
    ----------
    fromunit : str
        Unit to convert from
    tounit : str
        Unit to convert to
    value : scalar
        The value to convert
    fstep : int
        The sampling frame step of the simulation in nanoseconds
    timestep : int
        The timestep of the simulation in femtoseconds

    Returns
    -------
    conv : scalra
        The converted value
    """

    ureg = UnitRegistry()
    ureg.define('frame = {} * ns'.format(fstep))
    ureg.define('step = ({} / 1000000) * ns = timestep'.format(timestep))

    q = ureg.Quantity(value, fromunit)
    convval = q.to(tounit)
    if convval.units == 'frame' or convval.units == 'step':
        vals = np.round(convval.magnitude).astype(int)
        if vals.size == 1:  # Fix for PyEMMA tica. remove in future
            return int(vals)
        return vals
    else:
        return convval.magnitude
예제 #3
0
파일: unit.py 프로젝트: tomalrussell/smif
class UnitAdaptor(Adaptor):
    """Scalar conversion of units
    """
    def __init__(self, name):
        self._register = UnitRegistry()
        super().__init__(name)

    def before_model_run(self, data_handle: DataHandle):
        """Register unit definitions in registry before model run
        """
        units = data_handle.read_unit_definitions()
        for unit in units:
            self._register.define(unit)

    def convert(self, data_array, to_spec, coefficients):
        data = data_array.data
        from_spec = data_array.spec

        try:
            quantity = self._register.Quantity(data, from_spec.unit)
        except UndefinedUnitError:
            raise ValueError('Cannot convert from undefined unit {}'.format(
                from_spec.unit))

        try:
            converted_quantity = quantity.to(to_spec.unit)
        except UndefinedUnitError as ex:
            raise ValueError('Cannot convert undefined unit {}'.format(
                to_spec.unit)) from ex
        except DimensionalityError as ex:
            msg = 'Cannot convert unit from {} to {}'
            raise ValueError(msg.format(from_spec.unit, to_spec.unit)) from ex

        return converted_quantity.magnitude

    def get_coefficients(self, data_handle, from_spec, to_spec):
        # override with no-op - all the work is done in convert with scalar operations
        pass

    def generate_coefficients(self, from_spec, to_spec):
        # override with no-op - all the work is done in convert with scalar operations
        pass

    def parse_unit(self, unit_string):
        """Parse a unit string (abbreviation or full) into a Unit object

        Parameters
        ----------
        unit : str

        Returns
        -------
        quantity : :class:`pint.Unit`
        """
        try:
            unit = self._register.parse_units(unit_string)
        except UndefinedUnitError:
            self.logger.warning("Unrecognised unit: %s", unit_string)
            unit = None
        return unit
예제 #4
0
def convert(fromunit, tounit, value, fstep=1, timestep=4):
    """ Converts values between units

    Parameters
    ----------
    fromunit : str
        Unit to convert from
    tounit : str
        Unit to convert to
    value : scalar
        The value to convert
    fstep : int
        The sampling frame step of the simulation in nanoseconds
    timestep : int
        The timestep of the simulation in femtoseconds

    Returns
    -------
    conv : scalra
        The converted value
    """

    ureg = UnitRegistry()
    ureg.define('frame = {} * ns'.format(fstep))
    ureg.define('step = ({} / 1000000) * ns = timestep'.format(timestep))

    q = ureg.Quantity(value, fromunit)
    convval = q.to(tounit)
    if convval.units == 'frame' or convval.units == 'step':
        vals = np.round(convval.magnitude).astype(int)
        if vals.size == 1:  # Fix for PyEMMA tica. remove in future
            return int(vals)
        return vals
    else:
        return convval.magnitude
예제 #5
0
    def test_pickle_definition_syntax_error(self):
        # OffsetUnitCalculusError raised from a custom ureg must be pickleable even if
        # the ureg is not registered as the application ureg
        ureg = UnitRegistry(filename=None)
        ureg.define("foo = [bar]")
        ureg.define("bar = 2 foo")
        q1 = ureg.Quantity("1 foo")
        q2 = ureg.Quantity("1 bar")

        for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
            for ex in [
                    DefinitionSyntaxError("foo", filename="a.txt", lineno=123),
                    RedefinitionError("foo", "bar"),
                    UndefinedUnitError("meter"),
                    DimensionalityError("a", "b", "c", "d", extra_msg=": msg"),
                    OffsetUnitCalculusError(
                        Quantity("1 kg")._units,
                        Quantity("1 s")._units),
                    OffsetUnitCalculusError(q1._units, q2._units),
            ]:
                with self.subTest(protocol=protocol, etype=type(ex)):
                    pik = pickle.dumps(ureg.Quantity("1 foo"), protocol)
                    with self.assertRaises(UndefinedUnitError):
                        pickle.loads(pik)

                    # assert False, ex.__reduce__()
                    ex2 = pickle.loads(pickle.dumps(ex, protocol))
                    assert type(ex) is type(ex2)
                    self.assertEqual(ex.args, ex2.args)
                    self.assertEqual(ex.__dict__, ex2.__dict__)
                    self.assertEqual(str(ex), str(ex2))
예제 #6
0
 def test_issue29(self):
     ureg = UnitRegistry()
     ureg.define("molar = mole / liter = M")
     t = 4 * ureg("mM")
     self.assertEqual(t.magnitude, 4)
     self.assertEqual(t.units, UnitsContainer(millimolar=1))
     self.assertEqual(t.to("mole / liter"), 4e-3 * ureg("M"))
예제 #7
0
 def test_issue29(self):
     ureg = UnitRegistry()
     ureg.define('molar = mole / liter = M')
     t = 4 * ureg('mM')
     self.assertEqual(t.magnitude, 4)
     self.assertEqual(t._units, UnitsContainer(millimolar=1))
     self.assertEqual(t.to('mole / liter'), 4e-3 * ureg('M'))
예제 #8
0
 def test_issue29(self):
     ureg = UnitRegistry()
     ureg.define('molar = mole / liter = M')
     t = 4 * ureg['mM']
     self.assertEqual(t.magnitude, 4)
     self.assertEqual(t.units, UnitsContainer(millimolar=1))
     self.assertEqual(t.to('mole / liter'), 4e-3 * ureg['M'])
예제 #9
0
 def test_pickle_crash(self, protocol):
     ureg = UnitRegistry(None)
     ureg.define("foo = []")
     q = ureg.Quantity(123, "foo")
     b = pickle.dumps(q, protocol)
     self.assertRaises(UndefinedUnitError, pickle.loads, b)
     b = pickle.dumps(q.units, protocol)
     self.assertRaises(UndefinedUnitError, pickle.loads, b)
예제 #10
0
def _load_pint_units() -> UnitRegistry:
    """Missing units found in project-haystack Added to the registry"""
    unit_ureg = UnitRegistry(on_redefinition='ignore')
    unit_ureg.load_definitions(
        os.path.join(os.path.dirname(__file__), 'haystack_units.pint'))
    unit_ureg.define(
        UnitDefinition('%', 'percent', (), ScaleConverter(1 / 100.0)))
    return unit_ureg
예제 #11
0
class TestCustomApplicationRegistry(BaseTestCase):
    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

    def tearDown(self):
        super().tearDown()
        set_application_registry(self.ureg_bak)

    def test_unit(self):
        u = Unit("foo")
        self.assertEqual(str(u), "foo")
        u = pickle.loads(pickle.dumps(u))
        self.assertEqual(str(u), "foo")

    def test_quantity_1arg(self):
        q = Quantity("123 foo")
        self.assertEqual(str(q.units), "foo")
        self.assertEqual(q.to("bar").magnitude, 246)
        q = pickle.loads(pickle.dumps(q))
        self.assertEqual(str(q.units), "foo")
        self.assertEqual(q.to("bar").magnitude, 246)

    def test_quantity_2args(self):
        q = Quantity(123, "foo")
        self.assertEqual(str(q.units), "foo")
        self.assertEqual(q.to("bar").magnitude, 246)
        q = pickle.loads(pickle.dumps(q))
        self.assertEqual(str(q.units), "foo")
        self.assertEqual(q.to("bar").magnitude, 246)

    @requires_uncertainties()
    def test_measurement_2args(self):
        m = Measurement(Quantity(123, "foo"), Quantity(10, "bar"))
        self.assertEqual(m.value.magnitude, 123)
        self.assertEqual(m.error.magnitude, 5)
        self.assertEqual(str(m.units), "foo")
        m = pickle.loads(pickle.dumps(m))
        self.assertEqual(m.value.magnitude, 123)
        self.assertEqual(m.error.magnitude, 5)
        self.assertEqual(str(m.units), "foo")

    @requires_uncertainties()
    def test_measurement_3args(self):
        m = Measurement(123, 5, "foo")
        self.assertEqual(m.value.magnitude, 123)
        self.assertEqual(m.error.magnitude, 5)
        self.assertEqual(str(m.units), "foo")
        m = pickle.loads(pickle.dumps(m))
        self.assertEqual(m.value.magnitude, 123)
        self.assertEqual(m.error.magnitude, 5)
        self.assertEqual(str(m.units), "foo")
예제 #12
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")
예제 #13
0
파일: test_issues.py 프로젝트: abmyii/pint
 def test_issue856b(self):
     # Test that, after a deepcopy(), the two UnitRegistries are
     # independent from each other
     ureg1 = UnitRegistry()
     ureg2 = copy.deepcopy(ureg1)
     ureg1.define("test123 = 123 kg")
     ureg2.define("test123 = 456 kg")
     assert ureg1("1 test123").to("kg").magnitude == 123
     assert ureg2("1 test123").to("kg").magnitude == 456
예제 #14
0
 def test_pickle_crash(self, protocol):
     ureg = UnitRegistry(None)
     ureg.define("foo = []")
     q = ureg.Quantity(123, "foo")
     b = pickle.dumps(q, protocol)
     with pytest.raises(UndefinedUnitError):
         pickle.loads(b)
     b = pickle.dumps(q.units, protocol)
     with pytest.raises(UndefinedUnitError):
         pickle.loads(b)
예제 #15
0
def convert(fromunit, tounit, value, fstep=1):
    ureg = UnitRegistry()
    ureg.define('frame = {} * ns = step'.format(fstep))

    q = ureg.Quantity(value, fromunit)
    convval = q.to(tounit)
    if convval.units == 'frame':
        return np.round(convval.magnitude).astype(int)
    else:
        return convval.magnitude
예제 #16
0
 def test_issue25(self):
     x = ParserHelper.from_string("10 %")
     self.assertEqual(x, ParserHelper(10, {"%": 1}))
     x = ParserHelper.from_string("10 ‰")
     self.assertEqual(x, ParserHelper(10, {"‰": 1}))
     ureg = UnitRegistry()
     ureg.define("percent = [fraction]; offset: 0 = %")
     ureg.define("permille = percent / 10 = ‰")
     x = ureg.parse_expression("10 %")
     self.assertEqual(x, ureg.Quantity(10, {"%": 1}))
     y = ureg.parse_expression("10 ‰")
     self.assertEqual(y, ureg.Quantity(10, {"‰": 1}))
     self.assertEqual(x.to("‰"), ureg.Quantity(1, {"‰": 1}))
예제 #17
0
 def test_issue25(self):
     x = ParserHelper.from_string("10 %")
     self.assertEqual(x, ParserHelper(10, {"%": 1}))
     x = ParserHelper.from_string("10 ‰")
     self.assertEqual(x, ParserHelper(10, {"‰": 1}))
     ureg = UnitRegistry()
     ureg.define("percent = [fraction]; offset: 0 = %")
     ureg.define("permille = percent / 10 = ‰")
     x = ureg.parse_expression("10 %")
     self.assertEqual(x, ureg.Quantity(10, {"%": 1}))
     y = ureg.parse_expression("10 ‰")
     self.assertEqual(y, ureg.Quantity(10, {"‰": 1}))
     self.assertEqual(x.to("‰"), ureg.Quantity(1, {"‰": 1}))
예제 #18
0
 def test_issue25(self):
     x = ParserHelper.from_string('10 %')
     self.assertEqual(x, ParserHelper(10, {'%': 1}))
     x = ParserHelper.from_string('10 ‰')
     self.assertEqual(x, ParserHelper(10, {'‰': 1}))
     ureg = UnitRegistry()
     ureg.define('percent = [fraction]; offset: 0 = %')
     ureg.define('permille = percent / 10 = ‰')
     x = ureg.parse_expression('10 %')
     self.assertEqual(x, ureg.Quantity(10, {'%': 1}))
     y = ureg.parse_expression('10 ‰')
     self.assertEqual(y, ureg.Quantity(10, {'‰': 1}))
     self.assertEqual(x.to('‰'), ureg.Quantity(1, {'‰': 1}))
예제 #19
0
 def test_issue25(self):
     x = ParserHelper.from_string('10 %')
     self.assertEqual(x, ParserHelper(10, {'%': 1}))
     x = ParserHelper.from_string('10 ‰')
     self.assertEqual(x, ParserHelper(10, {'‰': 1}))
     ureg = UnitRegistry()
     ureg.define('percent = [fraction]; offset: 0 = %')
     ureg.define('permille = percent / 10 = ‰')
     x = ureg.parse_expression('10 %')
     self.assertEqual(x, ureg.Quantity(10, {'%': 1}))
     y = ureg.parse_expression('10 ‰')
     self.assertEqual(y, ureg.Quantity(10, {'‰': 1}))
     self.assertEqual(x.to('‰'), ureg.Quantity(1, {'‰': 1}))
예제 #20
0
def _build_unit_registry():
    try:
        from pint import UnitRegistry

        registry = UnitRegistry()
        registry.define('FPS = 1 * hertz')
    except ImportError:
        class NoUnitRegistry:

            def __init__(self):
                pass

            def __getattr__(self, item):
                return 1

        registry = NoUnitRegistry()

    return registry
예제 #21
0
def _load_units():
    units = UnitRegistry()

    custom_units = redis.hgetall(UNIT_KEY)
    logger.info("Loading units (%d custom definitions)", len(custom_units))

    for name, definition in custom_units.items():
        logger.debug("loading custom unit: %s = %s", name, definition)

        if definition.startswith("__age"):
            birthday = date.fromisoformat(definition.split(" ")[1])
            age = (date.today() - birthday).total_seconds()

            definition = f"{age} seconds"
            logger.debug("Converted date: %s to: %s", birthday, definition)

        units.define(f"{name} = {definition}")

    return units
 def setup_class(self):
     #
     ureg = UnitRegistry()
     ureg.define('micron = um')
     self.ureg = ureg
     #
     self.convert_value_test = [
         (0.0, 'degC', 'degK', ureg.Quantity(0.0, 'degC').to('degK')),
         (1.0, 'psi', 'SI', ureg.Quantity(1, 'psi').to_base_units()),
         (1.0, 'cP', 'dyne*s/cm^2', ureg.Quantity(1.0,
                                                  'cP').to('dyne*s/cm^2')),
         (1000.0, 'microns', 'SI', ureg.Quantity(1000,
                                                 'microns').to_base_units())
     ]
     #
     self._convertion_factor_test = [
         ('psi', 'kN/m^2', ureg('psi').to('kN/m^2').magnitude),
         ('lbf', 'N', ureg('lbf').to('N').magnitude),
         ('micron', 'SI', ureg('micron').to('m').magnitude),
         ('ml/min', 'SI', ureg('ml/min').to('m^3/sec').magnitude)
     ]
예제 #23
0
    def init_unit_reg():
        ureg = UnitRegistry(on_redefinition="ignore")

        ureg.define("hash = [hash] = H")
        ureg.define("solution = [solution] = Sol")
        ureg.define("bitcoin = [currency] = BTC")

        ureg.default_format = '~'

        Benchmarker.ureg = ureg
예제 #24
0
def get_pint_units():
    from pint import UnitRegistry

    # Add new units to UnitRegistry
    units = UnitRegistry()
    units.define('gram N = mol / 14 = gN')
    units.define('gram C = mol / 12 = gC')
    units.define('year = 365 day = yr')
    units.define('micromoles_per_kilogram = umol / kg')  # used in WOA datasets

    # Define final units
    PgC_per_year = 'PgC/yr'
    TgN_per_year = 'TgN/yr'
    uM = 'uM'

    final_units = dict()
    final_units['photoC_TOT_zint'] = PgC_per_year
    final_units['photoC_diat_zint'] = PgC_per_year
    final_units['photoC_TOT_zint_100m'] = PgC_per_year
    final_units['photoC_diat_zint_100m'] = PgC_per_year
    final_units['POC_FLUX_100m'] = PgC_per_year
    final_units['CaCO3_FLUX_100m'] = PgC_per_year
    final_units['SiO2_FLUX_100m'] = 'Tmol/yr'
    final_units['diaz_Nfix'] = TgN_per_year
    final_units['NOx_FLUX'] = TgN_per_year
    final_units['NHy_FLUX'] = TgN_per_year
    final_units['NHx_SURFACE_EMIS'] = TgN_per_year
    final_units['DENITRIF'] = TgN_per_year
    final_units['ponToSed'] = TgN_per_year
    final_units['SedDenitrif'] = TgN_per_year
    final_units['DON_RIV_FLUX'] = TgN_per_year
    final_units['DONr_RIV_FLUX'] = TgN_per_year
    final_units['NO3_RIV_FLUX'] = TgN_per_year
    final_units['FG_CO2'] = PgC_per_year
    final_units['O2'] = 'uM'
    final_units['O2_under_thres'] = 'Pm * m^2'

    return units, final_units
예제 #25
0
from pint import UnitRegistry

units = UnitRegistry()

units.define('dollars = 100 * cents')
units.define('milli_beta = 10 * cents')
units.define('cents = []')
units.define('per_cent_mille = 0.001 * per_cent_delta_k = pcm')
units.define('mult_factor = [] = 1000 * pcm = keff')
units.define('per_cent_delta_k = 0.01 * delta_k')
units.define('delta_k = keff/keff')

units.define('MeV = 1.6e-19 * joules')
예제 #26
0
import pytz
from pint import UnitRegistry


tz = pytz.timezone('Canada/Pacific')
ureg = UnitRegistry()
Q_ = ureg.Quantity
for def_ in (
        "degreeC = degC; offset: 273.15",
        "degreeF = 5 / 9 * kelvin; offset: 255.372222",
        "degreeK = degK; offset: 0"
):
    ureg.define(def_)
예제 #27
0
파일: unit.py 프로젝트: gridsim/gridsim
class _Unit(object):

    def __init__(self):
        """
        Also commented in top of file for website.

        It provides an object call ``units`` which is a wrapper to all useful features
        of pint, thus it should used as follow::

            >>> from gridsim.unit import units
            >>> area = 1.2*units.meter * 2.5*units.meter
            >>> print area
            3.0 meter ** 2
            >>> print units.value(area)
            3.0
            >>> print units.dimension(area)
            [length] ** 2
            >>> print units.unit(area)
            meter ** 2

        As it is possible to create a measurement by crossing a number value by the unit::

            >>> size1 = 1.2*units.meter

        it is also possible to create a measurement in an oriented-object way::

            >>> size2 = units(1.2, units.meter)

        and::

            >>> size1 == size2
            True

        .. warning:: The second method to create a measurement MUST be used to define
                     non standard temperature and SHALL be converted in standard unit
                     before sending to the simulator unless
                     a ``pint.unit.OffsetUnitCalculusError`` will be raised::

                        celsius = units(20, units.degC)                                   # define temperature in degree celsius
                        room = sim.thermal.add(ThermalProcess.room('room',
                                                   50*units.meter*units.meter,            # define square metre
                                                   2.5*units.metre,                       # define metre
                                                   units.convert(celsius, units.kelvin))) # convert celsius to kelvin for the simulation

                     Also, there is a delta counterpart to specify temperature
                     differences. Absolute units have no delta counterpart.
                     For example, the change in celsius is equal to the change
                     in kelvin, but not in fahrenheit (as the scaling factor is
                     different)::

                         >>> hysteresis = 2.4*units.delta_degC
                         >>> print(hysteresis.to(units.kelvin))
                         2.4 kelvin
                         >>> print(hysteresis.to(units.delta_degF))
                         4.32 delta_degF


        """
        self._registry = UnitRegistry(os.path.dirname(__file__)+'/gridsim_en.unit')
        self._registry.define('heat_capacity = J/(kg*K)')
        self._registry.define('mass_density = kg/(m*m*m)')
        self._registry.define('thermal_conductivity = W/(K*m)')

        self._Quantity_class = self._registry.Quantity
        self._Unit_class = self._registry.Quantity

    @property
    def Quantity(self):
        return self._Quantity_class

    @property
    def Unit(self):
        return self._Unit_class

    def __call__(self, *args, **kwargs):
        if len(args) is 1:
            return self._registry(args[0])
        return self._Quantity_class(args[0], args[1])

    def __getattr__(self, item):
        return getattr(self._registry, item)

    def to_si(self, measurement_or_unit):
        if isinstance(measurement_or_unit, self._Quantity_class):
            _measurement = measurement_or_unit.to_base_units()
            return _measurement
        elif isinstance(measurement_or_unit, self._Unit_class):
            _unit = self.unit(self.to_si(1*measurement_or_unit))
            return _unit
        else:
            raise AttributeError('Attribute must be a unit or a measurement not a '+str(type(measurement_or_unit)))

    def value(self, measurement, unit=None):
        if unit is not None:
            _measurement = self.convert(measurement, unit)
        else:
            _measurement = measurement

        if isinstance(_measurement, self._Quantity_class):
            return _measurement.magnitude
        else:
            return _measurement

    def unit(self, measurement):
        if isinstance(measurement, self._Quantity_class):
            return str(measurement.units)
        else:
            return ""

    def dimension(self, measurement):
        if isinstance(measurement, self._Quantity_class):
            return str(measurement.dimensionality)
        else:
            return ""

    def convert(self, m, u):
        if isinstance(m, (int, float)):
            return self._Quantity_class(m, u)
        else:
            return m.to(u)
예제 #28
0
import pytest
import resppol
import resppol.resppol
import os
from pint import UnitRegistry

ROOT_DIR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..',
                             '..')

ureg = UnitRegistry()
Q_ = ureg.Quantity
ureg.define('bohr = 0.52917721067 * angstrom')
#######################################################################################
# The following tests are based on 2 or 3 atoms and can be calculate easily on a piece of paper as well.
######################################################################################


def test_simple_charges():
    datei = os.path.join(ROOT_DIR_PATH,
                         'resppol/data/fast_test_data/test2.mol2')
    test = resppol.resppol.TrainingSet()
    test.add_molecule(datei)
    test.molecules[0].add_conformer_from_mol2(datei)
    espfile = os.path.join(ROOT_DIR_PATH,
                           'resppol/data/fast_test_data/test1.gesp')
    test.molecules[0].conformers[0].add_baseESP(espfile)
    test.optimize_charges()
    for charge in test.molecules[0].q:
        assert charge.magnitude == pytest.approx(0.0, 0.001)

예제 #29
0
class HomeDisplayApp(App):
    def build(self):
        self.display = HomeDisplay()
        return self.display

    def connected(self, client, userdata, flags, rc):
        if rc == 0:
            client.subscribe("indoor/#")
            client.subscribe("outdoor/#")

    def messaged(self, client, userdata, msg):
        data = json.loads(msg.payload)
        if not data or not "value" in data or not "unit" in data:
            return
        quantity = "{:~P}".format(self.Q_(data["value"], data["unit"]))
        level = msg.topic.split("/")
        if len(level
               ) == 2 and level[0] == "outdoor" and level[1] == "temperature":
            self.display.outdoorTemperature = quantity
        elif len(level) == 3 and level[0] == "indoor":
            if level[1] == "upstairs":
                if level[2] == "temperature":
                    self.display.upstairsTemperature = quantity
                elif level[2] == "humidity":
                    self.display.upstairsHumidity = quantity
            elif level[1] == "downstairs":
                if level[2] == "temperature":
                    self.display.downstairsTemperature = quantity
                elif level[2] == "humidity":
                    self.display.downstairsHumidity = quantity

    def getOnboardReading(self, key, *largs):
        if self._client.is_connected:
            humidity, temperature = Adafruit_DHT.read_retry(
                Adafruit_DHT.DHT22, 2)
            if humidity is not None:
                self._client.publish(
                    "indoor/downstairs/humidity",
                    json.dumps({
                        "value": round(humidity, 1),
                        "unit": "percent"
                    }))
            if temperature is not None:
                self._client.publish(
                    "indoor/downstairs/temperature",
                    json.dumps({
                        "value": round(temperature, 1),
                        "unit": "degC"
                    }))

    def on_start(self):
        self._ureg = UnitRegistry()
        self._ureg.define("percent = 1e-2 [] = % = pc")
        self.Q_ = self._ureg.Quantity
        self._client = mqtt.Client(userdata={"self": self})
        self._client.on_connect = self.connected
        self._client.on_message = self.messaged
        self._client.connect(MQTT_URL, MQTT_PORT)
        self._client.loop_start()
        if "Adafruit_DHT" in sys.modules:
            Clock.schedule_interval(self.getOnboardReading, 2)
예제 #30
0
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
from pint import UnitRegistry
ureg = UnitRegistry()
ureg.define('electron_volt = 1.60217657*10**(-19)*joules')

dk_1d = 0.1

a_cc = 0.142 #* ureg.nanometer
a_1 = a_cc/2 * np.array([3, np.sqrt(3)]) 
a_2 = a_cc/2 * np.array([3, -np.sqrt(3)]) 

b_1 = 2*np.pi/(3*a_cc) * np.array([1, np.sqrt(3)]) 
b_2 = 2*np.pi/(3*a_cc) * np.array([1, -np.sqrt(3)]) 

K = 2*np.pi/(3*a_cc) * np.array([1, 1/np.sqrt(3)])
K_prime = 2*np.pi/(3*a_cc) * np.array([1, -1/np.sqrt(3)]) 

def E(k_x, k_y):
	t = 2.8 #* ureg.electron_volt
	return np.array([t*np.sqrt(3+f(k_x, k_y)), -t*np.sqrt(3+f(k_x, k_y))])

def f(k_x, k_y):
	return 2*np.cos(np.sqrt(3)*k_y*a_cc)+ \
               4*np.cos(np.sqrt(3)/2*k_y*a_cc)*np.cos(3/2*k_x*a_cc)

fig = plt.figure()

im = plt.imread('Arpes3crop.png')
예제 #31
0
import matplotlib.style
matplotlib.style.use('ggplot')
# matplotlib.style.use('matplotlibrc')
import matplotlib.pyplot as plt
import numpy as np
import scipy.constants as c
from pint import UnitRegistry
u = UnitRegistry()
u.define('electronvolts = 10E-19 * joule = eV')
u.define('megaelectronvolts = 10E-13 * joule = MeV')

from IPython import embed
def electron_density(rho):
    ## assume air is made of nitrogen and nothing else. -> We all die.
    Z = 7
    A = Z + 7 #plus 7 neutrons
    n = ( Z *rho ) / ( A *u.amu ) # multiply atomic mass unit
    return n

def bethe(n, z, v, I):
    ln = np.log((2 * c.m_e*u.kilogram * v**2) / I)
    eps = c.epsilon_0*(u.ampere*u.second/(u.volt*u.meter))
    a = (4 * np.pi * n * z**2)/(c.m_e*u.kilogram * v**2) * ((c.e*u.coulomb)**2 / (4 *np.pi *eps))**2
    return a*ln


am_energy = 5.408 * u.MeV
alpha_mass = 4*u.amu
speed = np.sqrt(2*am_energy /  alpha_mass).to('meter/second') #meter per second

#nitrogen exitation?
예제 #32
0
파일: ur.py 프로젝트: peterfiflis1/pyrk
from pint import UnitRegistry

units = UnitRegistry()
units.define('dollars = 100 * cents')
units.define('milli_beta = 10 * cents')
units.define('cents = []')
units.define('per_cent_mille = 0.00001 * delta_k = pcm')
units.define('mult_factor = [] = 1000 * pcm = keff')
units.define('per_cent_delta_k = 0.01 * delta_k')
units.define('delta_k = keff/keff')

units.define('MeV = 1.6e-19 * joules')
예제 #33
0
import math
import re

# units
from pint import UnitRegistry
units = UnitRegistry()

# my guess as to why 508 is the magic number is the motor steps and the belt TPI
# i am guessing the belt is 2.54 TPI, and the motor can provide 200 steps
# 2.54 * 200 = 508
units.define('steps = inch / 508.0 = step')

# For SVG files, Silhouette Studio defines one inch as 72 points
units.define('dpi = inch / 72.0')

def steps(val):
    val = unit(val, unit=None)
    return int(val.to("steps").magnitude)

## units

DEFAULT_UNIT = "mm"

def unit(val, **kw):
    _unit = kw.get("unit", DEFAULT_UNIT)
    if _unit != None:
        _unit = units.parse_expression(_unit)
    if type(val) != units.Quantity:
        if type(val) in (int, float):
            assert _unit, "value %r of type '%r' requires a unit definition" % (val, type(val))
            val = val * _unit
예제 #34
0
파일: units.py 프로젝트: olemke/typhon
# -*- 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))}
예제 #35
0
파일: axedit.py 프로젝트: vpaeder/terapy
for y in [["hertz", "Hz"], ["meter", "m"], ["second", "s"], ["volt", "V"], ["ampere", "A"]]:
    for x in [
        ["atto", 1.0e-18, "a"],
        ["femto", 1.0e-15, "f"],
        ["pico", 1.0e-12, "p"],
        ["nano", 1.0e-9, "n"],
        ["micro", 1.0e-6, "u"],
        ["milli", 1.0e-3, "m"],
        ["kilo", 1.0e3, "k"],
        ["mega", 1.0e6, "M"],
        ["giga", 1.0e9, "G"],
        ["tera", 1.0e12, "T"],
        ["peta", 1.0e15, "P"],
        ["exa", 1.0e18, "E"],
    ]:
        urg.define("%s%s = %1.0e*%s = %s%s" % (x[0], y[0], x[1], y[0], x[2], y[1]))

# default units
du = {}
for x in default_units:
    try:
        du[x] = Q_(1.0, urg[default_units[x]])
    except:
        print "WARNING: can't understand units'%s' " % (x)


class AxesPropertiesDialog(wx.Dialog):
    """
    
        Axes properties selection dialog
    
예제 #36
0
"""
Defines common/useful physical constants.  
"""

import math
import warnings
from pint import UnitRegistry, Quantity

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

unit_registry = UnitRegistry()
unit_registry.setup_matplotlib()

# Register gamma*beta units for electrons
unit_registry.define('GB = 510998.946 * eV/c')

# physical_constants
c = 299792458 * unit_registry.parse_expression("m/s")
e = 1.602176634e-19 * unit_registry.parse_expression(
    "coulomb")  # Fundamental Charge Unit
qe = -e  # Charge on electron
me = 9.1093837015e-31 * unit_registry.kg  # Mass of electron
MC2 = (me * c * c).to(unit_registry.electron_volt)  # Electron rest mass

# Mathematical constants
pi = math.pi * unit_registry("rad")
예제 #37
0
from math import isclose
import sys

import CoolProp
from pint import UnitRegistry, DimensionalityError
from pint.unit import UnitsContainer, UnitDefinition
from pint.converters import ScaleConverter

try:  # pragma: no cover
    from IPython.core.ultratb import AutoFormattedTB
except ImportError:  # pragma: no cover
    AutoFormattedTB = None

units = UnitRegistry(autoconvert_offset_to_baseunit=True)
Q_ = units.Quantity
units.define(UnitDefinition("percent", "pct", (), ScaleConverter(1.0 / 100.0)))
units.setup_matplotlib()

# Don't add the _render_traceback_ function to DimensionalityError if
# IPython isn't present. This function is only used by the IPython/ipykernel
# anyways, so it doesn't matter if it's missing if IPython isn't available.
if AutoFormattedTB is not None:  # pragma: no cover

    def render_traceback(self):
        """Render a minimized version of the DimensionalityError traceback.

        The default Jupyter/IPython traceback includes a lot of
        context from within pint that actually raises the
        DimensionalityError. This context isn't really needed for
        this particular error, since the problem is almost certainly in
        the user code. This function removes the additional context.
예제 #38
0
import itertools
from pint import UnitRegistry
import numpy

ureg = UnitRegistry()
Quantity = ureg.Quantity
ureg.define('molar = 1 * mole / liter = M')
ureg.define('standard_concentration = 1 M')


def permutation_with_replacement(n, seq):
    """
    Returns a list of all possible combinations of elements in seq, with length n.
    (Like permutation with replacement)
    """
    options = list()
    for p in itertools.product(seq, repeat=n):
        options.append(p)
    return options

@ureg.wraps(ureg.dimensionless, ureg.dimensionless, strict=False)
def compute_rm(c):
    """Calculate the ratio Rm of titrant to titrand.
        c = [M]_0 * Ka
        R_m = 6.4/c^0.2 + 13/c
    """
    rm = 6.4 / numpy.power(c, 0.2) + 13 / c
    return rm
예제 #39
0
"""
Manipulation of physical quantities (with units, etc.).

See https://pint.readthedocs.io/en/latest/
"""
from pint import UnitRegistry
ureg = UnitRegistry()
Q_ = ureg.Quantity
ureg.define('electronvolt = e * volt = eV')
ureg.define('electronvolt_per_c = eV / c = eV_c')
ureg.define('electronvolt_per_c2 = eV / c**2 = eV_c2')
ureg.define('gauss = 1e-4 * tesla = G')  # see https://github.com/hgrecco/pint/issues/1105
예제 #40
0
from pint import UnitRegistry

_unitRegistry = UnitRegistry()
_unitRegistry.define("mil = inch / 1000")


def _toUnit(floatOrUnited, unitName):
    try:
        return floatOrUnited.to(unitName).magnitude
    except:
        return _unitRegistry.Quantity(floatOrUnited, unitName).magnitude

toInch = lambda f: _toUnit(f, 'inch')
toMM = lambda f: _toUnit(f, 'inch')
inch = _unitRegistry.inch
mil = _unitRegistry.mil
cm = _unitRegistry.cm
mm = _unitRegistry.mm
예제 #41
0
파일: units.py 프로젝트: palenque/geonode
from pint import UnitRegistry

units = UnitRegistry()
units.define('ha = hm**2')
units.define('m2 = m**2')
units.define('h = hr')

VOLUME_MAGNITUDES = (
    ('m3','m3'),
    ('cm3','cm3'),
)

YIELD_MAGNITUDES = (
    ('ton/ha','ton/ha'),
)

SPEED_MAGNITUDES = (
    ('m/s','m/s'),
    ('km/h','km/h'),
)

FLOW_MAGNITUDES = (
    ('kg/s','kg/s'),
)

DISTANCE_MAGNITUDES = (
    ('m','m'),
    ('cm','cm'),
)

TIME_MAGNITUDES = (
예제 #42
0
파일: axedit.py 프로젝트: vpaeder/terapy
    Classes for axes labels and units management

"""

import wx.grid
from wx.lib import sheet
from terapy.core import default_units
from pint import UnitRegistry
from numpy import log10

urg = UnitRegistry()
Q_ = urg.Quantity
for y in [['hertz','Hz'],['meter','m'],['second','s'],['volt','V'],['ampere','A']]:
    for x in [['atto',1.0e-18,'a'],['femto',1.0e-15,'f'],['pico',1.0e-12,'p'],['nano',1.0e-9,'n'],['micro',1.0e-6,'u'],['milli',1.0e-3,'m'],['kilo',1.0e3,'k'],['mega',1.0e6,'M'],['giga',1.0e9,'G'],['tera',1.0e12,'T'],['peta',1.0e15,'P'],['exa',1.0e18,'E']]:
        urg.define('%s%s = %1.0e*%s = %s%s' % (x[0],y[0],x[1],y[0],x[2],y[1]))

# default units
du = {}
for x in default_units:
    try:
        du[x] = Q_(1.0,urg[default_units[x]])
    except:
        print "WARNING: can't understand units'%s' " % (x)

class AxesPropertiesDialog(wx.Dialog):
    """
    
        Axes properties selection dialog
    
    """
예제 #43
0
from mongoengine import ValidationError
from mongoengine.base.datastructures import BaseDict
from itsdangerous import URLSafeTimedSerializer
from pint import UnitRegistry
from pint.unit import UnitDefinition
from pint.converters import ScaleConverter
from string import punctuation
from boltons.iterutils import remap, default_enter

ureg = UnitRegistry(preprocessors=[
    lambda s: s.replace("%%", " permille "),
    lambda s: s.replace("%", " percent "),
])
ureg.default_format = "P~"

ureg.define(UnitDefinition("percent", "%", (), ScaleConverter(0.01)))
ureg.define(UnitDefinition("permille", "%%", (), ScaleConverter(0.001)))
ureg.define(UnitDefinition("ppm", "ppm", (), ScaleConverter(1e-6)))
ureg.define(UnitDefinition("ppb", "ppb", (), ScaleConverter(1e-9)))
ureg.define("atom = 1")
ureg.define("bohr_magneton = e * hbar / (2 * m_e) = µᵇ = µ_B = mu_B")
ureg.define("electron_mass = 9.1093837015e-31 kg = mₑ = m_e")

Q_ = ureg.Quantity
delimiter, max_depth = ".", 3
max_dgts = 6
invalidChars = set(punctuation.replace("*", ""))
invalidChars.add(" ")
quantity_keys = {"display", "value", "unit"}

for mod in [
예제 #44
0
def define_haystack_units():
    """
    Missing units found in project-haystack
    Added to the registry
    """
    ureg = UnitRegistry()
    ureg.define('% = [] = percent')
    ureg.define('pixel = [] = px = dot = picture_element = pel')
    ureg.define('decibel = [] = dB')
    ureg.define('ppu = [] = parts_per_unit')
    ureg.define('ppm = [] = parts_per_million')
    ureg.define('ppb = [] = parts_per_billion')
    ureg.define('%RH = [] = percent_relative_humidity = percentRH')
    ureg.define('cubic_feet = ft ** 3 = cu_ft')
    ureg.define('cfm = cu_ft * minute = liter_per_second / 0.4719475')
    ureg.define('cfh = cu_ft * hour')
    ureg.define('cfs = cu_ft * second')
    ureg.define('VAR = volt * ampere')
    ureg.define('kVAR = 1000 * volt * ampere')
    ureg.define('MVAR = 1000000 * volt * ampere')
    ureg.define('inH2O = in_H2O')
    ureg.define('dry_air = []')
    ureg.define('gas = []')
    ureg.define('energy_efficiency_ratio = [] = EER')
    ureg.define('coefficient_of_performance = [] = COP')
    ureg.define('data_center_infrastructure_efficiency = [] = DCIE')
    ureg.define('power_usage_effectiveness = [] = PUE')
    ureg.define('formazin_nephelometric_unit = [] = fnu')
    ureg.define('nephelometric_turbidity_units = [] = ntu')
    ureg.define('power_factor = [] = PF')
    ureg.define('degree_day_celsius = [] = degdaysC')
    ureg.define('degree_day_farenheit = degree_day_celsius * 9 / 5 = degdaysF')
    ureg.define('footcandle = lumen / sq_ft = ftcd')
    ureg.define('Nm = newton * meter')
    ureg.define('%obsc = [] = percent_obscuration = percentobsc')
    ureg.define('cycle = []')
    ureg.define('cph = cycle / hour')
    ureg.define('cpm = cycle / minute')
    ureg.define('cps = cycle / second')
    ureg.define('hecto_cubic_foot = 100 * cubic_foot')
    ureg.define('tenths_second = second / 10')
    ureg.define('hundredths_second = second / 100')

    #ureg.define('irradiance = W / sq_meter = irr')
    # In the definition of project haystack, there's a redundancy as irr = W/m^2
    # no need to use : watts_per_square_meter_irradiance
    
    # CURRENCY
    # I know...we won'T be able to convert right now !
    ureg.define('australian_dollar = [] = AUD')
    ureg.define('british_pound = [] = GBP = £')
    ureg.define('canadian_dollar = [] = CAD')
    ureg.define('chinese_yuan = [] = CNY = 元')
    ureg.define('emerati_dirham = [] = AED')
    ureg.define('euro = [] = EUR = €')
    ureg.define('indian_rupee = [] = INR = ₹')
    ureg.define('japanese_yen = [] = JPY = ¥')
    ureg.define('russian_ruble = [] = RUB = руб')
    ureg.define('south_korean_won = [] = KRW = ₩')
    ureg.define('swedish_krona = [] = SEK = kr')
    ureg.define('swiss_franc = [] = CHF = Fr')
    ureg.define('taiwan_dollar = [] = TWD')
    ureg.define('us_dollar = [] = USD = $')
    ureg.define('new_israeli_shekel = [] = NIS')

    return ureg
예제 #45
0
"""Core settings"""
from pint import UnitRegistry

UNITS = UnitRegistry()
UNITS.define('knots = knot')
UNITS.define('nmi = nautical_mile')

UNIT_SETTING = {'speed': 'knots', 'dist': 'nmi'}

DATETIME_FORMAT_STR = "%Y-%m-%dT%H:%M:%S%z"
예제 #46
0
# Preload UnitRegistry (Use default Pints definition file as a base)
_UnitRegistry = UnitRegistry()

'''Map string representation of Pint units over to Autoprotocol format'''
# Map Temperature Unit names
_UnitRegistry._units["degC"]._name = "celsius"
_UnitRegistry._units["celsius"]._name = "celsius"
_UnitRegistry._units["degF"]._name = "fahrenheit"
_UnitRegistry._units["fahrenheit"]._name = "fahrenheit"
_UnitRegistry._units["degR"]._name = "rankine"
_UnitRegistry._units["rankine"]._name = "rankine"
# Map Speed Unit names
_UnitRegistry._units["revolutions_per_minute"]._name = "rpm"

'''Add support for Molarity Unit'''
_UnitRegistry.define('molar = mole/liter = M')


class Unit(_Quantity):
    """
    A representation of a measure of physical quantities such as length,
    mass, time and volume.
    Uses Pint's Quantity as a base class for implementing units and
    inherits functionalities such as conversions and proper unit
    arithmetic.
    Note that the magnitude is stored as a double-precision float, so
    there are inherent issues when dealing with extremely large/small
    numbers as well as numerical rounding for non-base 2 numbers.

    Example
    -------
예제 #47
0
    # if hours > 0:
    #     return '%dh%dm%ds' % (hours, minutes, seconds)
    # elif minutes > 0:
    #     return '%dm%ds' % (minutes, seconds)
    # else:
    #     return '%ds' % (seconds,)

    if hours > 0:
        return '%02d:%02d:%02d' % (hours, minutes, seconds)
    else:
        return '%02d:%02d' % (minutes, seconds)


from pint import UnitRegistry, DimensionalityError
unitRegistry = UnitRegistry()
unitRegistry.define('pt = point')
Quantity = unitRegistry.Quantity


def as_unit(v, u):
    if u:
        q = Quantity(v)
        if q.dimensionless:
            return float(v)
        else:
            return q.m_as(u)
    else:
        return float(v)


def parse_value(v, default, minmax, unit=None):
예제 #48
0
            "Tag": None
        },  #SettingsSorterGeneral
        "9cdcea3f-88aa-40cf-89db-818315a2644a": {
            "McsPyClass": "ActivitySummary",
            "Tag": None
        },  #Activity Summary group
    }

    @classmethod
    def get_mcs_class_name(self, typeID):
        """
        Returns the McsPy class name, that corresponds to a given Mcs HDF5 file structure type. The function also checks if the requested class supports 
        the Mcs HDF5 file structure type version

        :param typeID: name of the type that is tested
        :returns: a McsCMOSMEA class if the given type and version is supported
        """
        if not typeID in McsHdf5Types.SUPPORTED_TYPES:
            return None
        class_name = McsHdf5Types.SUPPORTED_TYPES[typeID]['McsPyClass']
        if class_name is None:
            return None
        return getattr(McsCMOSMEA, class_name)


from pint import UnitRegistry
ureg = UnitRegistry()
Q_ = ureg.Quantity
ureg.define('NoUnit = [quantity]')

from McsPy import McsCMOSMEA
예제 #49
0
파일: __init__.py 프로젝트: hoburg/gpkit
"wraps pint in gpkit monomials"
import os
try:
    from pint import UnitRegistry, DimensionalityError

    ureg = UnitRegistry()  # pylint: disable=invalid-name
    ureg.load_definitions(os.sep.join([os.path.dirname(__file__),
                                       "usd_cpi.txt"]))
    # next line patches https://github.com/hgrecco/pint/issues/366
    ureg.define("nautical_mile = 1852 m = nmi")
    Quantity = ureg.Quantity
except ImportError:  # pint is not installed; provide dummy imports
    ureg = None  # pylint: disable=invalid-name
    Quantity = lambda a, b: None
    DimensionalityError = None

QTY_CACHE = {}
MON_CACHE = {}


def qty(unit):
    "Returns a Quantity, caching the result for future retrievals"
    if unit not in QTY_CACHE:
        QTY_CACHE[unit] = Quantity(1, unit)
    return QTY_CACHE[unit]


class GPkitUnits(object):
    "Return Monomials instead of Quantitites"

    def __call__(self, arg):
예제 #50
0
from pint import UnitRegistry

units = UnitRegistry()
units.define("dollars = 100 * cents")
units.define("milli_beta = 10 * cents")
units.define("cents = []")
units.define("per_cent_mille = 0.00001 * delta_k = pcm")
units.define("mult_factor = [] = 1000 * pcm = keff")
units.define("per_cent_delta_k = 0.01 * delta_k")
units.define("delta_k = keff/keff")

units.define("Pa = kg/meter/second**2")
units.define("MeV = 1.6e-19 * joules")
예제 #51
0
파일: constants.py 프로젝트: vhirtham/weldx
"""Define constants for global library use."""

from pint import UnitRegistry

WELDX_UNIT_REGISTRY = UnitRegistry(
    preprocessors=[lambda string: string.replace("%", "percent")
                   ],  # allow %-sign
    force_ndarray_like=True,
)
WELDX_QUANTITY = WELDX_UNIT_REGISTRY.Quantity

# add percent unit
WELDX_UNIT_REGISTRY.define("percent = 0.01*count = %")
# swap plank constant for hour definition
WELDX_UNIT_REGISTRY.define("hour = 60*minute = h = hr")
예제 #52
0
파일: units.py 프로젝트: tuxxi/OpenBurn
from pint import UnitRegistry

# Pint's unit registry has many units, but we need to define a few ourselves.
ureg = UnitRegistry()

# for some reason slugs are not a default unit (probably because slugs are ridicules and awful )
ureg.define('slug = lbf * s**2 / foot = slug')

# density units
ureg.define('lb_per_cubic_inch = pounds / (inch**3) = lb_per_in3')
ureg.define('slug_per_cubic_inch = slug / (inch**3) = slug_per_in3')
ureg.define('kg_per_cubic_meter = kilogram / (meter**3) = kg_per_m3')

# velocity units
ureg.define('feet_per_second = feet / second = fps')
ureg.define('meters_per_second = meters / second = mps')

# burn rate units
ureg.define('inch_per_second = inch / second = ips')
ureg.define('mm_per_second = mm / second = mmps')

# mass flux units
ureg.define('lb_per_sec_per_sq_in = lb / second / inch**2')
ureg.define('kg_per_sec_per_sq_m = kg / second / meter**2')


def convert_magnitude(val: float, from_: str, to_: str) -> float:
    """
    Convert a magnitude to a new unit
    :param val: the magnitude to convert
    :param from_: the unit to convert from, a str defined in the pint unit registry @ureg
예제 #53
0
파일: rail.py 프로젝트: vishnubob/camrail
import time
import math
import pigpio

# units
from pint import UnitRegistry
units = UnitRegistry()
units.define('steps = in / 254 = step')

DEFAULT_UNIT = units.parse_expression("steps")

def unit(val, **kw):
    _unit = kw.get("unit", DEFAULT_UNIT)
    val = units.parse_expression(val)
    if type(val) != units.Quantity:
        if type(val) in (int, float):
            assert _unit, "value %r of type '%r' requires a unit definition" % (val, type(val))
            val = val * _unit
        else:
            raise TypeError, "I don't know how to convert type '%s' to a unit" % str(type(val))
    assert type(val) == units.Quantity, "%r != %r" % (type(val), units.Quantity)
    if _unit:
        val = val.to(_unit)
    return val

def steps(val):
    val = unit(val)
    return int(val.to("steps").magnitude)

class CameraRail(object):
    pin_enable = 2
예제 #54
0
# *****************************************************************
# IonControl:  Copyright 2016 Sandia Corporation
# This Software is released under the GPL license detailed
# in the file "license.txt" in the top-level IonControl directory
# *****************************************************************
from pint import UnitRegistry, set_application_registry
from functools import lru_cache
from pint.util import UnitsContainer, infer_base_unit

ureg = UnitRegistry()
ureg.default_format = "~"
ureg.define('samples = count / second')
ureg.define('sample = count / second')
set_application_registry(ureg)
Q = ureg.Quantity


# define a hash function for quantity
def quantityHash(self):
    return hash(self.to_tuple())

Q.__hash__ = quantityHash


def is_Q(q):
    return isinstance(q, Q)


def value(q, unit=None):
    if is_Q(q):
        return q.m_as(unit)