Skip to content

Commit a155850

Browse files
committed
Define SpecificTypeQuantity and use it for Angle, Distance.
1 parent d3f65ac commit a155850

5 files changed

Lines changed: 136 additions & 74 deletions

File tree

‎astropy/coordinates/angles.py‎

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
signed_dms_tuple = namedtuple('signed_dms_tuple', ('sign', 'd', 'm', 's'))
3131

3232

33-
class Angle(u.Quantity):
33+
class Angle(u.SpecificTypeQuantity):
3434
"""
3535
One or more angular value(s) with units equivalent to radians or degrees.
3636
@@ -83,6 +83,7 @@ class Angle(u.Quantity):
8383
`~astropy.units.UnitsError`
8484
If a unit is not provided or it is not an angular unit.
8585
"""
86+
_equivalent_unit = u.radian
8687
_include_easy_conversion_members = True
8788

8889
def __new__(cls, angle, unit=None, dtype=None, copy=True):
@@ -111,21 +112,9 @@ def __new__(cls, angle, unit=None, dtype=None, copy=True):
111112
angle.dtype.kind not in 'SUVO')):
112113
angle = [Angle(x, unit, copy=False) for x in angle]
113114

114-
self = super(Angle, cls).__new__(cls, angle, unit, dtype=dtype,
115+
return super(Angle, cls).__new__(cls, angle, unit, dtype=dtype,
115116
copy=copy)
116117

117-
if not isinstance(angle, Angle):
118-
self._unit = cls._convert_unit_to_angle_unit(self.unit)
119-
if not self.unit.is_equivalent(u.radian):
120-
if self.unit is u.dimensionless_unscaled:
121-
raise u.UnitsError("No unit was given - "
122-
"must be some kind of angle")
123-
else:
124-
raise u.UnitsError("Unit {0} is not an angle"
125-
.format(self.unit))
126-
127-
return self
128-
129118
@staticmethod
130119
def _tuple_to_float(angle, unit):
131120
"""
@@ -140,16 +129,12 @@ def _tuple_to_float(angle, unit):
140129
else:
141130
raise u.UnitsError("Can not parse '{0}' as unit '{1}'"
142131
.format(angle, unit))
143-
144132
@staticmethod
145133
def _convert_unit_to_angle_unit(unit):
146134
return u.hourangle if unit is u.hour else unit
147135

148-
def __quantity_subclass__(self, unit):
149-
if unit.is_equivalent(u.radian):
150-
return Angle, True
151-
else:
152-
return super(Angle, self).__quantity_subclass__(unit)[0], False
136+
def _set_unit(self, unit):
137+
super(Angle, self)._set_unit(self._convert_unit_to_angle_unit(unit))
153138

154139
@property
155140
def hour(self):
@@ -258,8 +243,7 @@ def to_string(self, unit=None, decimal=False, sep='fromunit',
258243
if unit is None:
259244
unit = self.unit
260245
else:
261-
unit = u.Unit(unit)
262-
unit = self._convert_unit_to_angle_unit(unit)
246+
unit = self._convert_unit_to_angle_unit(u.Unit(unit))
263247

264248
separators = {
265249
None: {

‎astropy/coordinates/distances.py‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
__doctest_requires__ = {'*': ['scipy.integrate']}
1818

1919

20-
class Distance(u.Quantity):
20+
class Distance(u.SpecificTypeQuantity):
2121
"""
2222
A one-dimensional distance.
2323
@@ -87,6 +87,7 @@ class Distance(u.Quantity):
8787
>>> d7 = Distance(Distance(10 * u.Mpc))
8888
"""
8989

90+
_equivalent_unit = u.m
9091
_include_easy_conversion_members = True
9192

9293
def __new__(cls, value=None, unit=None, z=None, cosmology=None,
@@ -144,21 +145,12 @@ def __new__(cls, value=None, unit=None, z=None, cosmology=None,
144145
cls, value, unit, dtype=dtype, copy=copy, order=order,
145146
subok=subok, ndmin=ndmin)
146147

147-
if not distance.unit.is_equivalent(u.m):
148-
raise u.UnitsError('Unit "{0}" is not a length type'.format(unit))
149-
150148
if not allow_negative and np.any(distance.value < 0):
151149
raise ValueError("Distance must be >= 0. Use the argument "
152150
"'allow_negative=True' to allow negative values.")
153151

154152
return distance
155153

156-
def __quantity_subclass__(self, unit):
157-
if unit.is_equivalent(u.m):
158-
return Distance, True
159-
else:
160-
return super(Distance, self).__quantity_subclass__(unit)[0], False
161-
162154
@property
163155
def z(self):
164156
"""Short for ``self.compute_z()``"""

‎astropy/coordinates/tests/test_angles.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,19 @@ def test_create_angles():
119119

120120
assert a1 is not None
121121

122+
123+
def test_angle_from_view():
124+
q = np.arange(3.) * u.deg
125+
a = q.view(Angle)
126+
assert type(a) is Angle
127+
assert a.unit is q.unit
128+
assert np.all(a == q)
129+
130+
q2 = np.arange(4) * u.m
131+
with pytest.raises(u.UnitTypeError):
132+
q2.view(Angle)
133+
134+
122135
def test_angle_ops():
123136
"""
124137
Tests operations on Angle objects
@@ -162,6 +175,9 @@ def test_angle_ops():
162175
with pytest.raises(TypeError):
163176
a6 *= a5
164177

178+
with pytest.raises(TypeError):
179+
a6 *= u.m
180+
165181
with pytest.raises(TypeError):
166182
np.sin(a6, out=a6)
167183

‎astropy/units/core.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@
2727
# TODO: Support function units, e.g. log(x), ln(x)
2828

2929
__all__ = [
30-
'UnitsError', 'UnitsWarning', 'UnitConversionError', 'UnitBase',
31-
'NamedUnit', 'IrreducibleUnit', 'Unit', 'def_unit', 'CompositeUnit',
32-
'PrefixUnit', 'UnrecognizedUnit', 'get_current_unit_registry',
30+
'UnitsError', 'UnitsWarning', 'UnitConversionError', 'UnitTypeError',
31+
'UnitBase', 'NamedUnit', 'IrreducibleUnit', 'Unit', 'CompositeUnit',
32+
'PrefixUnit', 'UnrecognizedUnit', 'def_unit', 'get_current_unit_registry',
3333
'set_enabled_units', 'add_enabled_units',
3434
'set_enabled_equivalencies', 'add_enabled_equivalencies',
3535
'dimensionless_unscaled', 'one']
@@ -461,6 +461,11 @@ class UnitConversionError(UnitsError, ValueError):
461461
interpreting units in terms of other units.
462462
"""
463463

464+
class UnitTypeError(UnitsError, TypeError):
465+
"""
466+
Used specifically for errors in setting to units not allowed by a class.
467+
"""
468+
464469

465470
class UnitsWarning(AstropyWarning):
466471
"""

0 commit comments

Comments
 (0)