Python pint.DimensionalityError() Examples

The following are 22 code examples of pint.DimensionalityError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pint , or try the search function .
Example #1
Source File: validation.py    From PyKED with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _validate_isvalid_unit(self, isvalid_unit, field, value):
        """Checks for appropriate units using Pint unit registry.
        Args:
            isvalid_unit (`bool`): flag from schema indicating units to be checked.
            field (`str`): property associated with units in question.
            value (`dict`): dictionary of values from file associated with this property.

        The rule's arguments are validated against this schema:
            {'isvalid_unit': {'type': 'bool'}, 'field': {'type': 'str'},
             'value': {'type': 'dict'}}
        """
        quantity = 1.0 * units(value['units'])
        try:
            quantity.to(property_units[field])
        except pint.DimensionalityError:
            self._error(field, 'incompatible units; should be consistent '
                        'with ' + property_units[field]
                        ) 
Example #2
Source File: validation.py    From PyKED with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _validate_isvalid_quantity(self, isvalid_quantity, field, value):
        """Checks for valid given value and appropriate units.

        Args:
            isvalid_quantity (`bool`): flag from schema indicating quantity to be checked.
            field (`str`): property associated with quantity in question.
            value (`list`): list whose first element is a string representing a value with units

        The rule's arguments are validated against this schema:
            {'isvalid_quantity': {'type': 'bool'}, 'field': {'type': 'str'},
             'value': {'type': 'list'}}
        """
        quantity = Q_(value[0])
        low_lim = 0.0 * units(property_units[field])

        try:
            if quantity <= low_lim:
                self._error(
                    field, 'value must be greater than 0.0 {}'.format(property_units[field]),
                )
        except pint.DimensionalityError:
            self._error(field, 'incompatible units; should be consistent '
                        'with ' + property_units[field]
                        ) 
Example #3
Source File: units.py    From fluids with MIT License 6 votes vote down vote up
def convert_input(val, unit, ureg, strict=True):
    if val is None:
        return val # Handle optional units which are given
    if unit != 'dimensionless':
        try:
            return val.to(unit).magnitude
        except AttributeError:
            if strict:
                raise TypeError('%s has no quantity' %(val))
            else:
                return val
        except DimensionalityError as e:
            raise Exception('Converting %s to units of %s raised DimensionalityError: %s'%(val, unit, str(e)))
    else:
        if type(val) == ureg.Quantity:
            return val.magnitude
        else:
            return val 
Example #4
Source File: test_quantity.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _test_quantity_add_sub(self, unit, func):
        x = self.Q_(unit, 'centimeter')
        y = self.Q_(unit, 'inch')
        z = self.Q_(unit, 'second')
        a = self.Q_(unit, None)

        func(op.add, x, x, self.Q_(unit + unit, 'centimeter'))
        func(op.add, x, y, self.Q_(unit + 2.54 * unit, 'centimeter'))
        func(op.add, y, x, self.Q_(unit + unit / (2.54 * unit), 'inch'))
        func(op.add, a, unit, self.Q_(unit + unit, None))
        self.assertRaises(DimensionalityError, op.add, 10, x)
        self.assertRaises(DimensionalityError, op.add, x, 10)
        self.assertRaises(DimensionalityError, op.add, x, z)

        func(op.sub, x, x, self.Q_(unit - unit, 'centimeter'))
        func(op.sub, x, y, self.Q_(unit - 2.54 * unit, 'centimeter'))
        func(op.sub, y, x, self.Q_(unit - unit / (2.54 * unit), 'inch'))
        func(op.sub, a, unit, self.Q_(unit - unit, None))
        self.assertRaises(DimensionalityError, op.sub, 10, x)
        self.assertRaises(DimensionalityError, op.sub, x, 10)
        self.assertRaises(DimensionalityError, op.sub, x, z) 
Example #5
Source File: test_quantity.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _test_quantity_iadd_isub(self, unit, func):
        x = self.Q_(unit, 'centimeter')
        y = self.Q_(unit, 'inch')
        z = self.Q_(unit, 'second')
        a = self.Q_(unit, None)

        func(op.iadd, x, x, self.Q_(unit + unit, 'centimeter'))
        func(op.iadd, x, y, self.Q_(unit + 2.54 * unit, 'centimeter'))
        func(op.iadd, y, x, self.Q_(unit + unit / 2.54, 'inch'))
        func(op.iadd, a, unit, self.Q_(unit + unit, None))
        self.assertRaises(DimensionalityError, op.iadd, 10, x)
        self.assertRaises(DimensionalityError, op.iadd, x, 10)
        self.assertRaises(DimensionalityError, op.iadd, x, z)

        func(op.isub, x, x, self.Q_(unit - unit, 'centimeter'))
        func(op.isub, x, y, self.Q_(unit - 2.54, 'centimeter'))
        func(op.isub, y, x, self.Q_(unit - unit / 2.54, 'inch'))
        func(op.isub, a, unit, self.Q_(unit - unit, None))
        self.assertRaises(DimensionalityError, op.sub, 10, x)
        self.assertRaises(DimensionalityError, op.sub, x, 10)
        self.assertRaises(DimensionalityError, op.sub, x, z) 
Example #6
Source File: unit_converter.py    From EnergyPATHWAYS with MIT License 6 votes vote down vote up
def unit_convert(cls, data=1, unit_from_num=None, unit_from_den=None, unit_to_num=None, unit_to_den=None):
        uc = cls.get_instance()
        """return data converted from unit_from to unit_to"""
        # This is used to cancel out units that are the same but may not be recognized by the ureg
        if unit_from_num == unit_to_num:
            unit_from_num = unit_to_num = None
        if unit_from_den == unit_to_den:
            unit_from_den = unit_to_den = None
        if unit_from_num == unit_to_den:
            unit_from_num = unit_to_den = None
        if unit_from_den == unit_to_num:
            unit_from_den = unit_to_num = None

        input_unit = uc.ureg.parse_expression(unit_from_num) / uc.ureg.parse_expression(unit_from_den)
        output_unit = uc.ureg.parse_expression(unit_to_num) / uc.ureg.parse_expression(unit_to_den)
        try:
            factor = input_unit.to(output_unit).magnitude
            return data * factor
        except pint.DimensionalityError:
            factor = (1. / input_unit).to(output_unit).magnitude
            return (1. / data) * factor 
Example #7
Source File: test_quantity.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_exponentiation(self, input_tuple, expected):
        self.ureg.default_as_delta = False
        in1, in2 = input_tuple
        if type(in1) is tuple and type(in2) is tuple:
            in1, in2 = self.Q_(*in1), self.Q_(*in2)
        elif not type(in1) is tuple and type(in2) is tuple:
            in2 = self.Q_(*in2)
        else:
            in1 = self.Q_(*in1)
        input_tuple = in1, in2
        expected_copy = expected[:]
        for i, mode in enumerate([False, True]):
            self.ureg.autoconvert_offset_to_baseunit = mode
            if expected_copy[i] == 'error':
                self.assertRaises((OffsetUnitCalculusError,
                                   DimensionalityError), op.pow, in1, in2)
            else:
                if type(expected_copy[i]) is tuple:
                    expected = self.Q_(*expected_copy[i])
                    self.assertEqual(op.pow(in1, in2).units, expected.units)
                else:
                    expected = expected_copy[i]
                self.assertQuantityAlmostEqual(op.pow(in1, in2), expected) 
Example #8
Source File: units.py    From gpkit with MIT License 6 votes vote down vote up
def of_division(self, numerator, denominator):
        "Cached unit division. Requires Quantity inputs."
        if numerator.units is denominator.units:
            return 1
        key = (id(numerator.units), id(denominator.units))
        try:
            return self.division_cache[key]
        except KeyError:
            if numerator.units and denominator.units:
                conversion = numerator.units/denominator.units
            else:
                conversion = numerator.units or 1/denominator.units
            try:
                self.division_cache[key] = float(conversion)
            except DimensionalityError:
                raise DimensionalityError(numerator, denominator)
        return self.division_cache[key] 
Example #9
Source File: quantity.py    From molecular-design-toolkit with Apache License 2.0 6 votes vote down vote up
def convert(self, value):
        """ Returns quantity converted to these units

        Args:
            value (MdtQuantity or Numeric): value to convert

        Returns:
            MdtQuantity: converted value

        Raises:
            DimensionalityError: if the quantity does not have these units' dimensionality
        """
        if hasattr(value, 'to'):
            return value.to(self)
        elif self.dimensionless:
            return value * self
        else:
            raise DimensionalityError('Cannot convert "%s" to units of "%s"' % (value, self)) 
Example #10
Source File: runsander.py    From molecular-design-toolkit with Apache License 2.0 6 votes vote down vote up
def convert(q, units):
    """
    Convert a javascript quantity description into a floating point number in the desired units

    Args:
        q (dict): Quantity to convert (of form ``{value: <float>, units: <str>}`` )
        units (str): name of the units

    Returns:
        float: value of the quantity in the passed unit system

    Raises:
        pint.DimensionalityError: If the units are incompatible with the desired quantity

    Examples:
        >>> q = {'value':1.0, 'units':'nm'}
        >>> convert(q, 'angstrom')
        10.0
    """
    quantity = q['value'] * ureg(q['units'])
    return quantity.value_in(units)


##### helper routines below ###### 
Example #11
Source File: test_numpy.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_exponentiation_array_exp_2(self):
        arr = np.array(range(3), dtype=np.float)
        #q = self.Q_(copy.copy(arr), None)
        q = self.Q_(copy.copy(arr), 'meter')
        arr_cp = copy.copy(arr)
        q_cp = copy.copy(q)
        # this fails as expected since numpy 1.8.0 but...
        self.assertRaises(DimensionalityError, op.pow, arr_cp, q_cp)
        # ..not for op.ipow !
        # q_cp is treated as if it is an array. The units are ignored.
        # _Quantity.__ipow__ is never called
        arr_cp = copy.copy(arr)
        q_cp = copy.copy(q)
        self.assertRaises(DimensionalityError, op.ipow, arr_cp, q_cp) 
Example #12
Source File: units.py    From bifrost with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_units(value, old_units, new_units):
    old_quantity = value * ureg.parse_expression(old_units)
    try:
        new_quantity = old_quantity.to(new_units)
    except pint.DimensionalityError:
        raise ValueError("Cannot convert units %s to %s" %
                         (old_units, new_units))
    return new_quantity.magnitude

# TODO: May need something more flexible, like a Units wrapper class with __str__ 
Example #13
Source File: units.py    From pyam with Apache License 2.0 5 votes vote down vote up
def convert_gwp(context, qty, to):
    """Helper for :meth:`convert_unit` to perform GWP conversions."""
    # Remove a leading 'gwp_' to produce the metric name
    metric = context.split('gwp_')[1] if context else context

    # Extract the species from *qty* and *to*, allowing supported aliases
    species_from, units_from = extract_species(qty[1])
    species_to, units_to = extract_species(to)

    try:
        # Convert using a (magnitude, unit) tuple with only units, and explicit
        # input and output units
        result = iam_units.convert_gwp(metric, (qty[0], units_from),
                                       species_from, species_to)
    except (AttributeError, ValueError):
        # Missing *metric*, or *species_to* contains invalid units. pyam
        # promises UndefinedUnitError in these cases. Use a subclass (above) to
        # add a usage hint.
        raise UndefinedUnitError(species_to) from None
    except pint.DimensionalityError:
        # Provide an exception with the user's inputs
        raise pint.DimensionalityError(qty[1], to) from None

    # Other exceptions are not caught and will pass up through convert_unit()

    if units_to:
        # Also convert the units
        result = result.to(units_to)
    else:
        # *to* was only a species name. Provide units based on input and the
        # output species name.
        to = iam_units.format_mass(result, species_to, spec=':~')

    return result, to 
Example #14
Source File: components.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def _validate(self, change):
        import pint

        self._validated_value = None
        self._error_msg = False

        # Check that we can parse this
        try:
            val = u.ureg(change['new'])

        except (pint.UndefinedUnitError,
                pint.DimensionalityError,
                pint.compat.tokenize.TokenError):
            self._error_msg = "Failed to parse '%s'" % self.textbox.value

        except Exception as e:  # unfortunately, pint's parser sometimes raises bare exception class
            if e.__class__ != Exception:
                raise  # this isn't what we want
            self._error_msg = "Failed to parse '%s'" % self.textbox.value

        else:  # Check dimensionality
            valdim = u.get_units(val).dimensionality
            if self.dimensionality is not None and valdim != self.dimensionality:
                self._error_msg = "Requires dimensionality %s" % self.dimensionality

        if not self._error_msg:
            self.validated.value = '<span title="Valid quantity">%s</span>' % self.VALID
            self._validated_value = val
        else:
            self.validated.value = '<span title="%s">%s</span>' % (self._error_msg, self.INVALID) 
Example #15
Source File: quantity.py    From molecular-design-toolkit with Apache License 2.0 5 votes vote down vote up
def value_of(self, value):
        """ Returns numeric value of the quantity in these units

        Args:
            value (MdtQuantity or Numeric): value to convert

        Returns:
            Numeric: value in this object's units

        Raises:
            DimensionalityError: if the quantity does not have these units' dimensionality
        """
        v = self.convert(value)
        return v.magnitude 
Example #16
Source File: test_unit.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_to_and_from_offset_units(self, input_tuple, expected):
        src, dst = input_tuple
        src, dst = UnitsContainer(src), UnitsContainer(dst)
        value = 10.
        convert = self.ureg.convert
        if isinstance(expected, string_types):
            self.assertRaises(DimensionalityError, convert, value, src, dst)
            if src != dst:
                self.assertRaises(DimensionalityError, convert, value, dst, src)
        else:
            self.assertQuantityAlmostEqual(convert(value, src, dst),
                                           expected, atol=0.001)
            if src != dst:
                self.assertQuantityAlmostEqual(convert(expected, dst, src),
                                               value, atol=0.001) 
Example #17
Source File: test_unit.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_errors(self):
        x = ('meter', )
        msg = "'meter' is not defined in the unit registry"
        self.assertEqual(str(UndefinedUnitError(x)), msg)
        self.assertEqual(str(UndefinedUnitError(list(x))), msg)
        self.assertEqual(str(UndefinedUnitError(set(x))), msg)

        msg = "Cannot convert from 'a' (c) to 'b' (d)msg"
        ex = DimensionalityError('a', 'b', 'c', 'd', 'msg')
        self.assertEqual(str(ex), msg) 
Example #18
Source File: test_unit.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_str_errors(self):
        self.assertEqual(str(UndefinedUnitError('rabbits')), "'{0!s}' is not defined in the unit registry".format('rabbits'))
        self.assertEqual(str(UndefinedUnitError(('rabbits', 'horses'))), "{0!s} are not defined in the unit registry".format(('rabbits', 'horses')))
        self.assertEqual(u(str(DimensionalityError('meter', 'second'))),
                         "Cannot convert from 'meter' to 'second'")
        self.assertEqual(str(DimensionalityError('meter', 'second', 'length', 'time')),
                         "Cannot convert from 'meter' (length) to 'second' (time)") 
Example #19
Source File: test_quantity.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_inplace_exponentiation(self, input_tuple, expected):
        self.ureg.default_as_delta = False
        in1, in2 = input_tuple
        if type(in1) is tuple and type(in2) is tuple:
            (q1v, q1u), (q2v, q2u) = in1, in2
            in1 = self.Q_(*(np.array([q1v]*2, dtype=np.float), q1u))
            in2 = self.Q_(q2v, q2u)
        elif not type(in1) is tuple and type(in2) is tuple:
            in2 = self.Q_(*in2)
        else:
            in1 = self.Q_(*in1)

        input_tuple = in1, in2

        expected_copy = expected[:]
        for i, mode in enumerate([False, True]):
            self.ureg.autoconvert_offset_to_baseunit = mode
            in1_cp = copy.copy(in1)
            if expected_copy[i] == 'error':
                self.assertRaises((OffsetUnitCalculusError,
                                   DimensionalityError), op.ipow, in1_cp, in2)
            else:
                if type(expected_copy[i]) is tuple:
                    expected = self.Q_(np.array([expected_copy[i][0]]*2,
                                                dtype=np.float),
                                       expected_copy[i][1])
                    self.assertEqual(op.ipow(in1_cp, in2).units, expected.units)
                else:
                    expected = np.array([expected_copy[i]]*2, dtype=np.float)


                in1_cp = copy.copy(in1)
                self.assertQuantityAlmostEqual(op.ipow(in1_cp, in2), expected) 
Example #20
Source File: test_quantity.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_quantity_float_complex(self):
        x = self.Q_(-4.2, None)
        y = self.Q_(4.2, None)
        z = self.Q_(1, 'meter')
        for fun in (float, complex):
            self.assertEqual(fun(x), fun(x.magnitude))
            self.assertEqual(fun(y), fun(y.magnitude))
            self.assertRaises(DimensionalityError, fun, z) 
Example #21
Source File: units.py    From gpkit with MIT License 5 votes vote down vote up
def of_product(self, thing1, thing2):
        "Cached unit division. Requires united inputs."
        key = (thing1.units, thing2.units)
        try:
            return self.multiplication_cache[key]
        except KeyError:
            mul_units = qty((thing1*thing2).units)
            try:
                self.multiplication_cache[key] = (None, float(mul_units))
            except DimensionalityError:
                self.multiplication_cache[key] = (mul_units, None)
        return self.multiplication_cache[key] 
Example #22
Source File: validation.py    From PyKED with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _validate_isvalid_history(self, isvalid_history, field, value):
        """Checks that the given time history is properly formatted.

        Args:
            isvalid_history (`bool`): flag from schema indicating units to be checked.
            field (`str`): property associated with history in question.
            value (`dict`): dictionary of values from file associated with this property.

        The rule's arguments are validated against this schema:
            {'isvalid_history': {'type': 'bool'}, 'field': {'type': 'str'},
             'value': {'type': 'dict'}}
        """
        # Check the type has appropriate units
        history_type = value['type']
        if history_type.endswith('emission'):
            history_type = 'emission'
        elif history_type.endswith('absorption'):
            history_type = 'absorption'
        quantity = 1.0*(units(value['quantity']['units']))
        try:
            quantity.to(property_units[history_type])
        except pint.DimensionalityError:
            self._error(field, 'incompatible units; should be consistent '
                        'with ' + property_units[history_type])

        # Check that time has appropriate units
        time = 1.0*(units(value['time']['units']))
        try:
            time.to(property_units['time'])
        except pint.DimensionalityError:
            self._error(field, 'incompatible units; should be consistent '
                        'with ' + property_units['time'])

        # Check that the values have the right number of columns
        n_cols = len(value['values'][0])
        max_cols = max(value['time']['column'],
                       value['quantity']['column'],
                       value.get('uncertainty', {}).get('column', 0)) + 1
        if n_cols > max_cols:
            self._error(field, 'too many columns in the values')
        elif n_cols < max_cols:
            self._error(field, 'not enough columns in the values')