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
def __init__(self, name, symbol, aliases, ): self.reference = reference self.is_base = is_base if isinstance(converter, string_types): converter = ParserHelper.from_string(converter) self.reference = UnitsContainer(converter) converter = ScaleConverter(converter.scale) super(UnitDefinition, self).__init__(name, symbol, aliases, converter)
def test_converter_inplace(self): for c in (ScaleConverter(20.0), OffsetConverter(20.0, 2)): fun1 = lambda x, y: c.from_reference(c.to_reference(x, y), y) fun2 = lambda x, y: c.to_reference(c.from_reference(x, y), y) for fun, (inplace, comp) in itertools.product( (fun1, fun2), ((True, self.assertIs), (False, self.assertIsNot))): a = np.ones((1, 10)) ac = np.ones((1, 10)) r = fun(a, inplace) np.testing.assert_allclose(r, ac) comp(a, r)
def test_multiplicative_converter(self): c = ScaleConverter(20.0) self.assertTrue(c.is_multiplicative) self.assertFalse(c.is_logarithmic) self.assertEqual(c.from_reference(c.to_reference(100)), 100) self.assertEqual(c.to_reference(c.from_reference(100)), 100)
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 [
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.
def test_multiplicative_converter(self): c = ScaleConverter(20.0) assert c.is_multiplicative assert not c.is_logarithmic assert c.from_reference(c.to_reference(100)) == 100 assert c.to_reference(c.from_reference(100)) == 100
def constructCurrencyDefinition(rate): parserHelper=ParserHelper.from_word(baseCurrencyISOCode) * rate.rate unit=UnitDefinition(rate.iso, symbol=None, aliases=[rate.name.replace(" ", "_")], reference=UnitsContainer(parserHelper), is_base=False, converter=ScaleConverter(parserHelper)) #return unit return rate.iso+" = "+str(rate.rate)+" "+baseCurrencyISOCode
def test_multiplicative_converter(self): c = ScaleConverter(20.) self.assertEqual(c.from_reference(c.to_reference(100)), 100) self.assertEqual(c.to_reference(c.from_reference(100)), 100)
""" 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))) # 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. """
import numpy as np from math import ceil from dataclasses import dataclass, replace from pint import UnitRegistry from pint.definitions import UnitDefinition from pint.converters import ScaleConverter from typing import Callable, Tuple, Optional ureg = UnitRegistry() ureg.define(UnitDefinition('percent', None, (), ScaleConverter(1 / 100))) ureg.load_definitions('units.txt') Q = ureg.Quantity @dataclass class Mortgage(object): loan_amount: Q = Q(500_000, 'dollars') home_value: Q = Q(600_000, 'dollars') duration: Q = Q(10, 'years') base_rate: Q = Q(4, 'percent') / Q(1, 'year') base_closing_costs: Q = Q(5_000, 'dollars') #: The cost as a ratio of the loan amount for each point. #: See the CFPB for more detail: #: #: https://www.consumerfinance.gov/ask-cfpb/what-are-discount-points-and-lender-credits-and-how-do-they-work-en-136/ #: cost_per_point: Q = Q(1, 'percent / dp')
if globals().get('U_', None) is None: # filename = resource_filename(PKG, 'spectrochempy.txt') U_ = UnitRegistry(on_redefinition='ignore') # filename) U_.define('__wrapped__ = 1') # <- hack to avoid an error with pytest (doctest activated) U_.define('@alias point = count') U_.define('transmittance = 1. / 100.') 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 = '' # .2fK' Q_ = U_.Quantity Q_.default_format = '' # .2fK' 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')