| 1 |
from asdf.extension import Converter |
| 2 |
from asdf.tags.core.ndarray import NDArrayType |
| 3 |
|
| 4 |
|
| 5 |
def _card_to_node(card): |
| 6 |
from astropy.io.fits import Undefined |
| 7 |
|
| 8 |
value = "" if isinstance(card.value, Undefined) else card.value |
| 9 |
|
| 10 |
if card.comment: |
| 11 |
return [card.keyword, value, card.comment] |
| 12 |
|
| 13 |
if value: |
| 14 |
return [card.keyword, value] |
| 15 |
|
| 16 |
if card.keyword: |
| 17 |
return [card.keyword] |
| 18 |
|
| 19 |
return [] |
| 20 |
|
| 21 |
|
| 22 |
class FitsConverter(Converter): |
| 23 |
def to_yaml_tree(self, obj, tag, ctx): |
| 24 |
from astropy.table import Table |
| 25 |
|
| 26 |
node = [] |
| 27 |
for hdu in obj: |
| 28 |
header_node = [_card_to_node(c) for c in hdu.header.cards] |
| 29 |
hdu_node = {"header": header_node} |
| 30 |
|
| 31 |
if hdu.data is not None: |
| 32 |
if hdu.data.dtype.names is not None: |
| 33 |
hdu_node["data"] = Table(hdu.data) |
| 34 |
else: |
| 35 |
hdu_node["data"] = hdu.data |
| 36 |
|
| 37 |
node.append(hdu_node) |
| 38 |
|
| 39 |
return node |
| 40 |
|
| 41 |
def from_yaml_tree(self, node, tag, ctx): |
| 42 |
from astropy.io import fits |
| 43 |
|
| 44 |
hdus = [] |
| 45 |
first = True |
| 46 |
for hdu_node in node: |
| 47 |
header = fits.Header([fits.Card(*x) for x in hdu_node["header"]]) |
| 48 |
|
| 49 |
data = hdu_node.get("data") |
| 50 |
if isinstance(data, NDArrayType): |
| 51 |
# TODO: Why doesn't NDArrayType work? This needs some research |
| 52 |
# and documentation. |
| 53 |
data = data._make_array() |
| 54 |
|
| 55 |
if first: |
| 56 |
hdu = fits.PrimaryHDU(data=data, header=header) |
| 57 |
first = False |
| 58 |
elif data.dtype.names is not None: |
| 59 |
hdu = fits.BinTableHDU(data=data, header=header) |
| 60 |
else: |
| 61 |
hdu = fits.ImageHDU(data=data, header=header) |
| 62 |
|
| 63 |
hdus.append(hdu) |
| 64 |
|
| 65 |
return fits.HDUList(hdus) |
| 66 |
|
| 67 |
|
| 68 |
class AsdfFitsConverter(FitsConverter): |
| 69 |
tags = ("tag:stsci.edu:asdf/fits/fits-*",) |
| 70 |
types = () |
| 71 |
|
| 72 |
|
| 73 |
class AstropyFitsConverter(FitsConverter): |
| 74 |
tags = ("tag:astropy.org:astropy/fits/fits-*",) |
| 75 |
types = ("astropy.io.fits.hdu.hdulist.HDUList",) |