Exemple #1
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')
Exemple #2
0
"""Ingest the COBS data file

  Run from RUN_20_AFTER.sh
"""
from __future__ import print_function
import datetime
import os
import sys

import pandas as pd
import pytz
from pint import UnitRegistry
from pyiem.observation import Observation
from pyiem.util import get_dbconn

UREG = UnitRegistry()
QUANTITY = UREG.Quantity
SID = 'OT0012'
DIRPATH = "/mnt/mesonet/home/mesonet/ot/ot0005/incoming/Pederson"

HOURLYCONV = {
    'Batt_Volt': 'battery',
    'PTemp_C': None,  # Panel Temperature ?
    'Rain_in_Tot': 'phour',
    'SlrW_Avg': 'srad',
    'SlrMJ_Tot': None,
    'AirTF_Avg': 'tmpf',
    'RH': 'relh',
    'WS_mph_Avg': 'sknt',
    'WS_mph_Max': 'gust',
    'WindDir': 'drct',
Exemple #3
0
from pint import UnitRegistry

unit = UnitRegistry()
Exemple #4
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)
Exemple #5
0
def export_video(
    datafile,
    outfile,
    overwrite,
    style,
    dpi,
    figsize,
    writer,
    show,
    budget,
    till_time,
    from_time,
    fps,
    bitrate,
    artist_tag,
    progress,
):
    """
    Export video from model data
    """

    from matplotlib import animation
    from microbenthos.dataview import HDFModelData, ModelPlotter
    from tqdm import tqdm
    import h5py as hdf
    from pint import UnitRegistry

    dirname = os.path.dirname(datafile)
    outfile = outfile or os.path.join(dirname, 'simulation.mp4')

    if not os.path.splitext(outfile)[1] == '.mp4':
        outfile += '.mp4'

    if os.path.exists(outfile) and not overwrite:
        click.confirm('Overwrite existing file: {}?'.format(outfile),
                      abort=True)

    try:
        Writer = animation.writers[writer]
    except:
        click.secho(
            'Animation writer {!r} not available. Is it installed?'.format(
                writer),
            fg='red')
        click.Abort()

    artist_tag = artist_tag or 'MicroBenthos'
    from datetime import datetime
    year = datetime.today().year

    writer = Writer(fps=fps,
                    bitrate=bitrate,
                    metadata=dict(artist=artist_tag, copyright=str(year)))

    ureg = UnitRegistry()
    ureg.define('hour = 60 * minute = h = hr')

    with hdf.File(datafile, 'r') as hf:
        dm = HDFModelData(store=hf)

        dp_ = dm.diel_period
        # this is a fipy PhysicalField
        diel_period_definition = f'diel_period = {float(dp_.value)} * {dp_.unit.name()} = ' \
            f'day = d = dp'
        ureg.define(diel_period_definition)
        click.echo(f'Defined: {diel_period_definition}')

        clock_times = ureg.Quantity(dm.times.value, dm.times.unit.name())

        if from_time:
            from_time_ = ureg(from_time)
            tidx1 = abs(clock_times - from_time_).argmin()
        else:
            tidx1 = 0
            from_time_ = None

        if till_time:
            till_time_ = ureg(till_time)
            tidx2 = abs(clock_times - till_time_).argmin() + 1
        else:
            tidx2 = len(clock_times)
            till_time_ = None

        click.secho(
            f'Export times: FROM "{from_time}" = "{from_time_}" = index {tidx1} '
            f'TILL "{till_time}" = "{till_time_}" = index {tidx2} || '
            f'DIEL_PERIOD = {ureg("1 d").to("h")}',
            fg='yellow')
        sim_times = dm.times[tidx1:tidx2]

        plot = ModelPlotter(model=dm,
                            style=style,
                            figsize=figsize,
                            dpi=dpi,
                            track_budget=budget)
        if show:
            plot.show(block=False)

        click.secho('Exporting video to {} (size={}, dpi={})'.format(
            outfile, figsize, dpi),
                    fg='green')

        with writer.saving(plot.fig, outfile, dpi=dpi):

            for i in tqdm(range(tidx1, tidx2),
                          position=progress,
                          leave=False,
                          desc=os.path.basename(dirname)):
                plot.update_artists(tidx=i)
                plot.draw()
                writer.grab_frame()

        click.secho('Video export completed', fg='green')
Exemple #6
0
from flask import Flask, jsonify, request
from pint import UnitRegistry
import requests

from ingreedypy import Ingreedy

from web.recipeml import render, wrap


app = Flask(__name__)
pint = UnitRegistry()


def generate_subtexts(description):
    yield description
    if '/' in description:
        pre_text, post_text = description.split('/', 1)
        post_tokens = post_text.split(' ')
        if pre_text:
            yield u'{} {}'.format(pre_text, u' '.join(post_tokens[1:]))
        yield u' '.join(post_tokens)
    yield description.replace(',', '')


def parse_quantity(quantity):
    # Workaround: pint treats 'pinch' as 'pico-inch'
    # https://github.com/hgrecco/pint/issues/273
    if quantity['unit'] == 'pinch':
        quantity['unit'] = 'ml'
        quantity['amount'] = (quantity.get('amount') or 1) * 0.25
Exemple #7
0
def test_unit_format_babel():
    ureg = UnitRegistry(fmt_locale="fr_FR")
    volume = ureg.Unit("ml")
    assert volume.format_babel() == "millilitre"
Exemple #8
0
 def test_issue170(self):
     Q_ = UnitRegistry().Quantity
     q = Q_("1 kHz") / Q_("100 Hz")
     iq = int(q)
     self.assertEqual(iq, 10)
     self.assertIsInstance(iq, int)
Exemple #9
0
 def test_issue252(self):
     ur = UnitRegistry()
     q = ur("3 F")
     t = copy.deepcopy(q)
     u = t.to(ur.mF)
     self.assertQuantityEqual(q.to(ur.mF), u)
Exemple #10
0
"wraps pint in gpkit monomials"
import os
from pint import UnitRegistry, DimensionalityError

ureg = UnitRegistry()  # pylint: disable=invalid-name
ureg.load_definitions(os.sep.join([os.path.dirname(__file__), "usd_cpi.txt"]))
# next line patches https://github.com/hgrecco/pint/issues/366
ureg.define("nautical_mile = 1852 m = nmi")


class GPkitUnits(object):
    "Return monomials instead of Quantitites"

    def __init__(self):
        self.Quantity = ureg.Quantity  # pylint: disable=invalid-name
        if hasattr(ureg, "__nonzero__"):
            # that is, if it's a DummyUnits object
            self.__nonzero__ = ureg.__nonzero__
            self.__bool__ = ureg.__bool__

    def __getattr__(self, attr):
        from .. import Monomial
        return Monomial(self.Quantity(1, getattr(ureg, attr)))

    def __call__(self, arg):
        from .. import Monomial
        return Monomial(self.Quantity(1, ureg(arg)))


units = GPkitUnits()
Exemple #11
0
    lantz
    ~~~~~

    An automation and instrumentation toolkit with a clean, well-designed and
    consistent interface.

    :copyright: 2012 by The Lantz Authors
    :license: BSD, see LICENSE for more details.
"""

import pkg_resources

__version__ = pkg_resources.get_distribution('lantz').version

from pint import UnitRegistry
Q_ = UnitRegistry().Quantity

from .log import LOGGER
from .driver import Driver, Feat, DictFeat, Action

__all__ = ['Driver', 'Action', 'Feat', 'DictFeat', 'Q_']


def run_pyroma(data):
    import sys
    from zest.releaser.utils import ask
    if not ask("Run pyroma on the package before uploading?"):
        return
    try:
        from pyroma import run
        result = run(data['tagdir'])
Exemple #12
0
from pint import UnitRegistry
import datetime as dt
import aiohttp
import random
import json
from PyDictionary import PyDictionary

with open("H:\Documents\Bot Folder\PoiBot\credentials\\credentials.txt") as f:
    creds = json.load(f)
    token = creds["owm"]
    owm = pyowm.OWM(token)
    client_id = creds["anilist_client_id"]
    anilist_secret = creds["anilist_client_secret"]
    timezone_db_key = creds["timezonedb_key"]
registry = owm.city_id_registry()
ureg = UnitRegistry(autoconvert_offset_to_baseunit=True)
Q_ = ureg.Quantity


class Commands():
    def __init__(self, bot):
        self.bot = bot

    @commands.command(no_pm=True)
    async def convert(self, number: str, source_unit: str, *,
                      converted_unit: str):
        """Converts one amount of unit to another"""
        source_and_amount = number + " " + source_unit
        converted_unit = converted_unit.lstrip("to ")
        try:
            result = Q_(source_and_amount).to(converted_unit)
Exemple #13
0
# -*- coding: utf-8 -*-
"""Top-level package for mechmat."""

__author__ = """Jelle Spijker"""
__email__ = '*****@*****.**'
__version__ = '0.2.4'

from pint import UnitRegistry, set_application_registry

ureg = UnitRegistry(autoconvert_offset_to_baseunit=True,
                    default_as_delta=False)
ureg.setup_matplotlib(True)
Q_ = ureg.Quantity
set_application_registry(ureg)

from mechmat.core.bibliography import bib
from mechmat.core.chainable import Chainable, Guarded
from mechmat.material import material_factory
Exemple #14
0
"""Handles conversion between units used in the `SosModel`

First implementation delegates to pint.
"""
import logging

from pint import UndefinedUnitError, UnitRegistry

LOGGER = logging.getLogger()
__UNIT_REGISTRY = UnitRegistry(on_redefinition='raise')


def parse_unit(unit_string):
    """Parse a unit string (abbreviation or full) into a Unit object

    Parameters
    ----------
    unit : str

    Returns
    -------
    quantity : :class:`pint.Unit`
    """
    try:
        unit = __UNIT_REGISTRY.parse_units(unit_string)
    except UndefinedUnitError:
        LOGGER.warning("Unrecognised unit: %s", unit_string)
        unit = None
    return unit

Exemple #15
0
    # as an unavoidable side effect, this also becomes possible
    >>> NOx.to("N2O", "NOx_conversions")
    <Quantity(0.9565217391304348, 'N2O')>
"""

from typing import Dict, Sequence, Union

import numpy as np
from pint import Context, UnitRegistry
from pint.errors import (  # noqa: F401 # pylint: disable=unused-import
    DimensionalityError, UndefinedUnitError,
)

# Start a unit registry using the default variables:
unit_registry = UnitRegistry()
"""`obj`:`pint.registry.UnitRegistry`: OpenSCM's unit registry

The unit registry contains all of our recognised units. A couple of examples

.. code:: python

    >>> from openscm.units import unit_registry
    >>> unit_registry("CO2")
    <Quantity(1, 'CO2')>

    >>> emissions_aus = 0.34 * unit_registry("Gt C / yr")
    >>> emissions_aus
    <Quantity(0.34, 'C * gigametric_ton / a')>

    >>> emissions_aus.to("Mt C / week")
Exemple #16
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
Exemple #17
0
import pytest
import pkg_resources
from pint import UnitRegistry
from gemd.units import parse_units, 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",
Exemple #18
0
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions

import pint
from pint import UnitRegistry
from importlib_resources import files
from distutils.version import LooseVersion

# Create ureg here so it is only created once
if LooseVersion(pint.__version__) < LooseVersion('0.10'):
    # Bohr, unified_atomic_mass_unit not defined in pint 0.9, so load
    # pint 0.16.1 definition file
    ureg = UnitRegistry(str(files('euphonic.data') / 'default_en.txt'))
else:
    ureg = UnitRegistry()
ureg.enable_contexts('spectroscopy')
Quantity = ureg.Quantity

from .spectra import Spectrum1D, Spectrum1DCollection, Spectrum2D
from .crystal import Crystal
from .debye_waller import DebyeWaller
from .qpoint_frequencies import QpointFrequencies
from .structure_factor import StructureFactor
from .qpoint_phonon_modes import QpointPhononModes
from .force_constants import ForceConstants
Exemple #19
0
from pint import UnitRegistry
import logging
import math

u = UnitRegistry()
logging.basicConfig(level=logging.INFO)
'''
+ exec(s)
+ replace("# {", "=> {"
+ If "# {" in line: formatargs.append(split("=")[0])
+ But then also auto-formatting and auto-unit
+ Also add things to summary, so I can print them later
+ Also take care of namespaces by using functions?
+ that way vars don't get reused unexcpectedly
+ Make sure global vars can be used though!

Eurocode.

1. Load factors

LoadFactors(grens, gevolg)

2. Pen gat verbinding

Symmetrisch: PinMidHole(string)
Assymetrisch: PinSideHole(string)

2b. Pen 

Symmetrisch: PinMid(string)
Assymetrisch: PinSide(string)
Exemple #20
0
    def statistics(self,
                   sb_position=None,
                   sb='lower',
                   high_cf=False,
                   fringe_contrast_algorithm='statistical',
                   apodization='hanning',
                   single_values=True,
                   show_progressbar=False,
                   parallel=None):
        """
        Calculates following statistics for off-axis electron holograms:

        1. Fringe contrast using either statistical definition or
        Fourier space approach (see description of `fringe_contrast_algorithm` parameter)
        2. Fringe sampling (in pixels)
        3. Fringe spacing (in calibrated units)
        4. Carrier frequency (in calibrated units, radians and 1/px)

        Parameters
        ----------
        sb_position : tuple, :class:`~hyperspy.signals.Signal1D, None
            The sideband position (y, x), referred to the non-shifted FFT.
            It has to be tuple or to have the same dimensionality as the hologram.
            If None, sideband is determined automatically from FFT.
        sb : str, None
            Select which sideband is selected. 'upper', 'lower', 'left' or 'right'.
        high_cf : bool, optional
            If False, the highest carrier frequency allowed for the sideband location is equal to
            half of the Nyquist frequency (Default: False).
        fringe_contrast_algorithm : str
            Select fringe contrast algorithm between:

            'fourier'
                fringe contrast is estimated as:
                2 * <I(k_0)> / <I(0)>,
                where I(k_0) is intensity of sideband and I(0) is the intensity of central band (FFT origin).
                This method delivers also reasonable estimation if
                interference pattern do not cover full field of view.
            'statistical'
                fringe contrast is estimated by dividing standard deviation by mean
                of the hologram intensity in real space. This algorithm relays on that the fringes are regular and
                covering entire field of view.

            (Default: 'statistical')
        apodization: str or None, optional
            Used with `fringe_contrast_algorithm='fourier'`. If 'hanning' or 'hamming' apodization window
            will be applied in real space before FFT for estimation of fringe contrast.
            Apodization is typically needed to suppress striking  due to sharp edges of the image,
            which often results in underestimation of the fringe contrast. (Default: 'hanning')
        single_values : bool, optional
            If True calculates statistics only for the first navigation pixels and
            returns the values as single floats (Default: True)
        show_progressbar : bool, optional
            Shows progressbar while iterating over different slices of the
            signal (passes the parameter to map method). (Default: False)
        parallel : bool, None, optional
            Run the reconstruction in parallel

        Returns
        -------
        statistics_dict :
            Dictionary with the statistics

        Examples
        --------
        >>> import hyperspy.api as hs
        >>> s = hs.datasets.example_signals.reference_hologram()
        >>> sb_position = s.estimate_sideband_position(high_cf=True)
        >>> s.statistics(sb_position=sb_position)
        {'Fringe spacing (nm)': 3.4860442674236256,
        'Carrier frequency (1/px)': 0.26383819985575441,
        'Carrier frequency (mrad)': 0.56475154609203482,
        'Fringe contrast': 0.071298357213623778,
        'Fringe sampling (px)': 3.7902017241882331,
        'Carrier frequency (1 / nm)': 0.28685808994016415}
        """

        # Testing match of navigation axes of reference and self
        # (exception: reference nav_dim=1):

        # Parsing sideband position:
        (sb_position,
         sb_position_temp) = _parse_sb_position(self, None, sb_position, sb,
                                                high_cf, parallel)

        # Calculate carrier frequency in 1/px and fringe sampling:
        fourier_sampling = 1. / np.array(self.axes_manager.signal_shape)
        if single_values:
            carrier_freq_px = calculate_carrier_frequency(
                _first_nav_pixel_data(self),
                sb_position=_first_nav_pixel_data(sb_position),
                scale=fourier_sampling)
        else:
            carrier_freq_px = self.map(calculate_carrier_frequency,
                                       sb_position=sb_position,
                                       scale=fourier_sampling,
                                       inplace=False,
                                       ragged=False,
                                       show_progressbar=show_progressbar,
                                       parallel=parallel)
        fringe_sampling = np.divide(1., carrier_freq_px)

        ureg = UnitRegistry()
        try:
            units = ureg.parse_expression(
                str(self.axes_manager.signal_axes[0].units))
        except UndefinedUnitError:
            raise ValueError('Signal axes units should be defined.')

        # Calculate carrier frequency in 1/units and fringe spacing in units:
        f_sampling_units = np.divide(1., [
            a * b for a, b in zip(self.axes_manager.signal_shape, (
                self.axes_manager.signal_axes[0].scale,
                self.axes_manager.signal_axes[1].scale))
        ])
        if single_values:
            carrier_freq_units = calculate_carrier_frequency(
                _first_nav_pixel_data(self),
                sb_position=_first_nav_pixel_data(sb_position),
                scale=f_sampling_units)
        else:
            carrier_freq_units = self.map(calculate_carrier_frequency,
                                          sb_position=sb_position,
                                          scale=f_sampling_units,
                                          inplace=False,
                                          ragged=False,
                                          show_progressbar=show_progressbar,
                                          parallel=parallel)
        fringe_spacing = np.divide(1., carrier_freq_units)

        # Calculate carrier frequency in mrad:
        try:
            ht = self.metadata.Acquisition_instrument.TEM.beam_energy
        except BaseException:
            raise AttributeError("Please define the beam energy."
                                 "You can do this e.g. by using the "
                                 "set_microscope_parameters method.")

        momentum = 2 * constants.m_e * constants.elementary_charge * ht * \
            1000 * (1 + constants.elementary_charge * ht *
                    1000 / (2 * constants.m_e * constants.c ** 2))
        wavelength = constants.h / np.sqrt(momentum) * 1e9  # in nm
        carrier_freq_quantity = wavelength * \
            ureg('nm') * carrier_freq_units / units * ureg('rad')
        carrier_freq_mrad = carrier_freq_quantity.to('mrad').magnitude

        # Calculate fringe contrast:
        if fringe_contrast_algorithm == 'fourier':
            if single_values:
                fringe_contrast = estimate_fringe_contrast_fourier(
                    _first_nav_pixel_data(self),
                    sb_position=_first_nav_pixel_data(sb_position),
                    apodization=apodization)
            else:
                fringe_contrast = self.map(estimate_fringe_contrast_fourier,
                                           sb_position=sb_position,
                                           apodization=apodization,
                                           inplace=False,
                                           ragged=False,
                                           show_progressbar=show_progressbar,
                                           parallel=parallel)
        elif fringe_contrast_algorithm == 'statistical':
            if single_values:
                fringe_contrast = _first_nav_pixel_data(
                    self).std() / _first_nav_pixel_data(self).mean()
            else:
                fringe_contrast = _estimate_fringe_contrast_statistical(self)
        else:
            raise ValueError(
                "fringe_contrast_algorithm can only be set to fourier or statistical."
            )

        return {
            'Fringe contrast': fringe_contrast,
            'Fringe sampling (px)': fringe_sampling,
            'Fringe spacing ({:~})'.format(units.units): fringe_spacing,
            'Carrier frequency (1/px)': carrier_freq_px,
            'Carrier frequency ({:~})'.format((1. / units).units):
            carrier_freq_units,
            'Carrier frequency (mrad)': carrier_freq_mrad
        }
Exemple #21
0
import re
import yaml
import numpy as np
from pint import UnitRegistry
ureg = UnitRegistry()


def scan_info(cell_id, basedir):
    """
    Scans the info.dat for meta information about the recording.

    Args:
        cell_id: id of the cell
        basedir: base directory where the data lives


    """
    info = open(basedir + cell_id + '/info.dat').readlines()
    info = [re.sub(r'[^\x00-\x7F]+', ' ', e[1:]) for e in info]
    meta = yaml.load(''.join(info))
    return meta


def get_number_and_unit(value_string):
    """
    Get the number and the unit from a string.

    :param value_string: string with number and unit
    :return: value, unit
    """
    if value_string.endswith('%'):
Exemple #22
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)