Exemple #1
0
def main(wf):
    """Run workflow Script Filter.

    Args:
        wf (workflow.Workflow): Current Workflow object.

    """
    global ureg
    ureg = UnitRegistry(wf.decode(DEFAULT_UNIT_DEFINITIONS))
    ureg.default_format = 'P'

    wf.magic_arguments['appkey'] = open_currency_instructions

    if not len(wf.args):
        return

    query = wf.args[0]  # .lower()
    log.debug('query : %s', query)

    handle_update(wf)
    # Create data files if necessary
    bootstrap(wf)

    # Add workflow and user units to unit registry
    register_units()

    # Notify of available update
    if wf.update_available:
        wf.add_item('A newer version is available',
                    'Action this item to download & install the new version',
                    autocomplete='workflow:update',
                    icon=ICON_UPDATE)

    # Load cached data
    exchange_rates = wf.cached_data(CURRENCY_CACHE_NAME, max_age=0)

    if exchange_rates:  # Add exchange rates to conversion database
        register_exchange_rates(exchange_rates)

    if not wf.cached_data_fresh(CURRENCY_CACHE_NAME, CURRENCY_CACHE_AGE):
        # Update currency rates
        cmd = ['/usr/bin/python', wf.workflowfile('currency.py')]
        run_in_background('update', cmd)
        wf.rerun = 0.5

    if is_running('update'):
        wf.rerun = 0.5
        if exchange_rates is None:  # No data cached yet
            wf.add_item(u'Fetching exchange rates…',
                        'Currency conversions will be momentarily possible',
                        icon=ICON_INFO)
        else:
            wf.add_item(u'Updating exchange rates…',
                        icon=ICON_INFO)

    return convert(query)
def main(wf):
    """Run workflow Script Filter.

    Args:
        wf (workflow.Workflow): Current Workflow object.

    """
    global ureg
    ureg = UnitRegistry(wf.decode(DEFAULT_UNIT_DEFINITIONS))
    ureg.default_format = 'P'

    wf.magic_arguments['appkey'] = open_currency_instructions

    if not len(wf.args):
        return

    query = wf.args[0]  # .lower()
    log.debug('query : %s', query)

    handle_update(wf)
    # Create data files if necessary
    bootstrap(wf)

    # Add workflow and user units to unit registry
    register_units()

    # Notify of available update
    if wf.update_available:
        wf.add_item('A newer version is available',
                    'Action this item to download & install the new version',
                    autocomplete='workflow:update',
                    icon=ICON_UPDATE)

    # Load cached data
    exchange_rates = wf.cached_data(CURRENCY_CACHE_NAME, max_age=0)

    if exchange_rates:  # Add exchange rates to conversion database
        register_exchange_rates(exchange_rates)

    if not wf.cached_data_fresh(CURRENCY_CACHE_NAME, CURRENCY_CACHE_AGE):
        # Update currency rates
        cmd = ['/usr/bin/python', wf.workflowfile('currency.py')]
        run_in_background('update', cmd)
        wf.rerun = 0.5

    if is_running('update'):
        wf.rerun = 0.5
        if exchange_rates is None:  # No data cached yet
            wf.add_item(u'Fetching exchange rates…',
                        'Currency conversions will be momentarily possible',
                        icon=ICON_INFO)
        else:
            wf.add_item(u'Updating exchange rates…',
                        icon=ICON_INFO)

    return convert(query)
Exemple #3
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
Exemple #4
0
def convertTemp(T,top1,top2):
    #The 3 lines here for ureg are just setting the baseline for our temperature units
    ureg = UnitRegistry(autoconvert_offset_to_baseunit = True)
    ureg.default_format = '.3f'
    Q_ = ureg.Quantity
    if top1 == 0:
        home = Q_(T, ureg.degC)
    elif top1 == 1:
        home = Q_(T, ureg.degF)
    elif top1 == 2:
        home = Q_(T, ureg.degK)        
    return home.to(tTypes[top2])
Exemple #5
0
 def test_default_formatting(self):
     ureg = UnitRegistry()
     x = ureg.Quantity(4.12345678, UnitsContainer(meter=2, kilogram=1, second=-1))
     for spec, result in (('L', r'4.12345678 \frac{kilogram \cdot meter^{2}}{second}'),
                          ('P', '4.12345678 kilogram·meter²/second'),
                          ('H', '4.12345678 kilogram meter<sup>2</sup>/second'),
                          ('~', '4.12345678 kg * m ** 2 / s'),
                          ('L~', r'4.12345678 \frac{kg \cdot m^{2}}{s}'),
                          ('P~', '4.12345678 kg·m²/s'),
                          ('H~', '4.12345678 kg m<sup>2</sup>/s'),
                          ):
         ureg.default_format = spec
         self.assertEqual('{0}'.format(x), result)
Exemple #6
0
 def test_default_formatting(self):
     ureg = UnitRegistry()
     x = ureg.Quantity(4.12345678, UnitsContainer(meter=2, kilogram=1, second=-1))
     for spec, result in (('L', r'4.12345678 \frac{kilogram \cdot meter^{2}}{second}'),
                          ('P', '4.12345678 kilogram·meter²/second'),
                          ('H', '4.12345678 kilogram meter<sup>2</sup>/second'),
                          ('C', '4.12345678 kilogram*meter**2/second'),
                          ('~', '4.12345678 kg * m ** 2 / s'),
                          ('L~', r'4.12345678 \frac{kg \cdot m^{2}}{s}'),
                          ('P~', '4.12345678 kg·m²/s'),
                          ('H~', '4.12345678 kg m<sup>2</sup>/s'),
                          ('C~', '4.12345678 kg*m**2/s'),
                          ):
         ureg.default_format = spec
         self.assertEqual('{0}'.format(x), result)
Exemple #7
0
def unit_conversion(result):
    data = _get_entities(result)
    response = {
        "tts": "",
        "file": "",
        "save": True,
    }
    if data:
        units = UnitRegistry()
        units.default_format = '.2f'
        base = data["base"]
        conversion = data["conversion"]
        try:
            amount = data["amount"] * units(input_string=base)
        except UndefinedUnitError as e:
            response[
                "tts"] = "The base unit does not appear to be in the unit registry."
            response["file"] = "base_unit_undefined.mp3"
        else:
            try:
                result = amount.to(conversion)
            except DimensionalityError as e:
                response[
                    "tts"] = f"I can't conver the base unit to the conversion unit."
                response["file"] = "conversion_dimensionality.mp3"
            except UndefinedUnitError as e:
                response[
                    "tts"] = "The conversion unit does not appear to be in the unit registry."
                response["file"] = "conversion_unit_undefined.mp3"
            else:
                response["tts"] = f"{amount} is {result}"
                response["save"] = False
        return response
    response["tts"] = "I wasn't able to convert those units."
    response["file"] = "conversion_failure.mp3"
    return response
Exemple #8
0
from pint import UnitRegistry
u = UnitRegistry()
u.default_format = '~P'
Q_ = u.Quantity
from .atoms import Atom, AtomMixed
from .unitCell import UnitCell
from .structure import Structure
from .simulation import Simulation
from .xray import Xray
from .xrayKin import XrayKin
from .xrayDyn import XrayDyn

__all__ = [
    'Atom', 'AtomMixed', 'UnitCell', 'Structure', 'Simulation', 'Xray',
    'XrayKin', 'XrayDyn', 'u', 'Q_'
]
Exemple #9
0
# http://taurus-scada.org
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Taurus is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
##
# Taurus is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
##
# You should have received a copy of the GNU Lesser General Public License
# along with Taurus.  If not, see <http://www.gnu.org/licenses/>.
##
#############################################################################
"""
This module provides a pint unit registry instance (`UR`) to be used by all
taurus objects. It also provides the `Quantity` factory from that registry
(also aliased as `Q_`).
"""

from pint import UnitRegistry

# Ininitialize the unit registry for taurus
UR = UnitRegistry()
UR.default_format = '~'  # use abbreviated units
Q_ = Quantity = UR.Quantity
Exemple #10
0
# 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:
    """
    Class for storing and retrieving measured parameter values together with their
Exemple #11
0
    CUSTOM_DEFINITIONS_FILENAME,
    DECIMAL_PLACES,
    DECIMAL_SEPARATOR,
    DEFAULT_SETTINGS,
    HELP_URL,
    ICON_UPDATE,
    THOUSANDS_SEPARATOR,
    UPDATE_SETTINGS,
)
from defaults import Defaults

log = None

# Pint objects
ureg = UnitRegistry()
ureg.default_format = 'P'
# Q = ureg.Quantity


class NoToUnits(Exception):
    """Raised if there are no to units (or defaults)."""


class Input(object):
    """Parsed user query."""

    def __init__(self, number, dimensionality, from_unit, to_unit=None):
        self.number = number
        self.dimensionality = dimensionality
        self.from_unit = from_unit
        self.to_unit = to_unit
Exemple #12
0
 def test_issue_1300(self):
     ureg = UnitRegistry()
     ureg.default_format = "~P"
     m = ureg.Measurement(1, 0.1, "meter")
     assert m.default_format == "~P"
Exemple #13
0
Author: Matthew C. Jones
Email: [email protected]

:copyright: 2020 Matthew C. Jones
:license: MIT License, see LICENSE for more details.
"""

from inspect import currentframe

from numpy import sqrt
from ambiance import Atmosphere
from pint import UnitRegistry

unit = UnitRegistry(system='mks')
unit.default_format = '~P'
dimless = unit('dimensionless')


def name_of_var(var):
    """Find name of variables using local items.

    :var: dimensioned variable
    :returns: user-coded name of variable

    """
    try:
        local_vars = currentframe().f_back.f_back.f_locals.items()
        match = [name for name, val in local_vars if val is var]
    except AttributeError:
        local_vars = currentframe().f_back.f_locals.items()
import numpy as np
import six
from IPython.display import Latex
import matplotlib.pyplot as plt
import pytablewriter
from enum import Enum
from collections import UserList
from pint import UnitRegistry, set_application_registry
from pint import __version__ as pint_version

u = UnitRegistry(autoconvert_offset_to_baseunit=True)
if int(pint_version.split('.')[0]) * 10 + int(pint_version.split('.')[1]) > 8:
    u.setup_matplotlib(True)

u.default_format = '.4f~L'
set_application_registry(u)

np.set_printoptions(precision=3)

__all__ = [
    'density', 'specific_volume', 'u', 'np', 'latex', 'V_flux', 'delta_u',
    'speed', 'Delta_speed', 'isentropisch_work', 'isentropische_dT',
    'isentropische_dV', 'isentropische_dv', 'isentropische_dP', 'isobaar_heat',
    'isobaar_work', 'isobaar_dv', 'isobaar_dT', 'technical_work',
    'delta_e_kin', 'delta_h', 'ProcessType', 'TransitionState', 'Transition',
    'Cycle', 'States', 'mass_flux'
]


class ProcessType(Enum):
    POLYTROPIC = -1
Exemple #15
0
from flasgger.base import Swagger

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"}
Exemple #16
0
    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 = "~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):
Exemple #17
0
    # 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')


# Context for NMR
# ----------------------------------------------------------------------------------------------------------------------
def set_nmr_context(larmor):
import numbers

import numpy as np
import uncertainties
from interval import imath, inf, interval
from IPython.display import Latex, display
from pint import DimensionalityError, UnitRegistry
from typeguard import typechecked
from uncertainties import ufloat

ureg = UnitRegistry()
ureg.default_format = "~P"
ureg.define("GRAPI = 1.0")  # added base unit for gamma ray log
Q_ = ureg.Quantity

esc = lambda s: s.replace('"\"', '"\\"')


@typechecked
class Limits:
    def __init__(self, limits: (tuple, list)):
        assert len(limits) == 2
        lower, upper = limits
        try:
            assert lower.dimensionality == upper.dimensionality
        except DimensionalityError as exc:
            raise exc
        try:
            assert isinstance(lower.m, numbers.Number)
            assert isinstance(upper.m, numbers.Number)
        except AssertionError as e:
Exemple #19
0
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:
    '''
    Class for storing and retrieving measured parameter values together with their
Exemple #20
0
from pint import UnitRegistry

units = UnitRegistry()
units.default_format = ".5~P"
units.default_LaTeX_format = ":~L"
Quantity = units.Quantity

# define custom units for dealing with humid air
# lbmol
units.define("pound_mole = 453.59237*mol = lbmol")
# mass of dry air
units.define("gram_dry_air = [mass_dry_air] = g_a = g_dry_air = ga ")
units.define(
    "pound_dry_air = 453.59237 * gram_dry_air = lb_dry_air = lba = lb_a = lbm_a = lbma = lb_dry_air = lbm_dry_air"
)
# mass of humid air
units.define("gram_humid_air = [mass_humid_air] = gha = g_ha = g_humid_air")
units.define(
    "pound_humid_air = 453.59237 * gram_humid_air = lb_humid_air = lbha = lbmha = lbm_humid_air"
)
# mass of water
units.define("gram_water = [mass_water] = g_water = gw = g_w")
units.define(
    "pound_water = 453.59237 * gram_water = lb_water = lb_w = lbw = lbmw = lbm_w = lbm_water"
)
# molecules of dry air
units.define(
    "mole_dry_air = [substance_dry_air] = mol_dry_air = mol_a = mola = mol_da = molda"
)
units.define(
    "pound_mole_dry_air = 453.59237 * mol_dry_air = lbmol_dry_air = lbmol_a = lbmola = lbmol_da = lbmolda"
Exemple #21
0
from pint import UnitRegistry
ureg = UnitRegistry()
Q = ureg.Quantity
ureg.default_format = '.2f~P'
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt

from pint import UnitRegistry

ureg = UnitRegistry()
ureg.default_format = "Lx"

mpl.rcParams["text.latex.preamble"] = r"\usepackage{xfrac}\usepackage{siunitx}"


def plot_halftime_sequence():
    halftime = pd.read_csv("data/scope_4_1.csv", header=[0, 1])

    fig = plt.figure()
    ax = fig.add_subplot(211)

    ax.plot(halftime["x-axis"], halftime["1"], label="Burst Sequenz")

    ax.legend()
    ax.set_xlabel(r"$t \:\:/\:\: \si{\second}$")
    ax.set_ylabel(r"$U \:\:/\:\: \si{\volt}$")

    peak = halftime[25000:29500]
    peak["1"] -= peak["1"].values[0]

    mask = peak["1"] <= peak["1"].min() / 2

    halftimes_x = peak["x-axis"].values[mask][[0, -1]]
Exemple #23
0
    'reaction'
])

#: Chemical engineering plant cost index (defaults to 567.5 at 2017)
CE = 567.5

# %% Import base utils

import pandas as pd
import numpy as np
from pint import UnitRegistry
import os

# Set pint Unit Registry
_ureg = UnitRegistry()
_ureg.default_format = '~P'
_ureg.load_definitions(
    os.path.dirname(os.path.realpath(__file__)) + '/my_units_defs.txt')
_Q = _ureg.Quantity
_Q._repr_latex_ = _Q._repr_html_ = _Q.__str__ = _Q.__repr__ = lambda self: self.__format__(
    '')

# Set number of digits displayed
np.set_printoptions(suppress=False)
np.set_printoptions(precision=3)
pd.options.display.float_format = '{:.3g}'.format
pd.set_option('display.max_rows', 35)
pd.set_option('display.max_columns', 10)
pd.set_option('max_colwidth', 35)
del np, pd, os, UnitRegistry
Exemple #24
0
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:
    '''
    Class for storing and retrieving measured parameter values together with their
    units, context, and reference information.
Exemple #25
0
import sqlite3 as sql
import pandas as pd
import random
import math
import os
from pint import UnitRegistry, UndefinedUnitError

dbConn = sql.connect(":memory:", check_same_thread=False)
dbConn.row_factory = sql.Row
u_reg = UnitRegistry()
u_reg.default_format = "H"


def setup():
    cur = dbConn.cursor()
    for root, dirs, files in os.walk("data"):
        for file in files:
            if file.endswith(".csv"):
                readFile = pd.read_csv(os.path.join(root, file))
                readFile.to_sql(file.split(".")[0], dbConn, index=False)
                cur.execute("SELECT * FROM " + file.split(".")[0] + ";")


def get_random_record(record_type: str):
    if record_type not in ["volumes", "times", "mass", "lengths"]:
        return None

    cur = dbConn.cursor()
    cur.execute("SELECT * FROM " + record_type +
                " WHERE rowid = abs(random()) % (SELECT max(rowid) FROM " +
                record_type + ") + 1;")
Exemple #26
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)