| 1 |
""" |
| 2 |
Creation of resource descriptors |
| 3 |
|
| 4 |
The first part of this is an early experiment to automatically create |
| 5 |
resource descriptors from structured data representations. |
| 6 |
|
| 7 |
While parts of this may be recoverable for smarter gavo start functionality, |
| 8 |
doing this so that the result is actually useful is hard. |
| 9 |
|
| 10 |
Instead, the new gavo start functionality just fetches one of a few |
| 11 |
commented RD templates, fills out a thing or two and leaves the rest to |
| 12 |
the operator. |
| 13 |
""" |
| 14 |
|
| 15 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 16 |
#c |
| 17 |
#c This program is free software, covered by the GNU GPL. See the |
| 18 |
#c COPYING file in the source distribution. |
| 19 |
|
| 20 |
|
| 21 |
import datetime |
| 22 |
import os |
| 23 |
import re |
| 24 |
import sys |
| 25 |
|
| 26 |
import pkg_resources |
| 27 |
|
| 28 |
from gavo import base |
| 29 |
from gavo import grammars |
| 30 |
from gavo import rscdef |
| 31 |
from gavo import votable |
| 32 |
from gavo import utils |
| 33 |
from gavo.base import macros |
| 34 |
from gavo.grammars import fitsprodgrammar |
| 35 |
from gavo.grammars import fitstablegrammar |
| 36 |
from gavo.formats import votableread |
| 37 |
from gavo.utils import ElementTree |
| 38 |
from gavo.utils import fitstools |
| 39 |
|
| 40 |
MS = base.makeStruct |
| 41 |
|
| 42 |
|
| 43 |
FT_TYPE_MAP = { |
| 44 |
"L": "boolean", |
| 45 |
"B": "bytea", |
| 46 |
"A": "char", |
| 47 |
"I": "smallint", |
| 48 |
"J": "integer", |
| 49 |
"K": "bigint", |
| 50 |
"E": "real", |
| 51 |
"D": "double precision", |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
def getTypeForFTFormat(format, name): |
| 56 |
"""returns a DaCHS type for FITS table column. |
| 57 |
""" |
| 58 |
typeCode = None |
| 59 |
|
| 60 |
# variable-length array FITS codes |
| 61 |
mat = re.match(r"(\d*)P(.)\(\d*\)$", format) |
| 62 |
if mat: |
| 63 |
typeCode = mat.group(2) |
| 64 |
arrSize = "100" # just a sentinel |
| 65 |
|
| 66 |
# "conventional FITS codes |
| 67 |
else: |
| 68 |
mat = re.match(r"(\d*)(.)$", format) |
| 69 |
if mat: |
| 70 |
arrSize, typeCode = mat.group(1), mat.group(2) |
| 71 |
|
| 72 |
if typeCode not in FT_TYPE_MAP: |
| 73 |
raise base.ReportableError(f"FITS type code '{format}' of {name}" |
| 74 |
" not handled by gavo mkrd; add handling if you can.") |
| 75 |
|
| 76 |
dbType = FT_TYPE_MAP[typeCode] |
| 77 |
if arrSize and int(arrSize)>1: |
| 78 |
if dbType=="char": |
| 79 |
dbType = "text" |
| 80 |
else: |
| 81 |
dbType = dbType+"[]" |
| 82 |
|
| 83 |
return dbType |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
# ======================= Begin deprecated ui and implementation =========== |
| 88 |
|
| 89 |
ignoredFITSHeaders = set(["COMMENT", "SIMPLE", "BITPIX", "EXTEND", |
| 90 |
"NEXTEND", "SOFTNAME", "SOFTVERS", "SOFTDATE", "SOFTAUTH", "SOFTINST", |
| 91 |
"HISTORY", "BZERO", "BSCALE", "DATAMIN", "DATAMAX"]) |
| 92 |
wcsKey = re.compile("CD.*|CRVAL.*|CDELT.*|NAXIS.*|CRPIX.*|CTYPE.*|CUNIT.*" |
| 93 |
r"|CROTA.*|RADECSYS|AP?_\d_\d|BP?_\d_\d|LATPOLE|LONPOLE") |
| 94 |
|
| 95 |
|
| 96 |
def isIgnoredKeyword(kw): |
| 97 |
"""returns true if kw should not be translated or put into the table. |
| 98 |
|
| 99 |
This is important for all WCS keywords when you want to compute |
| 100 |
SIAP bboxes; these keywords must not be translated. |
| 101 |
""" |
| 102 |
return kw in ignoredFITSHeaders or wcsKey.match(kw) |
| 103 |
|
| 104 |
|
| 105 |
def makeTableFromFT(rd, srcName, opts): |
| 106 |
from gavo.utils import pyfits |
| 107 |
cols, nameMaps = [], {} |
| 108 |
nameMaker = base.VOTNameMaker() |
| 109 |
|
| 110 |
hdus = pyfits.open(srcName) |
| 111 |
for fitsCol in hdus[1].columns: |
| 112 |
destName = nameMaker.makeName(fitsCol) |
| 113 |
if destName!=fitsCol.name: |
| 114 |
nameMaps[destName] = fitsCol.name |
| 115 |
cols.append(MS(rscdef.Column, |
| 116 |
type=getTypeForFTFormat(fitsCol.format, fitsCol.name), |
| 117 |
name=destName, |
| 118 |
unit=fitsCol.unit, |
| 119 |
ucd="", |
| 120 |
description="FILL IN")) |
| 121 |
table = rscdef.TableDef(rd, id=opts.tableName, onDisk=True, |
| 122 |
columns=cols) |
| 123 |
table.nameMaps = nameMaps |
| 124 |
hdus.close() |
| 125 |
return table |
| 126 |
|
| 127 |
|
| 128 |
def makeDataForFT(rd, srcName, opts): |
| 129 |
targetTable = rd.tables[0] |
| 130 |
# nameMaps left by makeTableFromFT |
| 131 |
rmkMaps =[MS(rscdef.MapRule, key=key, content_="vars['%s']"%src) |
| 132 |
for key, src in targetTable.nameMaps.items()] |
| 133 |
|
| 134 |
grammar = MS(fitstablegrammar.FITSTableGrammar) |
| 135 |
sources = MS(rscdef.SourceSpec, |
| 136 |
pattern=["*.fits"], recurse=True) |
| 137 |
rowmaker = MS(rscdef.RowmakerDef, id="gen_rmk", idmaps="*", maps=[rmkMaps]) |
| 138 |
make = MS(rscdef.Make, |
| 139 |
table=targetTable, |
| 140 |
rowmaker=rowmaker) |
| 141 |
|
| 142 |
return MS(rscdef.DataDescriptor, |
| 143 |
id="import", |
| 144 |
sources=sources, |
| 145 |
grammar=grammar, |
| 146 |
rowmakers=[rowmaker], |
| 147 |
make=make) |
| 148 |
|
| 149 |
|
| 150 |
def makeTableFromFITS(rd, srcName, opts): |
| 151 |
keyMappings = [] |
| 152 |
table = rscdef.TableDef(rd, id=opts.tableName, onDisk=True) |
| 153 |
hdus = fitstools.openFits(srcName) |
| 154 |
headerCards = hdus[0].header.cards |
| 155 |
for index, card in enumerate(headerCards): |
| 156 |
if isIgnoredKeyword(card.keyword): |
| 157 |
continue |
| 158 |
colName = re.sub("[^a-z]", "_", card.keyword.lower()) |
| 159 |
if not colName: |
| 160 |
continue |
| 161 |
|
| 162 |
if isinstance(card.value, str): |
| 163 |
type = "text" |
| 164 |
elif isinstance(card.value, int): |
| 165 |
type = "integer" |
| 166 |
else: |
| 167 |
type = "real" |
| 168 |
|
| 169 |
table.feedObject("column", MS(rscdef.Column, |
| 170 |
name=colName, unit="FILLIN", ucd="FILLIN", type=type, |
| 171 |
description=card.comment)) |
| 172 |
keyMappings.append((colName, card.keyword)) |
| 173 |
rd.setProperty("mapKeys", ", ".join("%s:%s"%(v,k) for k,v in keyMappings)) |
| 174 |
hdus.close() |
| 175 |
return table.finishElement() |
| 176 |
|
| 177 |
|
| 178 |
def makeDataForFITS(rd, srcName, opts): |
| 179 |
targetTable = rd.tables[0] |
| 180 |
dd = rscdef.DataDescriptor(rd, id="import_"+opts.tableName) |
| 181 |
grammar = fitsprodgrammar.FITSProdGrammar(dd) |
| 182 |
grammar.feedObject("qnd", True) |
| 183 |
rowfilter = base.parseFromString(grammars.Rowfilter, """ |
| 184 |
<rowfilter procDef="//products#define"> |
| 185 |
<bind key="table">"%s"</bind> |
| 186 |
<bind key="owner">"FILLIN"</bind> |
| 187 |
<bind key="embargo">"FILLIN"</bind> |
| 188 |
</rowfilter>"""%(targetTable.getQName())) |
| 189 |
grammar.feedObject("rowfilter", rowfilter) |
| 190 |
grammar.feedObject("mapKeys", MS(grammars.MapKeys, |
| 191 |
content_=rd.getProperty("mapKeys"))) |
| 192 |
grammar.finishElement() |
| 193 |
dd.grammar = grammar |
| 194 |
dd.feedObject("sources", MS(rscdef.SourceSpec, |
| 195 |
pattern=["*.fits"], recurse=True)) |
| 196 |
dd.feedObject("rowmaker", MS(rscdef.RowmakerDef, idmaps="*", id="gen_rmk")) |
| 197 |
dd.feedObject("make", MS(rscdef.Make, table=targetTable, rowmaker="gen_rmk")) |
| 198 |
return dd |
| 199 |
|
| 200 |
|
| 201 |
def makeTableFromVOTable(rd, srcName, opts): |
| 202 |
with open(srcName, "rb") as f: |
| 203 |
rawTable = next(votable.parse(f)) |
| 204 |
return votableread.makeTableDefForVOTable(opts.tableName, |
| 205 |
rawTable.tableDefinition, onDisk=True) |
| 206 |
|
| 207 |
|
| 208 |
def makeDataForVOTable(rd, srcName, opts): |
| 209 |
rowmaker = MS(rscdef.RowmakerDef, id="makerows_"+opts.tableName, |
| 210 |
idmaps="*") |
| 211 |
|
| 212 |
# The qualifiedId monkeying is necessary since otherwise the |
| 213 |
# ReferenceAttribute.unparse thinks it's ok to return the objects raw. |
| 214 |
# Face it: I've not really had serialization in mind when writing all |
| 215 |
# this. |
| 216 |
rowmaker.qualifiedId = rowmaker.id |
| 217 |
rd.tables[0].qualifiedId = rd.tables[0].id |
| 218 |
|
| 219 |
return MS(rscdef.DataDescriptor, |
| 220 |
grammar=MS(rscdef.getGrammar("voTableGrammar")), |
| 221 |
sources=MS(rscdef.SourceSpec, pattern=srcName), |
| 222 |
rowmaker=rowmaker, |
| 223 |
makes=[MS(rscdef.Make, table=rd.tables[0], rowmaker=rowmaker)]) |
| 224 |
|
| 225 |
|
| 226 |
tableMakers = { |
| 227 |
"FITS": makeTableFromFITS, |
| 228 |
"VOT": makeTableFromVOTable, |
| 229 |
"FT": makeTableFromFT, |
| 230 |
} |
| 231 |
|
| 232 |
dataMakers = { |
| 233 |
"FITS": makeDataForFITS, |
| 234 |
"VOT": makeDataForVOTable, |
| 235 |
"FT": makeDataForFT, |
| 236 |
} |
| 237 |
|
| 238 |
|
| 239 |
def makeRD(args, opts): |
| 240 |
from gavo import rscdesc |
| 241 |
rd = rscdesc.RD(None, schema=os.path.basename(opts.resdir), |
| 242 |
resdir=opts.resdir) |
| 243 |
|
| 244 |
for key, value in [ |
| 245 |
("title", "FILL-IN"), |
| 246 |
("creationDate", utils.formatISODT(datetime.datetime.utcnow())), |
| 247 |
("description", "FILL-IN a long text (and maybe do format='plain'" |
| 248 |
" or even format='rst'"), |
| 249 |
("copyright", "Free to use."), |
| 250 |
("creator.name", "Author, S."), |
| 251 |
("creator", ""), |
| 252 |
("creator.name", "Other, A."), |
| 253 |
("subject", "One Keyword"), |
| 254 |
("subject", "Two Words"), |
| 255 |
("content.type", "Catalog"), |
| 256 |
("coverage.waveband", "Optical"), |
| 257 |
("coverage.profile", "AllSky ICRS"),]: |
| 258 |
rd.addMeta(key, value) |
| 259 |
|
| 260 |
rd.feedObject("table", tableMakers[opts.srcForm](rd, args[0], opts)) |
| 261 |
rd.feedObject("data", dataMakers[opts.srcForm](rd, args[0], opts)) |
| 262 |
return rd.finishElement() |
| 263 |
|
| 264 |
|
| 265 |
def indent(elem, level=0): |
| 266 |
i = "\n" + level*"\t" |
| 267 |
if len(elem): |
| 268 |
if not elem.text or not elem.text.strip(): |
| 269 |
elem.text = i + "\t" |
| 270 |
if not elem.tail or not elem.tail.strip(): |
| 271 |
elem.tail = i |
| 272 |
for child in elem: |
| 273 |
indent(child, level+1) |
| 274 |
if not child.tail or not child.tail.strip(): |
| 275 |
child.tail = i |
| 276 |
if not elem.tail or not elem.tail.strip(): |
| 277 |
elem.tail = i |
| 278 |
else: |
| 279 |
if level and (not elem.tail or not elem.tail.strip()): |
| 280 |
elem.tail = i |
| 281 |
|
| 282 |
|
| 283 |
def writePrettyPrintedXML(root): |
| 284 |
indent(root) |
| 285 |
ElementTree.ElementTree(root).write(sys.stdout.buffer, encoding="utf-8") |
| 286 |
|
| 287 |
|
| 288 |
def parseCommandLine(): |
| 289 |
from optparse import OptionParser |
| 290 |
parser = OptionParser(usage = "%prog [options] <sample>" |
| 291 |
" DEPRECATED, use dachs start instead") |
| 292 |
parser.add_option("-f", "--format", help="Input file format: " |
| 293 |
" FITS, VOT or FT (FITS table)" |
| 294 |
" Default: Detect from file name", dest="srcForm", default=None, |
| 295 |
action="store", type="str") |
| 296 |
parser.add_option("-t", "--table-name", help="Name of the generated table", |
| 297 |
dest="tableName", default="main", action="store", type="str") |
| 298 |
parser.add_option("-r", "--resdir", help="Override resdir (and schema)", |
| 299 |
dest="resdir", default=os.getcwd(), action="store", type="str") |
| 300 |
opts, args = parser.parse_args() |
| 301 |
if len(args)!=1: |
| 302 |
parser.print_help(file=sys.stderr) |
| 303 |
sys.exit(1) |
| 304 |
if not opts.srcForm: |
| 305 |
ext = os.path.splitext(args[0])[1].lower() |
| 306 |
if ext in set([".xml", ".vot"]): |
| 307 |
opts.srcForm = "VOT" |
| 308 |
elif ext==".fits": |
| 309 |
opts.srcForm = "FITS" |
| 310 |
else: |
| 311 |
sys.stderr.write("Cannot guess format, use -f option: %s\n"%args[0]) |
| 312 |
parser.print_help(file=sys.stderr) |
| 313 |
sys.exit(1) |
| 314 |
return opts, args |
| 315 |
|
| 316 |
|
| 317 |
def main(): |
| 318 |
# hack to make id and onDisk copyable so we see them on iterEvent |
| 319 |
rscdef.TableDef._id.copyable = rscdef.TableDef._onDisk.copyable = True |
| 320 |
rscdef.DataDescriptor._id.copyable = True |
| 321 |
opts, args = parseCommandLine() |
| 322 |
rd = makeRD(args, opts) |
| 323 |
rd._metaAttr.copyable = True |
| 324 |
eTree = base.structToETree(rd) |
| 325 |
writePrettyPrintedXML(eTree) |
| 326 |
|
| 327 |
# ======================= End deprecated ui and implementation =========== |
| 328 |
|
| 329 |
|
| 330 |
def iterColAttrsFITS(table): |
| 331 |
"""yields dicts of column attributes from a FITS binary table HDU. |
| 332 |
""" |
| 333 |
hdr = table.header |
| 334 |
for colInd in range(1, hdr["TFIELDS"]+1): |
| 335 |
colMeta = [ |
| 336 |
("name", re.sub("[^0-9a-z_]", "_", hdr[f"TTYPE{colInd}"].lower())), |
| 337 |
("type", getTypeForFTFormat( |
| 338 |
hdr[f"TFORM{colInd}"], hdr[f"TTYPE{colInd}"])), |
| 339 |
("ucd", hdr.get(f"TUCD{colInd}", None)), |
| 340 |
("utype", hdr.get(f"TUTYP{colInd}", None)), |
| 341 |
("unit", hdr.get(f"TUNIT{colInd}", None)), |
| 342 |
("description", hdr.get(f"TCOMM{colInd}", None |
| 343 |
) or hdr.cards[f"TTYPE{colInd}"].comment or ""), |
| 344 |
("verbLevel", 1),] |
| 345 |
|
| 346 |
yield dict((k,v) for k,v in colMeta if v is not None) |
| 347 |
|
| 348 |
|
| 349 |
def iterColAttrsVOTable(inFile, tableInd): |
| 350 |
"""tries to parse (binary) inFile as a VOTable and yields colAttrs |
| 351 |
dictionaries for all FIELDs in it. |
| 352 |
""" |
| 353 |
yielding = tableInd==1 |
| 354 |
|
| 355 |
for el in votable.parse(inFile, watchset=[votable.V.TABLE, votable.V.FIELD]): |
| 356 |
if isinstance(el, votable.V.TABLE): |
| 357 |
if yielding: |
| 358 |
break # done parsing our table |
| 359 |
else: |
| 360 |
tableInd -= 1 |
| 361 |
if tableInd==1: |
| 362 |
yielding = True |
| 363 |
|
| 364 |
if yielding and isinstance(el, votable.V.FIELD): |
| 365 |
colMeta = [ |
| 366 |
("name", el.name), |
| 367 |
("unit", el.unit), |
| 368 |
("ucd", el.ucd or ""), |
| 369 |
("utype", el.utype), |
| 370 |
("type", base.voTableToSQLType(el.datatype, el.arraysize, el.xtype)), |
| 371 |
("description", el.getDescription()), |
| 372 |
("verbLevel", 1),] |
| 373 |
yield dict((k,v) for k,v in colMeta if v is not None) |
| 374 |
|
| 375 |
|
| 376 |
class VizBBBParser(object): |
| 377 |
"""A simple and naive parser for VizieR Byte-by-Byte descriptions. |
| 378 |
|
| 379 |
The results are available in the colAttrs and bytesForCols attributes. |
| 380 |
""" |
| 381 |
bbbLinePat = re.compile( |
| 382 |
r"\s*(?P<from>\d+)\s*-\s*(?P<to>\d+)" |
| 383 |
r"\s+(?P<format>[A-Z0-9.]+)" |
| 384 |
r"\s+(?P<units>[^\s]*)" |
| 385 |
r"\s+(?P<label>[^\s]*)" |
| 386 |
r"\s+(?P<description>.*)") |
| 387 |
tableBorderPat = re.compile("--------+") |
| 388 |
|
| 389 |
def __init__(self): |
| 390 |
self.state = "scanning" |
| 391 |
self.infoSoFar = {} |
| 392 |
self.colAttrs = [] |
| 393 |
self.bytesForCols = [] |
| 394 |
|
| 395 |
def _parse_finished(self, ln): |
| 396 |
"""we've found and parsed the BBB table. |
| 397 |
""" |
| 398 |
pass |
| 399 |
|
| 400 |
def _parse_scanning(self, ln): |
| 401 |
"""we're waiting for the table header of the first BBB block. |
| 402 |
""" |
| 403 |
if ln.startswith("Byte-by-byte Description"): |
| 404 |
self.state = "skip_header" |
| 405 |
|
| 406 |
def _parse_skip_header(self, ln): |
| 407 |
"""we're skipping over the table header of the first BBB block. |
| 408 |
""" |
| 409 |
mat = self.bbbLinePat.match(ln) |
| 410 |
if mat: |
| 411 |
self.state = "bbb_colhead" |
| 412 |
self._parse_bbb_colhead(ln, mat) |
| 413 |
|
| 414 |
elif self.tableBorderPat.match(ln) or re.match(r"\s*Bytes", ln): |
| 415 |
pass |
| 416 |
|
| 417 |
else: |
| 418 |
raise Exception(f"Expected BBB table, got '{ln}'") |
| 419 |
|
| 420 |
def _parse_bbb_colhead(self, ln, mat=None): |
| 421 |
"""we're expecting either a BBB column or the end of the table. |
| 422 |
""" |
| 423 |
if mat is None: |
| 424 |
mat = self.bbbLinePat.match(ln) |
| 425 |
|
| 426 |
if not mat: |
| 427 |
if self.tableBorderPat.match(ln): |
| 428 |
self.state = "finished" |
| 429 |
else: |
| 430 |
raise Exception("Expected BBB column def, got '{ln}'") |
| 431 |
|
| 432 |
self.infoSoFar = mat.groupdict() |
| 433 |
self.state = "bbb_moreexpl" |
| 434 |
|
| 435 |
def _parse_bbb_moreexpl(self, ln): |
| 436 |
"""we're expecting either a BBB column, a continuation line for the |
| 437 |
explanation, or the end of the table. |
| 438 |
|
| 439 |
In this state, there's non-shipped column data in infoSoFar. |
| 440 |
""" |
| 441 |
mat = self.bbbLinePat.match(ln) |
| 442 |
if mat: |
| 443 |
self._shipout() |
| 444 |
self.state = "bbb_colhead" |
| 445 |
self._parse_bbb_colhead(ln, mat) |
| 446 |
|
| 447 |
elif self.tableBorderPat.match(ln): |
| 448 |
self._shipout() |
| 449 |
self.state = "finished" |
| 450 |
|
| 451 |
else: |
| 452 |
self.infoSoFar["description"] += (" "+ln.strip()) |
| 453 |
|
| 454 |
def _getTypeForTypeCode(self, typeCode): |
| 455 |
"""returns one of our SQL types for a VizieR BBB type code. |
| 456 |
""" |
| 457 |
baseType = typeCode[0] |
| 458 |
|
| 459 |
if baseType=="A": |
| 460 |
return "text" |
| 461 |
|
| 462 |
elif baseType=="I": |
| 463 |
return { |
| 464 |
"I1": "smallint", |
| 465 |
"I2": "smallint", |
| 466 |
"I4": "integer"}.get(typeCode, "bigint") |
| 467 |
|
| 468 |
elif baseType in "FE": |
| 469 |
if int(typeCode[1:].split(".")[0])>7: |
| 470 |
return "double precision" |
| 471 |
else: |
| 472 |
return "real" |
| 473 |
|
| 474 |
def _shipout(self): |
| 475 |
"""takes infoSoFar and makes bytesForCols and colAttrs entries from |
| 476 |
it. |
| 477 |
""" |
| 478 |
unit = self.infoSoFar["units"] |
| 479 |
rec = [ |
| 480 |
("name", self.infoSoFar["label"]), |
| 481 |
("unit", None if unit=="---" else unit), |
| 482 |
("ucd", ""), |
| 483 |
("verbLevel", "1"), |
| 484 |
("type", self._getTypeForTypeCode(self.infoSoFar["format"])), |
| 485 |
("description", self.infoSoFar["description"].strip())] |
| 486 |
self.colAttrs.append(dict((k,v) for k,v in rec if v is not None)) |
| 487 |
|
| 488 |
self.bytesForCols.append("{label}: {from}-{to}".format(**self.infoSoFar)) |
| 489 |
|
| 490 |
def feed(self, line): |
| 491 |
getattr(self, "_parse_"+self.state)(line) |
| 492 |
|
| 493 |
|
| 494 |
def iterColAttrsViz(inFile, dumpRanges=False): |
| 495 |
"""tries to parse (text) inFile as a VizieR-Style bytes-by-bytes |
| 496 |
description and yields colAttrs for the first described table. |
| 497 |
|
| 498 |
dumpRanges is for interactive use, where the function additionally |
| 499 |
dumps a colDefs content to stdout. |
| 500 |
""" |
| 501 |
parser = VizBBBParser() |
| 502 |
for ln in inFile: |
| 503 |
parser.feed(ln) |
| 504 |
|
| 505 |
if parser.state!="finished": |
| 506 |
base.ui.notifyWarning("Probably invalid VizieR byte-by-byte: parser" |
| 507 |
f" ended up in {parser.state}") |
| 508 |
|
| 509 |
if dumpRanges: |
| 510 |
print("\n".join(parser.bytesForCols)+"\n") |
| 511 |
|
| 512 |
return parser.colAttrs |
| 513 |
|
| 514 |
|
| 515 |
COLUMN_ELEMENT_TEMPLATES = ['<column', |
| 516 |
' name="{name}"', ' type="{type}"', |
| 517 |
'\n ', 'unit="{unit}" ', 'ucd="{ucd}"', |
| 518 |
'\n utype="{utype}"', |
| 519 |
'\n tablehead="{tablehead}"', |
| 520 |
'\n description="{description}"', |
| 521 |
'\n displayHint="{displayHint}"', |
| 522 |
'\n verbLevel="{verbLevel}"', |
| 523 |
"/>"] |
| 524 |
|
| 525 |
def formatColumnElement(colAttrs): |
| 526 |
"""returns a column element XML literal for colAttrs in Markus' |
| 527 |
preferred formatting. |
| 528 |
""" |
| 529 |
accum = [] |
| 530 |
for template in COLUMN_ELEMENT_TEMPLATES: |
| 531 |
try: |
| 532 |
accum.append(template.format(**colAttrs)) |
| 533 |
except KeyError: |
| 534 |
# skip this template element as there's no value for it |
| 535 |
pass |
| 536 |
return "".join(accum) |
| 537 |
|
| 538 |
|
| 539 |
def getColumnXML(colAttrs): |
| 540 |
"""returns formatted XML for a sequence for column attributes. |
| 541 |
|
| 542 |
colAttrs is a sequence of dicts with fillers into COLUMN_ELEMENT_TEMPLATES; |
| 543 |
the must already be escaped for use in XML attributes. |
| 544 |
""" |
| 545 |
accum = [] |
| 546 |
for fillers in colAttrs: |
| 547 |
accum.append(formatColumnElement(fillers)) |
| 548 |
return "\n".join(accum) |
| 549 |
|
| 550 |
|
| 551 |
def parseGenColCommandLine(): |
| 552 |
import argparse |
| 553 |
parser = argparse.ArgumentParser(description="Write column definitions" |
| 554 |
" for representing a table") |
| 555 |
parser.add_argument("table", metavar="FILE", action="store", |
| 556 |
type=str, help="Source file to generate the columns from." |
| 557 |
" This can be a FITS, a VOTable, or Vizier Column-by-column" |
| 558 |
" description, and DaCHS will guess based on the extension. Use" |
| 559 |
" the format option if it guesses wrong") |
| 560 |
|
| 561 |
parser.add_argument("-f", "--format", dest="format", action="store", |
| 562 |
choices=["fits", "vot", "viz"], |
| 563 |
help="Format of the input table: FITS binary, VOTable, or Vizier" |
| 564 |
" byte-by-byte.") |
| 565 |
parser.add_argument("-x", "--extension", dest="extension", action="store", |
| 566 |
type=int, default=1, |
| 567 |
help="Extension to work on, for VOTables the table to work on." |
| 568 |
" In VOTables, counting starts at one.") |
| 569 |
|
| 570 |
return parser.parse_args() |
| 571 |
|
| 572 |
|
| 573 |
def gencol(): |
| 574 |
"""a UI function generating columns element from FITS binary tables. |
| 575 |
""" |
| 576 |
from gavo.utils import pyfits |
| 577 |
|
| 578 |
args = parseGenColCommandLine() |
| 579 |
|
| 580 |
if args.table.endswith(".fits") or args.format=="fits": |
| 581 |
try: |
| 582 |
table = pyfits.open(args.table)[args.extension] |
| 583 |
colIterator = iterColAttrsFITS(table) |
| 584 |
except Exception as exc: |
| 585 |
base.ui.notifyError(f"Cannot open {args.table} as a FITS binary table: " |
| 586 |
+str(exc)) |
| 587 |
sys.exit(1) |
| 588 |
|
| 589 |
elif (args.table.endswith(".vot") |
| 590 |
or args.table.endswith(".xml") |
| 591 |
or args.format=="vot"): |
| 592 |
try: |
| 593 |
with open(args.table, "rb") as f: |
| 594 |
colIterator = list(iterColAttrsVOTable(f, args.extension)) |
| 595 |
except Exception as exc: |
| 596 |
base.ui.notifyError(f"Cannot open {args.table} as a VOTable: " |
| 597 |
+str(exc)) |
| 598 |
|
| 599 |
elif (args.table.endswith(".txt") |
| 600 |
or args.table=="README" |
| 601 |
or args.format=="viz"): |
| 602 |
try: |
| 603 |
with open(args.table, "rb") as f: |
| 604 |
colIterator = iterColAttrsViz(f, True) |
| 605 |
except Exception as exc: |
| 606 |
base.ui.notifyError(f"Cannot open {args.table} as a VizieR" |
| 607 |
" Byte-by-Byte file: "+str(exc)) |
| 608 |
|
| 609 |
else: |
| 610 |
base.ui.notifyError(f"Do not know how to read {args.table}. Please" |
| 611 |
" use --format") |
| 612 |
sys.exit(1) |
| 613 |
|
| 614 |
print(utils.fixIndentation( |
| 615 |
getColumnXML( |
| 616 |
colIterator), " ")) |
| 617 |
|
| 618 |
|
| 619 |
# ====================== Begin templating ========================= |
| 620 |
|
| 621 |
|
| 622 |
def _listProtocols(): |
| 623 |
"""writes to stdout a list of protocols we can generate RD templates |
| 624 |
for. |
| 625 |
|
| 626 |
This is read from the resources coming with DaCHS, where we evaluate |
| 627 |
a magic =tpldesc Desc= string that must be embedded in the template. |
| 628 |
""" |
| 629 |
templateDir ="resources/src/" |
| 630 |
for fName in pkg_resources.resource_listdir( |
| 631 |
"gavo", templateDir): |
| 632 |
mat = re.match(r"template-(.*)\.rd_$", fName) |
| 633 |
if not mat: |
| 634 |
continue |
| 635 |
protName = mat.group(1) |
| 636 |
|
| 637 |
with pkg_resources.resource_stream('gavo', templateDir+fName) as f: |
| 638 |
tplHead = f.read(1000).decode("utf-8") |
| 639 |
mat = re.search(r"\\tpldesc{(.*?)}", tplHead) |
| 640 |
if not mat: |
| 641 |
continue |
| 642 |
protDesc = mat.group(1) |
| 643 |
|
| 644 |
print("%s -- %s"%(protName, protDesc)) |
| 645 |
|
| 646 |
|
| 647 |
def parseStartCommandLine(): |
| 648 |
import argparse |
| 649 |
parser = argparse.ArgumentParser(description="Write a template" |
| 650 |
" q.rd for a certain data type") |
| 651 |
parser.add_argument("protocol", metavar="PROTO", action="store", |
| 652 |
type=str, help="Generate an RD template for PROTO; use list to" |
| 653 |
" see what is available.") |
| 654 |
parser.add_argument("-o", "--output", |
| 655 |
metavar="FILENAME", action="store", default="q.rd", |
| 656 |
type=str, help="Write generated RD to FILENAME rather than q.rd") |
| 657 |
|
| 658 |
args = parser.parse_args() |
| 659 |
if args.protocol=="list": |
| 660 |
_listProtocols() |
| 661 |
sys.exit(0) |
| 662 |
return args |
| 663 |
|
| 664 |
|
| 665 |
class TemplateMacroPackage(macros.MacroPackage): |
| 666 |
"""Macros for RD templates. |
| 667 |
""" |
| 668 |
def macro_tpldesc(self, description): |
| 669 |
"""A silent macro used for self-documentation. |
| 670 |
""" |
| 671 |
return "" |
| 672 |
|
| 673 |
def macro_now(self): |
| 674 |
"""returns an ISO representation of just about now UTC. |
| 675 |
""" |
| 676 |
return utils.formatISODT(datetime.datetime.utcnow()) |
| 677 |
|
| 678 |
def macro_resdir(self): |
| 679 |
"""returns the last element of the current path. |
| 680 |
|
| 681 |
This is assumed to be the intended resource directory. |
| 682 |
""" |
| 683 |
return os.path.split(os.getcwd())[-1] |
| 684 |
|
| 685 |
def macro_commonmeta(self): |
| 686 |
"""expands to the content of tpart-commonmeta.xml. |
| 687 |
""" |
| 688 |
with pkg_resources.resource_stream('gavo', |
| 689 |
"resources/src/tpart-commonmeta.xml") as f: |
| 690 |
return f.read().decode("utf-8") |
| 691 |
|
| 692 |
|
| 693 |
class MkrdMacroProcessor(macros.MacroExpander): |
| 694 |
"""a macro expander for RD templates. |
| 695 |
""" |
| 696 |
def __init__(self): |
| 697 |
macros.MacroExpander.__init__(self, TemplateMacroPackage()) |
| 698 |
|
| 699 |
|
| 700 |
def start(): |
| 701 |
args = parseStartCommandLine() |
| 702 |
outputName = args.output |
| 703 |
|
| 704 |
try: |
| 705 |
source = pkg_resources.resource_stream('gavo', |
| 706 |
"resources/src/template-%s.rd_"%args.protocol) |
| 707 |
except IOError: |
| 708 |
base.ui.notifyError("No template for %s."%args.protocol) |
| 709 |
sys.exit(1) |
| 710 |
|
| 711 |
if os.path.exists(outputName): |
| 712 |
base.ui.notifyError( |
| 713 |
"Output %s already exists. Move it away and try again."%outputName) |
| 714 |
sys.exit(1) |
| 715 |
else: |
| 716 |
proc = MkrdMacroProcessor() |
| 717 |
rdSource = proc.expand(source.read().decode("utf-8")) |
| 718 |
with open(outputName, "wb") as dest: |
| 719 |
dest.write(rdSource.encode("utf-8")) |
| 720 |
|
| 721 |
source.close() |