◐ Shell
reader mode source ↗
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
File filter
Conversations
Jump to
Diff view
Apply and reload
Show whitespace
Diff view
Apply and reload
10 changes: 5 additions & 5 deletions quantities/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ def __call__(self, new_method):
header = self.header

if original_doc and new_doc:
new_method.__doc__ = """
{}
{}
{}
""".format(original_doc, header, new_doc)

elif original_doc:
new_method.__doc__ = original_doc
Expand Down
6 changes: 3 additions & 3 deletions quantities/markup.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ def format_units(udict):
u = key.symbol
if d>0:
if d != 1:
u = u + ('**%s'%d).rstrip('0').rstrip('.')
num.append(u)
elif d<0:
d = -d
if d != 1:
u = u + ('**%s'%d).rstrip('0').rstrip('.')
den.append(u)
res = '*'.join(num)
if len(den):
Expand Down Expand Up @@ -156,6 +156,6 @@ def format_units_html(udict,font='%s',mult=r'&sdot;',paren=False):
# Remove multiplication signs
res = re.sub(r'\*',mult,res)
if paren and not compound:
res = '(%s)' % res
res = font % res
return res
24 changes: 9 additions & 15 deletions quantities/quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ def validate_unit_quantity(value):
assert value.magnitude == 1
except AssertionError:
raise ValueError(
'units must be a scalar Quantity with unit magnitude, got %s'\
%value
)
return value

@@ -40,8 +39,7 @@ def validate_dimensionality(value):
return value.copy()
else:
raise TypeError(
'units must be a quantity, string, or dimensionality, got %s'\
%type(value)
)

def get_conversion_factor(from_u, to_u):
Expand Down Expand Up @@ -187,8 +185,7 @@ def units(self, units):
cf = get_conversion_factor(from_u, to_u)
except AssertionError:
raise ValueError(
'Unable to convert between units of "%s" and "%s"'
%(from_u._dimensionality, to_u._dimensionality)
)
mag = self.magnitude
mag *= cf
Expand All @@ -204,7 +201,7 @@ def rescale(self, units=None, dtype=None):
try:
return self.rescale_preferred()
except Exception as e:
raise Exception('No argument passed to `.rescale` and %s' % e)
to_dims = validate_dimensionality(units)
if dtype is None:
dtype = self.dtype
Expand All @@ -216,8 +213,7 @@ def rescale(self, units=None, dtype=None):
cf = get_conversion_factor(from_u, to_u)
except AssertionError:
raise ValueError(
'Unable to convert between units of "%s" and "%s"'
%(from_u._dimensionality, to_u._dimensionality)
)
new_magnitude = cf*self.magnitude
dtype = np.result_type(dtype, new_magnitude)
Expand Down Expand Up @@ -277,9 +273,9 @@ def __array_prepare__(self, obj, context=None):
res._dimensionality = p_dict[uf](*objs)
except KeyError:
raise ValueError(
"""ufunc %r not supported by quantities
please file a bug report at https://github.com/python-quantities
""" % uf
)
return res

Expand Down Expand Up @@ -367,17 +363,15 @@ def __round__(self, decimals=0):

@with_doc(np.ndarray.__repr__)
def __repr__(self):
return '%s * %s'%(
repr(self.magnitude), self.dimensionality.string
)

@with_doc(np.ndarray.__str__)
def __str__(self):
if markup.config.use_unicode:
dims = self.dimensionality.unicode
else:
dims = self.dimensionality.string
return '%s %s'%(str(self.magnitude), dims)

if tuple(map(int, np.__version__.split('.')[:2])) >= (1, 14):
# in numpy 1.14 the formatting of scalar values was changed
5 changes: 2 additions & 3 deletions quantities/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __getitem__(self, string):
except NameError:
# could return self['UnitQuantity'](string)
raise LookupError(
'Unable to parse units: "%s"'%string
)

def __setitem__(self, string, val):
Expand All @@ -32,8 +32,7 @@ def __setitem__(self, string, val):
if val == self.__context[string]:
return
raise KeyError(
'%s has already been registered for %s'
% (string, self.__context[string])
)
self.__context[string] = val

Expand Down
5 changes: 2 additions & 3 deletions quantities/tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def assertQuantityEqual(self, q1, q2, msg=None, delta=None):
precision.
"""
delta = 1e-5 if delta is None else delta
msg = '' if msg is None else ' (%s)' % msg

q1 = Quantity(q1)
q2 = Quantity(q2)
Expand All @@ -30,8 +30,7 @@ def assertQuantityEqual(self, q1, q2, msg=None, delta=None):
)
if not np.all(np.abs(q1.magnitude - q2.magnitude) < delta):
raise self.failureException(
"Magnitudes differ by more than %g (%s vs %s)%s"
% (delta, q1.magnitude, q2.magnitude, msg)
)

d1 = getattr(q1, '_dimensionality', None)
Expand Down
2 changes: 1 addition & 1 deletion quantities/tests/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def setunits(u, v):
u.units = v

def inplace(op, u, val):
getattr(u, '__i%s__'%op)(val)

self.assertRaises(AttributeError, setunits, pq.m, pq.ft)
self.assertRaises(TypeError, inplace, 'add', pq.m, pq.m)
Expand Down
6 changes: 2 additions & 4 deletions quantities/umath.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,7 @@ def arctan2(x1, x2, out=None):

if x1._dimensionality.simplified != x2._dimensionality.simplified:
raise ValueError(
'x1 and x2 must have identical units, got "%s" and "%s"'\
% (str(x1._dimensionality), str(x2._dimensionality))
)

return Quantity(
Expand All @@ -369,8 +368,7 @@ def hypot(x1, x2, out = None):

if x1._dimensionality != x2._dimensionality:
raise ValueError(
'x1 and x2 must have identical units, got "%s" and "%s"'\
% (str(x1._dimensionality), str(x2._dimensionality))
)

return Quantity(
Expand Down
6 changes: 1 addition & 5 deletions quantities/uncertainquantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,11 +184,7 @@ def __str__(self):
dims = self.dimensionality.unicode
else:
dims = self.dimensionality.string
s = '%s %s\n+/-%s (1 sigma)'%(
str(self.magnitude),
dims,
str(self.uncertainty)
)
if markup.config.use_unicode:
return s.replace('+/-', '±').replace(' sigma', 'σ')
return s
Expand Down
29 changes: 13 additions & 16 deletions quantities/unitquantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,12 @@ def __new__(
try:
assert isinstance(name, str)
except AssertionError:
raise TypeError('name must be a string, got %s (not unicode)'%name)
try:
assert symbol is None or isinstance(symbol, str)
except AssertionError:
raise TypeError(
'symbol must be a string, '
'got %s (u_symbol can be unicode)'%symbol
)

ret = numpy.array(1, dtype='d').view(cls)
Expand Up @@ -139,29 +138,27 @@ def units(self, units):
def __repr__(self):
ref = self._definition
if ref:
ref = ', %s * %s'%(str(ref.magnitude), ref.dimensionality.string)
else:
ref = ''
symbol = self._symbol
symbol = ', %s'%(repr(symbol)) if symbol else ''
if markup.config.use_unicode:
u_symbol = self._u_symbol
u_symbol = ', %s'%(repr(u_symbol)) if u_symbol else ''
else:
u_symbol = ''
return '%s(%s%s%s%s)'%(
self.__class__.__name__, repr(self.name), ref, symbol, u_symbol
)

@with_doc(Quantity.__str__, use_header=False)
def __str__(self):
if self.u_symbol != self.name:
if markup.config.use_unicode:
s = '1 %s (%s)'%(self.u_symbol, self.name)
else:
s = '1 %s (%s)'%(self.symbol, self.name)
else:
s = '1 %s'%self.name

return s

Expand Down Expand Up @@ -381,14 +378,14 @@ def __init__(self, name):

@with_doc(UnitQuantity.__add__, use_header=False)
def __repr__(self):
return '1 %s'%self.name

@property
def name(self):
if markup.config.use_unicode:
return '(%s)'%(markup.superscript(self._name))
else:
return '(%s)'%self._name

def __reduce__(self):
"""
Expand Up @@ -476,7 +473,7 @@ def set_default_units(
try:
assert system in ('si', 'cgs')
except AssertionError:
raise ValueError('system must be "SI" or "cgs", got "%s"' % system)
if system == 'si':
UnitCurrent.set_default_unit('A')
UnitLength.set_default_unit('m')
Expand Down
Toggle all file notes Toggle all file annotations