本文整理汇总了Python中pint.DimensionalityError方法的典型用法代码示例。如果您正苦于以下问题:Python pint.DimensionalityError方法的具体用法?Python pint.DimensionalityError怎么用?Python pint.DimensionalityError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pint
的用法示例。
在下文中一共展示了pint.DimensionalityError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: of_division
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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]
示例2: _validate_isvalid_unit
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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]
)
示例3: _validate_isvalid_quantity
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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]
)
示例4: convert_input
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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
示例5: _test_quantity_add_sub
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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)
示例6: _test_quantity_iadd_isub
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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)
示例7: test_exponentiation
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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)
示例8: convert
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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 ######
示例9: convert
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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))
示例10: unit_convert
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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
示例11: of_product
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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]
示例12: test_quantity_float_complex
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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)
示例13: test_inplace_exponentiation
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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)
示例14: test_exponentiation_array_exp_2
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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)
示例15: test_str_errors
# 需要导入模块: import pint [as 别名]
# 或者: from pint import DimensionalityError [as 别名]
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)")