Skip to content

Commit 32e9468

Browse files
committed
Make frame representation_attrs completely dynamic
In order to remove boilerplate code in defining frames, a new fully dynamic system for getting the representation attribute names and units (ra, dec, etc) was added. This relies on - Global registry of representations (REPRESENTATION_CLASSES) - _default_names and _default_units therein - _representation_attrs defined in the frame class The latter now only has to specify what is different from the defaults defined in the representations. With this change now every frame automatically has every representation available for display or initialization.
1 parent 13cdcae commit 32e9468

4 files changed

Lines changed: 63 additions & 73 deletions

File tree

‎astropy/coordinates/baseframe.py‎

Lines changed: 49 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,19 @@
99
# Standard library
1010
import inspect
1111
import warnings
12+
from copy import deepcopy
1213

1314
# Dependencies
1415

1516
# Project
1617
from ..extern import six
1718
from ..utils.exceptions import AstropyDeprecationWarning
1819
from .. import units as u
20+
from ..utils import OrderedDict
1921
from .transformations import TransformGraph
20-
from .representation import BaseRepresentation, CartesianRepresentation, \
21-
SphericalRepresentation, UnitSphericalRepresentation
22+
from .representation import (BaseRepresentation, CartesianRepresentation,
23+
SphericalRepresentation, UnitSphericalRepresentation,
24+
REPRESENTATION_CLASSES)
2225

2326
__all__ = ['BaseCoordinateFrame', 'frame_transform_graph', 'GenericFrame']
2427

@@ -110,13 +113,49 @@ def representation(self, value):
110113
# In reality do validation of `value` and allow string input
111114
self._representation = value
112115

116+
@classmethod
117+
def _get_representation_attrs(cls):
118+
# This exists as a class method only to support handling frame inputs
119+
# without units, which are deprecated and will be removed. This can be
120+
# moved into the property at that time.
121+
repr_attrs = {}
122+
for name, repr_cls in REPRESENTATION_CLASSES.items():
123+
if hasattr(repr_cls, '_default_names') and hasattr(repr_cls, '_default_units'):
124+
repr_attrs[name] = {'names': repr_cls._default_names,
125+
'units': repr_cls._default_units}
126+
127+
# Override defaults as needed for this frame
128+
repr_attrs.update(getattr(cls, '_representation_attrs', {}))
129+
130+
# Use the class, not the name for the key in representation_attrs
131+
repr_attrs = dict((REPRESENTATION_CLASSES[name], attrs)
132+
for name, attrs in repr_attrs.items())
133+
134+
return deepcopy(repr_attrs) # Don't let upstream mess with frame internals
135+
136+
@property
137+
def representation_attrs(self):
138+
return self._get_representation_attrs()
139+
113140
@property
114141
def representation_names(self):
115-
return self.representation_attrs[self.representation]['names']
142+
data_names = self.representation._attr_classes.keys()
143+
repr_names = self.representation_attrs[self.representation]['names']
144+
out = OrderedDict()
145+
for repr_name, data_name in zip(repr_names, data_names):
146+
out[repr_name] = data_name
147+
return out
116148

117149
@property
118150
def representation_units(self):
119-
return self.representation_attrs[self.representation]['units']
151+
repr_attrs = self.representation_attrs[self.representation]
152+
repr_names = repr_attrs['names']
153+
repr_units = repr_attrs['units']
154+
out = OrderedDict()
155+
for repr_name, repr_unit in zip(repr_names, repr_units):
156+
if repr_unit:
157+
out[repr_name] = repr_unit
158+
return out
120159

121160
_representation = None
122161

@@ -160,7 +199,7 @@ def __new__(cls, *args, **kwargs):
160199

161200
if not use_skycoord:
162201
representation = kwargs.get('representation') or cls._representation
163-
for key in cls.representation_attrs[representation]['names']:
202+
for key in cls._get_representation_attrs()[representation]['names']:
164203
if key in kwargs:
165204
if not isinstance(kwargs[key], u.Quantity):
166205
warnings.warn("Initializing frames using non-Quantity "
@@ -340,29 +379,11 @@ def represent_as(self, new_representation, in_frame_units=False):
340379
# set of names and units, then use that.
341380
new_attrs = self.representation_attrs.get(new_representation)
342381
if new_attrs and in_frame_units:
343-
new_attr_names = new_attrs['names']
344-
new_attr_units = new_attrs['units']
345-
346-
# if necessary, make a new representation with new_attr_units
347-
if new_attr_units:
348-
# first figure out how to map *representation* attribute
349-
# names to units
350-
comp_to_unit = {}
351-
for attnm, unit in new_attr_units.items():
352-
if attnm not in new_attr_names:
353-
msg = ('The attribute {0} in `representation_units`'
354-
' is not in `representation_names`')
355-
raise ValueError(msg.format(attnm))
356-
comp_to_unit[new_attr_names[attnm]] = unit
357-
358-
# Now actually create a new representation with the new units
359-
datakwargs = {}
360-
for comp in data.components:
361-
datakwargs[comp] = getattr(data, comp)
362-
newu = comp_to_unit.get(comp, None)
363-
if newu:
364-
datakwargs[comp] = datakwargs[comp].to(newu)
365-
data = data.__class__(**datakwargs)
382+
datakwargs = dict((comp, getattr(data, comp)) for comp in data.components)
383+
for comp, new_attr_unit in zip(data.components, new_attrs['units']):
384+
if new_attr_unit:
385+
datakwargs[comp] = datakwargs[comp].to(new_attr_unit)
386+
data = data.__class__(**datakwargs)
366387

367388
self._rep_cache[new_representation.__name__, in_frame_units] = data
368389

‎astropy/coordinates/builtin_frames.py‎

Lines changed: 9 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,6 @@ class ICRS(BaseCoordinateFrame):
5656
The Distance for this object along the line-of-sight.
5757
(``representation`` must be None).
5858
"""
59-
representation_attrs = dict(
60-
[SphericalRepresentation.attr_dict(('ra', 'dec', 'distance'), (u.deg, u.deg, None)),
61-
UnitSphericalRepresentation.attr_dict(('ra', 'dec'), (u.deg, u.deg)),
62-
CartesianRepresentation.attr_dict(('x', 'y', 'z'), (None, None, None))])
63-
6459
_representation = SphericalRepresentation
6560

6661
frame_attr_names = {} # not necessary if empty, but this makes it clearer
@@ -108,13 +103,7 @@ class FK5(BaseCoordinateFrame):
108103
The equinox of this frame.
109104
"""
110105

111-
representation_attrs = dict(
112-
[SphericalRepresentation.attr_dict(('ra', 'dec', 'distance'), (u.deg, u.deg, None)),
113-
UnitSphericalRepresentation.attr_dict(('ra', 'dec'), (u.deg, u.deg)),
114-
CartesianRepresentation.attr_dict(('x', 'y', 'z'), (None, None, None))])
115-
116106
_representation = SphericalRepresentation
117-
118107
frame_attr_names = {'equinox': _EQUINOX_J2000}
119108

120109
@staticmethod
@@ -170,13 +159,7 @@ class FK4(BaseCoordinateFrame):
170159
``equinox``.
171160
"""
172161

173-
representation_attrs = dict(
174-
[SphericalRepresentation.attr_dict(('ra', 'dec', 'distance'), (u.deg, u.deg, None)),
175-
UnitSphericalRepresentation.attr_dict(('ra', 'dec'), (u.deg, u.deg)),
176-
CartesianRepresentation.attr_dict(('x', 'y', 'z'), (None, None, None))])
177-
178162
_representation = SphericalRepresentation
179-
180163
frame_attr_names = {'equinox': _EQUINOX_B1950, 'obstime': None}
181164

182165
@property
@@ -219,13 +202,7 @@ class FK4NoETerms(BaseCoordinateFrame):
219202
``equinox``.
220203
"""
221204

222-
representation_attrs = dict(
223-
[SphericalRepresentation.attr_dict(('ra', 'dec', 'distance'), (u.deg, u.deg, None)),
224-
UnitSphericalRepresentation.attr_dict(('ra', 'dec'), (u.deg, u.deg)),
225-
CartesianRepresentation.attr_dict(('x', 'y', 'z'), (None, None, None))])
226-
227205
_representation = SphericalRepresentation
228-
229206
frame_attr_names = {'equinox': _EQUINOX_B1950, 'obstime': None}
230207

231208
@property
@@ -291,13 +268,12 @@ class Galactic(BaseCoordinateFrame):
291268
The Distance for this object along the line-of-sight.
292269
"""
293270

294-
representation_attrs = dict(
295-
[SphericalRepresentation.attr_dict(('l', 'b', 'distance'), (u.deg, u.deg, None)),
296-
UnitSphericalRepresentation.attr_dict(('l', 'b'), (u.deg, u.deg)),
297-
CartesianRepresentation.attr_dict(('x', 'y', 'z'), (None, None, None))])
298-
271+
_representation_attrs = {
272+
'spherical': {'names': ('l', 'b', 'distance'), 'units': (u.deg, u.deg, None)},
273+
'unitspherical': {'names': ('l', 'b'), 'units': (u.deg, u.deg)},
274+
'cartesian': {'names': ('w', 'u', 'v'), 'units': (None, None, None)}
275+
}
299276
_representation = SphericalRepresentation
300-
301277
frame_attr_names = {}
302278

303279
# North galactic pole and zeropoint of l in FK4/FK5 coordinates. Needed for
@@ -334,13 +310,11 @@ class AltAz(BaseCoordinateFrame):
334310
distance : :class:`~astropy.units.Quantity`, optional, must be keyword
335311
The Distance for this object along the line-of-sight.
336312
"""
337-
representation_attrs = dict(
338-
[SphericalRepresentation.attr_dict(('az', 'alt', 'distance'), (u.deg, u.deg, None)),
339-
UnitSphericalRepresentation.attr_dict(('az', 'alt'), (u.deg, u.deg)),
340-
CartesianRepresentation.attr_dict(('x', 'y', 'z'), (None, None, None))])
341-
313+
_representation_attrs = {
314+
'spherical': {'names': ('az', 'alt', 'distance'), 'units': (u.deg, u.deg, None)},
315+
'unitspherical': {'names': ('az', 'alt'), 'units': (u.deg, u.deg)}
316+
}
342317
_representation = SphericalRepresentation
343-
344318
frame_attr_names = {'obstime': None, 'location': None}
345319

346320
def __init__(self, *args, **kwargs):
@@ -363,14 +337,7 @@ class NoFrame(BaseCoordinateFrame):
363337
public API.
364338
365339
"""
366-
367-
representation_attrs = dict(
368-
[SphericalRepresentation.attr_dict(('ra', 'dec', 'distance'), (u.deg, u.deg, None)),
369-
UnitSphericalRepresentation.attr_dict(('ra', 'dec'), (u.deg, u.deg)),
370-
CartesianRepresentation.attr_dict(('x', 'y', 'z'), (None, None, None))])
371-
372340
_representation = SphericalRepresentation
373-
374341
frame_attr_names = {}
375342

376343

‎astropy/coordinates/tests/test_frames.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,10 @@ def test_converting_units():
119119

120120
#but that *shouldn't* hold if we turn off units for the representation
121121
class FakeICRS(ICRS):
122-
representation_attrs = dict(
123-
[SphericalRepresentation.attr_dict(('ra', 'dec', 'distance'), (None, None, None))])
122+
_representation_attrs = {'spherical': {'names': ('ra', 'dec', 'distance'),
123+
'units': (None, None, None)},
124+
'unitspherical': {'names': ('ra', 'dec'),
125+
'units': (None, None)}}
124126

125127

126128
fi = FakeICRS(i4.data)

‎docs/coordinates/skycoord.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ and |SkyCoord| (aka high-level class)::
351351
>>> sc.frame
352352
<ICRS Coordinate: ra=1.0 deg, dec=2.0 deg>
353353

354-
>>> sc.representation_units is sc.frame.representation_units
354+
>>> sc.has_data is sc.frame.has_data
355355
True
356356

357357
>>> sc.frame.<TAB> # doctest: +SKIP

0 commit comments

Comments
 (0)