"""Setup and run dustywave calculations.""" from pathlib import Path from typing import Any, Dict, Tuple import numba import numpy as np import phantomsetup import pint from numba import float64 from numpy import ndarray from ..config import EXTRA_COMPILER_ARGUMENTS units = pint.UnitRegistry(system='cgs') def setup_calculation(params: Dict[str, Any], run_directory: Path, phantom_dir: Path, hdf5root: Path) -> phantomsetup.Setup: """Set up a Phantom dustywave calculation. Parameters ---------- params The parameters for this calculation. run_directory The path to the directory containing the run. phantom_dir The path to the Phantom repository. hdf5root The path to the root directory containing the HDF5 library.
def ureg_custom(): import pint ureg = pint.UnitRegistry() ureg.define("test_unit = 123 kg") return ureg
""" A wrapper for the pint ureg data """ # Import some nice unicode features from __future__ import unicode_literals import pint import os # We only want the ureg exposed __all__ = ["ureg"] # Find the local path file_dir = os.path.dirname(os.path.abspath(__file__)) pint_default_units_path = os.path.join(file_dir, "default_units.txt") # Build the ureg and set context ureg = pint.UnitRegistry(pint_default_units_path) # ureg.enable_contexts('chemistry')
def build_units_registry(context): """Builds a pint UnitRegistry based on a given PhysicalConstantsContext. Parameters ---------- context : PhysicalConstantsContext The context to use for the values. """ import pint phys_const = context.raw_codata ureg = pint.UnitRegistry(on_redefinition="ignore") # Explicitly update relevant 2014 codata # Definitions ureg.define("avogadro_constant = {} / mol = N_A".format( phys_const["avogadro constant"]["value"])) ureg.define("boltzmann_constant = {} * joule / kelvin".format( phys_const["boltzmann constant"]["value"])) ureg.define("speed_of_light = {} * meter / second".format( phys_const["speed of light in vacuum"]["value"])) ureg.define("hartree_inverse_meter = {} / hartree / m".format( phys_const["hartree-inverse meter relationship"]["value"])) # Energy ureg.define("hartree = {} * joule = E_h = hartree_energy".format( phys_const["hartree energy"]["value"])) ureg.define("electron_volt = {} * J = eV".format( phys_const["electron volt-joule relationship"]["value"])) # Constants ureg.define("electron_mass = {} * kg".format( phys_const["electron mass"]["value"])) ureg.define("elementary_charge = {} * coulomb = e".format( phys_const["elementary charge"]["value"])) ureg.define("plancks_constant = {} * joule * s".format( phys_const["planck constant"]["value"])) # Distance ureg.define("bohr = {} * meter = bohr_radius = Bohr".format( phys_const["bohr radius"]["value"])) ureg.define("wavenumber = 1 / centimeter") ureg.define("Angstrom = angstrom") # Masses ureg.define( "atomic_mass_unit = {} * kilogram = u = amu = dalton = Da".format( phys_const["atomic mass constant"]["value"])) # Define relationships _const_rename = { "inverse meter": "inverse_meter", "atomic mass unit": "atomic_mass_unit", "electron volt": "electron_volt" } _nist_units = set() for k, v in phys_const.items(): # Automatically builds the following: # electron_volt_to_kelvin = 1.16045221e4 / electron_volt * kelvin # hartree_to_atomic_mass_unit = 2.9212623197e-8 / hartree * atomic_mass_unit if not (("-" in k) and ("relationship" in k)): continue # Rename where needed left_unit, right_unit = k.split('-') left_unit = _const_rename.get(left_unit, left_unit) _nist_units.add(left_unit) right_unit = right_unit.replace(" relationship", "") right_unit = _const_rename.get(right_unit, right_unit) # Inverse is a special case if "inverse_meter" == left_unit: ratio1 = "* meter" else: ratio1 = "/ " + left_unit if "inverse_meter" == right_unit: ratio2 = "/ meter" else: ratio2 = "* " + right_unit definition = "{}_to_{} = {} {} {}".format(left_unit, right_unit, v["value"], ratio1, ratio2) ureg.define(definition) # print(definition) # Add contexts def _find_nist_unit(unit): """Converts pint datatypes to NIST datatypes """ for value in unit.to_tuple()[1]: if value[1] < 1: continue if any(x in value[0] for x in _nist_units): return value[0] for value in unit.to_tuple()[1]: if (value[0] == "meter") and (value[1] == -1): return "inverse_meter" return None def build_transformer(right_unit, default): """Builds a transformer that attempts first to use the NIST values exactly and then falls back on to canonical Pint tech. The NIST values are not "exact" and will fail the triangle rule due to the inherent uncertainties of the values. Parameters ---------- right_unit : str The NIST value to convert to default : str A fall back conversion rule to apply """ def transformer(ureg, val): left_unit = _find_nist_unit(val) if left_unit is None: return val * ureg.parse_expression(default) else: return val * ureg.parse_expression("{}_to_{}".format( left_unit, right_unit)) return transformer # Allows hartree <-> frequency c1 = pint.Context("energy_frequency") c1.add_transformation("[energy]", "[frequency]", build_transformer("hertz", "1 / plancks_constant")) c1.add_transformation("[frequency]", "[energy]", build_transformer("hartree", "plancks_constant")) # Allows hartree <-> inverse_length c2 = pint.Context("energy_inverse_length") c2.add_transformation( "[energy]", "1 / [length]", build_transformer("inverse_meter", "hartree_to_inverse_meter")) c2.add_transformation( "1 / [length]", "[energy]", build_transformer("hartree", "inverse_meter_to_hartree")) # Allows hartree <-> mass c3 = pint.Context("energy_mass") c3.add_transformation("[energy]", "[mass]", build_transformer("kilogram", "hartree_to_kilogram")) c3.add_transformation("[mass]", "[energy]", build_transformer("hartree", "kilogram_to_hartree")) # Allows hartree <-> temperature c4 = pint.Context("energy_temperature") c4.add_transformation("[energy]", "[temperature]", build_transformer("kelvin", "hartree_to_kelvin")) c4.add_transformation("[temperature]", "[energy]", build_transformer("hartree", "kelvin_to_hartree")) # Allows energy <-> energy / mol c5 = pint.Context("substance_relation") c5.add_transformation("[energy]", "[energy] / [substance]", lambda ureg, val: val * ureg.N_A) c5.add_transformation("[energy] / [substance]", "[energy]", lambda ureg, val: val / ureg.N_A) # Add the context ureg.enable_contexts(c1, c2, c3, c4, c5) return ureg
def unit_convert( x, frm, to=None, system=None, unit_string_map={}, ignore_units=[], gauge_pressures={}, ambient_pressure=1.0, ambient_pressure_unit="atm", ): """Convert the quantity x to a different set of units. X can be a numpy array or pandas series. The from unit is translated into a string that pint can recognize by first looking in unit_string_map then looking in know aliases defined in this file. If it is neither place it will be given to pint as-is. This translation of the unit is done so that data can be read in with the original provided units. Args: x (float, numpy.array, pandas.series): quantity to convert frm (str): original unit string to (str): new unit string, or specify "system" system (str): unit system to covert to, or specify "to" unit_string_map (dict): keys are unit strings and values are corresponding strings that pint can recognize. This only applies to the from string. ignore_units (list, or tuple): units to not convert gauge_pressures (dict): keys are units strings to be considered gauge pressures and the values are corresponding absolute pressure units ambient_pressure (float, numpy.array, pandas.series): pressure to add to gauge pressure to convert it to absolute pressure. The default is 1. The unit is atm by default, but can be changed with the ambient_pressure_unit argument. ambient_pressure_unit (str): Unit for ambient pressure, default is atm, and should be a unit recognized by pint Returns: (tuple): quantity and unit string """ ureg = pint.UnitRegistry(system=system) for u in _register_new_units: ureg.define(u) if frm in unit_string_map: frm = unit_string_map[frm] elif frm in _unit_strings: frm = _unit_strings[frm] # Now check for gauge pressure gauge = False if frm in gauge_pressures: gauge = True frm = gauge_pressures[frm] elif frm in _gauge_pressures: gauge = True frm = _gauge_pressures[frm] q = ureg.Quantity if (frm in _ignore_units) or (frm in ignore_units): return (x, frm) else: try: ureg.parse_expression(frm) except pint.errors.UndefinedUnitError: warnings.warn( "In unit conversion, from unit '{}' is not defined." " No conversion.".format(frm), UserWarning, ) return x, frm if to is None: y = q(np.array(x), ureg.parse_expression(frm)).to_base_units() else: y = q(np.array(x), ureg.parse_expression(frm)).to(to) if gauge: # convert gauge pressure to absolute y = y + ambient_pressure * ureg.parse_expression(ambient_pressure_unit) return (y.magnitude, str(y.units))
def test_convert(self): env = src.calc.Environment() ureg = pint.UnitRegistry() assert src.calc.calculate('3.6{kg} -> {mg}', env) == 3600000.0 * ureg('mg')
def plot(self): # Create base figure fig = plt.figure(figsize=self.figuresize, dpi=self.dpi) # Setup figure layout width = 2 if self.showmap else 1 # Scale TS Diagram to be double the size of location map width_ratios = [1, 3] if self.showmap else None # Create layout helper gs = gridspec.GridSpec(1, width, width_ratios=width_ratios) # Render point location if self.showmap: utils.point_plot( np.array([ [x[0] for x in self.points], # Latitudes [x[1] for x in self.points], ]), gs[0, 0]) # Longitudes # Plot Sound Speed profile plt.subplot(gs[:, 1 if self.showmap else 0]) ax = plt.gca() for i, ss in enumerate(self.sspeed): ax.plot(ss, self.temperature_depths[i], "-") minspeed = np.amin(self.sspeed) maxspeed = np.amax(self.sspeed) ax.set_xlim([ np.amin(self.sspeed) - (maxspeed - minspeed) * 0.1, np.amax(self.sspeed) + (maxspeed - minspeed) * 0.1, ]) ax.set_xlabel(gettext("Sound Speed (m/s)"), fontsize=14) ax.set_ylabel(gettext("Depth (m)"), fontsize=14) ax.invert_yaxis() ax.xaxis.set_ticks_position("top") ax.xaxis.set_label_position("top") x_format = tkr.FuncFormatter(lambda x, pos: "%d" % x) ax.xaxis.set_major_formatter(x_format) if not self.plotTitle: ax.set_title( gettext("Sound Speed Profile for (%s)\n%s") % (", ".join( self.names), self.date_formatter(self.iso_timestamp)), fontsize=15, ) else: ax.set_title(self.plotTitle, fontsize=15) ax.title.set_position([0.5, 1.10]) plt.subplots_adjust(top=0.85) ax.xaxis.grid(True) self.plot_legend(fig, self.names) ylim = ax.get_ylim() ax2 = ax.twinx() ureg = pint.UnitRegistry() ax2.set_ylim((ylim * ureg.meters).to(ureg.feet).magnitude) ax2.set_ylabel(gettext("Depth (ft)"), fontsize=14) # This is a little strange where we want to skip calling the TSP.plot and go straigh # to Point.plot return super(TemperatureSalinityPlotter, self).plot(fig)
""" Correctly keeping track of units in calculations can be very difficult, particularly if there are places where different units can be used. For example, it is very easy to forget to convert between different units – feet/inches into meters – or metric prefixes – converting 1 km into 1,000 m, for instance. This module illustrates how to use the Pint package to keep track of units of measurement in calculations. """ import pint ureg = pint.UnitRegistry(system="mks") @ureg.wraps(ureg.meter, ureg.second) def calc_depth(dropping_time): # s = u*t + 0.5*a*t*t # u = 0; a = 9.81 return 0.5 * 9.81 * dropping_time * dropping_time distance = 5280 * ureg.feet print(distance.to("miles")) print(distance.to_base_units()) print(distance.to_base_units().to_compact()) depth = calc_depth(0.05 * ureg.minute) print("Depth:", depth) # Depth 44.144999999999996 meter
def __init__(self): self.path = '' self.registry = pint.UnitRegistry() self.warned = False self.unknown = {}
from discord.ext.commands import CommandNotFound, DisabledCommand, CheckFailure, MissingRequiredArgument, \ BadArgument, TooManyArguments, UserInputError, CommandOnCooldown, CommandInvokeError config = ConfigParser() config.read_file(codecs.open('./config/config.ini', "r", "utf8")) logger = logging TOKEN = os.environ['TOKEN'] prefix = config["General"]["prefix"] version = config["Info"]["version"] extensions = config["Extensions"]["extensions"] start = datetime.datetime.now() logger.basicConfig(level=logging.INFO) bot = commands.Bot(commands.when_mentioned_or(prefix)) bot.registry = pint.UnitRegistry() bot.quantity = bot.registry.Quantity bot.paginator = commands.Paginator(prefix='```', suffix='```', max_size=1950) bot.page = 0 extensions = config["Extensions"]["extensions"] startup_extensions = [] for ext in extensions.split(', '): startup_extensions.append(ext) def setup_registry(): bot.registry.load_definitions('./config/defs.txt') @bot.event
def __init__(self, **kwargs): """ Initialises all the parameters and computes the scaling factors. All parameters should be pint Quantities. :Parameters: **kwargs: The following are all required: R : Stimulated scattering rate g_C : Polariton-polariton interaction strength g_R: gamma_C : Polariton relaxation rate gamma_R m : Polariton effective mass, in units of the electron mass The following are optional: k: Value of dispersive coefficient. If not provided, defaults to hbar**2 / (2 * m) charT: a characteristic time to scale by. If not provded, defaults to (gamma_C) ^ -1 charL: a charactersitic length to scale by. If not provided, defaults to ( hbar * charT / (2 * m * gamma_C) )^1/2. """ self.singleComp = True if 'gamma_nl' in kwargs else False self.__checkArgs(kwargs) # Define the output units and actual units of the parameters # We'll make them strings to make life easy, and because we want them to # be reported int the right way self.ureg = pint.UnitRegistry() m_e = self.ureg.electron_mass.to_base_units().magnitude hbar = self.ureg.hbar.to_base_units().magnitude self.gOutput = "millieV * micrometer**2" self.rOutput = "millieV * micrometer**2 * hbar**-1" self.gammaOutput = "picosecond ** -1" self.gammaNlBase = "meter**2 * second**-1" self.mOutput = "electron_mass" self.charLOutput = "micrometer" self.charTOutput = "picosecond" self.gammaNlOutput = "millieV * micrometer**2 * hbar**-1" self.mBase = "gram" self.gBase = "gram * meter **4 * second ** -2" self.rBase = "meter**2 * second **-1" self.gammaBase = "second ** -1" self.charLBase = "meter" self.charTBase = "second" # Read in the keyword arguments for (k, v) in kwargs.items(): setattr(self, k, v.to_base_units().magnitude) # Set mass. We read in mass in units of electron mass for convenience, # but it must be converted to SI units # self.m_scaled = self.m # self.m = self.__class__.__m_e * self.m # m is now read in as a pint quantity. We don't need to scale it up by # the electron mass, but we do need to find the scaled mass self.m_scaled = self.m / m_e # Read in k or set to default self.k = kwargs.get('k', hbar**2 / (2 * self.m)) # Define our characteristic length, time, and energy scales. # If t' is the (nondimensional) time variable used in the # nondimensionalised GPE, then t = charT * t'. For example, R' is the # stimulated scattering rate used in the normalised GPE, so R = charR * # R'. If they are not provided, we will set them to the default, which # is the scaling that makes k=1 and gamma'_C = 1. self.charT = kwargs.get('charT', 1.0 / self.gamma_C) if 'charT' in kwargs.keys(): self.charT = self.charT.to_base_units().magnitude self.charL = kwargs.get('charL', np.sqrt((hbar * self.charT) / (2.0 * self.m))) if 'charL' in kwargs.keys(): self.charL = self.charL.to_base_units().magnitude # A characteristic energy self.charU = hbar / self.charT self.charg = (hbar * self.charL**2) / self.charT self.charR = self.charL**2 / self.charT self.charGamma = 1.0 / self.charT self.charGammaNl = self.charL**2 / self.charT # TODO: Check self.chark = (hbar * self.charL**2) / self.charT # This may not be required - the P term in the GPE is phenomonological, # and the experimentalist probably only knows it in terms of Pth self.charP = 1.0 / (self.charT * self.charL**2) # Scaled parameters - these are the ones to used in the # nondimensionalised GPE self.g_C_scaled = self.g_C / self.charg self.gamma_C_scaled = self.gamma_C / self.charGamma self.k_scaled = self.k / self.chark self.g_R_scaled = self.g_R / self.charg self.gamma_R_scaled = self.gamma_R / self.charGamma self.R_scaled = self.R / self.charR # Compute threshold pump power for the normalised GPE. self.Pth_scaled = ((self.gamma_R_scaled * self.gamma_C_scaled) / self.R_scaled) # Compute threshold pump power for unnormalised GPE. We can get this # from the scaled one. self.Pth = self.charP * self.Pth_scaled if self.singleComp: self.gamma_nl_scaled = self.gamma_nl / self.charGammaNl
def analyze(file_name, lis_struct, time, args): """ Analyzes LIS results, looking for events related to ALT, and puts events into a dict {file_name -> {event_time -> (event_str)}}. :param file_name: (str) name of current JSON file being read :param lis_struct: (dict) dict containing item and value pairs :param time: (str) time when results were obtained (as contained in JSON file) :param args: (dict) switches provided to lisanalyze.py via argparse :returns: False """ #global __alias # Use "ALT" as the standard name for k in lis_struct[time].keys(): if k in __alias.keys(): lis_struct[time].update({__alias[k]: lis_struct[time][k]}) # Basic checks and value-setting if "ALT" in lis_struct[time].keys(): if args.warn and lis_struct[time]["ALT"]["unit"] != __unit: print("WARNING: unit mismatch in entry for {}".format(time), file=sys.stderr) alt_val = float(lis_struct[time]["ALT"]["lab_value"]) else: return None # Unit conversion if args.convert: import pint ureg = pint.UnitRegistry() ureg.define('kat = 1 mol / s') ureg.define('U = 1.657e-8 kat') factor = (ureg.parse_expression( lis_struct[time]["ALT"]["unit"])).to(__unit).magnitude alt_val *= factor # Out-of-normal-range warning; provided values take precedence if "ref_high" in lis_struct[time]["ALT"].keys(): if lis_struct[time]["ALT"]["lab_value"] > lis_struct[time]["ALT"][ "ref_high"]: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "ALT too high (current value {}; reference value {} ({}))".format( lis_struct[time]["ALT"]["lab_value"], lis_struct[time]["ALT"]["ref_high"], lis_struct[time]["ALT"]["unit"]) __event_dict[file_name][event_time].append(event_str) else: if args.warn: print( "WARNING: higher reference value not provided; falling back to built-in value", file=sys.stderr) if alt_val > __alt_ul: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "ALT too high (current value {}; reference value {} ({}))".format( alt_val, __alt_ul, __unit) __event_dict[file_name][event_time].append(event_str) if "ref_low" in lis_struct[time]["ALT"].keys(): if lis_struct[time]["ALT"]["lab_value"] < lis_struct[time]["ALT"][ "ref_low"]: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "ALT too low (current value {}; reference value {} ({}))".format( lis_struct[time]["ALT"]["lab_value"], lis_struct[time]["ALT"]["ref_low"], lis_struct[time]["ALT"]["unit"]) __event_dict[file_name][event_time].append(event_str) else: if args.warn: print( "WARNING: lower reference value not provided; falling back to built-in value", file=sys.stderr) if alt_val < __alt_ll: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "ALT too low (current value {}; reference value {} ({}))".format( alt_val, __alt_ll, __unit) __event_dict[file_name][event_time].append(event_str) # ALT > 1000 suggests ischemia, viral infection, toxicity (Lange Pocket Guide to Diagnostic Tests, 6e, p.531) if alt_val > 1000: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "ALT markedly elevated ({} ({})); consider ischemia, infection, toxicity".format( alt_val, __unit) __event_dict[file_name][event_time].append(event_str) # AST / ALT > 2 suggests alcoholism (Lange Pocket Guide to Diagnostic Tests, 6e, p.531) import lisanalyze_ast ast_passthrough = lisanalyze_ast.passthrough(file_name, lis_struct, time, args) if ast_passthrough: ast, unit = alt_passthrough if (ast / alt_val) > 2: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "AST/ALT > 2 (AST: {}, ALT: {}, AST/ALT: {}); consider alcoholic hepatitis".format( ast, alt_val, ast / alt_val) __event_dict[file_name][event_time].append(event_str) # AST / ALT > 1 suggests cirrhosis in patients with hepatitis C (Lange Pocket Guide to Diagnostic Tests, 6e, p.73) import lisanalyze_ast ast_passthrough = lisanalyze_ast.passthrough(file_name, lis_struct, time, args) if ast_passthrough: ast, unit = alt_passthrough if ast > alt_val: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "AST/ALT > 1 (AST: {}, ALT: {}, AST/ALT: {}); possible cirrhosis if patient has hepatitis C".format( ast, alt_val, ast / alt_val) __event_dict[file_name][event_time].append(event_str) return False
def analyze(file_name, lis_struct, time, args): """ Analyzes LIS results, looking for events related to sodium, and puts events into a dict {file_name -> {event_time -> (event_str)}}. :param file_name: (str) name of current JSON file being read :param lis_struct: (dict) dict containing item and value pairs :param time: (str) time when results were obtained (as contained in JSON file) :param args: (dict) switches provided to lisanalyze.py via argparse :returns: False """ #global __alias # Use "Na" as the standard name for k in list(lis_struct[time]): if k in __alias.keys(): lis_struct[time].update({__alias[k]: lis_struct[time][k]}) # Basic checks and value-setting if "Na" in lis_struct[time].keys(): if args.warn and lis_struct[time]["Na"]["unit"] != __unit: print("WARNING: unit mismatch in entry for {}".format(time), file=sys.stderr) na_val = float(lis_struct[time]["Na"]["lab_value"]) else: return None # Unit conversion if args.convert: lis_struct[time]["Na"]["unit"] = lis_struct[time]["Na"]["unit"].lower( ).replace("eq", "mol") import pint ureg = pint.UnitRegistry() factor = (ureg.parse_expression( lis_struct[time]["Na"]["unit"])).to(__unit).magnitude na_val *= factor # Correction for glucose (Lange Pocket Guide to Diagnostic Tests, 6e, p.260) if not args.no_correct: import modules.analyzers.lisanalyze_glucose as lisanalyze_glucose glucose_passthrough = lisanalyze_glucose.passthrough( file_name, lis_struct, time, args) if glucose_passthrough: glucose, unit = glucose_passthrough if glucose > 110: na_val += (glucose - 110) * 1.6 / 100 # Out-of-normal-range warning; provided values take precedence if "ref_high" in lis_struct[time]["Na"].keys(): if lis_struct[time]["Na"]["lab_value"] > lis_struct[time]["Na"][ "ref_high"]: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "Hypernatremia (current value {}; reference value {} ({}))".format( lis_struct[time]["Na"]["lab_value"], lis_struct[time]["Na"]["ref_high"], lis_struct[time]["Na"]["unit"]) __event_dict[file_name][event_time].append(event_str) else: if args.warn: print( "WARNING: higher reference value not provided; falling back to built-in value", file=sys.stderr) if na_val > __na_ul: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "Hypernatremia (current value {}; reference value {} ({}))".format( na_val, __na_ul, __unit) __event_dict[file_name][event_time].append(event_str) if "ref_low" in lis_struct[time]["Na"].keys(): if lis_struct[time]["Na"]["lab_value"] < lis_struct[time]["Na"][ "ref_low"]: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "Hyponatremia (current value {}; reference value {} ({}))".format( lis_struct[time]["Na"]["lab_value"], lis_struct[time]["Na"]["ref_low"], lis_struct[time]["Na"]["unit"]) __event_dict[file_name][event_time].append(event_str) else: if args.warn: print( "WARNING: lower reference value not provided; falling back to built-in value", file=sys.stderr) if na_val < __na_ll: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "Hyponatremia (current value {}; reference value {} ({}))".format( na_val, __na_ll, __unit) __event_dict[file_name][event_time].append(event_str) # Panic if Na > 155 mmol/l or Na < 125 mmol/l (Lange Pocket Guide to Diagnostic Tests, 6e, p.260) if na_val > 155: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "Severe hypernatremia ({} ({}))".format(na_val, __unit) __event_dict[file_name][event_time].append(event_str) if na_val < 125: event_time = time if file_name not in __event_dict.keys(): __event_dict[file_name] = {} if event_time not in __event_dict[file_name].keys(): __event_dict[file_name][event_time] = [] event_str = "Severe hyponatremia ({} ({}))".format(na_val, __unit) __event_dict[file_name][event_time].append(event_str) return False
import sys if sys.version_info < (3, 6): logger.warn('modsim.py depends on Python 3.6 features.') import inspect import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy import sympy import seaborn as sns sns.set(style='white', font_scale=1.2) import pint UNITS = pint.UnitRegistry() Quantity = UNITS.Quantity # expose some names so we can use them without dot notation from copy import copy from numpy import sqrt, log, exp, pi from pandas import DataFrame, Series from time import sleep from scipy.interpolate import interp1d from scipy.interpolate import InterpolatedUnivariateSpline from scipy.integrate import odeint from scipy.integrate import solve_ivp from scipy.optimize import leastsq from scipy.optimize import minimize_scalar
"""Class to extend the HaloMassFunction class to compute the estimated merger rate of primordial black holes in different sized halos.""" import math import numpy as np import scipy.special import matplotlib matplotlib.use('PDF') import matplotlib.pyplot as plt import pint import concentration import halo_mass_function as hm #This is a global so that the decorator checking works. ureg_chk = pint.UnitRegistry() def ggconc(conc): """Utility function that drops out of the NFW profile. Eq. 10 of the attached pdf.""" return np.log(1 + conc) - conc / (1 + conc) class NFWHalo(hm.HaloMassFunction): """Class to add the ability to compute concentrations to the halo mass function""" def __init__(self, *args, conc_model="ludlow", conc_value=1., hubble=0.67, **kwargs): self.ureg = pint.UnitRegistry() self.ureg.define("Msolar = 1.98855*10**30 * kilogram") #Mpc newton's constant and light speed are already defined.
import pint import psutil import pyudev import six import stevedore from ironic_python_agent import encoding from ironic_python_agent import errors from ironic_python_agent import netutils from ironic_python_agent import utils _global_managers = None LOG = log.getLogger() CONF = cfg.CONF UNIT_CONVERTER = pint.UnitRegistry(filename=None) UNIT_CONVERTER.define('MB = []') UNIT_CONVERTER.define('GB = 1024 MB') NODE = None def _get_device_vendor(dev): """Get the vendor name of a given device.""" try: devname = os.path.basename(dev) with open('/sys/class/block/%s/device/vendor' % devname, 'r') as f: return f.read().strip() except IOError: LOG.warning("Can't find the device vendor for device %s", dev)
""" Created on Thu Jun 8 2017 @author: Monroe Weber-Shirk Last modified: Fri Aug 11 2017 By: Ethan Keller Module containing global `pint` unit registry. The `pint` module supports arithmetic involving *physical quantities* each of which has a magnitude and units, for example 1 cm or 3 kg. The units of a quantity come from a `pint` *unit registry*, and it appears that `pint` supports arithmetic operations only on quantities whose units come from the same unit registry (an attempt to perform an operation on quantities whose units come from different unit registries raises an exception). This module contains a single global unit registry `unit_registry` that can be used by any number of other modules. """ import os import pint unit_registry = pint.UnitRegistry(system='mks', autoconvert_offset_to_baseunit=True) unit_registry.load_definitions( os.path.join(os.path.dirname(__file__), "data/unit_definitions.txt"))
import numpy as np import matplotlib.pyplot as plt import uncertainties.unumpy as unp from uncertainties.unumpy import nominal_values as noms from uncertainties.unumpy import std_devs as stds from uncertainties import ufloat from scipy.optimize import curve_fit import scipy.constants as const import imageio from scipy.signal import find_peaks from scipy.signal import argrelmin from scipy.signal import argrelmax import pint import string as str from tab2tex import make_table ureg = pint.UnitRegistry(auto_reduce_dimensions = True) Q_ = ureg.Quantity #------------------------Verwendete Konstanten-------------------- c = Q_(const.value('speed of light in vacuum'), const.unit('speed of light in vacuum')) h = Q_(const.value('Planck constant'), const.unit('Planck constant')) # c = const.c # h = const.h muB = const.value('Bohr magneton') gyro_faktor = 2.6752219 #rad/(sT) max_gradient = -9 gp = const.physical_constants["proton gyromag. ratio"] print("Gyromagnetischer Faktor eines Protons:", gp) k = const.physical_constants["Boltzmann constant"]
def test_make_units(self): env = src.calc.Environment() ureg = pint.UnitRegistry() assert src.calc.calculate('3.6 {(kg * m) / s}->{(mg * m)/s}', env) == 3600000.0 * ureg('(mg * m)/s')
'long_name': 'Data 1 values', 'units': 'degF' }), 'data2': ('time', data2, { 'long_name': 'Data 2 values', 'units': 'degC' }) }, coords={'time': ('time', time, { 'long_name': 'Time in UTC' })}) # But we need the units of the two data variables to be the same. # Let's use Pint to fix that. desired_temp_unit = 'degK' # The units we want unit_registry = pint.UnitRegistry() # Set up the regestry object. if False: # Using the .data_vars method on the Dataset we can get a list of all # variables in the object instead of typing their names. # Notice the print out is more than the names. print('\nxr_ds.data_vars:\n', xr_ds.data_vars) # When we convet it to a list it automatically just has variable names. print('\nlist(xr_ds.data_vars):\n', list(xr_ds.data_vars)) print() # We loop over all the variables in the Dataset. Notice some magic here # where the loop knows how to extract the variable names only and sets # the var_name for each itteration to the variable name not the full # DataArray.
from .object import Object from ..postgres import ArrayPosition, ArrayPositions, Unnest import pandas as pd import ete3 import arrow import pint import geopy import datetime import version_parser.version as version import re import io from scipy.sparse import coo_matrix #This should be fine to live here, but may need to move if this file reloads often unitregistry = pint.UnitRegistry() pint.set_application_registry(unitregistry) Q_ = unitregistry.Quantity # CUSTOM FIELDS AND PARSERS # Probably move these to a fields.py soon class VersionParser(version.Version): digits = 4 number_version_pattern = re.compile(r"^(\d{1,%d})$" % (digits * 3, )) def __init__(self, raw_version, parse_number=False, *args, **kwargs): if not parse_number: self.number_version_pattern = re.compile( r"$a" ) #thanks StackOverflow, for this regex that's guaranteed not to match
""" =========== scikit-aero =========== Aeronautical engineering calculations in Python """ # Package version __version__ = "0.2.dev0" # Prellocate units module import pint units = pint.UnitRegistry()
import pint u = pint.UnitRegistry() pint.UnitRegistry(system='mks') import numpy as np import os c_h = 6.582119569e-34 # J * s c_e = 1.602176634e-19 # C c_ϵ_0 = 8.8541878128e-12 # A s / (V m) c_m_e = 9.1093837015e-31 # kg c_c_0 = 2.99792458e8 # m/s c_k_B = 1.38064852e-23 # J / K c_σ = 5.670374419e-8 # W / m**2 / K**4 c_h = 6.62607015e-34 # J s c_R = 8.314462618 # J / mol / K c_NA = 6.02214076e23 # 1 / mol c_m = 1.6605390666e-27 # kg u_h = c_h * u.J * u.s u_e = c_e * u.A * u.s u_ϵ_0 = c_ϵ_0 * u.A * u.s / (u.V * u.m) u_m_e = c_m_e * u.kg u_c_0 = c_c_0 * u.m / u.s u_k_B = c_k_B * u.J / u.K u_σ = c_σ * u.W / u.m**2 / u.K**4 u_h = c_h * u.J * u.s u_R = c_R * u.J / u.mol / u.K u_NA = c_NA / u.mol u_m = c_m * u.kg sun_Ts = 5778.0 # K
# -*- coding: utf-8 -*- """ Created on Fri Oct 6 14:51:48 2017 @author: tanner """ import pint as pynt u = pynt.UnitRegistry() def convertT(temp, unit): if unit == 'K': return temp if unit == 'R': temp = temp * u.rankine rtemp = temp.to(u.kelvin) return rtemp.magnitude if unit == 'F': tempF = u.Quantity fTemp = tempF(temp, u.degF) cTemp = fTemp.to(u.kelvin) return cTemp.magnitude if unit == 'C': tempC = u.Quantity cTemp = tempC(temp, u.degC) kTemp = cTemp.to(u.kelvin) return kTemp.magnitude
import numpy as np import pint ureg = pint.UnitRegistry() ureg.setup_matplotlib() import tools from generate_table import generate_table α1, α2_grün, α2_rot = np.genfromtxt(f'data/Prisma.csv', comments='#', delimiter=',', unpack=True) α1 *= ureg.deg # Einfallswinkel α2_grün *= ureg.deg # Austrittswinkel α2_rot *= ureg.deg # Austrittswinkel # assert all(α1 >= 10 & α1 <= 60)… def analyze(α2): γ = ureg('60 °') # brechender Winkel; lt. Versuchsanleitung n_lit = 1.510 * ureg.dimensionless # Brechungsindex für Kronglas; aus der Vorbereitungsaufgabe δ = (α1 + α2) - γ # Ablenkung print(f"{δ=}") assert all( δ < ureg('120 °') ) # sanity check – siehe Abbildung. Größere Werte ergeben keinen Sinn. return δ print('grün:') δ_grün = analyze(α2_grün)
from carousel.core.exceptions import (DuplicateRegItemError, MismatchRegMetaKeysError) warnings.simplefilter('always', DeprecationWarning) logging.captureWarnings(True) # create default logger from root logger with debug level, stream handler and # formatter with date-time, function name, line no and basic configuration LOG_DATEFMT = '%Y-%m-%d %H:%M:%S' LOG_FORMAT = ('\n> %(asctime)s %(funcName)s:%(lineno)d\n> ' + '\n'.join(logging.BASIC_FORMAT.rsplit(':', 1))) logging.basicConfig(datefmt=LOG_DATEFMT, format=LOG_FORMAT) LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.DEBUG) # unit registry, quantity constructor and extra units registry definitions UREG = pint.UnitRegistry() # registry of units Q_ = UREG.Quantity # quantity constructor for ambiguous quantities like degC UREG.define('lumen = cd * sr = lm') UREG.define('lux = lumen / m ** 2.0 = lx') UREG.define('fraction = []') # define new dimensionless base unit for percents UREG.define('percent = fraction / 100.0 = pct') # can't use "%" only ascii UREG.define('suns = []') # dimensionless unit equivalent to 1000.0 [W/m/m] # define PV solar context _PV = pint.Context('pv') # define transformation of suns to power flux and vice versa E0 = 1000.0 * UREG.W / UREG.m / UREG.m # 1 sun _PV.add_transformation('[]', '[power] / [area]', lambda ureg, x: x * E0) _PV.add_transformation('[power] / [area]', '[]', lambda ureg, x: x / E0) UREG.add_context(_PV)
from matplotlib import pyplot as plt import yaml import pint from collections import defaultdict import pandas as pd import network_data_analysis as nda from matplotlib.backends.backend_pdf import PdfPages import matplotlib.gridspec as gridspec import pn_kc_ggn_plot_mpl as myplot import neurograph as ng import timeit from sklearn import cluster, preprocessing plt.rc('font', size=11) _ur = pint.UnitRegistry() Q_ = _ur.Quantity datadir = 'D:\\biowulf_stage\\olfactory_network\\' datadir = '/data/rays3/ggn/olfactory_network/' # jid = '16034794' jid = '22295165' fname = nda.find_h5_file(jid, datadir) gs = gridspec.GridSpec(nrows=3, ncols=1, height_ratios=[2, 2, 1], hspace=0.05) fig = plt.figure() ax0 = fig.add_subplot(gs[0]) ax1 = fig.add_subplot(gs[1], sharex=ax0) ax2 = fig.add_subplot(gs[2], sharex=ax0) axes = [ax0, ax1, ax2]
import pint from decimal import Decimal import yaml u1 = pint.UnitRegistry() u2 = pint.UnitRegistry() u1.define('xx = 1*meter') u2.define('xx = 1*micrometer') def changesys(new_system, qty): orig_units = qty.units x = qty.to_base_units() x = new_system.Quantity(x.magnitude, x.units) try: x = x.to(str(orig_units)) except (pint.errors.UndefinedUnitError, pint.errors.DimensionalityError): pass return x y = changesys(u2, (Decimal(1) * u1.xx)) print(yaml.load(yaml.dump(y)).to_base_units())
# ------------------------------------------------------------- # TEMPORARY FILES PATH # ------------------------------------------------------------- if platform.system() == 'Windows': TMP_PATH = os.path.join(os.getenv('TEMP'), CONFIG.get('temp_files', 'temp_subfolder')) elif platform.system() == 'Linux': TMP_PATH = os.path.join('/var/tmp', CONFIG.get('temp_files', 'temp_subfolder')) else: raise OSError('Could not find a valid temp path.') COORDS_FILE_PATH = os.path.join(TMP_PATH, 'bus_coords_fromkml.csv') # ------------------------------------------------------------- # UNIT MEASURE REGISTRY # ------------------------------------------------------------- UM = pint.UnitRegistry() UM.define('percent = 0.01 * dimensionless = pct') UM.define('none = [generic_length] = unitlength') # when lengths are set as none, this creates a common basis UM.define('mt = meter') PINT_QTY_TYPE = type(1 * UM.m) # ------------------------------------------------------------- # DICTIONARY OF ERROR MESSAGE SUBSTRINGS # ------------------------------------------------------------- with open(ERROR_STRINGS_PATH, 'r') as ef: ERROR_STRINGS = json.load(ef) # ------------------------------------------------------------- # LIST OF STACKS UNCALLABLE IF UNCONVERGED # -------------------------------------------------------------
def test_datum_user_unit_registry(): ureg = pint.UnitRegistry() ureg.define('ell = 0.6275 * meter = ell') datum = 1 result = unit_convert(datum, src='ell', dst='m', ureg=ureg) np.testing.assert_equal(result, 0.6275)