| 1 |
""" |
| 2 |
A grammar supporting C language boosters (or possibly other mechanisms |
| 3 |
bypassing internal dbtable). |
| 4 |
|
| 5 |
These actually bypass most of our machinery and should only be used if |
| 6 |
performance is paramount. Otherwise, CustomGrammars play much nicer with |
| 7 |
the rest of the DC software. |
| 8 |
|
| 9 |
Currently, only one kind of DirectGrammar is supported: C boosters. |
| 10 |
""" |
| 11 |
|
| 12 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 13 |
#c |
| 14 |
#c This program is free software, covered by the GNU GPL. See the |
| 15 |
#c COPYING file in the source distribution. |
| 16 |
|
| 17 |
|
| 18 |
import os |
| •19 |
from gavo import pkg_resources |
| 20 |
import re |
| 21 |
import shutil |
| 22 |
import subprocess |
| 23 |
|
| 24 |
from gavo import base |
| 25 |
from gavo import utils |
| 26 |
from gavo import rscdef |
| 27 |
from gavo.grammars import common |
| 28 |
|
| 29 |
|
| 30 |
class CBooster(object): |
| 31 |
"""is a wrapper for an import booster written in C using the DC booster |
| 32 |
infrastructure. |
| 33 |
|
| 34 |
Warning: If you change the booster description, you'll need to touch |
| 35 |
the source to recompile. |
| 36 |
""" |
| 37 |
silence_for_test = False |
| 38 |
|
| 39 |
def __init__(self, srcName, dataDesc, recordSize=4000, gzippedInput=False, |
| 40 |
autoNull=None, preFilter=None, ignoreBadRecords=False, |
| 41 |
customFlags=""): |
| 42 |
self.dataDesc = dataDesc |
| 43 |
self.recordSize = recordSize |
| 44 |
self.resdir = dataDesc.rd.resdir |
| 45 |
self.srcName = os.path.join(self.resdir, srcName) |
| 46 |
self.autoNull, self.preFilter = autoNull, preFilter |
| 47 |
self.ignoreBadRecords = ignoreBadRecords |
| 48 |
self.gzippedInput = gzippedInput |
| 49 |
self.customFlags = customFlags |
| 50 |
self.bindir = os.path.join(self.resdir, "bin") |
| 51 |
self.binaryName = os.path.join(self.bindir, |
| 52 |
os.path.splitext(os.path.basename(srcName))[0]+"-"+base.getConfig( |
| 53 |
"platform")) |
| 54 |
self._ensureBinary() |
| 55 |
|
| 56 |
def _copySources(self, srcDir): |
| 57 |
def getResource(src, dest): |
| 58 |
inF = pkg_resources.resource_stream('gavo', src) |
| 59 |
with open(dest, "wb") as f: |
| 60 |
f.write(inF.read()) |
| 61 |
inF.close() |
| 62 |
getResource("resources/src/boosterskel.c", "boosterskel.c") |
| 63 |
getResource("resources/src/boosterskel.h", "boosterskel.h") |
| 64 |
shutil.copyfile(os.path.join(srcDir, self.srcName), "func.c") |
| 65 |
|
| 66 |
def _build(self): |
| 67 |
callArgs = {} |
| 68 |
if self.silence_for_test: |
| 69 |
# test instrumentation |
| 70 |
callArgs["stdout"] = utils.devnull() |
| 71 |
if subprocess.call("make", **callArgs): |
| 72 |
raise base.ReportableError("Booster build failed, messages above.") |
| 73 |
|
| 74 |
def _getMakefile(self, dd): |
| 75 |
res = [] |
| 76 |
if dd.grammar.type=="fits": |
| 77 |
res.append("LDFLAGS += -lcfitsio") |
| 78 |
|
| 79 |
if dd.grammar.type.startswith("hdf5"): |
| 80 |
flags = subprocess.check_output( |
| 81 |
["pkg-config", "--cflags", "hdf5"]).strip().decode("ascii") |
| 82 |
if flags: |
| 83 |
res.append(f"CFLAGS += {flags}") |
| 84 |
flags = subprocess.check_output( |
| 85 |
["pkg-config", "--libs", "hdf5"]).strip().decode("ascii") |
| 86 |
if flags: |
| 87 |
res.append(f"LDFLAGS += {flags}") |
| 88 |
|
| 89 |
query_n_pars = len(dd.makes[0].table.columns) |
| 90 |
res.append("LDFLAGS += -lm\n" |
| 91 |
"CFLAGS += -Wall -DINPUT_LINE_MAX=%d -DQUERY_N_PARS=%s"%( |
| 92 |
self.recordSize, query_n_pars)) |
| 93 |
if self.autoNull: |
| 94 |
res.append("CFLAGS += -DAUTO_NULL='%s'"%self.autoNull.replace( |
| 95 |
"\\", "\\\\")) |
| 96 |
if self.ignoreBadRecords: |
| 97 |
res.append("CFLAGS += -DIGNORE_BAD_RECORDS") |
| 98 |
res.append("CFLAGS += -g\n") |
| 99 |
|
| 100 |
res.append("booster: boosterskel.c func.c\n" |
| 101 |
"\t$(CC) $(CFLAGS) %s -o booster $^ $(LDFLAGS)"%self.customFlags) |
| 102 |
|
| 103 |
return "\n".join(res) |
| 104 |
|
| 105 |
def _ensureBinary(self): |
| 106 |
"""makes sure the booster binary exists and is up-to-date. |
| 107 |
""" |
| 108 |
if not os.path.exists(self.bindir): |
| 109 |
os.makedirs(self.bindir) |
| 110 |
try: |
| 111 |
if os.path.getmtime(self.srcName)<os.path.getmtime(self.binaryName): |
| 112 |
return |
| 113 |
except os.error: |
| 114 |
pass |
| 115 |
|
| 116 |
if not os.path.exists(self.srcName): |
| 117 |
raise base.ReportableError("Booster source does not exist." |
| 118 |
" You will not be able to import the enclosing data.", |
| 119 |
hint="Use gavo mkboost to create a skeleton for the booster.") |
| 120 |
|
| 121 |
with utils.sandbox() as origpath: |
| 122 |
dd = self.dataDesc |
| 123 |
if len(dd.makes)!=1: |
| 124 |
raise base.ReportableError( |
| 125 |
"Direct grammars can only work on single-make DDs") |
| 126 |
|
| 127 |
self._copySources(origpath) |
| 128 |
with open("Makefile", "w") as f: |
| 129 |
f.write(self._getMakefile(dd)) |
| 130 |
|
| 131 |
self._build() |
| 132 |
shutil.copyfile("booster", self.binaryName) |
| 133 |
os.chmod(self.binaryName, 0o775) |
| 134 |
|
| 135 |
def getOutput(self, argName): |
| 136 |
"""returns a pipe you can read the booster's output from. |
| 137 |
|
| 138 |
As a side effect, it also sets the attribute self.pipe. We need |
| 139 |
this to be able to retrieve the command status below. |
| 140 |
""" |
| 141 |
if self.preFilter: |
| 142 |
shellCommand = "%s '%s' | %s"%(self.preFilter, argName, self.binaryName) |
| 143 |
elif self.gzippedInput: |
| 144 |
shellCommand = "zcat '%s' | %s"%(argName, self.binaryName) |
| 145 |
else: |
| 146 |
shellCommand = "%s '%s'"%(self.binaryName, argName) |
| 147 |
|
| 148 |
pipeArgs = {"shell": True, "stdout": subprocess.PIPE} |
| 149 |
if self.silence_for_test: |
| 150 |
pipeArgs["stderr"] = utils.devnull() |
| 151 |
self.pipe = subprocess.Popen(shellCommand, **pipeArgs) |
| 152 |
return self.pipe.stdout |
| 153 |
|
| 154 |
def getStatus(self): |
| 155 |
return self.pipe.wait() |
| 156 |
|
| 157 |
|
| 158 |
class DirectGrammar(base.Structure, base.RestrictionMixin): |
| 159 |
"""A user-defined external grammar. |
| 160 |
|
| 161 |
See the :dachsdoc:`booster.html` on user-defined code on more on direct |
| 162 |
grammars. |
| 163 |
|
| 164 |
You will almost always use these in connection with C code generated |
| 165 |
by ``dachs mkboost``. |
| 166 |
|
| 167 |
Properties: |
| 168 |
|
| 169 |
* dataset: For HDF5 boosters, the HDF path to the table to be |
| 170 |
imported (in vaex, not including "columns"). Certain, hopefully |
| 171 |
sensible, defaults apply depending on the HDF5 dialect. |
| 172 |
* chunkSize: In HDF5 boosters, now many rows to pull into |
| 173 |
memory at one time (defaults to 5000). |
| 174 |
""" |
| 175 |
name_ = "directGrammar" |
| 176 |
|
| 177 |
notify = True |
| 178 |
|
| 179 |
_cbooster = rscdef.ResdirRelativeAttribute("cBooster", |
| 180 |
default=base.Undefined, |
| 181 |
description="resdir-relative path to the booster C source.", |
| 182 |
copyable=True) |
| 183 |
|
| 184 |
_gzippedInput = base.BooleanAttribute("gzippedInput", default=False, |
| 185 |
description="Pipe gzip before booster? (will not work for FITS)", |
| 186 |
copyable=True) |
| 187 |
|
| 188 |
_autoNull = base.UnicodeAttribute("autoNull", default=None, |
| 189 |
description="Use this string as general NULL value (when reading" |
| 190 |
" from plain text).", |
| 191 |
copyable=True) |
| 192 |
|
| 193 |
_ignoreBadRecords = base.BooleanAttribute("ignoreBadRecords", |
| 194 |
default=False, description="Let booster ignore invalid records?", |
| 195 |
copyable=True) |
| 196 |
|
| 197 |
_recordSize = base.IntAttribute("recordSize", default=4000, |
| 198 |
description="For bin boosters, read this many bytes to make" |
| 199 |
" up a record; for line-based boosters, this is the maximum" |
| 200 |
" length of an input line.", |
| 201 |
copyable=True) |
| 202 |
|
| 203 |
_preFilter = base.UnicodeAttribute("preFilter", default=None, |
| 204 |
description="Pipe input through this program before handing it to" |
| 205 |
" the booster; this string is shell-expanded (will not work for FITS).", |
| 206 |
copyable=True) |
| 207 |
|
| 208 |
_customFlags = base.UnicodeAttribute("customFlags", default="", |
| 209 |
description="Pass these flags to the C compiler when building the" |
| 210 |
" booster.", |
| 211 |
copyable=True) |
| 212 |
|
| 213 |
_type = base.EnumeratedUnicodeAttribute("type", default="col", |
| 214 |
validValues=["col", "bin", "fits", "split", "hdf5vaex", "hdf5rootarrs"], |
| 215 |
description="Make code for a booster parsing by column indices (col)," |
| 216 |
" by splitting along separators (split), by reading fixed-length" |
| 217 |
" binary records (bin), for from FITS binary tables (fits).", |
| 218 |
copyable=True) |
| 219 |
|
| 220 |
_splitChar = base.UnicodeAttribute("splitChar", default="|", |
| 221 |
description="For split boosters, use this as the separator.", |
| 222 |
copyable=True) |
| 223 |
|
| 224 |
_ext = base.IntAttribute("extension", default=1, |
| 225 |
description="For FITS table boosters, get the table from this extension.", |
| 226 |
copyable=True) |
| 227 |
|
| 228 |
_mapKeys = base.StructAttribute("mapKeys", childFactory=common.MapKeys, |
| 229 |
default=None, copyable=True, |
| 230 |
description="For certain input formats (FITS, HDF5), map input" |
| 231 |
" column names to database column name. For instance, to generate" |
| 232 |
" code for a FITS column flx to end up in the DB column flux," |
| 233 |
" say flux:flx).") |
| 234 |
|
| 235 |
_properties = base.PropertyAttribute() |
| 236 |
|
| 237 |
_rd = rscdef.RDAttribute() |
| 238 |
|
| 239 |
isDispatching = False |
| 240 |
|
| 241 |
def validate(self): |
| 242 |
super().validate() |
| 243 |
if self.type=='bin': |
| 244 |
if not self.recordSize: |
| 245 |
raise base.StructureError("DirectGrammars reading from binary need" |
| 246 |
" a recordSize attribute") |
| 247 |
if self.mapKeys is not None: |
| 248 |
if self.type not in {"fits", "hdf5vaex", "hdf5rootarrs"}: |
| 249 |
raise base.StructureError("mapKeys is not allowed for this" |
| 250 |
" kind of booster.") |
| 251 |
|
| 252 |
def onElementComplete(self): |
| 253 |
if self.type=="fits": |
| 254 |
if self.mapKeys: |
| 255 |
self.keyMap = self.mapKeys.maps |
| 256 |
else: |
| 257 |
self.keyMap = {} |
| 258 |
|
| 259 |
def getBooster(self): |
| 260 |
return CBooster(self.cBooster, self.parent, |
| 261 |
gzippedInput=self.gzippedInput, |
| 262 |
preFilter=self.preFilter, |
| 263 |
autoNull=self.autoNull, |
| 264 |
ignoreBadRecords=self.ignoreBadRecords, |
| 265 |
customFlags=self.customFlags, |
| 266 |
recordSize=self.recordSize) |
| 267 |
|
| 268 |
def parse(self, sourceToken, targetData=None): |
| 269 |
booster = self.getBooster() |
| 270 |
makes = self.parent.makes |
| 271 |
if len(makes)!=1: |
| 272 |
raise base.StructureError("Directgrammar only works for data having" |
| 273 |
" exactly one table, but data '%s' has %d"%( |
| 274 |
self.parent.id, len(makes))) |
| 275 |
|
| 276 |
def copyIn(data): |
| 277 |
if self.notify: |
| 278 |
base.ui.notifyNewSource(sourceToken) |
| 279 |
try: |
| 280 |
source = booster.getOutput(sourceToken) |
| 281 |
list(data.tables.values())[0].copyIn(source) |
| 282 |
source.close() |
| 283 |
if booster.getStatus(): |
| 284 |
raise base.SourceParseError( |
| 285 |
"Booster returned error signature", |
| 286 |
source=sourceToken) |
| 287 |
finally: |
| 288 |
base.ui.notifySourceFinished() |
| 289 |
|
| 290 |
return copyIn |
| 291 |
|
| 292 |
|
| 293 |
################################################### |
| 294 |
# booster source code generating functions |
| 295 |
|
| 296 |
import sys |
| 297 |
|
| 298 |
def getNameForItem(item): |
| 299 |
return "fi_"+item.name.lower() |
| 300 |
|
| 301 |
|
| 302 |
# Some pieces to puzzle together the createDumpfile functions |
| 303 |
COMMON_MAIN_HEADER = """ |
| 304 |
/* Common main header */ |
| 305 |
void createDumpfile(int argc, char **argv) |
| 306 |
{ |
| 307 |
FILE *destination=stdout; |
| 308 |
char inputLine[INPUT_LINE_MAX]; |
| 309 |
int recCount = 0; |
| 310 |
/* /Common main header */ |
| 311 |
""" |
| 312 |
|
| 313 |
NONSEEK_MAIN_INTRO = """ |
| 314 |
FILE *inF; |
| 315 |
|
| 316 |
/* seekable main intro */ |
| 317 |
if (argc>2) { |
| 318 |
die(USAGE); |
| 319 |
} |
| 320 |
if (argc==2) { |
| 321 |
if (!(inF = fopen(argv[1], "r"))) { |
| 322 |
die(strerror(errno)); |
| 323 |
} |
| 324 |
} else { |
| 325 |
inF = stdin; |
| 326 |
} |
| 327 |
/* /seekable main intro */ |
| 328 |
""" |
| 329 |
|
| 330 |
COMMON_MAIN_INTRO = """ |
| 331 |
/* common main intro */ |
| 332 |
writeHeader(destination); |
| 333 |
/* /common main intro */ |
| 334 |
""" |
| 335 |
|
| 336 |
|
| 337 |
LOOP_BODY_INTRO = """ |
| 338 |
Field *tuple; |
| 339 |
context = inputLine; |
| 340 |
if (!setjmp(ignoreRecord)) { |
| 341 |
""" |
| 342 |
|
| 343 |
|
| 344 |
LOOP_BODY_FOOT = """ |
| 345 |
if (!tuple) { |
| 346 |
handleBadRecord("Bad input line at record %d", recCount); |
| 347 |
} |
| 348 |
writeTuple(tuple, QUERY_N_PARS, destination); |
| 349 |
context = NULL; |
| 350 |
recCount ++; |
| 351 |
if (!(recCount%1000)) { |
| 352 |
fprintf(stderr, "%08d\\r", recCount); |
| 353 |
fflush(stderr); |
| 354 |
} |
| 355 |
} |
| 356 |
""" |
| 357 |
|
| 358 |
|
| 359 |
COMMON_MAIN_FOOT = """ |
| 360 |
writeEndMarker(destination); |
| 361 |
fprintf(stderr, "%08d records done.\\n", recCount); |
| 362 |
} |
| 363 |
""" |
| 364 |
|
| 365 |
|
| 366 |
def _getMakeMacro(item): |
| 367 |
"""returns a maker macro for a column object. |
| 368 |
""" |
| 369 |
try: |
| 370 |
return { |
| 371 |
"integer": "MAKE_INT", |
| 372 |
"smallint": "MAKE_SHORT", |
| 373 |
"double precision": "MAKE_DOUBLE", |
| 374 |
"real": "MAKE_FLOAT", |
| 375 |
"char": "MAKE_CHAR_NULL", |
| 376 |
"bytea": "MAKE_BYTE", |
| 377 |
"text": "MAKE_TEXT", |
| 378 |
"bigint": "MAKE_BIGINT", |
| 379 |
}[item.type] |
| 380 |
except KeyError: |
| 381 |
# not a simple case; this could be a place for doing arrays and such |
| 382 |
return "MAKE_somethingelse" |
| 383 |
|
| 384 |
|
| 385 |
class _CodeGenerator(object): |
| 386 |
"""a base class for code generators. |
| 387 |
|
| 388 |
You will at least have to override getItemParser and getFooter |
| 389 |
if this is to do anything useful. |
| 390 |
""" |
| 391 |
def __init__(self, grammar, tableDef): |
| 392 |
self.grammar, self.tableDef = grammar, tableDef |
| 393 |
|
| 394 |
def getSetupCode(self): |
| 395 |
"""returns a sequence of C lines for code between an item parser. |
| 396 |
""" |
| 397 |
return [] |
| 398 |
|
| 399 |
def getItemParser(self, item, index): |
| 400 |
"""returns code that parses item (a Column instance) at column index |
| 401 |
index. |
| 402 |
|
| 403 |
You're free to ignore index. |
| 404 |
""" |
| 405 |
return [] |
| 406 |
|
| 407 |
def getPreamble(self): |
| 408 |
"""returns a list of lines that make up the top of the booster. |
| 409 |
""" |
| 410 |
return [ |
| 411 |
'#include <stdio.h>', |
| 412 |
'#include <math.h>', |
| 413 |
'#include <string.h>', |
| 414 |
'#include <errno.h>', |
| 415 |
'#include "boosterskel.h"', |
| 416 |
'', |
| 417 |
'#define USAGE "Usage: don\'t."',] |
| 418 |
|
| 419 |
def getPrototype(self): |
| 420 |
"""returns the prototype of the getTuple function. |
| 421 |
""" |
| 422 |
return "Field *getTuple(char *inputLine, int recNo)" |
| 423 |
|
| 424 |
def getFooter(self): |
| 425 |
"""returns the code for the createDumpfile method. |
| 426 |
|
| 427 |
You want to use the C fragments above for that. |
| 428 |
|
| 429 |
The default returns something that bombs out. |
| 430 |
""" |
| 431 |
return '#error "No getFooter defined in the code generator"' |
| 432 |
|
| 433 |
|
| 434 |
class _LineBasedCodeGenerator(_CodeGenerator): |
| 435 |
"""a base class for code generators for reading line-based text files. |
| 436 |
""" |
| 437 |
def getFooter(self): |
| 438 |
"""returns the main function of the parser (and possibly other stuff) |
| 439 |
in a string. |
| 440 |
|
| 441 |
This default implementation works for line-based parsers. |
| 442 |
""" |
| 443 |
return (COMMON_MAIN_HEADER |
| 444 |
+NONSEEK_MAIN_INTRO |
| 445 |
+COMMON_MAIN_INTRO |
| 446 |
+""" |
| 447 |
while (fgets(inputLine, INPUT_LINE_MAX, inF)) {""" |
| 448 |
+LOOP_BODY_INTRO |
| 449 |
+""" |
| 450 |
tuple = getTuple(inputLine, recCount);""" |
| 451 |
+LOOP_BODY_FOOT |
| 452 |
+"}\n" |
| 453 |
+COMMON_MAIN_FOOT) |
| 454 |
|
| 455 |
|
| 456 |
class ColCodeGenerator(_LineBasedCodeGenerator): |
| 457 |
def getItemParser(self, item, index): |
| 458 |
t = item.type |
| 459 |
if "smallint" in t: |
| 460 |
func = "parseShort" |
| 461 |
elif "int" in t: |
| 462 |
func = "parseInt" |
| 463 |
elif t in ["real", "float"]: |
| 464 |
func = "parseFloat" |
| 465 |
elif "double" in t: |
| 466 |
func = "parseDouble" |
| 467 |
elif "char" in t: |
| 468 |
func = "parseString" |
| 469 |
elif "bool" in t: |
| 470 |
func = "parseBlankBoolean" |
| 471 |
else: |
| 472 |
func = "parseWhatever" |
| 473 |
return ["%s(inputLine, F(%s), start, len);"%(func, getNameForItem(item))] |
| 474 |
|
| 475 |
def getPrototype(self): |
| 476 |
"""returns the prototype of the getTuple function. |
| 477 |
""" |
| 478 |
return "Field *getTuple(char *inputLine, int recNo)" |
| 479 |
|
| 480 |
|
| 481 |
class SplitCodeGenerator(_LineBasedCodeGenerator): |
| 482 |
"""a code generator for parsing files with lineas and separators. |
| 483 |
""" |
| 484 |
def __init__(self, grammar, tableDef): |
| 485 |
self.splitChar = getattr(grammar, "splitChar", "|") |
| 486 |
_CodeGenerator.__init__(self, grammar, tableDef) |
| 487 |
|
| 488 |
def getPreamble(self): |
| 489 |
return _LineBasedCodeGenerator.getPreamble(self)+[ |
| 490 |
"/* delete the next line for POSIX strtok */", |
| 491 |
"#define strtok strtok_u"] |
| 492 |
|
| 493 |
def getSetupCode(self): |
| 494 |
return _LineBasedCodeGenerator.getSetupCode(self)+[ |
| 495 |
'char *curCont;', |
| 496 |
'curCont = strtok(inputLine, "%s");'%self.splitChar] |
| 497 |
|
| 498 |
def getItemParser(self, item, index): |
| 499 |
t = item.type |
| 500 |
fi = getNameForItem(item) |
| 501 |
if t=="text": |
| 502 |
parse = ["F(%s)->type = VAL_TEXT;"%fi, |
| 503 |
"F(%s)->length = strlen(curCont);"%fi, |
| 504 |
"F(%s)->val.c_ptr = curCont;"%fi,] |
| 505 |
else: |
| 506 |
if t=="smallint": |
| 507 |
cType = "VAL_SHORT" |
| 508 |
elif t=="bigint": |
| 509 |
cType = "VAL_BIGINT" |
| 510 |
elif "int" in t: |
| 511 |
cType = "VAL_INT" |
| 512 |
elif t in ["real", "float"]: |
| 513 |
cType = "VAL_FLOAT" |
| 514 |
elif "double" in t: |
| 515 |
cType = "VAL_DOUBLE" |
| 516 |
elif "char"==t: |
| 517 |
cType = "VAL_CHAR" |
| 518 |
elif "char" in t: |
| 519 |
cType = "VAL_TEXT" |
| 520 |
elif "bool" in t: |
| 521 |
cType = "VAL_BOOL" |
| 522 |
else: |
| 523 |
cType = "###No appropriate type###" |
| 524 |
parse = ["fieldscanf(curCont, %s, %s);"%(fi, cType)] |
| 525 |
parse.append('curCont = strtok(NULL, "%s");'%self.splitChar) |
| 526 |
return parse |
| 527 |
|
| 528 |
|
| 529 |
class BinCodeGenerator(_CodeGenerator): |
| 530 |
"""a code generator for reading fixed-length binary records. |
| 531 |
""" |
| 532 |
def getItemParser(self, item, index): |
| 533 |
t = item.type |
| 534 |
if t=="integer": |
| 535 |
pline = "%s(%s, *(int32_t*)(inputLine+));" |
| 536 |
elif t=="smallint": |
| 537 |
pline = "%s(%s, *(int16_t*)(inputLine+ ));" |
| 538 |
elif t=="double precision": |
| 539 |
pline = "%s(%s, *(double*)(inputLine+ ));" |
| 540 |
elif t=="real": |
| 541 |
pline = "%s(%s, *(float*)(inputLine+ ));" |
| 542 |
elif t=="char": |
| 543 |
pline = "%s(%s, *(char*)(inputLine+ ), '<nil>');" |
| 544 |
elif t=="bytea": |
| 545 |
pline = "%s(%s, *(double*)(inputLine+ ), '<nil>');" |
| 546 |
else: |
| 547 |
pline = "%s %s" |
| 548 |
return ["/* %s (%s) */"%(item.description, t), |
| 549 |
pline%(_getMakeMacro(item), getNameForItem(item))] |
| 550 |
|
| 551 |
def getPreamble(self): |
| 552 |
return _CodeGenerator.getPreamble(self)+[ |
| 553 |
"#define FIXED_RECORD_SIZE %d"%self.grammar.recordSize] |
| 554 |
|
| 555 |
def getFooter(self): |
| 556 |
return (COMMON_MAIN_HEADER |
| 557 |
+" int bytesRead = 0;\n" |
| 558 |
+NONSEEK_MAIN_INTRO |
| 559 |
+COMMON_MAIN_INTRO |
| 560 |
+""" |
| 561 |
while (1) { |
| 562 |
bytesRead = fread(inputLine, 1, FIXED_RECORD_SIZE, inF); |
| 563 |
if (bytesRead==0) { |
| 564 |
break; |
| 565 |
} else if (bytesRead!=FIXED_RECORD_SIZE) { |
| 566 |
die("Short record: Only %d bytes read.", bytesRead); |
| 567 |
} |
| 568 |
""" |
| 569 |
+LOOP_BODY_INTRO |
| 570 |
+""" |
| 571 |
tuple = getTuple(inputLine, recCount);""" |
| 572 |
+LOOP_BODY_FOOT |
| 573 |
+"}\n" |
| 574 |
+COMMON_MAIN_FOOT) |
| 575 |
|
| 576 |
|
| 577 |
class _NumpyMetaCodeGenerator(_CodeGenerator): |
| 578 |
"""A base class for code generators built using numpy-compatible |
| 579 |
metadata. |
| 580 |
""" |
| 581 |
fitsTypes = { |
| 582 |
"B": ("TBYTE", "char"), |
| 583 |
"A": ("TSTRING", "char *"), |
| 584 |
"I": ("TSHORT", "short"), |
| 585 |
"J": ("TLONG", "long"), |
| 586 |
"K": ("TLONGLONG", "long long"), |
| 587 |
"E": ("TFLOAT", "float"), |
| 588 |
"L": ("TLOGICAL", "unsigned char"), |
| 589 |
"D": ("TDOUBLE", "double")} |
| 590 |
numpyTypes = { |
| 591 |
"byte": "char", |
| 592 |
"int8": "char", |
| 593 |
"short": "short", |
| 594 |
"int16": "short", |
| 595 |
"cint": "int", |
| 596 |
"int32": "int", |
| 597 |
"int64": "int64_t", |
| 598 |
"ubyte": "unsigned char", |
| 599 |
"uint8": "unsigned char", |
| 600 |
"ushort": "unsigned short", |
| 601 |
"uint16": "unsigned char", |
| 602 |
"uintc": "unsigned int", |
| 603 |
"ulonglong": "unsigned long long", |
| 604 |
"uint64": "uint64_t", |
| 605 |
"single": "float", |
| 606 |
"float16": "float", |
| 607 |
"float32": "float", |
| 608 |
"double": "double", |
| 609 |
"float64": "double", |
| 610 |
} |
| 611 |
makers = { |
| 612 |
"bigint": "MAKE_BIGINT", |
| 613 |
"smallint": "MAKE_SHORT", |
| 614 |
"bytea": "MAKE_BYTE", |
| 615 |
"text": "MAKE_TEXT", |
| 616 |
"integer": "MAKE_INT", |
| 617 |
"real": "MAKE_FLOAT", |
| 618 |
"double precision": "MAKE_DOUBLE", |
| 619 |
} |
| 620 |
|
| 621 |
def _parseFITSFormat(self, format, colName): |
| 622 |
"""returns length and typecode for the supported FITS table types. |
| 623 |
|
| 624 |
All others raise errors. |
| 625 |
""" |
| 626 |
mat = re.match(r"(\d*)(.)$", format) |
| 627 |
if not mat: |
| 628 |
raise base.ReportableError("FITS type code '%s' of %s not handled" |
| 629 |
" by gavo mkboost; add handling if you can."%(format, colName)) |
| 630 |
if not mat.group(2) in self.fitsTypes: |
| 631 |
raise base.ReportableError("FITS type '%s' of %s not handled" |
| 632 |
" by gavo mkboost; add handling if you can."%( |
| 633 |
mat.group(2), colName)) |
| 634 |
return int(mat.group(1) or "1"), mat.group(2) |
| 635 |
|
| 636 |
|
| 637 |
class FITSCodeGenerator(_NumpyMetaCodeGenerator): |
| 638 |
"""A code generator for reading from FITS binary tables. |
| 639 |
""" |
| 640 |
def __init__(self, grammar, tableDef): |
| 641 |
from gavo.utils import pyfits |
| 642 |
_CodeGenerator.__init__(self, grammar, tableDef) |
| 643 |
self.forExtension = grammar.extension |
| 644 |
|
| 645 |
# now pull the table schema from the first source. |
| 646 |
if self.grammar.parent.sources is None: |
| 647 |
raise base.StructureError("Cannot make FITS bintable booster without" |
| 648 |
" a sources element on the embedding data.") |
| 649 |
try: |
| 650 |
hdus = pyfits.open( |
| 651 |
next(self.grammar.parent.sources.iterSources())) |
| 652 |
self.fitsTable = hdus[self.forExtension] |
| 653 |
except StopIteration: |
| 654 |
raise base.StructureError("Building a FITS bintable booster requires" |
| 655 |
" at least one matching source.") |
| 656 |
hdus.close() |
| 657 |
|
| 658 |
self._computeMatches() |
| 659 |
|
| 660 |
def _computeMatches(self): |
| 661 |
"""adds .fitsIndexForCol and .colForFITSIndex attributes. |
| 662 |
|
| 663 |
These are matches based on the respective column names, where |
| 664 |
we do a case-insensitive matching for now. |
| 665 |
|
| 666 |
Nones mean that no corresponding column is present; for FITS columns, |
| 667 |
this means they are ignored. For table columns, this means that |
| 668 |
stand-in code is generated for filling out later. |
| 669 |
""" |
| 670 |
tableColumns = dict((col.name.lower(), col) |
| 671 |
for col in self.tableDef) |
| 672 |
if len(tableColumns)!=len(self.tableDef.columns): |
| 673 |
raise base.StructureError("Table unsuitable for FITS boosting as" |
| 674 |
" column names identical after case folding are present.", |
| 675 |
hint="Use mapKeys to adapt FITS table names to resolve" |
| 676 |
" the ambiguity") |
| 677 |
|
| 678 |
self.colForFITSIndex = {} |
| 679 |
for index, fitsCol in enumerate(self.fitsTable.columns): |
| 680 |
columnName = self.grammar.keyMap.get(fitsCol.name, fitsCol.name).lower() |
| 681 |
self.colForFITSIndex[index] = tableColumns.get(columnName) |
| 682 |
|
| 683 |
self.fitsIndexForColName = {} |
| 684 |
for index, col in self.colForFITSIndex.items(): |
| 685 |
if col is None: |
| 686 |
continue |
| 687 |
self.fitsIndexForColName[col.name.lower()] = index |
| 688 |
|
| 689 |
def getItemParser(self, item, index): |
| 690 |
try: |
| 691 |
fitsIndex = self.fitsIndexForColName[item.name.lower()] |
| 692 |
fitsCol = self.fitsTable.columns[fitsIndex] |
| 693 |
castTo = self.fitsTypes[ |
| 694 |
self._parseFITSFormat(fitsCol.format, fitsCol.name)[1] |
| 695 |
][1] |
| 696 |
|
| 697 |
return [ |
| 698 |
"/* %s (%s) */"%(item.description, item.type), |
| 699 |
"if (nulls[%d][rowIndex]) {"%fitsIndex, |
| 700 |
" MAKE_NULL(%s);"%getNameForItem(item), |
| 701 |
"} else {", |
| 702 |
" %s(%s, ((%s*)(data[%d]))[rowIndex]);"%( |
| 703 |
self.makers[item.type], |
| 704 |
getNameForItem(item), |
| 705 |
castTo, |
| 706 |
fitsIndex), |
| 707 |
"}",] |
| 708 |
|
| 709 |
except KeyError: |
| 710 |
# no FITS table source column |
| 711 |
return ["MAKE_NULL(%s); /* %s(%s, FILL IN VALUE); */"%( |
| 712 |
getNameForItem(item), |
| 713 |
_getMakeMacro(item), |
| 714 |
getNameForItem(item))] |
| 715 |
|
| 716 |
def getPreamble(self): |
| 717 |
return _CodeGenerator.getPreamble(self)+[ |
| 718 |
"#include <fitsio.h>", |
| 719 |
"#include <assert.h>", |
| 720 |
"#define FITSCATCH(x) if (x) {fatalFitsError(status);}", |
| 721 |
"void fatalFitsError(int status) {", |
| 722 |
" if (status==0) {", |
| 723 |
" return;", |
| 724 |
" }", |
| 725 |
" fits_report_error(stderr, status);", |
| 726 |
" abort();", |
| 727 |
"}", |
| 728 |
] |
| 729 |
|
| 730 |
def getPrototype(self): |
| 731 |
return "Field *getTuple(void *data[], char *nulls[], int rowIndex)" |
| 732 |
|
| 733 |
def _parseFITSFormat(self, format, colName): |
| 734 |
"""returns length and typecode for the supported FITS table types. |
| 735 |
|
| 736 |
All others raise errors. |
| 737 |
""" |
| 738 |
mat = re.match(r"(\d*)(.)$", format) |
| 739 |
if not mat: |
| 740 |
raise base.ReportableError("FITS type code '%s' of %s not handled" |
| 741 |
" by gavo mkboost; add handling if you can."%(format, colName)) |
| 742 |
if not mat.group(2) in self.fitsTypes: |
| 743 |
raise base.ReportableError("FITS type '%s' of %s not handled" |
| 744 |
" by gavo mkboost; add handling if you can."%( |
| 745 |
mat.group(2), colName)) |
| 746 |
return int(mat.group(1) or "1"), mat.group(2) |
| 747 |
|
| 748 |
def _getColDescs(self): |
| 749 |
"""returns a C initializer for an array of FITSColDescs. |
| 750 |
""" |
| 751 |
res = [] |
| 752 |
for index, fcd in enumerate(self.fitsTable.columns): |
| 753 |
col = self.colForFITSIndex[index] |
| 754 |
if col is None: |
| 755 |
# table column not part of FITS table, suppress reading |
| 756 |
# by having .cSize=0 |
| 757 |
res.append("{.cSize = 0, .fitsType = 0, .index=0, .arraysize=0}") |
| 758 |
continue |
| 759 |
|
| 760 |
length, typecode = self._parseFITSFormat(fcd.format, fcd.name) |
| 761 |
|
| 762 |
if typecode=="A": |
| 763 |
# special handling for strings, as we need their size |
| 764 |
# var length strings have been rejected above |
| 765 |
res.append( |
| 766 |
"{.cSize = %d, .fitsType = TSTRING, .index=%d, .arraysize=1}"%( |
| 767 |
length, index+1)) |
| 768 |
|
| 769 |
else: |
| 770 |
res.append( |
| 771 |
"{.cSize = sizeof(%s), .fitsType = %s, .index=%d, .arraysize=%d}"%( |
| 772 |
self.fitsTypes[typecode][1], |
| 773 |
self.fitsTypes[typecode][0], |
| 774 |
index+1, |
| 775 |
length)) |
| 776 |
|
| 777 |
return res |
| 778 |
|
| 779 |
def getFooter(self): |
| 780 |
colDescs = self._getColDescs() |
| 781 |
infoDict = { |
| 782 |
"nCols": len(colDescs), |
| 783 |
"colDescs": "{\n%s\n}"%",\n".join(colDescs), |
| 784 |
"extension": self.forExtension, |
| 785 |
} |
| 786 |
return (""" |
| 787 |
typedef struct FITSColDesc_s { |
| 788 |
size_t cSize; |
| 789 |
int fitsType; |
| 790 |
int index; /* in the FITS columns */ |
| 791 |
size_t arraysize; |
| 792 |
} FITSColDesc; |
| 793 |
|
| 794 |
FITSColDesc COL_DESCS[%(nCols)d] = %(colDescs)s; |
| 795 |
"""%infoDict+COMMON_MAIN_HEADER |
| 796 |
+""" |
| 797 |
fitsfile *fitsInput; |
| 798 |
int ignored, i; |
| 799 |
int status = 0; |
| 800 |
int hdutype = 0; |
| 801 |
long nRows = 0; |
| 802 |
void *data[%(nCols)d]; |
| 803 |
char *nulls[%(nCols)d]; |
| 804 |
|
| 805 |
if (argc>2) { |
| 806 |
die(USAGE); |
| 807 |
} |
| 808 |
if (argc==2) { |
| 809 |
FITSCATCH(fits_open_table(&fitsInput, argv[1], READONLY, &status)); |
| 810 |
} else { |
| 811 |
die("FITS tables cannot be read from stdin."); |
| 812 |
} |
| 813 |
|
| 814 |
FITSCATCH(fits_movabs_hdu(fitsInput, %(extension)s+1, |
| 815 |
&hdutype, &status)); |
| 816 |
assert(hdutype==BINARY_TBL); |
| 817 |
|
| 818 |
FITSCATCH(fits_get_num_rows(fitsInput, &nRows, &status)); |
| 819 |
|
| 820 |
for (i=0; i<%(nCols)d; i++) { |
| 821 |
if (COL_DESCS[i].cSize==0) { |
| 822 |
/* Column not used */ |
| 823 |
continue; |
| 824 |
|
| 825 |
} else if (COL_DESCS[i].fitsType==TSTRING) { |
| 826 |
char *stringHoldings = NULL; |
| 827 |
if (!(data[i] = malloc(nRows*sizeof(char*))) |
| 828 |
|| !(stringHoldings = malloc(nRows*(COL_DESCS[i].cSize+1)))) { |
| 829 |
die("out of memory"); |
| 830 |
} else { |
| 831 |
int k; |
| 832 |
/* Initialize the char* in the data array */ |
| 833 |
for (k=0; k<nRows; k++) { |
| 834 |
((char**)(data[i]))[k] = stringHoldings+k*(COL_DESCS[i].cSize+1); |
| 835 |
} |
| 836 |
} |
| 837 |
|
| 838 |
} else { |
| 839 |
if (!(data[i] = malloc(nRows*COL_DESCS[i].cSize*COL_DESCS[i].arraysize))) { |
| 840 |
die("out of memory"); |
| 841 |
} |
| 842 |
} |
| 843 |
if (!(nulls[i] = malloc(nRows*sizeof(char)*COL_DESCS[i].arraysize))) { |
| 844 |
die("out of memory"); |
| 845 |
} |
| 846 |
FITSCATCH(fits_read_colnull(fitsInput, COL_DESCS[i].fitsType, |
| 847 |
COL_DESCS[i].index, 1, 1, |
| 848 |
nRows*COL_DESCS[i].arraysize, data[i], nulls[i], &ignored, &status)); |
| 849 |
}"""%infoDict |
| 850 |
+COMMON_MAIN_INTRO |
| 851 |
+""" for (i=0; i<nRows; i++) {""" |
| 852 |
+LOOP_BODY_INTRO |
| 853 |
+""" tuple = getTuple(data, nulls, i);""" |
| 854 |
+LOOP_BODY_FOOT |
| 855 |
+" }\n" |
| 856 |
+COMMON_MAIN_FOOT) |
| 857 |
|
| 858 |
|
| 859 |
def getHDF5Generator(name): |
| 860 |
"""a factory for HDF5 generators classes. |
| 861 |
|
| 862 |
This is built like this because directhdf5 imports this module and |
| 863 |
we need to avoid circular imports. If this kind of construct becomes |
| 864 |
more common, we should pull basic code generation stuff into a |
| 865 |
boostercommon module. Meanwhile, this is a convenient place to |
| 866 |
produce a useful error message for when h5py is not available. |
| 867 |
""" |
| 868 |
def _(*args, **kwargs): |
| 869 |
try: |
| 870 |
from gavo.grammars import directhdf5 |
| 871 |
except ImportError: |
| 872 |
raise base.ReportableError("HDF5 boosters can only be built if h5py" |
| 873 |
" (Debian: python3-h5py) is installed.") |
| 874 |
return getattr(directhdf5, name)(*args, **kwargs) |
| 875 |
return _ |
| 876 |
|
| 877 |
|
| 878 |
def getCodeGen(grammar, tableDef): |
| 879 |
"""returns the code generator suitable for making code for grammar. |
| 880 |
""" |
| 881 |
return { |
| 882 |
"bin": BinCodeGenerator, |
| 883 |
"split": SplitCodeGenerator, |
| 884 |
"fits": FITSCodeGenerator, |
| 885 |
"col": ColCodeGenerator, |
| 886 |
"hdf5vaex": getHDF5Generator("HDF5vaexCodeGenerator"), |
| 887 |
"hdf5rootarrs": getHDF5Generator("HDF5rootarrCodeGenerator"), |
| 888 |
}[grammar.type](grammar, tableDef) |
| 889 |
|
| 890 |
|
| 891 |
def getEnum(td, grammar): |
| 892 |
code = [ |
| 893 |
"#define QUERY_N_PARS %d\n"%len(list(td)), |
| 894 |
'enum outputFields {'] |
| 895 |
for item in td: |
| 896 |
desc = item.getLabel() |
| 897 |
if not desc: |
| 898 |
desc = item.description |
| 899 |
code.append("\t%-15s /* %s, %s */"%(getNameForItem(item)+",", |
| 900 |
desc, item.type)) |
| 901 |
code.append('};\n') |
| 902 |
return code |
| 903 |
|
| 904 |
|
| 905 |
def getGetTuple(td, codeGen): |
| 906 |
code = [ |
| 907 |
codeGen.getPrototype(), |
| 908 |
"{", |
| 909 |
"\tstatic Field vals[QUERY_N_PARS];"] |
| 910 |
code.extend(indent(codeGen.getSetupCode(), "\t")) |
| 911 |
for index, item in enumerate(td): |
| 912 |
code.extend(indent(codeGen.getItemParser(item, index), "\t")) |
| 913 |
code.extend([ |
| 914 |
"\treturn vals;", |
| 915 |
"}"]) |
| 916 |
return code |
| 917 |
|
| 918 |
|
| 919 |
def indent(stringList, indentChar): |
| 920 |
return [indentChar+s for s in stringList] |
| 921 |
|
| 922 |
|
| 923 |
def buildSource(grammar, td): |
| 924 |
"""returns (possibly incomplete) C source for a booster to read into td. |
| 925 |
""" |
| 926 |
try: |
| 927 |
codeGen = getCodeGen(grammar, td) |
| 928 |
except KeyError: |
| 929 |
raise base.NotFoundError(grammar.type, "Booster type", |
| 930 |
"DaCHS' booster type registry") |
| 931 |
|
| 932 |
code = codeGen.getPreamble() |
| 933 |
code.extend(getEnum(td, grammar)) |
| 934 |
code.extend(getGetTuple(td, codeGen)) |
| 935 |
code.append(codeGen.getFooter()) |
| 936 |
return "\n".join(code) |
| 937 |
|
| 938 |
|
| 939 |
def getGrammarAndTable(grammarId): |
| 940 |
"""returns a pair of directGrammar and table being fed for a cross-rd |
| 941 |
reference. |
| 942 |
""" |
| 943 |
grammar = rscdef.getReferencedElement(grammarId, forceType=DirectGrammar) |
| 944 |
# to figure out the table built, use the parent's make |
| 945 |
makes = grammar.parent.makes |
| 946 |
if len(makes)!=1: |
| 947 |
raise base.StructureError("Directgrammar only works for data having" |
| 948 |
" exactly one table, but data '%s' has %d"%( |
| 949 |
grammar.parent.id, len(makes))) |
| 950 |
tableDef = makes[0].table |
| 951 |
return grammar, tableDef |
| 952 |
|
| 953 |
|
| 954 |
def parseCmdLine(): |
| 955 |
from optparse import OptionParser |
| 956 |
parser = OptionParser(usage = "%prog <id-of-directGrammar>") |
| 957 |
(opts, args) = parser.parse_args() |
| 958 |
if len(args)!=1: |
| 959 |
parser.print_help() |
| 960 |
sys.exit(1) |
| 961 |
return opts, args[0] |
| 962 |
|
| 963 |
|
| 964 |
def getSource(grammarId): |
| 965 |
"""returns a bytestring containing C source to parse grammarId. |
| 966 |
""" |
| 967 |
grammar, td = getGrammarAndTable(grammarId) |
| 968 |
src = buildSource(grammar, td) |
| 969 |
return src |
| 970 |
|
| 971 |
|
| 972 |
def main(): |
| 973 |
from gavo import rscdesc #noflake: cache registration |
| 974 |
try: |
| 975 |
opts, grammarId = parseCmdLine() |
| 976 |
print(getSource(grammarId)) |
| 977 |
except SystemExit as msg: |
| 978 |
sys.exit(msg.code) |