| 1 |
""" |
| 2 |
Writing data in FITS binary tables |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import os |
| 12 |
import tempfile |
| 13 |
import time |
| 14 |
|
| 15 |
import numpy |
| 16 |
|
| 17 |
from gavo import base |
| 18 |
from gavo import rsc |
| 19 |
from gavo import utils |
| 20 |
from gavo.formats import common |
| 21 |
from gavo.utils import pyfits |
| 22 |
from gavo.votable import common as votcommon |
| 23 |
|
| 24 |
|
| 25 |
_fitsCodeMap = { |
| 26 |
"short": "I", |
| 27 |
"int": "J", |
| 28 |
"long": "K", |
| 29 |
"float": "E", |
| 30 |
"double": "D", |
| 31 |
"boolean": "L", |
| 32 |
"char": "A", |
| 33 |
"unicodeChar": "A", |
| 34 |
} |
| 35 |
|
| 36 |
_typeConstructors = { |
| 37 |
"short": int, |
| 38 |
"int": int, |
| 39 |
"long": int, |
| 40 |
"float": float, |
| 41 |
"double": float, |
| 42 |
"boolean": int, |
| 43 |
"char": str, |
| 44 |
"unicodeChar": str, |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
def _makeCharArray(values, colInd, colDesc): |
| 49 |
"""returns a pyfits-capable column array for strings stored in the |
| 50 |
colInd-th column of values. |
| 51 |
|
| 52 |
This is for char-valued columns, i.e., ASCII-only. |
| 53 |
""" |
| 54 |
arr = numpy.array([(v[colInd] or "").encode("ascii", "replace") |
| 55 |
for v in values], |
| 56 |
dtype=numpy.bytes_) |
| 57 |
return "%dA"%arr.itemsize, arr |
| 58 |
|
| 59 |
|
| 60 |
def _makeStringArray(values, colInd, colDesc): |
| 61 |
"""returns a pyfits-capable column array for strings stored in the |
| 62 |
colInd-th column of values. |
| 63 |
|
| 64 |
This is for unicodeChar-valued columns; we'd like to do something |
| 65 |
sensible with them; this implementation is FIXME, because we're |
| 66 |
essentially discaring all non-ASCII and write a normal char column. |
| 67 |
""" |
| 68 |
# Yeah, right now this is identical to _makeCharArray, but that's FIXME. |
| 69 |
arr = numpy.array([(v[colInd] or "").encode("ascii", "replace") |
| 70 |
for v in values], |
| 71 |
dtype=numpy.bytes_) |
| 72 |
return "%dA"%arr.itemsize, arr |
| 73 |
|
| 74 |
|
| 75 |
def _getNullValue(colDesc): |
| 76 |
"""returns a null value we consider ok for a column described by colDesc. |
| 77 |
|
| 78 |
This is mainly intended for array serialisation. It is also |
| 79 |
used for column construction for integer types. |
| 80 |
""" |
| 81 |
length = votcommon.getLength(colDesc["arraysize"]) |
| 82 |
if length and length>1: |
| 83 |
# TODO: figure out nullvalue interpretation in FITS arrays. |
| 84 |
return None |
| 85 |
|
| 86 |
nullValue = colDesc["nullvalue"] |
| 87 |
if nullValue is None: |
| 88 |
# enter some reasonable defaults |
| 89 |
if (colDesc["datatype"]=="float" |
| 90 |
or colDesc["datatype"]=="double"): |
| 91 |
nullValue = float("NaN") |
| 92 |
|
| 93 |
elif colDesc["datatype"]=="text": |
| 94 |
nullValue = "" |
| 95 |
|
| 96 |
else: |
| 97 |
nullValue = _typeConstructors[colDesc["datatype"]](nullValue) |
| 98 |
|
| 99 |
return nullValue |
| 100 |
|
| 101 |
|
| 102 |
def _computeTypeCode(colDesc): |
| 103 |
"""returns a FITS type code suitable for colDesc. |
| 104 |
""" |
| 105 |
baseCode = _fitsCodeMap[colDesc["datatype"]] |
| 106 |
length = votcommon.getLength(colDesc["arraysize"]) |
| 107 |
|
| 108 |
if length==1: |
| 109 |
return length, baseCode |
| 110 |
|
| 111 |
elif length is None: |
| 112 |
# a variable-length array (other than a string). We, in particular, |
| 113 |
# need this for polygons. |
| 114 |
return length, "P%s()"%(baseCode) |
| 115 |
|
| 116 |
else: |
| 117 |
return length, "%d%s"%(length, baseCode) |
| 118 |
|
| 119 |
|
| 120 |
def _makeValueArray(values, colInd, colDesc): |
| 121 |
"""returns a pyfits-capable column array for non-string values |
| 122 |
stored in the colInd-th column of values. |
| 123 |
""" |
| 124 |
length, typecode = _computeTypeCode(colDesc) |
| 125 |
nan = float("NaN") |
| 126 |
|
| 127 |
if length is None: |
| 128 |
# That's a variable-length array that we'll fill from a |
| 129 |
# numpy object array |
| 130 |
return typecode, numpy.array([list(v[colInd]) for v in values], |
| 131 |
dtype=numpy.object) |
| 132 |
|
| 133 |
elif length>1: |
| 134 |
# numpy 1:1.12.1-3 and pyfits from astropy 1.3-8 apparently |
| 135 |
# have trouble with masked arrays here, so we exploit |
| 136 |
# that in the VO and for floats NaN and NULL is treated equivalently. |
| 137 |
nullArray = numpy.array([nan]*length) |
| 138 |
def mkval(v): |
| 139 |
if v is None: |
| 140 |
return nullArray |
| 141 |
else: |
| 142 |
return numpy.array(v) |
| 143 |
|
| 144 |
else: |
| 145 |
def mkval(v, nullValue=_getNullValue(colDesc)): |
| 146 |
if v is None: |
| 147 |
if nullValue is None: |
| 148 |
raise ValueError("While serializing a FITS table: NULL" |
| 149 |
" detected in column '%s' but no null value declared"% |
| 150 |
colDesc["name"]) |
| 151 |
return nullValue |
| 152 |
else: |
| 153 |
return v |
| 154 |
|
| 155 |
arr = numpy.array([mkval(v[colInd]) for v in values]) |
| 156 |
return typecode, arr |
| 157 |
|
| 158 |
|
| 159 |
def _makeExtension(serMan): |
| 160 |
"""returns a pyfits hdu for the valuemappers.SerManager instance table. |
| 161 |
""" |
| 162 |
values = list(serMan.getMappedTuples()) |
| 163 |
columns = [] |
| 164 |
utypes = [] |
| 165 |
descriptions = [] |
| 166 |
|
| 167 |
for colInd, colDesc in enumerate(serMan): |
| 168 |
descriptions.append(utils.defuseFileName(colDesc["description"], False)) |
| 169 |
if colDesc["datatype"]=="char": |
| 170 |
makeArray = _makeCharArray |
| 171 |
elif colDesc["datatype"]=="unicodeChar": |
| 172 |
makeArray = _makeStringArray |
| 173 |
else: |
| 174 |
makeArray = _makeValueArray |
| 175 |
|
| 176 |
typecode, arr = makeArray(values, colInd, colDesc) |
| 177 |
# only pass on null values to integral types; FITS doesn't support |
| 178 |
# anything else, and I'll just leave Nones in non-integral columns |
| 179 |
# to astropy.io.fits -- with all the mess involved, in particular |
| 180 |
# that \0 and NULL or NaN and NULL can't be told apart in FITS. |
| 181 |
nullValue = None |
| 182 |
if typecode in 'BIJK': |
| 183 |
nullValue = _getNullValue(colDesc) |
| 184 |
|
| 185 |
columns.append(pyfits.Column(name=str(colDesc["name"]), |
| 186 |
unit=str(colDesc["unit"]), format=typecode, |
| 187 |
null=nullValue, array=arr)) |
| 188 |
if colDesc["utype"]: |
| 189 |
utypes.append((colInd, str(colDesc["utype"].lower()))) |
| 190 |
|
| 191 |
hdu = pyfits.BinTableHDU.from_columns( |
| 192 |
pyfits.ColDefs(columns)) |
| 193 |
for colInd, utype in utypes: |
| 194 |
hdu.header.set("TUTYP%d"%(colInd+1), utype) |
| 195 |
|
| 196 |
cards = hdu.header.cards |
| 197 |
for colInd, desc in enumerate(descriptions): |
| 198 |
cards["TTYPE%d"%(colInd+1)].comment = desc |
| 199 |
hdu.header.set("TCOMM%d"%(colInd+1), desc) |
| 200 |
|
| 201 |
if not hasattr(serMan.table, "IgnoreTableParams"): |
| 202 |
for param in serMan.table.iterParams(): |
| 203 |
if param.value is None: |
| 204 |
continue |
| 205 |
|
| 206 |
key, value, comment = str(param.name), param.value, param.description |
| 207 |
if isinstance(value, str): |
| 208 |
value = utils.defuseFileName(value, False) |
| 209 |
if isinstance(comment, str): |
| 210 |
comment = utils.defuseFileName(comment, False) |
| 211 |
if len(key)>8: |
| 212 |
key = "hierarch "+key |
| 213 |
|
| 214 |
try: |
| 215 |
hdu.header.set(key, value=value, comment=comment) |
| 216 |
except ValueError as ex: |
| 217 |
# do not fail just because some header couldn't be serialised |
| 218 |
base.ui.notifyWarning( |
| 219 |
"Failed to serialise param %s to a FITS header (%s)"%( |
| 220 |
param.name, |
| 221 |
utils.safe_str(ex))) |
| 222 |
|
| 223 |
return hdu |
| 224 |
|
| 225 |
|
| 226 |
def _makeFITSTableNOLOCK(dataSet, acquireSamples=True): |
| 227 |
"""returns a hdulist containing extensions for the tables in dataSet. |
| 228 |
|
| 229 |
You must make sure that this function is only executed once |
| 230 |
since pyfits is not thread-safe. |
| 231 |
""" |
| 232 |
tables = [base.SerManager(table, acquireSamples=acquireSamples) |
| 233 |
for table in list(dataSet.tables.values())] |
| 234 |
extensions = [_makeExtension(table) for table in tables] |
| 235 |
primary = pyfits.PrimaryHDU() |
| 236 |
primary.header.set("DATE", time.strftime("%Y-%m-%d"), |
| 237 |
"Date file was written") |
| 238 |
return pyfits.HDUList([primary]+extensions) |
| 239 |
|
| 240 |
|
| 241 |
def makeFITSTable(dataSet, acquireSamples=False): |
| 242 |
"""returns a hdulist containing extensions for the tables in dataSet. |
| 243 |
|
| 244 |
This function may block basically forever. Never call this from |
| 245 |
the main server, always use threads or separate processes (until |
| 246 |
pyfits is fixed to be thread-safe). |
| 247 |
|
| 248 |
This will add table parameters as header cards on the resulting FITS |
| 249 |
header. |
| 250 |
""" |
| 251 |
with utils.fitsLock(): |
| 252 |
return _makeFITSTableNOLOCK(dataSet, acquireSamples) |
| 253 |
|
| 254 |
|
| 255 |
def writeFITSTableFile(hdulist): |
| 256 |
"""returns the name of a temporary file containing the FITS data for |
| 257 |
hdulist. |
| 258 |
""" |
| 259 |
handle, pathname = tempfile.mkstemp(".fits", prefix="fitstable", |
| 260 |
dir=base.getConfig("tempDir")) |
| 261 |
|
| 262 |
# if there's more than the primary HDU, EXTEND=True is mandatory; let's |
| 263 |
# be defensive here |
| 264 |
if len(hdulist)>1: |
| 265 |
hdulist[0].header.set("EXTEND", True, "More exts following") |
| 266 |
|
| 267 |
with utils.silence(): |
| 268 |
hdulist.writeto(pathname, overwrite=True) |
| 269 |
os.close(handle) |
| 270 |
return pathname |
| 271 |
|
| 272 |
|
| 273 |
def makeFITSTableFile(dataSet, acquireSamples=True): |
| 274 |
"""returns the name of a temporary file containing a fits file |
| 275 |
representing dataSet. |
| 276 |
|
| 277 |
The caller is responsible to remove the file. |
| 278 |
""" |
| 279 |
hdulist = makeFITSTable(dataSet, acquireSamples) |
| 280 |
return writeFITSTableFile(hdulist) |
| 281 |
|
| 282 |
|
| 283 |
def writeDataAsFITS(data, outputFile, acquireSamples=False): |
| 284 |
"""a formats.common compliant data writer. |
| 285 |
|
| 286 |
This will write out table params as header cards. To serialise |
| 287 |
those yourself (as is required for spectral data model compliant |
| 288 |
tables), set an attribute IgnoreTableParams (with an arbitrary |
| 289 |
value) on the table. |
| 290 |
""" |
| 291 |
data = rsc.wrapTable(data) |
| 292 |
fitsName = makeFITSTableFile(data, acquireSamples) |
| 293 |
try: |
| 294 |
src = open(fitsName, "rb") |
| 295 |
utils.cat(src, outputFile) |
| 296 |
src.close() |
| 297 |
finally: |
| 298 |
os.unlink(fitsName) |
| 299 |
|
| 300 |
common.registerDataWriter("fits", writeDataAsFITS, "application/fits", |
| 301 |
"FITS Binary Table", ".fits") |