| 1 |
from asdf.extension import Converter |
| 2 |
|
| 3 |
from asdf_astropy.converters.utils import import_type |
| 4 |
|
| 5 |
|
| 6 |
class FrameConverter(Converter): |
| 7 |
def __init__(self, tags, frame_type_name): |
| 8 |
self._frame_type_name = frame_type_name |
| 9 |
self._frame_type = None |
| 10 |
|
| 11 |
if isinstance(tags, str): |
| 12 |
tags = [tags] |
| 13 |
self._tags = tags |
| 14 |
|
| 15 |
@property |
| 16 |
def tags(self): |
| 17 |
return self._tags |
| 18 |
|
| 19 |
@property |
| 20 |
def types(self): |
| 21 |
return [self._frame_type_name] |
| 22 |
|
| 23 |
@property |
| 24 |
def frame_type(self): |
| 25 |
# Delay import until the frame class is needed to improve speed |
| 26 |
# of loading the extension. |
| 27 |
if self._frame_type is None: |
| 28 |
self._frame_type = import_type(self._frame_type_name) |
| 29 |
return self._frame_type |
| 30 |
|
| 31 |
def to_yaml_tree(self, obj, tag, ctx): |
| 32 |
node = {} |
| 33 |
|
| 34 |
if obj.has_data: |
| 35 |
node["data"] = obj.data |
| 36 |
|
| 37 |
# TODO: Figure out why we can't use the frame_attributes |
| 38 |
# values and document. |
| 39 |
frame_attributes = {} |
| 40 |
for attr in obj.frame_attributes: |
| 41 |
value = getattr(obj, attr, None) |
| 42 |
if value is not None: |
| 43 |
frame_attributes[attr] = value |
| 44 |
node["frame_attributes"] = frame_attributes |
| 45 |
|
| 46 |
return node |
| 47 |
|
| 48 |
def from_yaml_tree(self, node, tag, ctx): |
| 49 |
data = node.get("data", None) |
| 50 |
if data is not None: |
| 51 |
return self.frame_type(node["data"], **node["frame_attributes"]) |
| 52 |
|
| 53 |
return self.frame_type(**node["frame_attributes"]) |
| 54 |
|
| 55 |
|
| 56 |
class LegacyICRSConverter(Converter): |
| 57 |
tags = ("tag:astropy.org:astropy/coordinates/frames/icrs-1.0.0",) |
| 58 |
# Leave the types list empty so that the 1.1.0 ICRS converter |
| 59 |
# is used on write. |
| 60 |
types = () |
| 61 |
|
| 62 |
def to_yaml_tree(self, obj, tag, ctx): |
| 63 |
from astropy.units import Quantity |
| 64 |
|
| 65 |
return { |
| 66 |
"ra": { |
| 67 |
"value": obj.ra.value, |
| 68 |
"unit": obj.ra.unit.to_string(), |
| 69 |
"wrap_angle": Quantity(obj.ra.wrap_angle), |
| 70 |
}, |
| 71 |
"dec": { |
| 72 |
"value": obj.dec.value, |
| 73 |
"unit": obj.dec.unit.to_string(), |
| 74 |
}, |
| 75 |
} |
| 76 |
|
| 77 |
def from_yaml_tree(self, node, tag, ctx): |
| 78 |
from astropy.coordinates import ICRS, Angle, Latitude, Longitude |
| 79 |
|
| 80 |
ra = Longitude(node["ra"]["value"], unit=node["ra"]["unit"], wrap_angle=Angle(node["ra"]["wrap_angle"])) |
| 81 |
|
| 82 |
dec = Latitude(node["dec"]["value"], unit=node["dec"]["unit"]) |
| 83 |
|
| 84 |
return ICRS(ra=ra, dec=dec) |