| 1 |
from asdf.extension import Converter |
| 2 |
|
| 3 |
from asdf_astropy.exceptions import InconsistentWCSError |
| 4 |
|
| 5 |
# These attributes don't end up in the hdulist and |
| 6 |
# instead will be stored in "attrs" |
| 7 |
_WCS_ATTRS = ("naxis", "colsel", "keysel", "key", "pixel_bounds", "pixel_shape") |
| 8 |
|
| 9 |
|
| 10 |
class WCSConverter(Converter): |
| 11 |
tags = ("tag:astropy.org:astropy/wcs/wcs-*",) |
| 12 |
types = ("astropy.wcs.wcs.WCS",) |
| 13 |
|
| 14 |
def from_yaml_tree(self, node, tag, ctx): |
| 15 |
from astropy.wcs import WCS |
| 16 |
|
| 17 |
hdulist = node["hdulist"] |
| 18 |
attrs = node["attrs"] |
| 19 |
|
| 20 |
if naxis := attrs.pop("naxis"): |
| 21 |
hdulist[0].header["naxis"] = naxis |
| 22 |
|
| 23 |
# pop attrs that are not valid kwargs |
| 24 |
pixel_shape = attrs.pop("pixel_shape") |
| 25 |
pixel_bounds = attrs.pop("pixel_bounds") |
| 26 |
|
| 27 |
wcs = WCS(hdulist[0].header, fobj=hdulist, **attrs) |
| 28 |
|
| 29 |
wcs.pixel_shape = pixel_shape |
| 30 |
wcs.pixel_bounds = pixel_bounds |
| 31 |
|
| 32 |
if wcs.sip is not None: |
| 33 |
# work around a bug in astropy where sip headers lose precision |
| 34 |
# see https://github.com/astropy/astropy/issues/17334 |
| 35 |
wcs.sip = wcs._read_sip_kw(hdulist[0].header, attrs.get("key", " ")) |
| 36 |
wcs.wcs.set() |
| 37 |
|
| 38 |
return wcs |
| 39 |
|
| 40 |
def to_yaml_tree(self, wcs, tag, ctx): |
| 41 |
# Check that wcs is consistent. Astropy inconsistently checks |
| 42 |
# that certain expected attributes match. We need to check this |
| 43 |
# here to prevent writing inconsistent files that would be problematic |
| 44 |
# to open. |
| 45 |
if naxis := wcs.naxis: |
| 46 |
for attr in ("pixel_shape", "pixel_bounds"): |
| 47 |
if value := getattr(wcs, attr): |
| 48 |
if len(value) != naxis: |
| 49 |
msg = f"{attr} shape ({len(value)}) does not match naxis ({naxis})" |
| 50 |
raise InconsistentWCSError(msg) |
| 51 |
hdulist = wcs.to_fits(relax=True) |
| 52 |
attrs = {a: getattr(wcs, a) for a in _WCS_ATTRS if hasattr(wcs, a)} |
| 53 |
return {"hdulist": hdulist, "attrs": attrs} |