| 1 |
""" |
| 2 |
Common definitions for the GAVO VOTable modules. |
| 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 codecs |
| 12 |
import functools |
| 13 |
|
| 14 |
from gavo import utils |
| 15 |
|
| 16 |
from gavo.utils.dachstypes import (cast, TYPE_CHECKING, |
| 17 |
Any, Callable, Dict, List, Optional, Sequence, Union) |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from gavo.votable.tableparser import _StreamData |
| 21 |
from gavo.votable.model import VOTable |
| 22 |
|
| 23 |
|
| 24 |
NaN = float("NaN") |
| 25 |
|
| 26 |
class VOTableError(utils.Error): |
| 27 |
"""The base class of VOTable-related errors. |
| 28 |
""" |
| 29 |
|
| 30 |
class BadVOTableLiteral(VOTableError): |
| 31 |
"""Raised when a literal in a VOTable is invalid. |
| 32 |
""" |
| 33 |
def __init__(self, |
| 34 |
type: str, |
| 35 |
literal: str, |
| 36 |
hint: Optional[str] = None, |
| 37 |
originalException: Optional[Exception] = None, |
| 38 |
name: Optional[str] = None) -> None: |
| 39 |
if name is None: |
| 40 |
name = "<Unknown>" |
| 41 |
|
| 42 |
VOTableError.__init__(self, |
| 43 |
"Invalid literal for %s (field %s): '%s'"%(type, name, repr(literal)), |
| 44 |
hint=hint) |
| 45 |
self.type, self.literal, self.name = type, literal, name |
| 46 |
self.originalException = originalException |
| 47 |
|
| 48 |
def __str__(self) -> str: |
| 49 |
return "Invalid literal for %s (field %s): %s"%( |
| 50 |
self.type, self.name, repr(self.literal)) |
| 51 |
|
| 52 |
class BadVOTableData(VOTableError): |
| 53 |
"""Raised when something is wrong with a value being inserted into |
| 54 |
a VOTable. |
| 55 |
""" |
| 56 |
def __init__(self, |
| 57 |
msg: str, |
| 58 |
val: object, |
| 59 |
fieldName: str, |
| 60 |
hint: Optional[str] = None) -> None: |
| 61 |
VOTableError.__init__(self, msg, hint=hint) |
| 62 |
self.fieldName, self.val = fieldName, repr(val) |
| 63 |
|
| 64 |
def __getstate__(self) -> Dict[str, Any]: |
| 65 |
return {"msg": self.msg, "val": self.val, "fieldName": self.fieldName} |
| 66 |
|
| 67 |
def __str__(self) -> str: |
| 68 |
return "Field '%s', value %s: %s"%(self.fieldName, self.val, self.msg) |
| 69 |
|
| 70 |
class VOTableParseError(VOTableError): |
| 71 |
"""Raised when something is grossly wrong with the document structure. |
| 72 |
|
| 73 |
Note that the message passed already contains line and position. I'd |
| 74 |
like to have them in separate attributes, but the expat library mashes |
| 75 |
them up. iterparse.getParseError is the canonical way of obtaining these |
| 76 |
when you have no positional information. |
| 77 |
""" |
| 78 |
|
| 79 |
|
| 80 |
def qmreplace(exc: UnicodeError) -> tuple[Union[str, bytes], int]: |
| 81 |
"""a dumb handler for decoder errors. |
| 82 |
|
| 83 |
This is like python's "replace" handler except that we'll always return |
| 84 |
question marks rather than ufffd. The latter makes sense in a unicode |
| 85 |
environment, but we need this for VOTable chars, and there that's just |
| 86 |
a nuisance. |
| 87 |
""" |
| 88 |
return '?', cast(UnicodeDecodeError, exc).start+1 |
| 89 |
|
| 90 |
|
| 91 |
codecs.register_error("qmreplace", qmreplace) |
| 92 |
|
| 93 |
|
| 94 |
def validateTDComplex(val: str) -> None: |
| 95 |
"""raises an error if val is not a Tabledata complex literal. |
| 96 |
""" |
| 97 |
_ = list(map(float, val.split())) |
| 98 |
|
| 99 |
|
| 100 |
def validateVOTInt(val: str) -> None: |
| 101 |
"""raise an error if val is not a valid Tabledata int literal. |
| 102 |
|
| 103 |
After the relaxed 1.3 rules, we allow the empty string (a NULL value), too. |
| 104 |
""" |
| 105 |
if val=="": |
| 106 |
return |
| 107 |
try: |
| 108 |
int(val[2:], 16) |
| 109 |
except ValueError: |
| 110 |
int(val) |
| 111 |
|
| 112 |
|
| 113 |
def indentList(lines: List[str], indent: str) -> List[str]: |
| 114 |
"""prepends indent to all elements in lines. |
| 115 |
""" |
| 116 |
return [indent+l for l in lines] |
| 117 |
|
| 118 |
|
| 119 |
def getLoopifier(field: "VOTable.TypedElement" |
| 120 |
) -> Callable[[List[str]], List[str]] | None: |
| 121 |
"""returns a function to map code over arrays. |
| 122 |
|
| 123 |
This is used by ``*XtypeEncoderCode`` functions below, and for now only |
| 124 |
deals with 1D arrays of xtyped things, which right now means 2D arrays |
| 125 |
of votable arrays. |
| 126 |
|
| 127 |
This will return a callable accepting a list of lines (the xtype |
| 128 |
decoder for an elementary thing), nor None if the array is too complex. |
| 129 |
""" |
| 130 |
# All xtyped things are 1D arrays so far. We're using this to decide |
| 131 |
# if we have to loop |
| 132 |
if field.isMultiDim(): |
| 133 |
if field.arraysize.count("x")==1: |
| 134 |
# 1-d array of xtyped thing; handle it |
| 135 |
def loopify(code: List[str]) -> List[str]: |
| 136 |
return [ |
| 137 |
"seq, arr = val, []", |
| 138 |
"for val in seq:", |
| 139 |
]+indentList(code, " ")+[ |
| 140 |
" arr.append(val)", |
| 141 |
"val = arr"] |
| 142 |
return loopify |
| 143 |
else: |
| 144 |
# just forget it; if there are native objects in the value, it's fail, |
| 145 |
# but since the decoder operate the same way, roundtrip will work. |
| 146 |
return None |
| 147 |
|
| 148 |
return lambda x: x |
| 149 |
|
| 150 |
|
| 151 |
def getXtypeEncoderCode(field: "VOTable.TypedElement") -> List[str]: |
| 152 |
"""returns code that turns special internal representations for |
| 153 |
xtyped fields to what's serialised in VOTables. |
| 154 |
|
| 155 |
For None or unknown xtypes, this will return an empty list. Otherwise, |
| 156 |
it expects the value in a local variable val and will leave the transformed |
| 157 |
value there. |
| 158 |
|
| 159 |
This is currently only called for char and float arrays, as no |
| 160 |
xtypes are defined for other types. If that changes, you'll have |
| 161 |
to change the ``*_enc`` modules. |
| 162 |
|
| 163 |
This will handle 1D arrays of xtyped things but nothing more deeply |
| 164 |
nested. More deeply nested structures will be left alone (which will |
| 165 |
only work under very special conditions and yield ugly error messages |
| 166 |
otherwise). |
| 167 |
""" |
| 168 |
loopify = getLoopifier(field) |
| 169 |
if loopify is None: |
| 170 |
return [] |
| 171 |
|
| 172 |
if (field.xtype=="adql:TIMESTAMP" # legacy, delete ~ 2024 |
| 173 |
or field.xtype=="timestamp"): |
| 174 |
return loopify([ |
| 175 |
"if isinstance(val, datetime.datetime):", |
| 176 |
" val = utils.formatISODT(val)"]) |
| 177 |
|
| 178 |
if field.xtype=="timestamp-interval": # local addition |
| 179 |
return loopify([ |
| 180 |
"if isinstance(val, datetime.datetime):", |
| 181 |
" val = utils.formatISODT(val)"]) |
| 182 |
|
| 183 |
elif field.xtype=="dachs:DATE": |
| 184 |
return loopify([ |
| 185 |
"if isinstance(val, datetime.date):", |
| 186 |
" val = val.isoformat()"]) |
| 187 |
|
| 188 |
elif field.xtype in ["adql:POINT", "adql:REGION"]: |
| 189 |
return loopify([ |
| 190 |
"if isinstance(val, pgsphere.PgSAdapter):", |
| 191 |
" val = val.asSTCS('UNKNOWNFrame')"]) |
| 192 |
|
| 193 |
elif field.xtype in ["point", "circle", "polygon", "moc", "x-box"]: |
| 194 |
return loopify([ |
| 195 |
"if isinstance(val, pgsphere.PgSAdapter):", |
| 196 |
" val = val.asDALI()"]) |
| 197 |
|
| 198 |
elif field.xtype=="json": |
| 199 |
return [ |
| 200 |
"if isinstance(val, (dict, list)):", |
| 201 |
" val = json.dumps(val)", |
| 202 |
"else:", |
| 203 |
" val = coding.forceASCII(val)"] |
| 204 |
|
| 205 |
else: |
| 206 |
return [] |
| 207 |
|
| 208 |
|
| 209 |
def getXtypeDecoderCode(field: "VOTable.TypedElement") -> List[str]: |
| 210 |
"""returns code that turns generic VOTable arrays into special internal |
| 211 |
representations based on xtype. |
| 212 |
|
| 213 |
This returns a list of lines or an empty list if no known xtype |
| 214 |
is found. The code is executed with the unpacked array seen as val, |
| 215 |
and it should set val to the special representation. |
| 216 |
|
| 217 |
This will handle 1D arrays of xtyped things but nothing more deeply |
| 218 |
nested. More deeply nested structures will be left alone (which is |
| 219 |
ok for round-tripping but probably will fail when DaCHS components |
| 220 |
want to process stuff). |
| 221 |
""" |
| 222 |
if not field.xtype: |
| 223 |
return [] |
| 224 |
|
| 225 |
|
| 226 |
loopify = getLoopifier(field) |
| 227 |
if loopify is None: |
| 228 |
return [] |
| 229 |
|
| 230 |
src = [ |
| 231 |
# the val.strip() is a workaround for a TOPCAT bug that would sometimes |
| 232 |
# turn empty strings into single blanks. |
| 233 |
"if not val or (isinstance(val, str) and not val.strip()):", |
| 234 |
" val = None", |
| 235 |
"else:"] |
| 236 |
|
| 237 |
if field.xtype=="adql:POINT": |
| 238 |
src.extend([ |
| 239 |
" val = stc.parseSimpleSTCS(val)"]) |
| 240 |
|
| 241 |
elif field.xtype=="adql:REGION": |
| 242 |
src.extend([ |
| 243 |
" val = stc.simpleSTCSToPolygon(val)"]) |
| 244 |
|
| 245 |
elif field.xtype=="point": |
| 246 |
src.extend([ |
| 247 |
" val = pgsphere.SPoint.fromDALI(val)"]) |
| 248 |
|
| 249 |
elif field.xtype=="circle": |
| 250 |
src.extend([ |
| 251 |
" val = pgsphere.SCircle.fromDALI(val)"]) |
| 252 |
|
| 253 |
elif field.xtype=="polygon": |
| 254 |
src.extend([ |
| 255 |
" val = pgsphere.SPoly.fromDALI(val)"]) |
| 256 |
|
| 257 |
elif field.xtype=="moc": |
| 258 |
src.extend([ |
| 259 |
" val = pgsphere.SMoc.fromDALI(val)"]) |
| 260 |
|
| 261 |
elif field.xtype=="x-box": |
| 262 |
src.extend([ |
| 263 |
" val = pgsphere.SBox.fromDALI(val)"]) |
| 264 |
|
| 265 |
elif (field.xtype=="adql:TIMESTAMP" |
| 266 |
or field.xtype=="timestamp" |
| 267 |
or field.xtype=="timestamp-interval"): |
| 268 |
src.extend([ |
| 269 |
" val = parseDefaultDatetime(val)"]) |
| 270 |
|
| 271 |
# GAVO-specific extension for consistency in our type systems |
| 272 |
elif field.xtype=="dachs:DATE": |
| 273 |
src.extend([ |
| 274 |
" val = parseDefaultDate(val)"]) |
| 275 |
|
| 276 |
else: |
| 277 |
# unknown xtype; ignore it and process stuff as usual |
| 278 |
return [] |
| 279 |
|
| 280 |
return loopify(src) |
| 281 |
|
| 282 |
|
| 283 |
class NULLFlags: |
| 284 |
"""an interface to the BINARY2 NULL flags. |
| 285 |
|
| 286 |
Construct it with the number of fields, then use |
| 287 |
""" |
| 288 |
masks = [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01] |
| 289 |
|
| 290 |
def __init__(self, nFields: int) -> None: |
| 291 |
self.nFields = nFields |
| 292 |
self.nBytes = (self.nFields+7)//8 |
| 293 |
|
| 294 |
def serialize(self, nullMap: List[bool]) -> bytes: |
| 295 |
"""returns null bytes for nullMap, which is a sequence of booleans |
| 296 |
with Trues where the field is NULL. |
| 297 |
|
| 298 |
It is an error to pass in nullMaps with lengths!=nFields. |
| 299 |
""" |
| 300 |
assert len(nullMap)==self.nFields |
| 301 |
mapBytes, curBits, val = [], 0, 0 |
| 302 |
for isNull in nullMap: |
| 303 |
if isNull: |
| 304 |
val = (val<<1)+1 |
| 305 |
else: |
| 306 |
val <<= 1 |
| 307 |
curBits += 1 |
| 308 |
if curBits==8: |
| 309 |
mapBytes.append(val) |
| 310 |
curBits, val = 0, 0 |
| 311 |
|
| 312 |
if curBits: |
| 313 |
val <<= (8-curBits) |
| 314 |
mapBytes.append(val) |
| 315 |
return bytes(mapBytes) |
| 316 |
|
| 317 |
def serializeFromRow(self, row: Sequence[object]) -> bytes: |
| 318 |
"""returns null bytes for a row, which is a sequence of values. |
| 319 |
Everything that's None is flagged as NULL. |
| 320 |
""" |
| 321 |
return self.serialize([v is None for v in row]) |
| 322 |
|
| 323 |
def deserialize(self, toDecode: bytes) -> List[bool]: |
| 324 |
"""returns a sequence of booleans giving for each element in a row |
| 325 |
if there's a NULL there. |
| 326 |
""" |
| 327 |
nulls = [] |
| 328 |
for byte in toDecode: |
| 329 |
for mask in self.masks: |
| 330 |
if mask&byte: |
| 331 |
nulls.append(True) |
| 332 |
else: |
| 333 |
nulls.append(False) |
| 334 |
if len(nulls)==self.nFields: |
| 335 |
break |
| 336 |
return nulls |
| 337 |
|
| 338 |
def getFromFile(self, file: "_StreamData") -> List[bool]: |
| 339 |
"""returns a sequence of booleans giving for each element in a row |
| 340 |
whethere there's a NULL there. |
| 341 |
""" |
| 342 |
return self.deserialize(file.read(self.nBytes)) |
| 343 |
|
| 344 |
|
| 345 |
def isMultiDim(arraysize: str) -> bool: |
| 346 |
"""returns True if the VOTable arraysize denotes a >1D-array. |
| 347 |
""" |
| 348 |
return arraysize is not None and "x" in arraysize |
| 349 |
|
| 350 |
|
| 351 |
def hasVarLength(arraysize: str) -> bool: |
| 352 |
"""returns True if the VOTable arraysize denotes a variable-length array. |
| 353 |
|
| 354 |
This is, of course, False for None arraysizes, |
| 355 |
""" |
| 356 |
return bool(arraysize) and arraysize.endswith("*") |
| 357 |
|
| 358 |
|
| 359 |
def getLength(arraysize: Optional[str]) -> int | None: |
| 360 |
"""returns the number of elements expected for an array described with |
| 361 |
the VOTable attribute arraysize. |
| 362 |
|
| 363 |
A 1-element array isn't told apart from a scalar here. Both return 1. |
| 364 |
For variable-length arrays, this returns None. |
| 365 |
|
| 366 |
Bad arraysize specs will give ValueErrors (perhaps not always with the |
| 367 |
most helpful messages). |
| 368 |
|
| 369 |
>>> getLength(None) |
| 370 |
1 |
| 371 |
>>> getLength("*") |
| 372 |
>>> getLength("5") |
| 373 |
5 |
| 374 |
>>> getLength("5x*") |
| 375 |
>>> getLength("5x6*") |
| 376 |
>>> getLength("7x5x6") |
| 377 |
210 |
| 378 |
>>> getLength("7*x5x6") |
| 379 |
Traceback (most recent call last): |
| 380 |
ValueError: invalid literal for int() with base 10: '7*' |
| 381 |
""" |
| 382 |
if arraysize is None: |
| 383 |
return 1 |
| 384 |
if arraysize.endswith("*"): |
| 385 |
return None |
| 386 |
elif isMultiDim(arraysize): |
| 387 |
return functools.reduce( |
| 388 |
lambda a, b: a*b, map(int, arraysize.split("x"))) |
| 389 |
else: |
| 390 |
try: |
| 391 |
return int(arraysize) |
| 392 |
except ValueError: |
| 393 |
# fall through to exception at function exit |
| 394 |
pass |
| 395 |
raise ValueError("Invalid arraysize specification: %s"%arraysize) |
| 396 |
|
| 397 |
|
| 398 |
def getShape(datatype: str, arraysize: Optional[str] |
| 399 |
) -> tuple[int, ...] | None: |
| 400 |
"""returns a numpy-compatible shape for a VOTable arraysize. |
| 401 |
|
| 402 |
For variable length 1D arrays, this returns None; for 2+D arrays, the |
| 403 |
last dimension is currently replaced by 1. Which doesn't sound smart. |
| 404 |
""" |
| 405 |
if arraysize is None: |
| 406 |
return None |
| 407 |
|
| 408 |
if datatype=="char" and not "x" in arraysize: |
| 409 |
# special case: 1d char arrays are just scalar strings |
| 410 |
return None |
| 411 |
|
| 412 |
if arraysize=="*": |
| 413 |
return None # What should we really return here? |
| 414 |
|
| 415 |
val = arraysize.replace("*", "") |
| 416 |
if "x" in val: |
| 417 |
if val.endswith("x"): # variable last dimension |
| 418 |
val = val+'1' |
| 419 |
return tuple(int(d) for d in val.split("x")) |
| 420 |
|
| 421 |
else: |
| 422 |
return (int(val),) |
| 423 |
|
| 424 |
|
| 425 |
if __name__=="__main__": # pragma: no cover |
| 426 |
import doctest |
| 427 |
doctest.testmod() |