def test_anonymous_context(self): ureg = UnitRegistry() c = Context() c.add_transformation("[length]", "[time]", lambda ureg, x: x / ureg("5 cm/s")) self.assertRaises(ValueError, ureg.add_context, c) x = ureg("10 cm") expect = ureg("2 s") self.assertQuantityEqual(x.to("s", c), expect) with ureg.context(c): self.assertQuantityEqual(x.to("s"), expect) ureg.enable_contexts(c) self.assertQuantityEqual(x.to("s"), expect) ureg.disable_contexts(1) self.assertRaises(DimensionalityError, x.to, "s") # Multiple anonymous contexts c2 = Context() c2.add_transformation("[length]", "[time]", lambda ureg, x: x / ureg("10 cm/s")) c2.add_transformation("[mass]", "[time]", lambda ureg, x: x / ureg("10 kg/s")) with ureg.context(c2, c): self.assertQuantityEqual(x.to("s"), expect) # Transformations only in c2 are still working even if c takes priority self.assertQuantityEqual(ureg("100 kg").to("s"), ureg("10 s")) with ureg.context(c, c2): self.assertQuantityEqual(x.to("s"), ureg("1 s"))
def test_enable_context_with_arg(self): ureg = UnitRegistry() add_arg_ctxs(ureg) q = 500 * ureg.meter s = (ureg.speed_of_light / q).to("Hz") self.assertRaises(ValueError, q.to, "Hz") ureg.enable_contexts("lc", n=1) self.assertEqual(q.to("Hz"), s) ureg.enable_contexts("ab") self.assertEqual(q.to("Hz"), s) self.assertEqual(q.to("Hz"), s) ureg.disable_contexts(1) ureg.disable_contexts(1) ureg.enable_contexts("ab") self.assertRaises(ValueError, q.to, "Hz") ureg.enable_contexts("lc", n=1) self.assertEqual(q.to("Hz"), s) ureg.disable_contexts(1) self.assertRaises(ValueError, q.to, "Hz") ureg.disable_contexts(1) ureg.enable_contexts("lc") self.assertRaises(TypeError, q.to, "Hz") ureg.disable_contexts(1)
def test_enable_context_with_arg(self): ureg = UnitRegistry() add_arg_ctxs(ureg) q = 500 * ureg.meter s = (ureg.speed_of_light / q).to('Hz') self.assertRaises(ValueError, q.to, 'Hz') ureg.enable_contexts('lc', n=1) self.assertEqual(q.to('Hz'), s) ureg.enable_contexts('ab') self.assertEqual(q.to('Hz'), s) self.assertEqual(q.to('Hz'), s) ureg.disable_contexts(1) ureg.disable_contexts(1) ureg.enable_contexts('ab') self.assertRaises(ValueError, q.to, 'Hz') ureg.enable_contexts('lc', n=1) self.assertEqual(q.to('Hz'), s) ureg.disable_contexts(1) self.assertRaises(ValueError, q.to, 'Hz') ureg.disable_contexts(1) ureg.enable_contexts('lc') self.assertRaises(TypeError, q.to, 'Hz') ureg.disable_contexts(1)
def test_enable_context_with_arg(self, func_registry): ureg = UnitRegistry() add_arg_ctxs(ureg) q = 500 * ureg.meter s = (ureg.speed_of_light / q).to("Hz") with pytest.raises(DimensionalityError): q.to("Hz") ureg.enable_contexts("lc", n=1) assert q.to("Hz") == s ureg.enable_contexts("ab") assert q.to("Hz") == s assert q.to("Hz") == s ureg.disable_contexts(1) ureg.disable_contexts(1) ureg.enable_contexts("ab") with pytest.raises(DimensionalityError): q.to("Hz") ureg.enable_contexts("lc", n=1) assert q.to("Hz") == s ureg.disable_contexts(1) with pytest.raises(DimensionalityError): q.to("Hz") ureg.disable_contexts(1) ureg.enable_contexts("lc") with pytest.raises(TypeError): q.to("Hz") ureg.disable_contexts(1)
def test_enable_context_with_arg(self): ureg = UnitRegistry() add_arg_ctxs(ureg) q = 500 * ureg.meter s = (ureg.speed_of_light / q).to("Hz") self.assertRaises(DimensionalityError, q.to, "Hz") ureg.enable_contexts("lc", n=1) self.assertEqual(q.to("Hz"), s) ureg.enable_contexts("ab") self.assertEqual(q.to("Hz"), s) self.assertEqual(q.to("Hz"), s) ureg.disable_contexts(1) ureg.disable_contexts(1) ureg.enable_contexts("ab") self.assertRaises(DimensionalityError, q.to, "Hz") ureg.enable_contexts("lc", n=1) self.assertEqual(q.to("Hz"), s) ureg.disable_contexts(1) self.assertRaises(DimensionalityError, q.to, "Hz") ureg.disable_contexts(1) ureg.enable_contexts("lc") self.assertRaises(TypeError, q.to, "Hz") ureg.disable_contexts(1)
def test_err_new_unit(): ureg = UnitRegistry(""" foo = [d] @context c bar = foo @end """.splitlines()) expected = "'bar' is not defined in the unit registry" with pytest.raises(UndefinedUnitError, match=expected): ureg.enable_contexts("c")
def test_err_new_unit(self): ureg = UnitRegistry(""" foo = [d] @context c bar = foo @end """.splitlines()) with self.assertRaises(UndefinedUnitError) as e: ureg.enable_contexts("c") self.assertEqual(str(e.exception), "'bar' is not defined in the unit registry")
def test_err_change_base_unit(): ureg = UnitRegistry(""" foo = [d1] bar = [d2] @context c bar = foo @end """.splitlines()) expected = "Can't redefine a base unit to a derived one" with pytest.raises(ValueError, match=expected): ureg.enable_contexts("c")
def test_err_redefine_with_prefix(self): ureg = UnitRegistry(""" kilo- = 1000 gram = [mass] pound = 454 gram @context c kilopound = 500000 gram @end """.splitlines()) with self.assertRaises(ValueError) as e: ureg.enable_contexts("c") self.assertEqual(str(e.exception), "Can't redefine a unit with a prefix: kilopound")
def test_err_change_base_unit(self): ureg = UnitRegistry(""" foo = [d1] bar = [d2] @context c bar = foo @end """.splitlines()) with self.assertRaises(ValueError) as e: ureg.enable_contexts("c") self.assertEqual(str(e.exception), "Can't redefine a base unit to a derived one")
def test_err_redefine_with_prefix(): ureg = UnitRegistry(""" kilo- = 1000 gram = [mass] pound = 454 gram @context c kilopound = 500000 gram @end """.splitlines()) expected = "Can't redefine a unit with a prefix: kilopound" with pytest.raises(ValueError, match=expected): ureg.enable_contexts("c")
def test_err_change_dimensionality(): ureg = UnitRegistry(""" foo = [d1] bar = [d2] baz = foo @context c baz = bar @end """.splitlines()) expected = re.escape( "Can't change dimensionality of baz from [d1] to [d2] in a context") with pytest.raises(ValueError, match=expected): ureg.enable_contexts("c")
def test_err_change_dimensionality(self): ureg = UnitRegistry(""" foo = [d1] bar = [d2] baz = foo @context c baz = bar @end """.splitlines()) with self.assertRaises(ValueError) as e: ureg.enable_contexts("c") self.assertEqual( str(e.exception), "Can't change dimensionality of baz from [d1] to [d2] in a context", )
def test_err_cyclic_dependency(self): ureg = UnitRegistry(""" foo = [d] bar = foo baz = bar @context c bar = baz @end """.splitlines()) # TODO align this exception and the one you get when you implement a cyclic # dependency within the base registry. Ideally this exception should be # raised by enable_contexts. ureg.enable_contexts("c") q = ureg.Quantity("bar") with self.assertRaises(RecursionError): q.to("foo")
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)
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)
def test_known_context_enable(self, func_registry): ureg = UnitRegistry() add_ctxs(ureg) ureg.enable_contexts("lc") assert ureg._active_ctx assert ureg._active_ctx.graph ureg.disable_contexts(1) assert not ureg._active_ctx assert not ureg._active_ctx.graph ureg.enable_contexts("lc", n=1) assert ureg._active_ctx assert ureg._active_ctx.graph ureg.disable_contexts(1) assert not ureg._active_ctx assert not ureg._active_ctx.graph
def construct_unitregistry( verbose: bool, debug: bool, ): #ureg = UnitRegistry(system='mks', non_int_type=Decimal) ureg = UnitRegistry(system='mks') ureg.enable_contexts( "Gaussian") # https://github.com/hgrecco/pint/issues/1205 # https://en.wikipedia.org/wiki/Ell ureg = add_unit_to_ureg( ureg, unit_name='ell', unit_def='45 * inch', unit_symbol='_', unit_aliases=[], verbose=verbose, debug=debug, ) ureg = add_unit_to_ureg( ureg, unit_name='scottish_ell', unit_def='37 * inch', unit_symbol='_', unit_aliases=[], verbose=verbose, debug=debug, ) # https://en.wikipedia.org/wiki/Ancient_Egyptian_units_of_measurement # https://www.youtube.com/watch?v=jyFkBaKARAs # pi/6 ureg = add_unit_to_ureg( ureg, unit_name='royal_cubit', unit_def='52.3 * cm', unit_symbol='_', unit_aliases=[], verbose=verbose, debug=debug, ) #14624 "sutu?" is 527km https://www.youtube.com/watch?v=s_fkpZSnz2I @ 18:45 return ureg
def test_redefine(self): ureg = UnitRegistry(""" foo = [d] = f = foo_alias bar = 2 foo = b = bar_alias baz = 3 bar = _ = baz_alias asd = 4 baz @context c # Note how we're redefining a symbol, not the base name, as a # function of another name b = 5 f """.splitlines()) # Units that are somehow directly or indirectly defined as a function of the # overridden unit are also affected foo = ureg.Quantity(1, "foo") bar = ureg.Quantity(1, "bar") asd = ureg.Quantity(1, "asd") # Test without context before and after, to verify that the cache and units have # not been polluted for enable_ctx in (False, True, False): with self.subTest(enable_ctx): if enable_ctx: ureg.enable_contexts("c") k = 5 else: k = 2 self.assertEqual(foo.to("b").magnitude, 1 / k) self.assertEqual(foo.to("bar").magnitude, 1 / k) self.assertEqual(foo.to("bar_alias").magnitude, 1 / k) self.assertEqual(foo.to("baz").magnitude, 1 / k / 3) self.assertEqual(bar.to("foo").magnitude, k) self.assertEqual(bar.to("baz").magnitude, 1 / 3) self.assertEqual(asd.to("foo").magnitude, 4 * 3 * k) self.assertEqual(asd.to("bar").magnitude, 4 * 3) self.assertEqual(asd.to("baz").magnitude, 4) ureg.disable_contexts()
def test_issue1112(self): ureg = UnitRegistry(""" m = [length] g = [mass] s = [time] ft = 0.305 m lb = 454 g @context c1 [time]->[length] : value * 10 m/s @end @context c2 ft = 0.3 m @end @context c3 lb = 500 g @end """.splitlines()) ureg.enable_contexts("c1") ureg.enable_contexts("c2") ureg.enable_contexts("c3")
def test_graph_enable(self): ureg = UnitRegistry() add_ctxs(ureg) l = UnitsContainer({'[length]': 1.}) t = UnitsContainer({'[time]': -1.}) c = UnitsContainer({'[current]': 1.}) g_sp = defaultdict(set) g_sp.update({l: set((t, )), t: set((l, ))}) g_ab = defaultdict(set) g_ab.update({l: set((c, )), c: set((l, ))}) g = defaultdict(set) g.update({l: set((t, c)), t: set((l, )), c: set((l, ))}) ureg.enable_contexts('lc') self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts('lc', n=1) self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts('ab') self.assertEqual(ureg._active_ctx.graph, g_ab) ureg.disable_contexts(1) ureg.enable_contexts('lc') ureg.enable_contexts('ab') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('ab') ureg.enable_contexts('lc') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('lc', 'ab') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('ab', 'lc') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2)
def test_graph_enable(self): ureg = UnitRegistry() add_ctxs(ureg) l = UnitsContainer({'[length]': 1.}) t = UnitsContainer({'[time]': -1.}) c = UnitsContainer({'[current]': 1.}) g_sp = defaultdict(set) g_sp.update({l: set((t,)), t: set((l,))}) g_ab = defaultdict(set) g_ab.update({l: set((c,)), c: set((l,))}) g = defaultdict(set) g.update({l: set((t, c)), t: set((l,)), c: set((l,))}) ureg.enable_contexts('lc') self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts('lc', n=1) self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts('ab') self.assertEqual(ureg._active_ctx.graph, g_ab) ureg.disable_contexts(1) ureg.enable_contexts('lc') ureg.enable_contexts('ab') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('ab') ureg.enable_contexts('lc') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('lc', 'ab') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('ab', 'lc') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2)
""" Pint quantities for converting au to other units """ from pint import UnitRegistry ureg = UnitRegistry() Q_ = ureg.Quantity ureg.setup_matplotlib(True) ureg.enable_contexts('sp') ureg.define('bohr = (5.2917721092 * 10**-11) * meter = a0') ureg.define('e_field_au = hartree/ (e*bohr) = au_e') ureg.define('b_field_au = hbar/ (e*bohr**2) = au_b') ureg.define('au_time = hbar/ hartree')
logger.addHandler(ch) # Units handling # here we assign the identifier 'unit' to the UnitRegistry unit = UnitRegistry() # use this to enable legacy handling of offset units # TODO fix this to handle offsets the way pint wants us to since 0.7 unit.autoconvert_offset_to_baseunit = True # append custom unit definitions and contexts directory = os.path.dirname(__file__) unit.load_definitions(directory + "/pint_custom_units.txt") # activate the "chemistry" context globally unit.enable_contexts("chem") # set the default string formatting for pint quantities unit.default_format = "P~" def testfunc(val): list = [] try: list.append(float(val) * unit("")) return list except ValueError: print("Value Error") return None class Parameter:
def test_graph_enable(self): ureg = UnitRegistry() add_ctxs(ureg) l = _freeze({"[length]": 1.0}) t = _freeze({"[time]": -1.0}) c = _freeze({"[current]": -1.0}) g_sp = defaultdict(set) g_sp.update({l: set((t,)), t: set((l,))}) g_ab = defaultdict(set) g_ab.update({l: set((c,)), c: set((l,))}) g = defaultdict(set) g.update({l: set((t, c)), t: set((l,)), c: set((l,))}) ureg.enable_contexts("lc") self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts("lc", n=1) self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts("ab") self.assertEqual(ureg._active_ctx.graph, g_ab) ureg.disable_contexts(1) ureg.enable_contexts("lc") ureg.enable_contexts("ab") self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts("ab") ureg.enable_contexts("lc") self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts("lc", "ab") self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts("ab", "lc") self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2)
from pint import UnitRegistry ureg = UnitRegistry() #the "spectroscopy" ("sp") context enables pinto #to convert frequency to wavelength and vice-versa ureg.enable_contexts('sp') def parse_length(length_str, name = "length"): length_in = length_m = None try: length = ureg.parse_expression(length_str) length_in = length.to(ureg.inch).magnitude length_m = length.to(ureg.meter).magnitude except AttributeError: print "Please speficy {:s} measure unit (m, cm, in, ..)".format(name) exit(-1) return length_in, length_m def parse_freq(freq_str, name = "frequency"): freq_hz = wlen_in = wlen_m = None try: freq = ureg.parse_expression(freq_str) freq_hz = freq.to(ureg.hertz).magnitude wlen_in = freq.to(ureg.inch).magnitude wlen_m = freq.to(ureg.meter).magnitude except AttributeError: print "Please specify {:s} measuere unit (Hz, MHz, ..)".format(name) exit(-1) return freq_hz, wlen_in, wlen_m
def test_graph_enable(self): ureg = UnitRegistry() add_ctxs(ureg) l = _freeze({'[length]': 1.}) t = _freeze({'[time]': -1.}) c = _freeze({'[current]': -1.}) g_sp = defaultdict(set) g_sp.update({ l: { t, }, t: { l, } }) g_ab = defaultdict(set) g_ab.update({ l: { c, }, c: { l, } }) g = defaultdict(set) g.update({ l: {t, c}, t: { l, }, c: { l, } }) ureg.enable_contexts('lc') self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts('lc', n=1) self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts('ab') self.assertEqual(ureg._active_ctx.graph, g_ab) ureg.disable_contexts(1) ureg.enable_contexts('lc') ureg.enable_contexts('ab') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('ab') ureg.enable_contexts('lc') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('lc', 'ab') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('ab', 'lc') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2)
# per the pint documentation, it's important that pint and its associated Unit # Registry are only imported once. from pint import UnitRegistry # here we assign the identifier 'unit' to the UnitRegistry unit = UnitRegistry() #use this to enable legacy handling of offset units # TODO fix this to handle offsets the way pint wants us to since 0.7 unit.autoconvert_offset_to_baseunit = True # append custom unit definitions and contexts import os directory = os.path.dirname(__file__) unit.load_definitions(directory+'/pint_custom_units.txt') # activate the "chemistry" context globally unit.enable_contexts('chem') # set the default string formatting for pint quantities unit.default_format = 'P~' def testfunc(val): list = [] try: list.append(float(val) * unit('')) return list except ValueError: print('Value Error') return None class Parameter: '''
def test_graph_enable(self): ureg = UnitRegistry() add_ctxs(ureg) l = _freeze({'[length]': 1.}) t = _freeze({'[time]': -1.}) c = _freeze({'[current]': -1.}) g_sp = defaultdict(set) g_sp.update({l: {t, }, t: {l, }}) g_ab = defaultdict(set) g_ab.update({l: {c, }, c: {l, }}) g = defaultdict(set) g.update({l: {t, c}, t: {l, }, c: {l, }}) ureg.enable_contexts('lc') self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts('lc', n=1) self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts('ab') self.assertEqual(ureg._active_ctx.graph, g_ab) ureg.disable_contexts(1) ureg.enable_contexts('lc') ureg.enable_contexts('ab') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('ab') ureg.enable_contexts('lc') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('lc', 'ab') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts('ab', 'lc') self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2)
def test_graph_enable(self): ureg = UnitRegistry() add_ctxs(ureg) l = UnitsContainer({"[length]": 1.0}) # noqa: E741 t = UnitsContainer({"[time]": -1.0}) c = UnitsContainer({"[current]": 1.0}) g_sp = defaultdict(set) g_sp.update({l: {t}, t: {l}}) g_ab = defaultdict(set) g_ab.update({l: {c}, c: {l}}) g = defaultdict(set) g.update({l: {t, c}, t: {l}, c: {l}}) ureg.enable_contexts("lc") self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts("lc", n=1) self.assertEqual(ureg._active_ctx.graph, g_sp) ureg.disable_contexts(1) ureg.enable_contexts("ab") self.assertEqual(ureg._active_ctx.graph, g_ab) ureg.disable_contexts(1) ureg.enable_contexts("lc") ureg.enable_contexts("ab") self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts("ab") ureg.enable_contexts("lc") self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts("lc", "ab") self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2) ureg.enable_contexts("ab", "lc") self.assertEqual(ureg._active_ctx.graph, g) ureg.disable_contexts(2)
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') # Context for NMR # ---------------------------------------------------------------------------------------------------------------------- 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
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 ---------- 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
# per the pint documentation, it's important that pint and its associated Unit # Registry are only imported once. from pint import UnitRegistry # here we assign the identifier 'unit' to the UnitRegistry unit = UnitRegistry() #use this to enable legacy handling of offset units # TODO fix this to handle offsets the way pint wants us to since 0.7 unit.autoconvert_offset_to_baseunit = True # append custom unit definitions and contexts import os directory = os.path.dirname(__file__) unit.load_definitions(directory + '/pint_custom_units.txt') # activate the "chemistry" context globally unit.enable_contexts('chem') # set the default string formatting for pint quantities unit.default_format = 'P~' def testfunc(val): list = [] try: list.append(float(val) * unit('')) return list except ValueError: print('Value Error') return None class Parameter:
import numpy as np import imp import csv cs_utils = imp.load_source('cs_utils',"/Users/tmarkovich/Dropbox/Projects/cslib2/cs_utils.py") drude_lorentz = imp.load_source('cs_utils',"/Users/tmarkovich/Dropbox/Projects/cslib2/drude_lorentz.py") Astruct = imp.load_source('Astruct', '/Users/tmarkovich/Dropbox/Projects/cslib2/Astruct.py') twist = imp.load_source('twist',"/Users/tmarkovich/Dropbox/Projects/cslib2/TwIST_Solver.py") time_range = [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100] # import pint for some unit special sauce from pint import UnitRegistry ureg = UnitRegistry() ureg.enable_contexts('spectroscopy') ureg.enable_contexts('boltzmann') Q_ = ureg.Quantity def signal_load(): asdf = np.loadtxt('signal.csv', delimiter=",") signal = asdf asdf = np.loadtxt('time.csv', delimiter=",") time = asdf return time*ureg.second, signal def super_resolution(): time, signal = signal_load() # Main loop that adds successively more time reproduced = np.zeros((len(time), len(time_range)))
[printing_unit] -> [length]: value * pixel_size * (meter / pixel) [length] -> [printing_unit]: value / pixel_size / (meter / pixel) @end """ import tensorflow as tf physical_devices = tf.config.list_physical_devices("GPU") try: tf.config.experimental.set_memory_growth(physical_devices[0], True) except: # Invalid device or cannot modify virtual devices once initialized. pass units.load_definitions(_pixel_context.split("\n")) units.enable_contexts("dt") from .features import * from .aberrations import * from .augmentations import * from .math import * from .noises import * from .optics import * from .scatterers import * from .sequences import * from .elementwise import * from .statistics import * from .image import array, strip
"""Implements all the reading and translation of facility specific data streams into a unified format that can be used by the analysis package.""" from __future__ import print_function, absolute_import # Compatibility with python 2 and 3 import os from pint import UnitRegistry from .worker import Worker # pylint: disable=unused-import from .event_translator import EventTranslator # pylint: disable=unused-import from .record import Record, add_record # pylint: disable=unused-import ureg = UnitRegistry() ureg.enable_contexts('spectroscopy') ureg.default_format = '~' ureg.load_definitions(os.path.join(os.path.dirname(__file__), 'units.txt'))
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Created on 26.09.17 @author: clonker @author: chrisfroe """ import os from pint import UnitRegistry current_dir = os.path.dirname(os.path.abspath(__file__)) unit_definitions = os.path.join(current_dir, 'readdy_units.txt') ureg = UnitRegistry(unit_definitions) # enable automatic conversion from energy to temperature and vice versa ureg.enable_contexts("boltzmann") Q_ = ureg.Quantity
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Created on 26.09.17 @author: clonker @author: chrisfroe """ import os from pint import UnitRegistry current_dir = os.path.dirname(os.path.abspath(__file__)) unit_definitions = os.path.join(current_dir, 'readdy_units.txt') ureg = UnitRegistry(unit_definitions) # enable automatic conversion from energy to temperature and vice versa ureg.enable_contexts("boltzmann") Q_ = ureg.Quantity