Python pint.UnitRegistry() Examples
The following are 30
code examples of pint.UnitRegistry().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pint
, or try the search function
.
Example #1
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 6 votes |
def test_issue74(self): ureg = UnitRegistry() v1 = np.asarray([1., 2., 3.]) v2 = np.asarray([3., 2., 1.]) q1 = v1 * ureg.ms q2 = v2 * ureg.ms np.testing.assert_array_equal(q1 < q2, v1 < v2) np.testing.assert_array_equal(q1 > q2, v1 > v2) np.testing.assert_array_equal(q1 <= q2, v1 <= v2) np.testing.assert_array_equal(q1 >= q2, v1 >= v2) q2s = np.asarray([0.003, 0.002, 0.001]) * ureg.s v2s = q2s.to('ms').magnitude np.testing.assert_array_equal(q1 < q2s, v1 < v2s) np.testing.assert_array_equal(q1 > q2s, v1 > v2s) np.testing.assert_array_equal(q1 <= q2s, v1 <= v2s) np.testing.assert_array_equal(q1 >= q2s, v1 >= v2s)
Example #2
Source File: test_contexts.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 6 votes |
def test_warnings(self): ureg = UnitRegistry() with self.capture_log() as buffer: add_ctxs(ureg) d = Context('ab') ureg.add_context(d) self.assertEqual(len(buffer), 1) self.assertIn("ab", str(buffer[-1])) d = Context('ab1', aliases=('ab',)) ureg.add_context(d) self.assertEqual(len(buffer), 2) self.assertIn("ab", str(buffer[-1]))
Example #3
Source File: test_contexts.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 6 votes |
def _test_ctx(self, ctx): ureg = UnitRegistry() q = 500 * ureg.meter s = (ureg.speed_of_light / q).to('Hz') nctx = len(ureg._contexts) self.assertNotIn(ctx.name, ureg._contexts) ureg.add_context(ctx) self.assertIn(ctx.name, ureg._contexts) self.assertEqual(len(ureg._contexts), nctx + 1 + len(ctx.aliases)) with ureg.context(ctx.name): self.assertEqual(q.to('Hz'), s) self.assertEqual(s.to('meter'), q) ureg.remove_context(ctx.name) self.assertNotIn(ctx.name, ureg._contexts) self.assertEqual(len(ureg._contexts), nctx)
Example #4
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 6 votes |
def test_issue39(self): x = np.matrix([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) ureg = UnitRegistry() q = ureg.meter * x self.assertIsInstance(q, ureg.Quantity) np.testing.assert_array_equal(q.magnitude, x) self.assertEqual(q.units, ureg.meter.units) q = x * ureg.meter self.assertIsInstance(q, ureg.Quantity) np.testing.assert_array_equal(q.magnitude, x) self.assertEqual(q.units, ureg.meter.units) m = np.matrix(2 * np.ones(3,3)) qq = q * m self.assertIsInstance(qq, ureg.Quantity) np.testing.assert_array_equal(qq.magnitude, x * m) self.assertEqual(qq.units, ureg.meter.units) qq = m * q self.assertIsInstance(qq, ureg.Quantity) np.testing.assert_array_equal(qq.magnitude, x * m) self.assertEqual(qq.units, ureg.meter.units)
Example #5
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 6 votes |
def test_issue37(self): x = np.ma.masked_array([1, 2, 3], mask=[True, True, False]) ureg = UnitRegistry() q = ureg.meter * x self.assertIsInstance(q, ureg.Quantity) np.testing.assert_array_equal(q.magnitude, x) self.assertEqual(q.units, ureg.meter.units) q = x * ureg.meter self.assertIsInstance(q, ureg.Quantity) np.testing.assert_array_equal(q.magnitude, x) self.assertEqual(q.units, ureg.meter.units) m = np.ma.masked_array(2 * np.ones(3,3)) qq = q * m self.assertIsInstance(qq, ureg.Quantity) np.testing.assert_array_equal(qq.magnitude, x * m) self.assertEqual(qq.units, ureg.meter.units) qq = m * q self.assertIsInstance(qq, ureg.Quantity) np.testing.assert_array_equal(qq.magnitude, x * m) self.assertEqual(qq.units, ureg.meter.units)
Example #6
Source File: ninjotiff.py From satpy with GNU General Public License v3.0 | 6 votes |
def convert_units(dataset, in_unit, out_unit): """Convert units of *dataset*.""" from pint import UnitRegistry ureg = UnitRegistry() # Commented because buggy: race condition ? # ureg.define("degree_Celsius = degC = Celsius = C = CELSIUS") in_unit = ureg.parse_expression(in_unit, False) if out_unit in ['CELSIUS', 'C', 'Celsius', 'celsius']: dest_unit = ureg.degC else: dest_unit = ureg.parse_expression(out_unit, False) data = ureg.Quantity(dataset, in_unit) attrs = dataset.attrs dataset = data.to(dest_unit).magnitude dataset.attrs = attrs dataset.attrs["units"] = out_unit return dataset
Example #7
Source File: test_contexts.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 6 votes |
def test_nested_context(self): ureg = UnitRegistry() add_ctxs(ureg) q = 500 * ureg.meter s = (ureg.speed_of_light / q).to('Hz') self.assertRaises(ValueError, q.to, 'Hz') with ureg.context('lc'): self.assertEqual(q.to('Hz'), s) with ureg.context('ab'): self.assertEqual(q.to('Hz'), s) self.assertEqual(q.to('Hz'), s) with ureg.context('ab'): self.assertRaises(ValueError, q.to, 'Hz') with ureg.context('lc'): self.assertEqual(q.to('Hz'), s) self.assertRaises(ValueError, q.to, 'Hz')
Example #8
Source File: unit_converter.py From EnergyPATHWAYS with MIT License | 6 votes |
def __init__(self, database_path): # Initiate pint for unit conversions self.ureg = pint.UnitRegistry() self.cfg_energy_unit = cfg.getParam('calculation_energy_unit') self.cfg_currency = cfg.getParam('currency_name') self.cfg_currency_year = cfg.getParamAsInt('currency_year') db = get_database(database_path) self.currency_table = db.get_table("CurrenciesConversion").data self.currency_table = self.currency_table.set_index(['currency', 'year']).sort_index() self.inflation_table = db.get_table("InflationConversion").data self.inflation_table = self.inflation_table.set_index(['currency', 'year']).sort_index() for unit_def in UnitConverter._unit_defs: unit_name = unit_def.split(' = ')[0] if hasattr(self.ureg, unit_name): logging.debug('pint already has unit {}, unit is not being redefined'.format(unit_name)) continue self.ureg.define(unit_def)
Example #9
Source File: test_contexts.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 6 votes |
def test_unknown_nested_context(self): ureg = UnitRegistry() add_ctxs(ureg) with ureg.context('lc'): x = dict(ureg._active_ctx) y = dict(ureg._active_ctx.graph) try: with ureg.context('la'): pass except KeyError as e: value = True except Exception as e: value = False self.assertTrue(value) self.assertEqual(x, ureg._active_ctx) self.assertEqual(y, ureg._active_ctx.graph) self.assertFalse(ureg._active_ctx) self.assertFalse(ureg._active_ctx.graph)
Example #10
Source File: test_units.py From pyam with Apache License 2.0 | 6 votes |
def test_convert_unit_with_custom_registry(test_df): # unit conversion with custom UnitRegistry df = get_units_test_df(test_df).rename(unit={'EJ/yr': 'foo'}) # check that conversion fails with application registry with pytest.raises(pint.UndefinedUnitError): df.convert_unit('foo', 'baz') # define a custom unit registry ureg = pint.UnitRegistry() ureg.define('baz = [custom]') ureg.define('foo = 3 * baz') exp = pd.Series([1., 6., 1.5, 9, 6, 21], name='value') assert_converted_units(df, 'foo', 'baz', exp, registry=ureg) # This test is parametrized as the product of three sets: # 1. The test_df fixture. # 2. Current species, context, and expected output magnitude. # 3. Input and output expressions, and any factor on the output magnitude due # to differences in units between these.
Example #11
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 6 votes |
def test_issue104(self): ureg = UnitRegistry() x = [ureg('1 meter'), ureg('1 meter'), ureg('1 meter')] y = [ureg('1 meter')] * 3 def summer(values): if not values: return 0 total = values[0] for v in values[1:]: total += v return total self.assertQuantityAlmostEqual(summer(x), ureg.Quantity(3, 'meter')) self.assertQuantityAlmostEqual(x[0], ureg.Quantity(1, 'meter')) self.assertQuantityAlmostEqual(summer(y), ureg.Quantity(3, 'meter')) self.assertQuantityAlmostEqual(y[0], ureg.Quantity(1, 'meter'))
Example #12
Source File: units.py From bazarr with GNU General Public License v3.0 | 6 votes |
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
Example #13
Source File: test_contexts.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 6 votes |
def test_known_context_enable(self): ureg = UnitRegistry() add_ctxs(ureg) ureg.enable_contexts('lc') self.assertTrue(ureg._active_ctx) self.assertTrue(ureg._active_ctx.graph) ureg.disable_contexts(1) self.assertFalse(ureg._active_ctx) self.assertFalse(ureg._active_ctx.graph) ureg.enable_contexts('lc', n=1) self.assertTrue(ureg._active_ctx) self.assertTrue(ureg._active_ctx.graph) ureg.disable_contexts(1) self.assertFalse(ureg._active_ctx) self.assertFalse(ureg._active_ctx.graph)
Example #14
Source File: test_contexts.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 6 votes |
def test_known_context(self): ureg = UnitRegistry() add_ctxs(ureg) with ureg.context('lc'): self.assertTrue(ureg._active_ctx) self.assertTrue(ureg._active_ctx.graph) self.assertFalse(ureg._active_ctx) self.assertFalse(ureg._active_ctx.graph) with ureg.context('lc', n=1): self.assertTrue(ureg._active_ctx) self.assertTrue(ureg._active_ctx.graph) self.assertFalse(ureg._active_ctx) self.assertFalse(ureg._active_ctx.graph)
Example #15
Source File: sound.py From Ocean-Data-Map-Project with GNU General Public License v3.0 | 6 votes |
def load_data(self): super(SoundSpeedPlotter, self).load_data() self.pressure = [seawater.pres(self.temperature_depths[idx], ll[0]) for idx, ll in enumerate(self.points)] ureg = pint.UnitRegistry() try: u = ureg.parse_units(self.variable_units[0].lower()) except: u = ureg.dimensionless if u == ureg.boltzmann_constant: u = ureg.kelvin if u == ureg.kelvin: temperature_c = ureg.Quantity( self.temperature, u).to(ureg.celsius).magnitude else: temperature_c = self.temperature self.sspeed = seawater.svel( self.salinity, temperature_c, self.pressure )
Example #16
Source File: mercator.py From Ocean-Data-Map-Project with GNU General Public License v3.0 | 6 votes |
def depths(self) -> np.ndarray: """Finds, caches, and returns the valid depths for the dataset. """ if self.__depths is None: var = None for v in self.nc_data.depth_dimensions: # Depth is usually a "coordinate" variable if v in self.nc_data.dataset.coords: # Get DataArray for depth var = self.nc_data.get_dataset_variable(v) break if var is not None: ureg = UnitRegistry() unit = ureg.parse_units(var.attrs['units'].lower()) self.__depths = ureg.Quantity(var[:].values, unit).to(ureg.meters).magnitude else: self.__depths = np.array([0]) self.__depths.flags.writeable = False return self.__depths
Example #17
Source File: nemo.py From Ocean-Data-Map-Project with GNU General Public License v3.0 | 6 votes |
def depths(self): """Finds, caches, and returns the valid depths for the dataset. """ if self.__depths is None: var = None # Look through possible dimension names for v in self.nc_data.depth_dimensions: # Depth is usually a "coordinate" variable if v in self.nc_data.dataset.coords: # Get DataArray for depth var = self.nc_data.get_dataset_variable(v) break if var is not None: ureg = UnitRegistry() unit = ureg.parse_units(var.attrs['units'].lower()) self.__depths = ureg.Quantity(var.values, unit).to(ureg.meters).magnitude else: self.__depths = np.array([0]) # Make immutable self.__depths.setflags(write=False) return self.__depths
Example #18
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
def test_issue50(self): ureg = UnitRegistry() Q_ = ureg.Quantity self.assertEqual(Q_(100), 100 * ureg.dimensionless) self.assertEqual(Q_('100'), 100 * ureg.dimensionless)
Example #19
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
def test_issue170b(self): Q_ = UnitRegistry().Quantity q = Q_('1 kHz')/Q_('100 Hz') iq = long(q) self.assertEqual(iq, long(10)) self.assertIsInstance(iq, long)
Example #20
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
def test_issue45(self): import math ureg = UnitRegistry() self.assertAlmostEqual(math.sqrt(4 * ureg.m/ureg.cm), math.sqrt(4 * 100)) self.assertAlmostEqual(float(ureg.V / ureg.mV), 1000.)
Example #21
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
def test_issue44(self): ureg = UnitRegistry() x = 4. * ureg.dimensionless np.sqrt(x) self.assertQuantityAlmostEqual(np.sqrt([4.] * ureg.dimensionless), [2.] * ureg.dimensionless) self.assertQuantityAlmostEqual(np.sqrt(4. * ureg.dimensionless), 2. * ureg.dimensionless)
Example #22
Source File: _on_demand_imports.py From unyt with BSD 3-Clause "New" or "Revised" License | 5 votes |
def UnitRegistry(self): if self._UnitRegistry is None: try: from pint import UnitRegistry except ImportError: UnitRegistry = NotAModule(self._name) self._UnitRegistry = UnitRegistry return self._UnitRegistry
Example #23
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
def test_issue105(self): ureg = UnitRegistry() func = ureg.parse_unit_name val = list(func('meter')) self.assertEqual(list(func('METER')), []) self.assertEqual(val, list(func('METER', False))) for func in (ureg.get_name, ureg.parse_expression): val = func('meter') self.assertRaises(ValueError, func, 'METER') self.assertEqual(val, func('METER', False))
Example #24
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
def test_issue62(self): ureg = UnitRegistry() m = ureg('m**0.5') self.assertEqual(str(m.units), 'meter ** 0.5')
Example #25
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
def test_issue75(self): ureg = UnitRegistry() v1 = np.asarray([1., 2., 3.]) v2 = np.asarray([3., 2., 1.]) q1 = v1 * ureg.ms q2 = v2 * ureg.ms np.testing.assert_array_equal(q1 == q2, v1 == v2) np.testing.assert_array_equal(q1 != q2, v1 != v2) q2s = np.asarray([0.003, 0.002, 0.001]) * ureg.s v2s = q2s.to('ms').magnitude np.testing.assert_array_equal(q1 == q2s, v1 == v2s) np.testing.assert_array_equal(q1 != q2s, v1 != v2s)
Example #26
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
def test_issue93(self): ureg = UnitRegistry() self.assertIsInstance(ureg.meter.magnitude, int) x = 5 * ureg.meter self.assertIsInstance(x.magnitude, int) y = 0.1 * ureg.meter self.assertIsInstance(y.magnitude, float) z = 5 * ureg.meter self.assertIsInstance(z.magnitude, int) z += y self.assertIsInstance(z.magnitude, float) self.assertQuantityAlmostEqual(x + y, 5.1 * ureg.meter) self.assertQuantityAlmostEqual(z, 5.1 * ureg.meter)
Example #27
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
def test_issue121(self): sh = (2, 1) ureg = UnitRegistry() z, v = 0, 2. self.assertEqual(z + v * ureg.meter, v * ureg.meter) self.assertEqual(z - v * ureg.meter, -v * ureg.meter) self.assertEqual(v * ureg.meter + z, v * ureg.meter) self.assertEqual(v * ureg.meter - z, v * ureg.meter) self.assertEqual(sum([v * ureg.meter, v * ureg.meter]), 2 * v * ureg.meter) z, v = np.zeros(sh), 2. * np.ones(sh) self.assertQuantityEqual(z + v * ureg.meter, v * ureg.meter) self.assertQuantityEqual(z - v * ureg.meter, -v * ureg.meter) self.assertQuantityEqual(v * ureg.meter + z, v * ureg.meter) self.assertQuantityEqual(v * ureg.meter - z, v * ureg.meter) z, v = np.zeros((3, 1)), 2. * np.ones(sh) for x, y in ((z, v), (z, v * ureg.meter), (v * ureg.meter, z) ): try: w = x + y self.assertTrue(False, "ValueError not raised") except ValueError: pass try: w = x - y self.assertTrue(False, "ValueError not raised") except ValueError: pass
Example #28
Source File: test_issues.py From cadquery-freecad-module with GNU Lesser General Public License v3.0 | 5 votes |
def _test_issueXX(self): ureg = UnitRegistry() try: ureg.convert(1, ureg.degC, ureg.kelvin * ureg.meter / ureg.nanometer) except: self.assertTrue(False, 'Error while trying to convert {} to {}'.format(ureg.degC, ureg.kelvin * ureg.meter / ureg.nanometer))
Example #29
Source File: test_omas_physics.py From omas with MIT License | 5 votes |
def test_handle_units(self): import pint ureg = pint.UnitRegistry() ods = ODS() ods['equilibrium.time_slice[0].constraints.diamagnetic_flux.time_measurement'] = 8.0 * ureg.milliseconds assert ods['equilibrium.time_slice[0].constraints.diamagnetic_flux.time_measurement'] == 0.008 with omas_environment(ods, unitsio=True): tmp = ods['equilibrium.time_slice[0].constraints.diamagnetic_flux.time_measurement'] assert tmp.magnitude == 0.008 assert tmp.units == 'second' return
Example #30
Source File: test_units.py From pyam with Apache License 2.0 | 5 votes |
def test_convert_unit_with_pint(test_df, current, to): # unit conversion with default UnitRegistry (i.e, application_registry) df = get_units_test_df(test_df) # replace EJ/yr by EJ to test pint with single unit if current == 'EJ': df.rename(unit={'EJ/yr': 'EJ'}, inplace=True) exp = pd.Series([1., 6., 138.88, 833.33, 555.55, 1944.44], name='value') assert_converted_units(df, current, to, exp)