Esempio n. 1
0
def convert(fromunit, tounit, value, fstep=1, timestep=4):
    """ Converts values between units

    Parameters
    ----------
    fromunit : str
        Unit to convert from
    tounit : str
        Unit to convert to
    value : scalar
        The value to convert
    fstep : int
        The sampling frame step of the simulation in nanoseconds
    timestep : int
        The timestep of the simulation in femtoseconds

    Returns
    -------
    conv : scalra
        The converted value
    """

    ureg = UnitRegistry()
    ureg.define('frame = {} * ns'.format(fstep))
    ureg.define('step = ({} / 1000000) * ns = timestep'.format(timestep))

    q = ureg.Quantity(value, fromunit)
    convval = q.to(tounit)
    if convval.units == 'frame' or convval.units == 'step':
        vals = np.round(convval.magnitude).astype(int)
        if vals.size == 1:  # Fix for PyEMMA tica. remove in future
            return int(vals)
        return vals
    else:
        return convval.magnitude
Esempio n. 2
0
    def test_get_compatible_units(self):
        ureg = UnitRegistry()

        g = ureg.get_group('test-imperial')
        g.add_units('inch', 'yard', 'pint')
        c = ureg.get_compatible_units('meter', 'test-imperial')
        self.assertEqual(c, frozenset([ureg.inch, ureg.yard]))
Esempio n. 3
0
 def test_issue29(self):
     ureg = UnitRegistry()
     ureg.define("molar = mole / liter = M")
     t = 4 * ureg("mM")
     self.assertEqual(t.magnitude, 4)
     self.assertEqual(t.units, UnitsContainer(millimolar=1))
     self.assertEqual(t.to("mole / liter"), 4e-3 * ureg("M"))
Esempio n. 4
0
    def test_babel(self):
        ureg = UnitRegistry()
        dirname = os.path.dirname(__file__)
        ureg.load_definitions(os.path.join(dirname, '../xtranslated.txt'))

        distance = 24.0 * ureg.meter
        self.assertEqual(
            distance.format_babel(locale='fr_FR', length='long'),
            "24.0 mètres"
        )
        time = 8.0 * ureg.second
        self.assertEqual(
            time.format_babel(locale='fr_FR', length='long'),
            "8.0 secondes"
        )
        self.assertEqual(
            time.format_babel(locale='ro', length='short'),
            "8.0 s"
        )
        acceleration = distance / time ** 2
        self.assertEqual(
            acceleration.format_babel(locale='fr_FR', length='long'),
            "0.375 mètre par seconde²"
        )
        mks = ureg.get_system('mks')
        self.assertEqual(
            mks.format_babel(locale='fr_FR'),
            "métrique"
        )
def parse_units_from_str(input_str):
    """Matches an input string to the closest matching scientific unit using Pint Package
    """
    unit_reg = UnitRegistry()
    
    if input_str:
        cleaned_str = re.sub('\*', '', input_str)
        cleaned_str = re.sub(u'μ', 'u', cleaned_str) # weird issue with Pint Package choking on mu signs
        cleaned_str = re.sub(u'Ω', 'ohm', cleaned_str) # weird issue with Pint Package choking on Omega signs
        cleaned_str = re.sub(u'\u2126', 'ohm', cleaned_str) # converting unicode sign for Omega
        cleaned_str = re.sub(u'\u03a9', 'ohm', cleaned_str) # converting unicode sign for Omega
        cleaned_str = re.sub(u'mohm', 'Mohm', cleaned_str) # deals with mOhm not being MOhm
        cleaned_str = re.sub('\%', 'ratio', cleaned_str) # weird issue with Pint Package choking on percent signs
        cleaned_str = re.sub('\s+', '', cleaned_str) # removing all whitespace in string
        # TODO: make below code more robust
        # check whether last character in string is capital M, if so assume it means mole
        if input_str[-1] == 'M':
            cleaned_str = re.sub(r'(\w)+M$', 'mole', cleaned_str) # adding M as synonym for mole

        try:
            matched_unit = unit_reg.parse_expression(cleaned_str)
            if hasattr(matched_unit, 'units'):
                return input_str, matched_unit
        except UndefinedUnitError:
            #print u'UndefinedUnitError during unit parsing : %s' % cleaned_str
            return None
        except AttributeError:
            #print u'Attribute Error during unit parsing : %s' % cleaned_str
            return None
        except Exception:
            #print u'unit parsing failed for some unexplained reason: %s' % cleaned_str
            return None
    else:
        return None
Esempio n. 6
0
 def test_issue29(self):
     ureg = UnitRegistry()
     ureg.define('molar = mole / liter = M')
     t = 4 * ureg('mM')
     self.assertEqual(t.magnitude, 4)
     self.assertEqual(t._units, UnitsContainer(millimolar=1))
     self.assertEqual(t.to('mole / liter'), 4e-3 * ureg('M'))
Esempio n. 7
0
 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))
Esempio n. 8
0
    def test_get_compatible_units(self):
        ureg = UnitRegistry()

        g = ureg.get_group("test-imperial")
        g.add_units("inch", "yard", "pint")
        c = ureg.get_compatible_units("meter", "test-imperial")
        self.assertEqual(c, frozenset([ureg.inch, ureg.yard]))
Esempio n. 9
0
 def test_issue66(self):
     ureg = UnitRegistry()
     self.assertEqual(
         ureg.get_dimensionality(UnitsContainer({"[temperature]": 1})), UnitsContainer({"[temperature]": 1})
     )
     self.assertEqual(ureg.get_dimensionality(ureg.kelvin.units), UnitsContainer({"[temperature]": 1}))
     self.assertEqual(ureg.get_dimensionality(ureg.degC.units), UnitsContainer({"[temperature]": 1}))
Esempio n. 10
0
 def _test_ctx(self, ctx):
     ureg = UnitRegistry()
     q = 500 * ureg.meter
     s = (ureg.speed_of_light / q).to('Hz')
     ureg.add_context(ctx)
     with ureg.context(ctx.name):
         self.assertEqual(q.to('Hz'), s)
         self.assertEqual(s.to('meter'), q)
Esempio n. 11
0
def is_proper_unit(vendor_name, unit, row, row_count):
    ureg = UnitRegistry()
    try:
        ureg.parse_expression(row[unit])
    except UndefinedUnitError:
        flash("Error parsing {}'s CSV file. Bad entry in the {} column, at row {} "
              .format(vendor_name, unit, row_count),'form-error')
        return False
    return True
Esempio n. 12
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)
Esempio n. 13
0
def convert(fromunit, tounit, value, fstep=1):
    ureg = UnitRegistry()
    ureg.define('frame = {} * ns = step'.format(fstep))

    q = ureg.Quantity(value, fromunit)
    convval = q.to(tounit)
    if convval.units == 'frame':
        return np.round(convval.magnitude).astype(int)
    else:
        return convval.magnitude
Esempio n. 14
0
    def test_context_with_arg_def(self):

        ureg = UnitRegistry()

        add_argdef_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')

        self.assertRaises(ValueError, q.to, 'Hz')
        with ureg.context('lc', n=2):
            self.assertEqual(q.to('Hz'), s / 2)
            with ureg.context('ab'):
                self.assertEqual(q.to('Hz'), s / 2)
            self.assertEqual(q.to('Hz'), s / 2)

        with ureg.context('ab'):
            self.assertRaises(ValueError, q.to, 'Hz')
            with ureg.context('lc', n=2):
                self.assertEqual(q.to('Hz'), s / 2)
            self.assertRaises(ValueError, q.to, 'Hz')
Esempio n. 15
0
    def test_context_with_arg_def(self):

        ureg = UnitRegistry()

        add_argdef_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")

        self.assertRaises(ValueError, q.to, "Hz")
        with ureg.context("lc", n=2):
            self.assertEqual(q.to("Hz"), s / 2)
            with ureg.context("ab"):
                self.assertEqual(q.to("Hz"), s / 2)
            self.assertEqual(q.to("Hz"), s / 2)

        with ureg.context("ab"):
            self.assertRaises(ValueError, q.to, "Hz")
            with ureg.context("lc", n=2):
                self.assertEqual(q.to("Hz"), s / 2)
            self.assertRaises(ValueError, q.to, "Hz")
Esempio n. 16
0
    def test_multiple_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', 'ab'):
            self.assertEqual(q.to('Hz'), s)
        self.assertRaises(ValueError, q.to, 'Hz')
Esempio n. 17
0
    def test_multiple_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", "ab"):
            self.assertEqual(q.to("Hz"), s)
        self.assertRaises(ValueError, q.to, "Hz")
Esempio n. 18
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)
Esempio n. 19
0
 def test_unknown_context(self):
     ureg = UnitRegistry()
     add_ctxs(ureg)
     try:
         with ureg.context("la"):
             pass
     except KeyError as e:
         value = True
     except Exception as e:
         value = False
     self.assertTrue(value)
     self.assertFalse(ureg._active_ctx)
     self.assertFalse(ureg._active_ctx.graph)
Esempio n. 20
0
    def test_get_compatible_units(self):
        sysname = "mysys1"
        ureg = UnitRegistry()

        g = ureg.get_group("test-imperial")

        g.add_units("inch", "yard", "pint")
        c = ureg.get_compatible_units("meter", "test-imperial")
        self.assertEqual(c, frozenset([ureg.inch, ureg.yard]))

        lines = ["@system %s using test-imperial" % sysname, "inch"]

        s = ureg.System.from_lines(lines, lambda x: x)
        c = ureg.get_compatible_units("meter", sysname)
        self.assertEqual(c, frozenset([ureg.inch, ureg.yard]))
Esempio n. 21
0
    def depths(self):
        if self.__depths is None:
            var = None
            for v in ['depth', 'deptht']:
                if v in self._dataset.variables:
                    var = self._dataset.variables[v]
                    break

            ureg = UnitRegistry()
            unit = ureg.parse_units(var.units.lower())
            self.__depths = ureg.Quantity(
                var[:], unit
            ).to(ureg.meters).magnitude
            self.__depths.flags.writeable = False

        return self.__depths
Esempio n. 22
0
    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)
Esempio n. 23
0
    def test_get_compatible_units(self):
        sysname = 'mysys1'
        ureg = UnitRegistry()

        g = ureg.get_group('test-imperial')

        g.add_units('inch', 'yard', 'pint')
        c = ureg.get_compatible_units('meter', 'test-imperial')
        self.assertEqual(c, frozenset([ureg.inch, ureg.yard]))

        lines = ['@system %s using test-imperial' % sysname,
                 'inch',
                 ]

        s = System.from_lines(lines, lambda x: x, g._groups_systems)
        c = ureg.get_compatible_units('meter', sysname)
        self.assertEqual(c, frozenset([ureg.inch, ureg.yard]))
Esempio n. 24
0
    def __init__(self, definitions=None, separator='>', precision=None):
        from pint import UnitRegistry

        self.ureg = UnitRegistry()
        self.ureg.load_definitions('unit_defs.txt')
        self.load_definitions(definitions)
        self.separator = separator
        self.precision = precision
Esempio n. 25
0
    def test_one_context(self):
        ureg = UnitRegistry()

        add_ctxs(ureg)

        q = 500 * ureg.meter
        s = (ureg.speed_of_light / q).to('Hz')

        meter_units = ureg.get_compatible_units(ureg.meter)
        hertz_units = ureg.get_compatible_units(ureg.hertz)

        self.assertRaises(ValueError, q.to, 'Hz')
        with ureg.context('lc'):
            self.assertEqual(q.to('Hz'), s)
            self.assertEqual(ureg.get_compatible_units(q), meter_units | hertz_units)
        self.assertRaises(ValueError, q.to, 'Hz')
        self.assertEqual(ureg.get_compatible_units(q), meter_units)
Esempio n. 26
0
    def test_get_base_units_different_exponent(self):
        sysname = "mysys3"

        ureg = UnitRegistry()

        g = ureg.get_group("test-imperial")
        g.add_units("inch", "yard", "pint")
        c = ureg.get_compatible_units("meter", "test-imperial")

        lines = ["@system %s using test-imperial" % sysname, "pint:meter"]

        s = ureg.System.from_lines(lines, ureg.get_base_units)
        ureg._systems[s.name] = s

        # base_factor, destination_units
        c = ureg.get_base_units("inch", system=sysname)
        self.assertAlmostEqual(c[0], 0.326, places=3)
        self.assertEqual(c[1], {"pint": 1.0 / 3})

        c = ureg.get_base_units("cm", system=sysname)
        self.assertAlmostEqual(c[0], 0.1283, places=3)
        self.assertEqual(c[1], {"pint": 1.0 / 3})

        c = ureg.get_base_units("inch**2", system=sysname)
        self.assertAlmostEqual(c[0], 0.326 ** 2, places=3)
        self.assertEqual(c[1], {"pint": 2.0 / 3})

        c = ureg.get_base_units("cm**2", system=sysname)
        self.assertAlmostEqual(c[0], 0.1283 ** 2, places=3)
        self.assertEqual(c[1], {"pint": 2.0 / 3})
Esempio n. 27
0
    def test_get_base_units_different_exponent(self):
        sysname = 'mysys3'

        ureg = UnitRegistry()

        g = ureg.get_group('test-imperial')
        g.add_units('inch', 'yard', 'pint')
        c = ureg.get_compatible_units('meter', 'test-imperial')

        lines = ['@system %s using test-imperial' % sysname,
                 'pint:meter',
                 ]

        s = System.from_lines(lines, ureg.get_base_units, g._groups_systems)

        # base_factor, destination_units
        c = ureg.get_base_units('inch', system=sysname)
        self.assertAlmostEqual(c[0], 0.326, places=3)
        self.assertEqual(c[1], {'pint': 1./3})

        c = ureg.get_base_units('cm', system=sysname)
        self.assertAlmostEqual(c[0], 0.1283, places=3)
        self.assertEqual(c[1], {'pint': 1./3})

        c = ureg.get_base_units('inch**2', system=sysname)
        self.assertAlmostEqual(c[0], 0.326**2, places=3)
        self.assertEqual(c[1], {'pint': 2./3})

        c = ureg.get_base_units('cm**2', system=sysname)
        self.assertAlmostEqual(c[0], 0.1283**2, places=3)
        self.assertEqual(c[1], {'pint': 2./3})
Esempio n. 28
0
    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]))
Esempio n. 29
0
    def test_graph(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,))})

        with ureg.context('lc'):
            self.assertEqual(ureg._active_ctx.graph, g_sp)

        with ureg.context('lc', n=1):
            self.assertEqual(ureg._active_ctx.graph, g_sp)

        with ureg.context('ab'):
            self.assertEqual(ureg._active_ctx.graph, g_ab)

        with ureg.context('lc'):
            with ureg.context('ab'):
                self.assertEqual(ureg._active_ctx.graph, g)

        with ureg.context('ab'):
            with ureg.context('lc'):
                self.assertEqual(ureg._active_ctx.graph, g)

        with ureg.context('lc', 'ab'):
            self.assertEqual(ureg._active_ctx.graph, g)

        with ureg.context('ab', 'lc'):
            self.assertEqual(ureg._active_ctx.graph, g)
Esempio n. 30
0
    def test_graph(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, }})

        with ureg.context('lc'):
            self.assertEqual(ureg._active_ctx.graph, g_sp)

        with ureg.context('lc', n=1):
            self.assertEqual(ureg._active_ctx.graph, g_sp)

        with ureg.context('ab'):
            self.assertEqual(ureg._active_ctx.graph, g_ab)

        with ureg.context('lc'):
            with ureg.context('ab'):
                self.assertEqual(ureg._active_ctx.graph, g)

        with ureg.context('ab'):
            with ureg.context('lc'):
                self.assertEqual(ureg._active_ctx.graph, g)

        with ureg.context('lc', 'ab'):
            self.assertEqual(ureg._active_ctx.graph, g)

        with ureg.context('ab', 'lc'):
            self.assertEqual(ureg._active_ctx.graph, g)
Esempio n. 31
0
import logging

from pint import UnitRegistry

logger = logging.getLogger(__name__)

ureg = UnitRegistry()
Quantity = ureg.Quantity

logger.debug("Using custom pint definition for molar unit.")
ureg.define('molar = 1 * mole / liter = M')
ureg.define('standard_concentration = 1 M')
Esempio n. 32
0
import pytest

from pint import UnitRegistry

# Conditionally import NumPy and any upcast type libraries
np = pytest.importorskip("numpy", reason="NumPy is not available")
sparse = pytest.importorskip("sparse", reason="sparse is not available")

# Set up unit registry and sample
ureg = UnitRegistry(force_ndarray_like=True)
q_base = (np.arange(25).reshape(5, 5).T + 1) * ureg.kg


# Define identity function for use in tests
def identity(x):
    return x


@pytest.fixture(params=["sparse", "masked_array"])
def array(request):
    """Generate 5x5 arrays of given type for tests."""
    if request.param == "sparse":
        # Create sample sparse COO as a permutation matrix.
        coords = [[0, 1, 2, 3, 4], [1, 3, 0, 2, 4]]
        data = [1.0] * 5
        return sparse.COO(coords, data, shape=(5, 5))
    elif request.param == "masked_array":
        # Create sample masked array as an upper triangular matrix.
        return np.ma.masked_array(
            np.arange(25, dtype=np.float).reshape((5, 5)),
            mask=np.logical_not(np.triu(np.ones((5, 5)))),
Esempio n. 33
0
 def test_issue170(self):
     Q_ = UnitRegistry().Quantity
     q = Q_("1 kHz") / Q_("100 Hz")
     iq = int(q)
     assert iq == 10
     assert isinstance(iq, int)
Esempio n. 34
0
 def test_issue902(self):
     ureg = UnitRegistry(auto_reduce_dimensions=True)
     velocity = 1 * ureg.m / ureg.s
     cross_section = 1 * ureg.um**2
     result = cross_section / velocity
     assert result == 1e-12 * ureg.m * ureg.s
Esempio n. 35
0
    def check_ti_scheduling(ti, logger):
        if NodeUtil.ureg is None:
            logger.warning("Inititalize Util-Helper!")
            NodeUtil.enable = Variable.get(key="util_scheduling",
                                           default_var=None)
            if NodeUtil.enable == None:
                Variable.set("util_scheduling", True)
                NodeUtil.enable = 'True'

            logger.warning("-> init UnitRegistry...")
            NodeUtil.ureg = UnitRegistry()
            units_file_path = os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                'kubernetes_units.txt')
            if not os.path.isfile(units_file_path):
                logger.warning(
                    "Could not find kubernetes_units.txt @  {} !".format(
                        units_file_path))
                logger.warning("abort.")
                exit(1)
            else:
                NodeUtil.ureg.load_definitions(units_file_path)
                logger.warning("done.")

            def names(self, names):
                self._names = names

            V1ContainerImage.names = V1ContainerImage.names.setter(names)
            k8s.config.load_incluster_config()
            NodeUtil.core_v1 = k8s.client.CoreV1Api()

        NodeUtil.enable = True if Variable.get(
            key="util_scheduling",
            default_var=None).lower() == "true" else False

        if not NodeUtil.enable:
            logger.warning("Util-scheduler is disabled!!")
            return True

        else:
            config = ti.executor_config
            if "ram_mem_mb" not in config:
                logger.warning("Execuexecutor_config not found!")
                logger.warning(ti.operator)
                logger.warning(ti)
                return False
            default_cpu = 70
            default_ram = 80
            NodeUtil.max_util_cpu = Variable.get(key="max_util_cpu",
                                                 default_var=None)
            NodeUtil.max_util_ram = Variable.get(key="max_util_ram",
                                                 default_var=None)
            if NodeUtil.max_util_cpu is None and NodeUtil.max_util_ram is None:
                Variable.set("max_util_cpu", default_cpu)
                Variable.set("max_util_ram", default_ram)
                NodeUtil.max_util_cpu = default_cpu
                NodeUtil.max_util_ram = default_ram
            else:
                NodeUtil.max_util_cpu = int(NodeUtil.max_util_cpu)
                NodeUtil.max_util_ram = int(NodeUtil.max_util_ram)

            now = datetime.now()
            if NodeUtil.last_update is None or (
                    now - NodeUtil.last_update).seconds >= 3:
                util_result = NodeUtil.compute_allocated_resources(
                    logger=logger)
                if not util_result:
                    logger.warning(
                        "############################################# COULD NOT FETCH UTILIZATION -> SKIPPING!"
                    )
                    return True

            NodeUtil.cpu_percent, return_code_cpu = NodeUtil.get_node_info(
                query=NodeUtil.cpu_util_per_query, logger=logger)
            if not return_code_cpu:
                logger.warning(
                    "############################################# Could not fetch cpu utilization from prometheus!!"
                )

            Variable.set("CPU_PERCENT", "{}".format(NodeUtil.cpu_percent))
            if NodeUtil.cpu_percent is None or NodeUtil.cpu_percent > NodeUtil.max_util_cpu:
                logger.warning(
                    "############################################# High CPU utilization -> waiting!"
                )
                logger.warning(
                    "############################################# cpu_percent: {}"
                    .format(NodeUtil.cpu_percent))
                return False

            NodeUtil.mem_percent, return_code_ram = NodeUtil.get_node_info(
                query=NodeUtil.mem_util_per_query, logger=logger)
            if not return_code_ram:
                logger.warning(
                    "############################################# Could not fetch ram utilization from prometheus!!"
                )
            Variable.set("RAM_PERCENT", "{}".format(NodeUtil.mem_percent))
            if NodeUtil.mem_percent is None or NodeUtil.mem_percent > NodeUtil.max_util_ram:
                logger.warning(
                    "############################################# High RAM utilization -> waiting!"
                )
                logger.warning(
                    "############################################# mem_percent: {}"
                    .format(NodeUtil.mem_percent))
                return False

            if not return_code_cpu or not return_code_ram:
                logger.warning(
                    "############################################# Could not fetch util from prometheus! -> waiting!"
                )
                return False

            if NodeUtil.memory_pressure:
                logger.warning(
                    "##########################################################################################"
                )
                logger.warning(
                    "#################################### Instable system! ####################################"
                )
                logger.warning(
                    "##################################### memory_pressure ####################################"
                )
                logger.warning(
                    "##########################################################################################"
                )
                return False

            if NodeUtil.disk_pressure:
                logger.warning(
                    "##########################################################################################"
                )
                logger.warning(
                    "#################################### Instable system! ####################################"
                )
                logger.warning(
                    "##################################### disk_pressure ####################################"
                )
                logger.warning(
                    "##########################################################################################"
                )
                return False

            if NodeUtil.pid_pressure:
                logger.warning(
                    "##########################################################################################"
                )
                logger.warning(
                    "#################################### Instable system! ####################################"
                )
                logger.warning(
                    "##################################### pid_pressure ####################################"
                )
                logger.warning(
                    "##########################################################################################"
                )
                return False

            ti_ram_mem_mb = 0 if config["ram_mem_mb"] == None else config[
                "ram_mem_mb"]
            ti_cpu_millicores = 0 if config[
                "cpu_millicores"] == None else config["cpu_millicores"]
            ti_gpu_mem_mb = 0 if config["gpu_mem_mb"] == None else config[
                "gpu_mem_mb"]

            if ti_ram_mem_mb >= NodeUtil.memory_available_req:
                # if ti_ram_mem_mb >= NodeUtil.memory_available_limit or ti_ram_mem_mb >= NodeUtil.memory_available_req:
                logger.warning("Not enough RAM -> not scheduling")
                logger.warning("MEM LIMIT: {}/{}".format(
                    ti_ram_mem_mb, NodeUtil.memory_available_req))
                logger.warning("MEM REQ:   {}/{}".format(
                    ti_ram_mem_mb, NodeUtil.memory_available_req))
                return False

            if ti_cpu_millicores >= NodeUtil.cpu_available_req:
                # if ti_cpu_millicores >= NodeUtil.cpu_available_limit or ti_cpu_millicores >= NodeUtil.cpu_available_req:
                logger.warning("Not enough CPU cores -> not scheduling")
                logger.warning("CPU LIMIT: {}/{}".format(
                    ti_cpu_millicores, NodeUtil.cpu_available_req))
                logger.warning("CPU REQ:   {}/{}".format(
                    ti_cpu_millicores, NodeUtil.cpu_available_req))
                return False

            if ti_gpu_mem_mb > 0 and NodeUtil.gpu_dev_free <= 1:
                logger.warning(
                    "All GPUs are in currently in use -> not scheduling")
                return False

            if ti_gpu_mem_mb > NodeUtil.gpu_memory_available:
                logger.warning("Not enough GPU memory -> not scheduling")
                logger.warning("GPU: {}/{}".format(
                    ti_gpu_mem_mb, NodeUtil.gpu_memory_available))
                return False

            tmp_memory_available_req = int(NodeUtil.memory_available_req -
                                           ti_ram_mem_mb)
            tmp_cpu_available_req = int(NodeUtil.cpu_available_req -
                                        ti_cpu_millicores)
            tmp_gpu_memory_available = int(NodeUtil.gpu_memory_available -
                                           ti_gpu_mem_mb)

            if tmp_memory_available_req < 0 or tmp_cpu_available_req < 0 or tmp_gpu_memory_available < 0:
                logger.error(
                    "############################################################### Error!"
                )
                logger.error("Detected negative resource availability!")
                logger.error("memory_available_req: {}".format(
                    tmp_memory_available_req))
                logger.error(
                    "cpu_available_req: {}".format(tmp_cpu_available_req))
                logger.error("gpu_memory_available: {}".format(
                    tmp_gpu_memory_available))
                return False

            NodeUtil.memory_available_req = tmp_memory_available_req
            NodeUtil.cpu_available_req = tmp_cpu_available_req
            NodeUtil.gpu_memory_available = tmp_gpu_memory_available
            NodeUtil.gpu_dev_free = max(0, NodeUtil.gpu_dev_free)
            NodeUtil.mem_req = NodeUtil.mem_req + ti_ram_mem_mb
            NodeUtil.mem_lmt = NodeUtil.mem_lmt + ti_ram_mem_mb

            Variable.set("CPU_NODE", "{}/{}".format(NodeUtil.cpu_lmt,
                                                    NodeUtil.cpu_alloc))
            Variable.set("CPU_FREE", "{}".format(NodeUtil.cpu_available_req))
            Variable.set("RAM_NODE", "{}/{}".format(NodeUtil.mem_req,
                                                    NodeUtil.mem_alloc))
            Variable.set("RAM_FREE",
                         "{}".format(NodeUtil.memory_available_req))
            Variable.set(
                "GPU_DEV", "{}/{}".format(NodeUtil.gpu_dev_free,
                                          NodeUtil.gpu_dev_count))
            Variable.set("GPU_DEV_FREE", "{}".format(NodeUtil.gpu_dev_free))
            Variable.set(
                "GPU_MEM", "{}/{}".format(NodeUtil.gpu_mem_used,
                                          NodeUtil.gpu_mem_alloc))
            Variable.set("GPU_MEM_FREE",
                         "{}".format(NodeUtil.gpu_memory_available))
            Variable.set("UPDATED", datetime.utcnow())

            return True
Esempio n. 36
0
"""
nashTubeStress.py
 -- steady-state temperature distribution (Gauss-Seidel iteration)
 -- biharmonic thermoelastic stress

See also:
 -- Solar Energy 160 (2018) 368-379
 -- https://doi.org/10.1016/j.solener.2017.12.003
"""

import sys, time, os
from math import exp, log, sqrt, pi, ceil, floor, asin

import numpy as np
from pint import UnitRegistry
UR_ = UnitRegistry()
Q_ = UR_.Quantity

import nashTubeStress as nts

################################### PLOTTING ###################################

import matplotlib as mpl
import matplotlib.pyplot as plt
## uncomment following if not in ~/.config/matplotlib/matplotlibrc already
#params = {'text.latex.preamble': [r'\usepackage{newtxtext,newtxmath,siunitx}']}
#plt.rcParams.update(params)
mpl.rc('figure.subplot', bottom=0.13, top=0.95)
mpl.rc('figure.subplot', left=0.15, right=0.95)
from matplotlib import colors, ticker, cm
from matplotlib.transforms import Affine2D
Esempio n. 37
0
def unit_registry():
    file_path = os.path.join(os.path.dirname(__file__), 'default_units.txt')
    return UnitRegistry(file_path)
Esempio n. 38
0
    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)
Esempio n. 39
0
    def test_graph(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, ))})

        with ureg.context('lc'):
            self.assertEqual(ureg._active_ctx.graph, g_sp)

        with ureg.context('lc', n=1):
            self.assertEqual(ureg._active_ctx.graph, g_sp)

        with ureg.context('ab'):
            self.assertEqual(ureg._active_ctx.graph, g_ab)

        with ureg.context('lc'):
            with ureg.context('ab'):
                self.assertEqual(ureg._active_ctx.graph, g)

        with ureg.context('ab'):
            with ureg.context('lc'):
                self.assertEqual(ureg._active_ctx.graph, g)

        with ureg.context('lc', 'ab'):
            self.assertEqual(ureg._active_ctx.graph, g)

        with ureg.context('ab', 'lc'):
            self.assertEqual(ureg._active_ctx.graph, g)
Esempio n. 40
0
import logging
from ulauncher.api.client.Extension import Extension
from ulauncher.api.client.EventListener import EventListener
from ulauncher.api.shared.event import KeywordQueryEvent
from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem
from ulauncher.api.shared.item.SmallResultItem import SmallResultItem
from ulauncher.api.shared.action.RenderResultListAction import RenderResultListAction
from ulauncher.api.shared.action.CopyToClipboardAction import CopyToClipboardAction
from pint import UnitRegistry

ureg = UnitRegistry(autoconvert_offset_to_baseunit=True)
Q_ = ureg.Quantity

logging.basicConfig()
logger = logging.getLogger(__name__)


class UnitsExtension(Extension):
    def __init__(self):

        super(UnitsExtension, self).__init__()
        self.subscribe(KeywordQueryEvent, KeywordQueryEventListener())


class KeywordQueryEventListener(EventListener):
    def on_event(self, event, extension):
        # Get query
        term = (event.get_argument() or '')
        elem = term.split(' to ')
        if len(elem) > 1:
            src, dst = term.split(' to ')
Esempio n. 41
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 25 17:05:06 2020

@author: wenjunchang
"""
from pint import UnitRegistry
ureg = UnitRegistry()
ureg.define("Msolar = 1.98855*10**30 * kilogram")


#The unit of inputing mass is Msolar
def Calcu_Schwarzchild_radius(mass):
    mass = mass * ureg.Msolar
    r = ureg.gravitational_constant * mass * 2 / ureg.c**2
    return r.to_base_units()


import numpy as np


def matrix_multi_loop(matrixA, matrixB):
    solv = np.zeros((len(matrixA), len(matrixB[0])), dtype=float)
    for j in range(len(matrixA)):
        for i in range(len(matrixB[0])):
            for k in range(len(matrixA[0])):
                solv[j][i] += matrixA[j][k] * matrixB[k][i]
    return solv

Esempio n. 42
0
import numpy as np
import uncertainties.unumpy as unp
from uncertainties import ufloat
from uncertainties.unumpy import nominal_values as noms
from uncertainties.unumpy import std_devs as stds
from uncertainties import correlated_values
import math
from scipy.optimize import curve_fit
from pint import UnitRegistry
import latex as l
r = l.Latexdocument('results.tex')
u = UnitRegistry()
Q_ = u.Quantity
import os


def abs_path(filename):
    return os.path.join(os.path.dirname(__file__), filename)


import matplotlib as mlp
mlp.use('pgf')
import matplotlib.pyplot as plt
from matplotlib import rcParams

rcParams['font.family'] = 'serif'
rcParams['font.serif'] = '[lmroman10-regular]:+tlig;'
rcParams['text.usetex'] = True
rcParams['pgf.texsystem'] = 'lualatex'
rcParams['font.size'] = 10
rcParams['mathtext.fontset'] = 'custom'
Esempio n. 43
0
class UnitConversion(LogicAdapter):
    """
    The UnitConversion logic adapter parse inputs to convert values
    between several metric units.

    For example:
        User: '******'
        Bot: '1000.0'

    :kwargs:
        * *language* (``object``) --
        The language is set to ``chatterbot.languages.ENG`` for English by default.
    """
    def __init__(self, chatbot, **kwargs):
        super().__init__(chatbot, **kwargs)
        from pint import UnitRegistry

        self.language = kwargs.get('language', languages.ENG)
        self.cache = {}
        self.patterns = [(re.compile(
            r'''
                   (([Hh]ow\s+many)\s+
                   (?P<target>\S+)\s+ # meter, celsius, hours
                   ((are)*\s*in)\s+
                   (?P<number>([+-]?\d+(?:\.\d+)?)|(a|an)|(%s[-\s]?)+)\s+
                   (?P<from>\S+)\s*) # meter, celsius, hours
                   ''' % (parsing.numbers),
            (re.VERBOSE | re.IGNORECASE)), lambda m: self.handle_matches(m)),
                         (re.compile(
                             r'''
                   ((?P<number>([+-]?\d+(?:\.\d+)?)|(%s[-\s]?)+)\s+
                   (?P<from>\S+)\s+ # meter, celsius, hours
                   (to)\s+
                   (?P<target>\S+)\s*) # meter, celsius, hours
                   ''' % (parsing.numbers), (re.VERBOSE | re.IGNORECASE)),
                          lambda m: self.handle_matches(m)),
                         (re.compile(
                             r'''
                   ((?P<number>([+-]?\d+(?:\.\d+)?)|(a|an)|(%s[-\s]?)+)\s+
                   (?P<from>\S+)\s+ # meter, celsius, hours
                   (is|are)\s+
                   (how\s+many)*\s+
                   (?P<target>\S+)\s*) # meter, celsius, hours
                   ''' % (parsing.numbers), (re.VERBOSE | re.IGNORECASE)),
                          lambda m: self.handle_matches(m))]
        self.unit_registry = UnitRegistry()

    def get_unit(self, unit_variations):
        """
        Get the first match unit metric object supported by pint library
        given a variation of unit metric names (Ex:['HOUR', 'hour']).

        :param unit_variations: A list of strings with names of units
        :type unit_variations: str
        """
        for unit in unit_variations:
            try:
                return getattr(self.unit_registry, unit)
            except Exception:
                continue
        return None

    def get_valid_units(self, from_unit, target_unit):
        """
        Returns the firt match `pint.unit.Unit` object for from_unit and
        target_unit strings from a possible variation of metric unit names
        supported by pint library.

        :param from_unit: source metric unit
        :type from_unit: str

        :param from_unit: target metric unit
        :type from_unit: str
        """
        from_unit_variations = [from_unit.lower(), from_unit.upper()]
        target_unit_variations = [target_unit.lower(), target_unit.upper()]
        from_unit = self.get_unit(from_unit_variations)
        target_unit = self.get_unit(target_unit_variations)
        return from_unit, target_unit

    def handle_matches(self, match):
        """
        Returns a response statement from a matched input statement.

        :param match: It is a valid matched pattern from the input statement
        :type: `_sre.SRE_Match`
        """
        response = Statement(text='')

        from_parsed = match.group("from")
        target_parsed = match.group("target")
        n_statement = match.group("number")

        if n_statement == 'a' or n_statement == 'an':
            n_statement = '1.0'

        n = mathparse.parse(n_statement, self.language.ISO_639.upper())

        from_parsed, target_parsed = self.get_valid_units(
            from_parsed, target_parsed)

        if from_parsed is None or target_parsed is None:
            response.confidence = 0.0
        else:
            from_value = self.unit_registry.Quantity(float(n), from_parsed)
            target_value = from_value.to(target_parsed)
            response.confidence = 1.0
            response.text = str(target_value.magnitude)

        return response

    def can_process(self, statement):
        response = self.process(statement)
        self.cache[statement.text] = response
        return response.confidence == 1.0

    def process(self,
                statement,
                additional_response_selection_parameters=None):
        response = Statement(text='')
        input_text = statement.text
        try:
            # Use the result cached by the process method if it exists
            if input_text in self.cache:
                response = self.cache[input_text]
                self.cache = {}
                return response

            for pattern, func in self.patterns:
                p = pattern.match(input_text)
                if p is not None:
                    response = func(p)
                    if response.confidence == 1.0:
                        break
        except Exception:
            response.confidence = 0.0
        finally:
            return response
Esempio n. 44
0
    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)
Esempio n. 45
0
class FANS_UI_MainView(QtGui.QMainWindow, Ui_NoiseMeasurement, DataContextWidget):
    ureg = UnitRegistry()
    voltage_format = "{:8.6f}"
    resistance_format = "{:.3f}"
    current_format = "{:.5e}"
    temperature_format = "{:.2f}"
   
    sample_voltage_start = uih.bind("ui_sample_voltage_start", "text", float, voltage_format)
    sample_voltage_end = uih.bind("ui_sample_voltage_end", "text", float, voltage_format)
    front_gate_voltage_start = uih.bind("ui_front_gate_voltage_start", "text", float, voltage_format)
    front_gate_voltage_end = uih.bind("ui_front_gate_voltage_end", "text", float, voltage_format)
    sample_current_start = uih.bind("ui_sample_current_start", "text", float, current_format)
    sample_current_end = uih.bind("ui_sample_current_end", "text", float, current_format)
    sample_resistance_start = uih.bind("ui_sample_resistance_start", "text", float,resistance_format)
    sample_resistance_end = uih.bind("ui_sample_resistance_end", "text", float, resistance_format)
    main_voltage_start = uih.bind("ui_main_voltage_start", "text", float, voltage_format)
    main_voltage_end = uih.bind("ui_main_voltage_end", "text", float, voltage_format)
    temperature_start = uih.bind("ui_temperature_start", "text", float, temperature_format)
    temperature_end = uih.bind("ui_temperature_end", "text", float, temperature_format)

    sigExperimentStart = QtCore.pyqtSignal()
    sigExperimentStop = QtCore.pyqtSignal()
    sigMainWindowClosing = QtCore.pyqtSignal()

    def __init__(self, parent = None):
    #    super(mainViewBase,self).__init__(parent)
       super().__init__(parent)
       self.setupUi()
       self.setupBinding()
       self.init_values()
       self._controller = None
       self._experiment_settings = None
       
    def showMaximized(self):
        super().showMaximized()

    def setupUi(self):
        print("setting the ui up")
        super().setupUi(self)
        # self.ui_expandable_container.setContentLayout(self.ui_scroll_area.layout())
        # flags = QtCore.Qt.FramelessWindowHint
        # self.setWindowFlags(flags)
        self._temperature_checkbox_group = QtGui.QButtonGroup()
        self._temperature_checkbox_group.addButton(self.ui_set_temperature_single)
        self._temperature_checkbox_group.addButton(self.ui_use_set_temperature_range)

        self._drain_source_checkbox_group = QtGui.QButtonGroup()
        self._drain_source_checkbox_group.addButton(self.ui_set_drain_source_voltage)
        self._drain_source_checkbox_group.addButton(self.ui_use_set_vds_range)

        self._gate_source_checkbox_group = QtGui.QButtonGroup()
        self._gate_source_checkbox_group.addButton(self.ui_set_gate_source_voltage)
        self._gate_source_checkbox_group.addButton(self.ui_use_set_vfg_range)

        self.__setup_folder_browse_button()
        self._spectrumPlotWidget =  plt.SpectrumPlotWidget(self.ui_plot,{0:(0,1600,1),1:(0,102400,64)}, create_helper_handles=True, update_history=True)
        self.progressBar = QtGui.QProgressBar(self)
        self.progressBar.setVisible(True)
        self.progressBar.setRange(0,100)
        self.statusbar.addPermanentWidget(self.progressBar)
        self.set_ui_idle()

        showHelperCurvesAction = QtGui.QWidgetAction(self.menuSettings)
        checkBox = QtGui.QCheckBox("Helper Curves")
        checkBox.toggled.connect(self.on_showHelperCurvesAction_toggled)
        checkBox.setChecked(False)
        self.on_showHelperCurvesAction_toggled(False)
        showHelperCurvesAction.setDefaultWidget(checkBox)
        self.menuSettings.addAction(showHelperCurvesAction)

        showHistoryCurvesAction = QtGui.QWidgetAction(self.menuSettings)
        checkBox = QtGui.QCheckBox("History Curves")
        checkBox.toggled.connect(self.on_showHistoryCurvesAction_toggled)
        checkBox.setChecked(False)
        self.on_showHistoryCurvesAction_toggled(False)
        showHistoryCurvesAction.setDefaultWidget(checkBox)
        self.menuSettings.addAction(showHistoryCurvesAction)
        
    def setupBinding(self):
        sourceObject = None
        self.calibrate_before_measurement = uih.Binding(self.ui_calibrate, "checked", sourceObject, "calibrate_before_measurement", converter=uih.AssureBoolConverter()) # uih.bind("ui_calibrate", "checked", bool)
        self.overload_reject = uih.Binding(self.ui_overload_reject, "checked", sourceObject, "overload_rejecion", converter=uih.AssureBoolConverter()) 
        self.simulate_measurement = uih.Binding(self.ui_simulate, "checked", sourceObject, "simulate_experiment", converter=uih.AssureBoolConverter())
        self.number_of_averages =  uih.Binding(self.ui_averages, "value", sourceObject, "averages", converter=uih.StringToIntConverter()) 
        self.use_homemade_amplifier = uih.Binding(self.ui_use_homemade_amplifier, "checked", sourceObject, "use_homemade_amplifier", converter=uih.AssureBoolConverter())
        self.second_amplifier_gain = uih.Binding(self.ui_second_amp_coeff, "currentText", sourceObject, "second_amp_coeff", converter=uih.StringToIntConverter())
        self.perform_temperature_measurement = uih.Binding(self.ui_need_meas_temp, "checked", sourceObject, "need_measure_temperature", converter=uih.AssureBoolConverter())
        self.current_temperature =  uih.Binding(self.ui_temperature, "text", sourceObject, "current_temperature", converter=uih.StringToFloatConverter(), stringFormat=self.temperature_format, validator=QtGui.QDoubleValidator()) 
        self.use_temperature_range =  uih.Binding(self.ui_use_set_temperature_range, "checked", sourceObject, "use_temperature_range", converter=uih.AssureBoolConverter()) 
        self.use_automated_temperature_control =  uih.Binding(self.ui_automated_temperature, "checked", sourceObject, "use_automated_temperature_control", converter=uih.AssureBoolConverter()) 
        self.use_single_temperature =  uih.Binding(self.ui_set_temperature_single, "checked", sourceObject, "use_single_temperature", converter=uih.AssureBoolConverter()) 

        self.load_resistance =  uih.Binding(self.ui_load_resistance, "text", sourceObject, "load_resistance", converter=uih.StringToFloatConverter(), validator=QtGui.QIntValidator())
        self.perform_measurement_of_gated_structure = uih.Binding(self.ui_meas_gated_structure, "checked", sourceObject, "meas_gated_structure", converter=uih.AssureBoolConverter())
        self.use_dut_selector = uih.Binding(self.ui_use_dut_selector, "checked", sourceObject, "use_transistor_selector", converter=uih.AssureBoolConverter())
        self.use_automated_voltage_control = uih.Binding(self.ui_use_automated_voltage_control, "checked", sourceObject, "use_automated_voltage_control", converter=uih.AssureBoolConverter())
        self.measurement_characteristic_type = uih.Binding(self.ui_meas_characteristic_type, "currentText", sourceObject, "meas_characteristic_type", converter=CharacteristicTypeToStrConverter())
        self.drain_source_voltage = uih.Binding(self.ui_drain_source_voltage, "text", sourceObject, "drain_source_voltage", converter=uih.StringToVoltageConverter(), validator=uih.VoltageValidator())
        self.use_single_vds =  uih.Binding(self.ui_set_drain_source_voltage, "checked", sourceObject, "use_single_vds", converter=uih.AssureBoolConverter()) 

        self.front_gate_voltage = uih.Binding(self.ui_front_gate_voltage, "text", sourceObject, "front_gate_voltage", converter=uih.StringToVoltageConverter(), validator=uih.VoltageValidator())
        self.use_single_vfg = uih.Binding(self.ui_set_gate_source_voltage, "checked", sourceObject, "use_single_vfg", converter=uih.AssureBoolConverter()) 

        self.use_drain_source_range = uih.Binding(self.ui_use_set_vds_range, "checked", sourceObject, "use_set_vds_range", converter=uih.AssureBoolConverter())
        self.use_gate_source_range = uih.Binding(self.ui_use_set_vfg_range, "checked", sourceObject, "use_set_vfg_range", converter=uih.AssureBoolConverter())
        self.experimentName = uih.Binding(self.ui_experimentName, "text", sourceObject, "experiment_name", validator=uih.NameValidator())
        self.measurementName = uih.Binding(self.ui_measurementName, "text", sourceObject, "measurement_name", validator=uih.NameValidator())
        self.measurementCount = uih.Binding(self.ui_measurementCount, "value", sourceObject, "measurement_count")
        self.timetrace_mode = uih.Binding(self.ui_timetrace_mode, "currentIndex", sourceObject, "timetrace_mode", converter=TimetraceModeToIndexConverter())
        self.timetrace_mode.targetData = TimetraceMode.FULL.value
        self.timetrace_length =uih.Binding(self.ui_timetrace_length, "value", sourceObject, "timetrace_length")
        self.set_zero_after_measurement = uih.Binding(self.ui_set_zero_after_measurement, "checked", sourceObject, "set_zero_after_measurement", converter=uih.AssureBoolConverter())
        self.use_smart_spectrum_option = uih.Binding(self.ui_use_smart_spectrum, "checked", sourceObject, "use_smart_spectrum_option", converter=uih.AssureBoolConverter()) 


       
    def on_showHistoryCurvesAction_toggled(self, state):
        print("show history curves {0}".format(state))
        self._spectrumPlotWidget.setHistoryCurvesVisible(state)

    def on_showHelperCurvesAction_toggled(self, state):
        self._spectrumPlotWidget.setHelperCurvesVisible(state)

    def connect(self, signal, slot):
        #assert isinstance(signal, QtCore.pyqtSignal), "signal should be of pyqtSignal type"
        signal.connect(slot)

    def disconnect(self, signal, slot):
        #assert isinstance(signal, QtCore.pyqtSignal), "signal should be of pyqtSignal type"
        signal.disconnect(slot)

    def subscribe_to_email_login_action(self, slot):
        self.connect(self.actionLoginEmail.triggered, slot)

    def subscribe_to_hardware_settings_action(self, slot):
        self.connect(self.actionHardwareSettings.triggered, slot)

    def subscribe_to_waterfall_noise_action(self, slot):
        self.connect(self.actionOpenRealtimeNoiseWindow.triggered, slot)

    def subscribe_to_timetrace_action(self, slot):
        self.connect(self.actionOpenTimetraceWindow.triggered,slot)

    def subscribe_to_open_console_window_action(self, slot):
        self.connect(self.actionOpenConsoleWindow.triggered, slot)

    def subscribe_to_open_remote_action(self, slot):
        self.connect(self.actionOpenRemote.triggered, slot)

    def subscribe_to_open_settings_action(self, slot):
        self.connect(self.action_open_settings.triggered, slot)

    def subscribe_to_save_settings_action(self, slot):
        self.connect(self.action_save_settings.triggered, slot)

    def subscribe_to_time_info_action(self, slot):
        self.connect(self.actionTimeInfoWindow.triggered, slot)

    def subscribe_to_about_action(self, slot):
        self.connect(self.actionAbout.triggered, slot)

    def subscribe_to_what_to_do_action(self,slot):
        self.connect(self.action_what_to_do.triggered, slot)

    def subscribe_to_lock_screen_action(self, slot):
        self.connect(self.actionLockScreen.triggered, slot)

    def subscribe_to_switch_theme_action(self,slot):
        self.connect(self.actionThemeSwitch.triggered, slot)

    def subscribe_to_analysis_window_open_action(self,slot):
        self.connect(self.actionOpenAnalysisWindow.triggered, slot)
        
    def subscribe_to_plotter_window_open_action(self,slot):
        self.connect(self.actionOpenPlotterWindow.triggered, slot)

    def subscribe_to_experiment_start_action(self, slot):
        self.connect(self.sigExperimentStart, slot)

    def subscribe_to_experiment_stop_acion(self, slot):
        self.connect(self.sigExperimentStop, slot)

    def subscribe_to_window_closing_action(self, slot):
        self.connect(self.sigMainWindowClosing, slot)

    def subscribe_to_voltage_control_clicked(self, slot):
        self.connect(self.ui_voltage_control.clicked, slot)

    def subscribe_to_timetrace_converter_action(self, slot):
        self.connect(self.actionTimetraceConversion.triggered, slot)

    def subscribe_to_dut_selector_action(self, slot):
        self.connect(self.ui_transistorSelector.clicked, slot)

    @property
    def controller(self):
        return self._controller
    
    @controller.setter
    def controller(self,value):
        assert isinstance(value, pyfans.main_controller.FANS_UI_Controller)
        self._controller = value
          
    def set_controller(self, controller):
        self.controller = controller

    def init_values(self):
        print("initializing values")
        #self._calibrate_before_measurement = False
        #self.front_gate_voltage = "123 mV"

    #  *************************************
    #   BROWSER BUTTON
    #

    def __setup_folder_browse_button(self):
        self.popMenu = QtGui.QMenu(self)
        self.selected_folder_context_menu_item = QtGui.QAction(self)
        self.selected_folder_context_menu_item.triggered.connect(self.on_open_folder_in_explorer)
        self.popMenu.addAction(self.selected_folder_context_menu_item)
        self.popMenu.addSeparator()
        self.folderBrowseButton.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.folderBrowseButton.customContextMenuRequested.connect(self.on_folder_browse_button_context_menu)
    
    def set_selected_folder_context_menu_item_text(self,text):
        self.selected_folder_context_menu_item.setText(text)

    def on_folder_browse_button_context_menu(self,point):
        self.popMenu.exec_(self.folderBrowseButton.mapToGlobal(point))

    def on_open_folder_in_explorer(self):
        util.open_folder_in_explorer(self.experiment_settings.working_directory)
        

    @QtCore.pyqtSlot()
    def on_folderBrowseButton_clicked(self):
        print("Select folder")
        folder_name = os.path.abspath(QtGui.QFileDialog.getExistingDirectory(self,caption="Select Folder", directory = self.experiment_settings.working_directory))
        
        msg = QtGui.QMessageBox()
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText("This is a message box")
        msg.setInformativeText("This is additional information")
        msg.setWindowTitle("MessageBox demo")
        msg.setDetailedText(folder_name)
        msg.setStandardButtons(QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
        retval = msg.exec_()
        if retval and self.experiment_settings:
            self.experiment_settings.working_directory = folder_name
            self.set_selected_folder_context_menu_item_text(folder_name)

    #
    # END BROWSER BUTTON
    #*****************************************
    
    @property
    def experiment_settings(self):
        return self._experiment_settings
    
    @experiment_settings.setter
    def experiment_settings(self, value):
        self.set_experiment_settings_object(value)

    def set_experiment_settings_object(self, settings):
        assert isinstance(settings, ExperimentSettings), "Unsupported experiment settings type"
        self._experiment_settings = settings
        self.dataContext = settings
        if settings.working_directory:
            self.set_selected_folder_context_menu_item_text(settings.working_directory)
        
    UI_STATE_IDLE, UI_STATE_STARTED, UI_STATE_STOPPING = ui_states = range(3)
    def set_ui_state(self, state):
        if not state in self.ui_states:
            return

        if state is self.UI_STATE_IDLE:
            self.ui_startButton.setEnabled(True)
            self.ui_stopButton.setEnabled(False)
            self.progressBar.setVisible(False)
            self.progressBar.setValue(0)
            self.ui_settings_frame.setEnabled(True)
        elif state is self.UI_STATE_STARTED:
            self.ui_startButton.setEnabled(False)
            self.ui_stopButton.setEnabled(True)
            self.progressBar.setVisible(True)
            self.progressBar.setValue(0)
            self.ui_settings_frame.setEnabled(False)
        elif state is self.UI_STATE_STOPPING:
            self.ui_startButton.setEnabled(False)
            self.ui_stopButton.setEnabled(False)
            self.progressBar.setVisible(True)
            self.ui_settings_frame.setEnabled(False)

    def set_ui_idle(self):
        self.set_ui_state(self.UI_STATE_IDLE)

    def set_ui_started(self):
        self.set_ui_state(self.UI_STATE_STARTED)

    def set_ui_stopping(self):
        self.set_ui_state(self.UI_STATE_STOPPING)

    #**************
    #event handlers
    #**************

    # TIMETRACE_NONE, TIMETRACE_PARTIAL, TIMETRACE_FULL = range(3)
    @QtCore.pyqtSlot(int)
    def on_ui_timetrace_mode_currentIndexChanged(self, index):
        print("timetrace mode changed to {0}".format(index))
        if index == TimetraceMode.NONE.value:
            self.ui_timetrace_length.hide()
        elif index == TimetraceMode.PARTIAL.value:
            self.ui_timetrace_length.show() 
        elif index == TimetraceMode.FULL.value:
            self.ui_timetrace_length.hide()

    @QtCore.pyqtSlot()
    def on_ui_open_hardware_settings_clicked(self):
        print("open hardware settings")
        #self.controller.show_hardware_settings_view()
        self.actionHardwareSettings.trigger()

    @QtCore.pyqtSlot()
    def on_ui_temp_range_button_clicked(self):
        print("settings vds range")
        rng = self.experiment_settings.temperature_range
        
        if not isinstance(rng, (mredit.RangeInfo, mredit.CenteredRangeInfo, mredit.CustomRangeInfo)):
            rng = mredit.RangeInfo(start=0, end=1, step=1, handler=mredit.HandlersEnum.normal, repeats=1)
        
        dialog = mredit.RangeEditorView()
        dialog.setRange(rng)
        res = dialog.exec_()
        if res:
            self.experiment_settings.temperature_range = dialog.generateRangeInfo()

    @QtCore.pyqtSlot()
    def on_VdsRange_clicked(self):
        print("settings vds range")
        rng = self.experiment_settings.vds_range
        
        if not isinstance(rng, (mredit.RangeInfo, mredit.CenteredRangeInfo, mredit.CustomRangeInfo)):
            rng = mredit.RangeInfo(start=0, end=1, step=1, handler=mredit.HandlersEnum.normal, repeats=1)
        
        dialog = mredit.RangeEditorView()
        dialog.setRange(rng)
        res = dialog.exec_()
        if res:
            self.experiment_settings.vds_range = dialog.generateRangeInfo()

    @QtCore.pyqtSlot()
    def on_VfgRange_clicked(self):
        print("settings vfg range")
        rng = self.experiment_settings.vfg_range
        if not isinstance(rng, (mredit.RangeInfo, mredit.CenteredRangeInfo, mredit.CustomRangeInfo)):
            rng = mredit.RangeInfo(start=0, end=1, step=1, handler=mredit.HandlersEnum.normal, repeats=1)
        
        dialog = mredit.RangeEditorView()
        dialog.setRange(rng)
        res = dialog.exec_()
        if res:
            self.experiment_settings.vfg_range = dialog.generateRangeInfo()

   
    @QtCore.pyqtSlot()
    def on_ui_startButton_clicked(self):
        self.set_ui_started()
        self.updateSourceData()
        self.sigExperimentStart.emit()
        # self.controller.start_experiment()
        

    @QtCore.pyqtSlot()
    def on_ui_stopButton_clicked(self):
        self.set_ui_stopping()
        self.sigExperimentStop.emit()
        # self.controller.stop_experiment()

    def closeEvent(self, event):
        self.updateSourceData()
        self.sigMainWindowClosing.emit()
        # if self.controller:
        #     self.controller.on_main_view_closing()

    #**************
    #end event handlers
    #**************

    def ui_show_message_in_status_bar(self, message = "",  timeout=0):
        self.statusbar.showMessage(message, timeout)

    def ui_show_message_in_popup_window(self, message):
        msg = QtGui.QMessageBox()
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText(message)
        #msg.setInformativeText("This is additional information")
        msg.setWindowTitle("Message from PyFANS")
        msg.setDetailedText(message)
        msg.setStandardButtons(QtGui.QMessageBox.Ok)
        retval = msg.exec_()


    def ui_set_measurement_info_start(self, measurement_info):
        if isinstance(measurement_info, MeasurementInfo):
            self.front_gate_voltage_start = measurement_info.start_gate_voltage
            self.sample_voltage_start = measurement_info.start_sample_voltage
            self.sample_current_start = measurement_info.sample_current_start
            self.sample_resistance_start = measurement_info.sample_resistance_start
            self.temperature_start = measurement_info.start_temperature
            self.main_voltage_start = measurement_info.start_main_voltage
            # pass
            
    def ui_set_measurement_info_end(self, measurement_info):
        if isinstance(measurement_info, MeasurementInfo):
            self.front_gate_voltage_end= measurement_info.end_gate_voltage
            self.sample_voltage_end = measurement_info.end_sample_voltage
            self.sample_current_end = measurement_info.sample_current_end
            self.sample_resistance_end = measurement_info.sample_resistance_end
            self.temperature_end = measurement_info.end_temperature
            self.main_voltage_end = measurement_info.end_main_voltage
            # pass


    def ui_set_measurement_count(self, measurement_count):
        self.experiment_settings.measurement_count = measurement_count
        # self.measurementCount = measurement_count

    def ui_increment_measurement_count(self):
        self.experiment_settings.measurement_count += 1
        # self.measurementCount += 1

    def ui_update_spectrum_data(self, rang, data):
        self._spectrumPlotWidget.update_spectrum(rang, data)

    def ui_update_resulting_spectrum_data(self, data):
        frequency = data[pcp.FREQUENCIES]
        spectrum_data = data[pcp.DATA]
        self._spectrumPlotWidget.updata_resulting_spectrum(frequency,spectrum_data)

    def ui_update_calculated_thermal_noise(self, data):
        frequency = data[pcp.FREQUENCIES]
        spectrum_data = data[pcp.DATA]
        self._spectrumPlotWidget.update_thermal_noise(frequency,spectrum_data)

    def ui_update_timetrace(self, data):
        pass

    def ui_update_progress(self, progress):
        self.progressBar.setValue(progress)
Esempio n. 46
0
"""Base ThermoState module."""
from math import isclose
import sys

import CoolProp
from pint import UnitRegistry, DimensionalityError
from pint.unit import UnitsContainer, UnitDefinition
from pint.converters import ScaleConverter

try:  # pragma: no cover
    from IPython.core.ultratb import AutoFormattedTB
except ImportError:  # pragma: no cover
    AutoFormattedTB = None

units = UnitRegistry(autoconvert_offset_to_baseunit=True)
Q_ = units.Quantity
units.define(UnitDefinition("percent", "pct", (), ScaleConverter(1.0 / 100.0)))

# Don't add the _render_traceback_ function to DimensionalityError if
# IPython isn't present. This function is only used by the IPython/ipykernel
# anyways, so it doesn't matter if it's missing if IPython isn't available.
if AutoFormattedTB is not None:  # pragma: no cover

    def render_traceback(self):
        """Render a minimized version of the DimensionalityError traceback.

        The default Jupyter/IPython traceback includes a lot of
        context from within pint that actually raises the
        DimensionalityError. This context isn't really needed for
        this particular error, since the problem is almost certainly in
        the user code. This function removes the additional context.
Esempio n. 47
0
import numpy as np
from math import ceil
from dataclasses import dataclass, replace

from pint import UnitRegistry
from pint.definitions import UnitDefinition
from pint.converters import ScaleConverter

from typing import Callable, Tuple, Optional

ureg = UnitRegistry()

ureg.define(UnitDefinition('percent', None, (), ScaleConverter(1 / 100)))
ureg.load_definitions('units.txt')
Q = ureg.Quantity


@dataclass
class Mortgage(object):
    loan_amount: Q = Q(500_000, 'dollars')
    home_value: Q = Q(600_000, 'dollars')
    duration: Q = Q(10, 'years')
    base_rate: Q = Q(4, 'percent') / Q(1, 'year')
    base_closing_costs: Q = Q(5_000, 'dollars')

    #: The cost as a ratio of the loan amount for each point.
    #: See the CFPB for more detail:
    #:
    #:     https://www.consumerfinance.gov/ask-cfpb/what-are-discount-points-and-lender-credits-and-how-do-they-work-en-136/
    #:
    cost_per_point: Q = Q(1, 'percent / dp')
Esempio n. 48
0
 def _build_empty_reg_root(self):
     ureg = UnitRegistry(None)
     grp = ureg.get_group("root")
     grp.remove_units("pi")
     grp.invalidate_members()
     return ureg, ureg.get_group("root")
Esempio n. 49
0
"""

from collections import defaultdict
from types import SimpleNamespace

from pystol.operator import load_kubernetes_config

from flask import Flask, redirect, render_template, request, url_for

import kubernetes

from pint import UnitRegistry

from app import app

ureg = UnitRegistry()
# Pod
ureg.define("pods = 1 = [pods]")

# Mem
ureg.define("kmemunits = 1 = [kmemunits]")
ureg.define("Ki = 1024 * kmemunits")
ureg.define("Mi = Ki^2")
ureg.define("Gi = Ki^3")
ureg.define("Ti = Ki^4")
ureg.define("Pi = Ki^5")
ureg.define("Ei = Ki^6")
# CPU
ureg.define("kcpuunits = 1 = [kcpuunits]")
ureg.define("m = 1/1000 * kcpuunits")
ureg.define("k = 1000 * kcpuunits")
Esempio n. 50
0
import copy
import math
import pprint

import pytest

from pint import Context, DimensionalityError, UnitRegistry, get_application_registry
from pint.compat import np
from pint.testsuite import QuantityTestCase, helpers
from pint.unit import UnitsContainer
from pint.util import ParserHelper

ureg = UnitRegistry()


class TestIssues(QuantityTestCase):

    kwargs = dict(autoconvert_offset_to_baseunit=False)

    @pytest.mark.xfail
    def test_issue25(self):
        x = ParserHelper.from_string("10 %")
        assert x == ParserHelper(10, {"%": 1})
        x = ParserHelper.from_string("10 ‰")
        assert x == ParserHelper(10, {"‰": 1})
        ureg.define("percent = [fraction]; offset: 0 = %")
        ureg.define("permille = percent / 10 = ‰")
        x = ureg.parse_expression("10 %")
        assert x == ureg.Quantity(10, {"%": 1})
        y = ureg.parse_expression("10 ‰")
        assert y == ureg.Quantity(10, {"‰": 1})
Esempio n. 51
0
 def test_issue_1300(self):
     ureg = UnitRegistry()
     ureg.default_format = "~P"
     m = ureg.Measurement(1, 0.1, "meter")
     assert m.default_format == "~P"
Esempio n. 52
0
## Imports the class Nuclide from the NuclideClass.py

#from NuclideClass import Nuclide

## Brings in the Unit Registry from the pint module. The pints module needs to be added in the "project interprer"
## in Pycharm or using pip. This deals automatically with any units added.
## This adds the definitions for years as 'y' as well as 'yr' from mydef.txt which is stored in the proj folder

from pint import UnitRegistry
ureg = UnitRegistry()
ureg.load_definitions('my_def.txt')

## Sets these values to quantites used by pint
A_ = ureg.Quantity
B_ = ureg.Quantity
C_ = ureg.Quantity

## This is the user input section

## This script constructs the quantity for halflife to make sure it is valid. If not it quits and drops an error.

common_name = input("Common Name: ")

try:
    half_life = float(input("Enter the halflife of the nuclide: "))
    hl_units = input("Half-life units i.e. s, h, d, m, y etc: ")
    full_HL = C_(half_life, hl_units)
except:
    print(
        "The half-life input is not recognised, maybe you entered incorrect units, please try again."
    )
Esempio n. 53
0
 def test_issue252(self):
     ur = UnitRegistry()
     q = ur("3 F")
     t = copy.deepcopy(q)
     u = t.to(ur.mF)
     helpers.assert_quantity_equal(q.to(ur.mF), u)
Esempio n. 54
0
############################################################
# Copyright 2013, by the California Institute of Technology#
# Author : Piyush Agram
############################################################

from .BasisFn import BasisFn
from . import datetimeUtils as DU
import numpy as np

try: 
    from pint import UnitRegistry
except ImportError:
    raise ImportError('Python pint library not available. Please install pint before proceeding.')

ureg = UnitRegistry()

class CenteredBasisFn(BasisFn):
    ''' Base class for timefn that needs a reference epoch in time.

    Attributes
    ----------
    tref : datetime.datetime
        Reference epoch for evluation of the function.
    units : str
        Time scale to be used for interpreting model parameters.
        

    Notes
    -----
Esempio n. 55
0
    def test_context_with_sharedarg_def(self):

        ureg = UnitRegistry()

        add_sharedargdef_ctxs(ureg)

        q = 500 * ureg.meter
        s = (ureg.speed_of_light / q).to('Hz')
        u = (1 / 500) * ureg.ampere

        with ureg.context('lc'):
            self.assertEqual(q.to('Hz'), s)
            with ureg.context('ab'):
                self.assertEqual(q.to('ampere'), u)

        with ureg.context('ab'):
            self.assertEqual(q.to('ampere'), 0 * u)
            with ureg.context('lc'):
                self.assertRaises(ZeroDivisionError, ureg.Quantity.to, q, 'Hz')

        with ureg.context('lc', n=2):
            self.assertEqual(q.to('Hz'), s / 2)
            with ureg.context('ab'):
                self.assertEqual(q.to('ampere'), 2 * u)

        with ureg.context('ab', n=3):
            self.assertEqual(q.to('ampere'), 3 * u)
            with ureg.context('lc'):
                self.assertEqual(q.to('Hz'), s / 3)

        with ureg.context('lc', n=2):
            self.assertEqual(q.to('Hz'), s / 2)
            with ureg.context('ab', n=4):
                self.assertEqual(q.to('ampere'), 4 * u)

        with ureg.context('ab', n=3):
            self.assertEqual(q.to('ampere'), 3 * u)
            with ureg.context('lc', n=6):
                self.assertEqual(q.to('Hz'), s / 6)
Esempio n. 56
0
"""
    McsPy
    ~~~~~

    McsPy is a Python module/package to read, handle and operate on HDF5-based raw data
    files converted from recordings of devices of the Multi Channel Systems MCS GmbH.

    :copyright: (c) 2018 by Multi Channel Systems MCS GmbH
    :license: see LICENSE for more details
"""

#print("McsPy init!")
version = "0.4.1"

from pint import UnitRegistry
ureg = UnitRegistry()
Q_ = ureg.Quantity
ureg.define('NoUnit = [quantity]')

#from McsPy import McsCMOSMEA
import pytest
import pkg_resources
from contextlib import contextmanager
from pint import UnitRegistry
from gemd.units import parse_units, convert_units, change_definitions_file, UndefinedUnitError

# use the default unit registry for now
_ureg = UnitRegistry(filename=pkg_resources.resource_filename("gemd.units", "citrine_en.txt"))


def test_parse_expected():
    """Test that we can parse the units that we expect to be able to."""
    expected = [
        "degC", "degF", "K",
        "g", "kg", "mg", "ton",
        "L", "mL",
        "inch", "ft", "mm", "um",
        "second", "ms", "hour", "minute", "ns",
        "g/cm^3", "g/mL", "kg/cm^3",
        _ureg("kg").u,
        "amu",  # A line that was edited
        "Seconds",  # Added support for some title-case units
        "delta_Celsius / hour"  # Added to make sure pint version is right (>0.10)
    ]
    for unit in expected:
        parse_units(unit)
    assert parse_units("") == 'dimensionless'


def test_parse_unexpected():
    """Test that we cannot parse the units that we do not expect to."""
Esempio n. 58
0
from pint import UnitRegistry
ureg = UnitRegistry()
ureg.default_format = "~P"
Q_ = ureg.Quantity

# x = 10 * ureg.meter
# x = 10 * ureg.parse_expression("meter")
# x = 10 * ureg("meter")
# x = Q_(10, "meter")
# x = Q_("10m")
# x_in_feet = Q_(x).to("feet")

# x.magnitude
# x.units

# f"{x:P}" == "10 meter"
# f"{x:~P}" == "10 m"

# ureg.default_format = "~P"
Esempio n. 59
0
def _build_unit_registry():
    registry = UnitRegistry()
    registry.define('FPS = 1 * hertz')

    return registry
import numpy as np

from scipy import signal
from scipy.optimize import curve_fit
import os
from uncertainties import ufloat
from pint import UnitRegistry
Q_ = UnitRegistry().Quantity

import matplotlib as mlp
mlp.use('pgf')
import matplotlib.pyplot as plt
from matplotlib import rcParams
import matplotlib.image as mpimg
rcParams['font.family'] = 'serif'
rcParams['font.serif'] = '[lmroman10-regular]:+tlig;'
rcParams['text.usetex'] = True
rcParams['pgf.texsystem'] = 'lualatex'
rcParams['font.size'] = 10
rcParams['mathtext.fontset'] = 'custom'
rcParams[
    'pgf.preamble'] = r'\usepackage[locale=DE]{siunitx}'  #\usepackage{tgpagella}
rcParams[
    'text.latex.preamble'] = r'\usepackage[math-style=ISO,bold-style=ISO,sans-style=italic,nabla=upright,partial=upright,]{unicode-math}'
rcParams['axes.formatter.use_mathtext'] = True
rcParams['legend.fontsize'] = 10
rcParams['savefig.dpi'] = 300
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']