| 1 |
""" |
| 2 |
Generating VOTables from internal data representations. |
| 3 |
|
| 4 |
This is glue code to the more generic GAVO votable library. In particular, |
| 5 |
it governs the application of base.SerManagers and their column descriptions |
| 6 |
(which are what is passed around as colDescs in this module to come up with |
| 7 |
VOTable FIELDs and the corresponding values. |
| 8 |
|
| 9 |
You should access this module through formats.votable. |
| 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 contextlib |
| 19 |
import datetime |
| 20 |
import functools |
| 21 |
import io |
| 22 |
import itertools |
| 23 |
|
| 24 |
from gavo import base |
| 25 |
from gavo import dm |
| 26 |
from gavo import rsc |
| 27 |
from gavo import stc |
| 28 |
from gavo import utils |
| 29 |
from gavo import votable |
| 30 |
from gavo.base import meta |
| 31 |
from gavo.base import valuemappers |
| 32 |
from gavo.formats import common |
| 33 |
from gavo.votable import V |
| 34 |
from gavo.votable import modelgroups |
| 35 |
|
| 36 |
|
| 37 |
class Error(base.Error): |
| 38 |
pass |
| 39 |
|
| 40 |
|
| 41 |
tableEncoders = { |
| 42 |
"td": V.TABLEDATA, |
| 43 |
"binary": V.BINARY, |
| 44 |
"binary2": V.BINARY2, |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
class VOTableContext(utils.IdManagerMixin): |
| 49 |
"""A context object for writing VOTables. |
| 50 |
|
| 51 |
The constructor arguments work as keyword arguments to ``getAsVOTable``. |
| 52 |
Some other high-level functions accept finished contexts. |
| 53 |
|
| 54 |
This class provides management for unique ID attributes, the value mapper |
| 55 |
registry, and possibly additional services for writing VOTables. |
| 56 |
|
| 57 |
VOTableContexts optionally take |
| 58 |
|
| 59 |
* a value mapper registry (by default, valuemappers.defaultMFRegistry) |
| 60 |
* the tablecoding (currently, td, binary, or binary2) |
| 61 |
* version=(1,1) to order a 1.1-version VOTable, (1,2) for 1.2. |
| 62 |
(default is now 1.4). |
| 63 |
* acquireSamples=False to suppress reading some rows to get |
| 64 |
samples for each column |
| 65 |
* suppressNamespace=False to leave out a namespace declaration |
| 66 |
(mostly convenient for debugging) |
| 67 |
* overflowElement (see votable.tablewriter.OverflowElement) |
| 68 |
|
| 69 |
There's also an attribute produceVODML that will automatically be |
| 70 |
set for VOTable 1.5; you can set it to true manually, but the |
| 71 |
resulting VOTables will probably be invalid. |
| 72 |
|
| 73 |
If VO-DML processing is enabled, the context also manages models declared; |
| 74 |
that's the modelsUsed dictionary, mapping prefix -> dm.Model instances |
| 75 |
""" |
| 76 |
def __init__(self, mfRegistry=valuemappers.defaultMFRegistry, |
| 77 |
tablecoding='binary', version=None, acquireSamples=True, |
| 78 |
suppressNamespace=False, overflowElement=None): |
| 79 |
self.mfRegistry = mfRegistry |
| 80 |
self.tablecoding = tablecoding |
| 81 |
self.version = version or (1,5) |
| 82 |
self.acquireSamples = acquireSamples |
| 83 |
self.suppressNamespace = suppressNamespace |
| 84 |
self.overflowElement = overflowElement |
| 85 |
self._containerStack = [] |
| 86 |
self._tableStack = [] |
| 87 |
self._dmAttrStack = [] |
| 88 |
self._pushedRefs = {} |
| 89 |
|
| 90 |
# state for VO-DML serialisation |
| 91 |
self.produceVODML = self.version[0]>1 or self.version[1]>5 |
| 92 |
# group-serialising annotations must enter their python ids when they |
| 93 |
# end up in the tree so they get only included once when |
| 94 |
# referenced by multiple other annotations. |
| 95 |
self.groupIdsInTree = set() |
| 96 |
self.modelsDeclared = set() |
| 97 |
self.rootVODML = V.VODML() |
| 98 |
self.vodmlTemplates = V.TEMPLATES() |
| 99 |
self.rootVODML[self.vodmlTemplates] |
| 100 |
|
| 101 |
# While we're producing both note-style STC1 utypes and ad-hoc |
| 102 |
# COOSYS refs from <stc>, make them share COOSYS elements based |
| 103 |
# on the id of the underlying STC ast. Remove this when we've |
| 104 |
# dumped STC1 utypes. |
| 105 |
self.coosysByAST = {} |
| 106 |
|
| 107 |
def addVODMLPrefix(self, prefix): |
| 108 |
"""arranges the DM with prefix to be included in modelsUsed. |
| 109 |
""" |
| 110 |
if prefix not in self.modelsDeclared: |
| 111 |
self.rootVODML[dm.getModelForPrefix(prefix).getVOT(self, None)] |
| 112 |
self.modelsDeclared.add(prefix) |
| 113 |
|
| 114 |
def addVODMLMaterial(self, stuff): |
| 115 |
"""adds VODML annotation to this VOTable. |
| 116 |
|
| 117 |
Note that it will only be rendered if produceVODML is true |
| 118 |
(in general, for target versions >1.5). |
| 119 |
""" |
| 120 |
self.vodmlTemplates[stuff] |
| 121 |
|
| 122 |
def makeTable(self, table): |
| 123 |
"""returns xmlstan for a table. |
| 124 |
|
| 125 |
This is exposed as a method of context as the dm subpackage |
| 126 |
needs it, but I don't want to import formats there (yet). |
| 127 |
|
| 128 |
This may go away as I fix the interdependence of dm, votable, and |
| 129 |
format. |
| 130 |
""" |
| 131 |
return makeTable(self, table) |
| 132 |
|
| 133 |
def getEnclosingTable(self): |
| 134 |
"""returns the xmlstan element of the table currently built. |
| 135 |
|
| 136 |
This returns a ValueError if the context isn't aware of a table |
| 137 |
being built. |
| 138 |
|
| 139 |
(This depends builders using activeContainer) |
| 140 |
""" |
| 141 |
for el in reversed(self._containerStack): |
| 142 |
if el.name_=="TABLE": |
| 143 |
return el |
| 144 |
raise ValueError("Not currently building a table.") |
| 145 |
|
| 146 |
def getEnclosingResource(self): |
| 147 |
"""returns the xmlstan element of the resource currently built. |
| 148 |
|
| 149 |
This returns a ValueError if the context isn't aware of a resource |
| 150 |
being built. |
| 151 |
|
| 152 |
(This depends builders using activeContainer) |
| 153 |
""" |
| 154 |
for el in reversed(self._containerStack): |
| 155 |
if el.name_=="RESOURCE": |
| 156 |
return el |
| 157 |
raise ValueError("Not currently building a table.") |
| 158 |
|
| 159 |
def getEnclosingContainer(self): |
| 160 |
"""returns the innermost container element the builders have declared. |
| 161 |
""" |
| 162 |
return self._containerStack[-1] |
| 163 |
|
| 164 |
@property |
| 165 |
def currentTable(self): |
| 166 |
"""the DaCHS table object from which things are currently built. |
| 167 |
|
| 168 |
If no builder has declared a table being built (using buildingFromTable), |
| 169 |
it's a value error. |
| 170 |
""" |
| 171 |
if not self._tableStack: |
| 172 |
raise ValueError("No table being processed.") |
| 173 |
return self._tableStack[-1] |
| 174 |
|
| 175 |
@contextlib.contextmanager |
| 176 |
def activeContainer(self, container): |
| 177 |
"""a context manager to be called by VOTable builders when |
| 178 |
they open a new TABLE or RESOURCE. |
| 179 |
""" |
| 180 |
self._containerStack.append(container) |
| 181 |
try: |
| 182 |
yield |
| 183 |
finally: |
| 184 |
self._containerStack.pop() |
| 185 |
|
| 186 |
@contextlib.contextmanager |
| 187 |
def buildingFromTable(self, table): |
| 188 |
"""a context manager to control code that works on a DaCHS table. |
| 189 |
""" |
| 190 |
self._tableStack.append(table) |
| 191 |
try: |
| 192 |
yield |
| 193 |
finally: |
| 194 |
self._tableStack.pop() |
| 195 |
|
| 196 |
@contextlib.contextmanager |
| 197 |
def settingAttribute(self, dmAttr): |
| 198 |
"""a context manager controlling the curDMAttr attribute. |
| 199 |
|
| 200 |
This is used by the DM annotators that sometimes need to directly |
| 201 |
manipulate the ATTRIBUTE element. |
| 202 |
""" |
| 203 |
self._dmAttrStack.append(dmAttr) |
| 204 |
try: |
| 205 |
yield dmAttr |
| 206 |
finally: |
| 207 |
self._dmAttrStack.pop() |
| 208 |
|
| 209 |
@property |
| 210 |
def curDMAttr(self): |
| 211 |
"""returns the V.ATTRIBUTE element currently worked on. |
| 212 |
|
| 213 |
This will raise an IndexError if not ATTRIBUTE is being built at the |
| 214 |
moment. |
| 215 |
""" |
| 216 |
return self._dmAttrStack[-1] |
| 217 |
|
| 218 |
def pushRefFor(self, rdEl, refVal): |
| 219 |
"""orders refVal to be set as ref on rdEl's VOTable representation |
| 220 |
if such a thing is being serialised. |
| 221 |
|
| 222 |
This currently is more a hack for PARAMs with COOSYS than something |
| 223 |
that should be really used; if this were to become a general pattern, |
| 224 |
we should work out a way to assign the ref if rdEl's representation |
| 225 |
already is in the tree... |
| 226 |
""" |
| 227 |
self._pushedRefs[id(rdEl)] = refVal |
| 228 |
|
| 229 |
def addID(self, rdEl, votEl): |
| 230 |
"""adds an ID attribute to votEl if rdEl has an id managed by self. |
| 231 |
|
| 232 |
Also, if a ref has been noted for rdEl, a ref attribute is being |
| 233 |
added, too. This is a special hack for params and coosys; and I suspect |
| 234 |
we shouldn't go beyond that. |
| 235 |
""" |
| 236 |
try: |
| 237 |
votEl.ID = self.getIdFor(rdEl) |
| 238 |
except base.NotFoundError: |
| 239 |
# the param is not referenced and thus needs no ID |
| 240 |
pass |
| 241 |
|
| 242 |
if id(rdEl) in self._pushedRefs: |
| 243 |
votEl.ref = self._pushedRefs[id(rdEl)] |
| 244 |
|
| 245 |
return votEl |
| 246 |
|
| 247 |
|
| 248 |
################# Turning simple metadata into VOTable elements. |
| 249 |
|
| 250 |
def _iterInfoInfos(dataSet): |
| 251 |
"""returns a sequence of V.INFO items from the info meta of dataSet. |
| 252 |
""" |
| 253 |
for infoItem in dataSet.getMeta("info", default=[]): |
| 254 |
name, value, id = infoItem.infoName, infoItem.infoValue, infoItem.infoId |
| 255 |
yield V.INFO(name=name, value=value, ID=id)[infoItem.getContent()] |
| 256 |
|
| 257 |
|
| 258 |
def _iterWarningInfos(dataSet): |
| 259 |
"""yields INFO items containing warnings from the tables in dataSet. |
| 260 |
""" |
| 261 |
for table in list(dataSet.tables.values()): |
| 262 |
for warning in table.getMeta("_warning", propagate=False, default=[]): |
| 263 |
yield V.INFO(name="warning", value="In table %s: %s"%( |
| 264 |
table.tableDef.id, warning.getContent("text", macroPackage=table))) |
| 265 |
|
| 266 |
|
| 267 |
def _iterDatalinkResources(ctx, dataSet): |
| 268 |
"""yields RESOURCE elements for datalink services defined for tables |
| 269 |
we have. |
| 270 |
|
| 271 |
This needs to be called before the tables are serialised because we |
| 272 |
put ids on fields. |
| 273 |
""" |
| 274 |
for table in list(dataSet.tables.values()): |
| 275 |
for svcMeta in table.iterMeta("_associatedDatalinkService"): |
| 276 |
try: |
| 277 |
service = base.resolveId(table.tableDef.rd, |
| 278 |
base.getMetaText(svcMeta, "serviceId")) |
| 279 |
|
| 280 |
# datalink cannot be globally imported, as we can't depend on |
| 281 |
# anything in protocols. Importing it here is ok, though; |
| 282 |
# we'll just not produce datalink declarations if the server |
| 283 |
# can't do it. |
| 284 |
from gavo.protocols import datalink |
| 285 |
yield datalink.makeDatalinkServiceDescriptor( |
| 286 |
ctx, service, table.tableDef, |
| 287 |
base.getMetaText(svcMeta, "idColumn")) |
| 288 |
|
| 289 |
# Temporary hack: for now, if something wants to have immediate |
| 290 |
# soda resources on results (so far, only SSAP does), they add |
| 291 |
# generating functions to data.sodaGenerators. This needs |
| 292 |
# to be replaced with something better when we understand what |
| 293 |
# we actually want. |
| 294 |
while getattr(dataSet, "sodaGenerators", []): |
| 295 |
yield dataSet.sodaGenerators.pop()(ctx) |
| 296 |
|
| 297 |
except Exception as ex: |
| 298 |
base.ui.notifyWarning("RD %s: request for datalink service" |
| 299 |
" could not be satisfied (%s)"%( |
| 300 |
getattr(table.tableDef.rd, "sourceId", "<internal>"), |
| 301 |
ex)) |
| 302 |
|
| 303 |
|
| 304 |
def _iterUniqueInfosFromMeta( |
| 305 |
ctx, metaCarriers, metaKey, infoName, ucd, infoText): |
| 306 |
"""yields standard INFOs from meta items on a sequence of metaCarriers. |
| 307 |
|
| 308 |
metaKey references the meta items to make INFOs from. InfoName and |
| 309 |
ucd are set on the INFO elements, infoText will be formatted |
| 310 |
into the body text, where this functions locals are template arguments. |
| 311 |
That includes value as the INFO's value. |
| 312 |
|
| 313 |
For when the UCD depends on the INFO's value, ucd can also be |
| 314 |
a callable, which receives the value and must return the UCD. |
| 315 |
|
| 316 |
The function makes sure that no item is returned more than once. |
| 317 |
""" |
| 318 |
seenItems = set() |
| 319 |
if ctx.version<(1,2): |
| 320 |
# No UCD on INFO for ancient VOTables |
| 321 |
ucd = None |
| 322 |
|
| 323 |
for mc in metaCarriers: |
| 324 |
for metaValue in mc.iterMeta(metaKey, propagate=True): |
| 325 |
value = metaValue.getContent("text", macroPackage=mc) |
| 326 |
if value in seenItems: |
| 327 |
continue |
| 328 |
seenItems.add(value) |
| 329 |
|
| 330 |
if callable(ucd): |
| 331 |
thisUCD = ucd(value) |
| 332 |
else: |
| 333 |
thisUCD = ucd |
| 334 |
|
| 335 |
yield V.INFO(name=infoName, value=value, ucd=thisUCD)[ |
| 336 |
infoText.format(**locals())] |
| 337 |
|
| 338 |
|
| 339 |
def _iterResourceMeta(ctx, dataSet): |
| 340 |
"""adds Data Origin metadata to the RESOURCE parent. |
| 341 |
|
| 342 |
At this point, we don't know the creating service any more, and depending |
| 343 |
on the sort of thing we are doing here, that's where we should take |
| 344 |
the metadata from. We therefore inspect the contributingMetaCarriers |
| 345 |
attribute on the data item coming in and integrate the metadata |
| 346 |
from everything that's in there (usually a service, but in the TAP |
| 347 |
case perhaps also joined tables). |
| 348 |
|
| 349 |
If this kind of things becomes more common, we should think of a |
| 350 |
less hacky way to smuggle extra meta sources in here. |
| 351 |
|
| 352 |
This, by the way, is where we mainly implement data origin, although |
| 353 |
renderers may need to cooperate for some items (e.g., request). |
| 354 |
""" |
| 355 |
yield V.DESCRIPTION[base.getMetaText(dataSet, "description", |
| 356 |
macroPackage=dataSet.dd.rd, propagate=False)] |
| 357 |
for el in itertools.chain( |
| 358 |
_iterInfoInfos(dataSet), _iterWarningInfos(dataSet)): |
| 359 |
yield el |
| 360 |
|
| 361 |
yield V.INFO(name="server_software", value=base.SERVER_SOFTWARE)[ |
| 362 |
"Software that produced this VOTable"] |
| 363 |
yield V.INFO(name="server", value=base.getConfig("web", "serverURL"))[ |
| 364 |
"Base URI of the server"] |
| 365 |
|
| 366 |
sources = dataSet.contributingMetaCarriers |
| 367 |
|
| 368 |
yield from _iterUniqueInfosFromMeta(ctx, sources, |
| 369 |
"howtociteLink", |
| 370 |
"citation", |
| 371 |
"", |
| 372 |
"Advice on citing this resource") |
| 373 |
yield from _iterUniqueInfosFromMeta(ctx, sources, |
| 374 |
"source", |
| 375 |
"publication_id", |
| 376 |
lambda value: "meta.bib.bibcode" |
| 377 |
if utils.couldBeABibcode(value) |
| 378 |
else "meta.bib", |
| 379 |
"A bibliographic source citable for (parts of) this data") |
| 380 |
|
| 381 |
yield from _iterUniqueInfosFromMeta(ctx, sources, |
| 382 |
"request_uri", |
| 383 |
"request", |
| 384 |
"meta.ref.url", |
| 385 |
"Request string that led up to this result.") |
| 386 |
|
| 387 |
for src in sources: |
| 388 |
if getattr(src, "name_", None)=="service": |
| 389 |
yield from _iterUniqueInfosFromMeta(ctx, [src], |
| 390 |
"published_identifier", |
| 391 |
"ivoid_service", |
| 392 |
"meta.ref.ivoid", |
| 393 |
"Originating VO service") |
| 394 |
else: |
| 395 |
yield from _iterUniqueInfosFromMeta(ctx, [src], |
| 396 |
"published_identifier", |
| 397 |
"ivoid", |
| 398 |
"meta.ref.ivoid", |
| 399 |
"Originating VO resource") |
| 400 |
|
| 401 |
yield from _iterUniqueInfosFromMeta(ctx, sources, |
| 402 |
"publisher", |
| 403 |
"publisher", |
| 404 |
None, |
| 405 |
"Data centre that has delivered the data") |
| 406 |
yield from _iterUniqueInfosFromMeta(ctx, sources, |
| 407 |
"rights", |
| 408 |
"rights", |
| 409 |
None, |
| 410 |
"Legal conditions applicable to (parts of) the data contained") |
| 411 |
yield from _iterUniqueInfosFromMeta(ctx, sources, |
| 412 |
"rights.rightsURI", |
| 413 |
"rights_uri", |
| 414 |
None, |
| 415 |
"URI of legal conditions applicable to (parts of) the data contained") |
| 416 |
|
| 417 |
yield V.INFO(name="request_date", ucd="time.creation", |
| 418 |
value=utils.formatISODT(datetime.datetime.utcnow())) |
| 419 |
yield from _iterUniqueInfosFromMeta(ctx, sources, |
| 420 |
"contact.email", |
| 421 |
"contact", |
| 422 |
"meta.email", |
| 423 |
"Contact option") |
| 424 |
yield from _iterUniqueInfosFromMeta(ctx, sources, |
| 425 |
"referenceURL", |
| 426 |
"reference_url", |
| 427 |
"meta.ref.url", |
| 428 |
"More information on the data Source") |
| 429 |
yield from _iterUniqueInfosFromMeta(ctx, sources, |
| 430 |
"version", |
| 431 |
"resource_version", |
| 432 |
"meta.version", |
| 433 |
"Version of a contributing resource.") |
| 434 |
yield from _iterUniqueInfosFromMeta(ctx, sources, |
| 435 |
"creator.name", |
| 436 |
"creator", |
| 437 |
"meta.bib.author", |
| 438 |
"Name of a person or entity that produced a contributing resource") |
| 439 |
|
| 440 |
|
| 441 |
def _iterToplevelMeta(ctx, dataSet): |
| 442 |
"""yields meta elements for the entire VOTABLE from dataSet's RD. |
| 443 |
""" |
| 444 |
rd = dataSet.dd.rd |
| 445 |
if rd is None: |
| 446 |
return |
| 447 |
yield V.DESCRIPTION[base.getMetaText(rd, "description", |
| 448 |
macroPackage=dataSet.dd.rd)] |
| 449 |
|
| 450 |
for infoItem in rd.iterMeta("copyright"): |
| 451 |
yield V.INFO(name="legal", value=infoItem.getContent("text", |
| 452 |
macroPackage=dataSet.dd.rd)) |
| 453 |
|
| 454 |
|
| 455 |
# link elements may be defined using the votlink meta on RESOURCE, TABLE, |
| 456 |
# GROUP, FIELD, or PARAM; within in the DC, GROUPs have no meta structure, |
| 457 |
# so we don't run _linkBuilder on them. |
| 458 |
|
| 459 |
def _makeLinkForMeta(args, localattrs=None): |
| 460 |
localattrs.update({"href": args[0]}) |
| 461 |
return V.LINK(**localattrs) |
| 462 |
|
| 463 |
|
| 464 |
_linkBuilder = meta.ModelBasedBuilder([ |
| 465 |
('votlink', _makeLinkForMeta, (), { |
| 466 |
"href": "href", |
| 467 |
"content_role": "role", |
| 468 |
"content_type": "contentType", |
| 469 |
"name": "linkname",})]) |
| 470 |
|
| 471 |
|
| 472 |
################# Generating FIELD and PARAM elements. |
| 473 |
|
| 474 |
def _makeValuesForColDesc(colDesc): |
| 475 |
"""returns a VALUES element for a column description. |
| 476 |
|
| 477 |
This just stringifies whatever is in colDesc's respective columns, |
| 478 |
so for anything fancy pass in byte strings to begin with. |
| 479 |
""" |
| 480 |
valEl = V.VALUES() |
| 481 |
if colDesc.get("min") is None: |
| 482 |
colDesc["min"] = getattr(colDesc.original.values, "min", None) |
| 483 |
if colDesc.get("max") is None: |
| 484 |
colDesc["max"] = getattr(colDesc.original.values, "max", None) |
| 485 |
|
| 486 |
if colDesc["max"] is utils.Infimum or colDesc["max"]=="": |
| 487 |
colDesc["max"] = None |
| 488 |
if colDesc["min"] is utils.Supremum or colDesc["min"]=="": |
| 489 |
colDesc["min"] = None |
| 490 |
|
| 491 |
if colDesc["min"] is not None: |
| 492 |
valEl[V.MIN(value=str(colDesc["min"]))] |
| 493 |
if colDesc["max"] is not None: |
| 494 |
valEl[V.MAX(value=str(colDesc["max"]))] |
| 495 |
if colDesc["nullvalue"] is not None: |
| 496 |
valEl(null=colDesc["nullvalue"]) |
| 497 |
|
| 498 |
for option in getattr(colDesc.original.values, "options", []): |
| 499 |
valEl[V.OPTION(value=option.content_ or "", name=option.title)] |
| 500 |
|
| 501 |
return valEl |
| 502 |
|
| 503 |
|
| 504 |
# keys copied from colDescs to FIELDs in _getFieldFor |
| 505 |
_voFieldCopyKeys = ["name", "datatype", "ucd", "utype", "ref"] |
| 506 |
|
| 507 |
def defineField(ctx, element, colDesc): |
| 508 |
"""adds attributes and children to element from colDesc. |
| 509 |
|
| 510 |
element can be a V.FIELD or a V.PARAM *instance* and is changed in place. |
| 511 |
|
| 512 |
This function returns None to remind people we're changing in place |
| 513 |
here. |
| 514 |
""" |
| 515 |
# bomb if you got an Element rather than an instance -- with an |
| 516 |
# Element, things would appear to work, but changes are lost when |
| 517 |
# this function ends. |
| 518 |
assert not isinstance(element, type), ("Got FIELD/PARAM element" |
| 519 |
" instead of instance in VOTable defineField") |
| 520 |
|
| 521 |
if colDesc["arraysize"]!='1': |
| 522 |
element(arraysize=colDesc["arraysize"]) |
| 523 |
# (for char, keep arraysize='1' to keep topcat happy) |
| 524 |
if colDesc["datatype"]=='char' and colDesc["arraysize"]=='1': |
| 525 |
element(arraysize='1') |
| 526 |
|
| 527 |
if colDesc["unit"]: |
| 528 |
element(unit=colDesc["unit"]) |
| 529 |
element(ID=colDesc["id"]) |
| 530 |
|
| 531 |
# don't include xtype if writing 1.1 |
| 532 |
xtype = colDesc.get("xtype") |
| 533 |
if ctx.version>(1,1): |
| 534 |
element(xtype=xtype) |
| 535 |
|
| 536 |
if isinstance(element, V.PARAM): |
| 537 |
if hasattr(colDesc.original, "getStringValue"): |
| 538 |
try: |
| 539 |
element(value=str(colDesc.original.getStringValue())) |
| 540 |
except: |
| 541 |
# there's too much that can legitimately go wrong here to bother: |
| 542 |
pass |
| 543 |
|
| 544 |
if colDesc.original: |
| 545 |
rscCol = colDesc.original |
| 546 |
if rscCol.hasProperty("targetType"): |
| 547 |
element[V.LINK( |
| 548 |
content_type=rscCol.getProperty("targetType"), |
| 549 |
title=rscCol.getProperty("targetTitle", "Link"))] |
| 550 |
|
| 551 |
element(**dict((key, colDesc.get(key) or None) |
| 552 |
for key in _voFieldCopyKeys))[ |
| 553 |
V.DESCRIPTION[colDesc["description"]], |
| 554 |
_makeValuesForColDesc(colDesc), |
| 555 |
_linkBuilder.build(colDesc.original) |
| 556 |
] |
| 557 |
|
| 558 |
|
| 559 |
def makeFieldFromColumn(ctx, colType, rscCol): |
| 560 |
"""returns a VOTable colType for a rscdef column-type thing. |
| 561 |
|
| 562 |
This function lets you make PARAM and FIELD elements (colType) from |
| 563 |
column or param instances. |
| 564 |
""" |
| 565 |
instance = colType() |
| 566 |
defineField(ctx, instance, valuemappers.AnnotatedColumn(rscCol)) |
| 567 |
return instance |
| 568 |
|
| 569 |
|
| 570 |
def _iterFields(ctx, serManager): |
| 571 |
"""iterates over V.FIELDs based on serManger's columns. |
| 572 |
""" |
| 573 |
for colDesc in serManager: |
| 574 |
el = V.FIELD() |
| 575 |
defineField(ctx, el, colDesc) |
| 576 |
yield el |
| 577 |
|
| 578 |
|
| 579 |
def _makeVOTParam(ctx, param): |
| 580 |
"""returns VOTable stan for param. |
| 581 |
""" |
| 582 |
# note that we're usually accessing the content, i.e., the string |
| 583 |
# serialization we got. The only exception is when we're seeing |
| 584 |
# nulls or null-equivalents. |
| 585 |
try: |
| 586 |
if param.content_ is base.NotGiven or param.value is None: |
| 587 |
content = None |
| 588 |
else: |
| 589 |
content = param.content_ |
| 590 |
except Exception as ex: |
| 591 |
content = f"not serialisable ({ex})" |
| 592 |
|
| 593 |
el = V.PARAM() |
| 594 |
defineField(ctx, el, valuemappers.AnnotatedColumn(param)) |
| 595 |
|
| 596 |
# id management is a particular pain for params at this moment, |
| 597 |
# because DM annotation uses the tableDef's params, whereas |
| 598 |
# we see the copied params here. We should stop copying |
| 599 |
# the params in rsc.common.ParamMixin. |
| 600 |
try: |
| 601 |
el.ID = ctx.getIdFor(param.originalParam) |
| 602 |
except (base.NotFoundError, AttributeError): |
| 603 |
try: |
| 604 |
el.ID = ctx.getIdFor(param) |
| 605 |
except base.NotFoundError: |
| 606 |
pass |
| 607 |
|
| 608 |
if content is None: |
| 609 |
el.value = "" |
| 610 |
else: |
| 611 |
el.value = content |
| 612 |
return el |
| 613 |
|
| 614 |
|
| 615 |
def _iterTableParams(ctx, serManager): |
| 616 |
"""iterates over V.PARAMs based on the table's param elements. |
| 617 |
""" |
| 618 |
for param in serManager.table.iterParams(): |
| 619 |
votEl = _makeVOTParam(ctx, param) |
| 620 |
if votEl is not None: |
| 621 |
ctx.addID(param, votEl) |
| 622 |
yield votEl |
| 623 |
|
| 624 |
|
| 625 |
####################### Tables and Resources |
| 626 |
|
| 627 |
# an ad-hoc mapping of what STC1 has in frame to what VOTable 1.1 has for |
| 628 |
# COOSYS/@system |
| 629 |
STC_FRAMES_TO_COOSYS = { |
| 630 |
'ICRS': 'ICRS', |
| 631 |
'FK5': 'eq_FK5', |
| 632 |
'FK4': 'eq_FK4', |
| 633 |
'ECLIPTIC': 'ecl_FK5', # neglecting the odds there's actually ecl_FK4 data |
| 634 |
'GALACTIC_II': 'galactic', |
| 635 |
'SUPERGALACTIC': 'supergalactic', |
| 636 |
None: None} |
| 637 |
|
| 638 |
# these are utypes for which column refs should be ref-ed to the COOSYS. |
| 639 |
COLUMN_REF_UTYPES = [ |
| 640 |
"stc:astrocoords.position2d.value2.c1", |
| 641 |
"stc:astrocoords.position2d.value2.c2", |
| 642 |
"stc:astrocoords.position2d.error2.c1", |
| 643 |
"stc:astrocoords.position2d.error2.c2", |
| 644 |
"stc:astrocoords.velocity2d.value2.c1", |
| 645 |
"stc:astrocoords.velocity2d.value2.c2", |
| 646 |
"stc:astrocoords.velocity2d.error2.c1", |
| 647 |
"stc:astrocoords.velocity2d.error2.c2", |
| 648 |
"stc:astrocoords.redshift.value", |
| 649 |
"stc:astrocoords.position3d.value3.c1", |
| 650 |
"stc:astrocoords.position3d.value3.c2", |
| 651 |
"stc:astrocoords.position3d.value3.c3", |
| 652 |
"stc:astrocoords.time.timeinstant", |
| 653 |
"stc:astrocoords.velocity3d.value3.c1", |
| 654 |
"stc:astrocoords.velocity3d.value3.c2", |
| 655 |
"stc:astrocoords.velocity3d.value3.c3", |
| 656 |
"stc:astrocoords.position2d.epoch", |
| 657 |
"stc:astrocoords.position3d.epoch", |
| 658 |
] |
| 659 |
|
| 660 |
|
| 661 |
def _addEpochToCoosys(coosys, utypeMap): |
| 662 |
"""tries to locate epoch information utypeMap and adds it to the |
| 663 |
V.COOSYS instance coosys if found. |
| 664 |
""" |
| 665 |
for epochBase in [ |
| 666 |
"stc:astrocoords.position2d.", "stc:astrocoords.position3d."]: |
| 667 |
if epochBase+"epoch" in utypeMap: |
| 668 |
break |
| 669 |
else: |
| 670 |
return |
| 671 |
|
| 672 |
epVal = utypeMap[epochBase+"epoch"] |
| 673 |
if not isinstance(epVal, stc.ColRef): |
| 674 |
# If the epoch is not a column reference, inline it. |
| 675 |
# (the code below will ignore it in that case) |
| 676 |
coosys(epoch="%s%s"%( |
| 677 |
utypeMap.get(epochBase+"epoch.yeardef", "J"), |
| 678 |
epVal)) |
| 679 |
|
| 680 |
|
| 681 |
def _makeCOOSYSFromSTC1(utypeMap, serManager): |
| 682 |
"""returns a VOTable 1.1 COOSYS element inferred from a map of stc utypes |
| 683 |
to STC1 values. |
| 684 |
|
| 685 |
We let through coordinate frames not defined in VOTable 1.1 at the |
| 686 |
expense of making the VOTables XSD-invalid with such frames; this |
| 687 |
seems preferable to not declaring anything. |
| 688 |
|
| 689 |
As a side effect, this will change column/@ref attributes (possibly also |
| 690 |
param/@ref). If a column is part of two STC structures, the first |
| 691 |
one will win. Yeah, that spec sucks. |
| 692 |
""" |
| 693 |
coosys = V.COOSYS() |
| 694 |
sysId = serManager.makeIdFor(coosys, "system") |
| 695 |
coosys(ID=sysId) |
| 696 |
|
| 697 |
_addEpochToCoosys(coosys, utypeMap) |
| 698 |
|
| 699 |
stcFrame = utypeMap.get( |
| 700 |
"stc:astrocoordsystem.spaceframe.coordrefframe", None) |
| 701 |
coosys(system=STC_FRAMES_TO_COOSYS.get(stcFrame, stcFrame)) |
| 702 |
|
| 703 |
if "references-from-coosys" in base.getConfig("future"): |
| 704 |
coosys(refposition=utypeMap.get( |
| 705 |
"stc:astrocoordsystem.spaceframe.referenceposition", None)) |
| 706 |
|
| 707 |
for utype in COLUMN_REF_UTYPES: |
| 708 |
if utype in utypeMap: |
| 709 |
val = utypeMap[utype] |
| 710 |
if isinstance(val, stc.ColRef): |
| 711 |
col = serManager.getColumnByName(str(val)) |
| 712 |
if not col.get("ref"): |
| 713 |
col["ref"] = sysId |
| 714 |
|
| 715 |
return coosys |
| 716 |
|
| 717 |
|
| 718 |
def _iterSTC(ctx, tableDef, serManager): |
| 719 |
"""adds STC groups for the systems to votTable fetching data from |
| 720 |
tableDef. |
| 721 |
""" |
| 722 |
def getColumnFor(colRef): |
| 723 |
try: |
| 724 |
return serManager.getColumnByName(colRef.dest) |
| 725 |
except KeyError: |
| 726 |
# in ADQL processing, names are lower-cased, and there's not |
| 727 |
# terribly much we can do about it without breaking other things. |
| 728 |
# Hence, let's try and see whether our target is there with |
| 729 |
# case normalization: |
| 730 |
return serManager.getColumnByName(colRef.dest.lower()) |
| 731 |
|
| 732 |
def getIdFor(colRef): |
| 733 |
return getColumnFor(colRef)["id"] |
| 734 |
|
| 735 |
for ast in tableDef.getSTCDefs(): |
| 736 |
container, utypeMap = modelgroups.marshal_STC(ast, getIdFor) |
| 737 |
if ctx.version>(1,1): |
| 738 |
# "Note-style" STC only supported in 1.2 and higher |
| 739 |
yield container |
| 740 |
# legacy COOSYS specification supported everywhere |
| 741 |
coosysEl = _makeCOOSYSFromSTC1(utypeMap, serManager) |
| 742 |
ctx.coosysByAST[str(id(ast))] = coosysEl |
| 743 |
ctx.getEnclosingResource()[coosysEl] |
| 744 |
|
| 745 |
|
| 746 |
def _addStupidRefByAnnotation(ctx, annotation, serManager, destId): |
| 747 |
"""adds a @ref attribute to destId to a PARAM or FIELD that |
| 748 |
annotation references. |
| 749 |
|
| 750 |
This is for legacy TIMESYS or COOSYS, and the born-legacy PHOTCAL |
| 751 |
group. Sigh. |
| 752 |
""" |
| 753 |
if isinstance(annotation, dm.ColumnAnnotation): |
| 754 |
col = serManager.getColumnByName(annotation.value.name) |
| 755 |
if not col.get("ref"): |
| 756 |
col["ref"] = destId |
| 757 |
|
| 758 |
elif isinstance(annotation, dm.ParamAnnotation): |
| 759 |
ctx.pushRefFor( |
| 760 |
serManager.table.getParamByName(annotation.value.name), |
| 761 |
destId) |
| 762 |
|
| 763 |
|
| 764 |
# mapping from our votable-stc role names to COOSYS utypes |
| 765 |
_STC_UTYPE_MAPPING = { |
| 766 |
"longitude": "votable:LonLatPoint-lon", |
| 767 |
"latitude": "votable:LonLatPoint-lat", |
| 768 |
"pm_longitude": "votable:ProperMotion-lon", |
| 769 |
"pm_latitude": "votable:ProperMotion-lat", |
| 770 |
"distance": "votable:LonLatPoint-dist", |
| 771 |
"rv": "votable:ProperMotion-rv", |
| 772 |
} |
| 773 |
|
| 774 |
|
| 775 |
if "references-from-coosys" in base.getConfig("future"): |
| 776 |
def _makeLegacyRefForAnn(ctx, annotation, utype): |
| 777 |
"""returns a PARAMref or FIELDref for annotation with the utype |
| 778 |
passed. |
| 779 |
|
| 780 |
The target of annotation will receive an id in ctx. If the |
| 781 |
""" |
| 782 |
valId = ctx.getOrMakeIdFor( |
| 783 |
annotation.value, suggestion=annotation.value.name) |
| 784 |
|
| 785 |
if isinstance(annotation, dm.ColumnAnnotation): |
| 786 |
return V.FIELDref(utype=utype, ref=valId) |
| 787 |
elif isinstance(annotation, dm.ParamAnnotation): |
| 788 |
return V.PARAMref(utype=utype, ref=valId) |
| 789 |
else: |
| 790 |
base.ui.notifyWarning(f"Unknown annotation {annotation}") |
| 791 |
# fall through to returning None, which the serialiser will swallow |
| 792 |
else: |
| 793 |
def _makeLegacyRefForAnn(ctx, annotation, utype): |
| 794 |
return None |
| 795 |
|
| 796 |
|
| 797 |
def _guessTimeOrigin(frame, timeCol): |
| 798 |
"""returns a plausible value for a TIMESYS' timeorigin attribute |
| 799 |
from a frame definition and a time column. |
| 800 |
|
| 801 |
This is a depressing mess; thanks, DM WG. |
| 802 |
""" |
| 803 |
if "time0" in frame: |
| 804 |
# that's the only sane option |
| 805 |
return frame.get("time0") |
| 806 |
|
| 807 |
if not isinstance(timeCol, dm.ParamLikeAnnotation): |
| 808 |
# it's a literal and we have no further metadata. |
| 809 |
return |
| 810 |
|
| 811 |
timeCol = timeCol.weakref() |
| 812 |
# let's guess time origin based on units and such. |
| 813 |
if timeCol.unit=="d": |
| 814 |
# assuming JD or MJD. Since people didn't give a time0, try to guess. |
| 815 |
if "mjd" in timeCol.name: |
| 816 |
return "MJD-origin" |
| 817 |
# JD is a silly default, but what can I do? SIGH! |
| 818 |
return "JD-origin" |
| 819 |
|
| 820 |
if timeCol.unit=="s": |
| 821 |
# if that's really not a unix timestamp, people need to |
| 822 |
# give a time0. |
| 823 |
return "2440587.5" |
| 824 |
|
| 825 |
# we ought to assert unit="yr" here |
| 826 |
return None |
| 827 |
|
| 828 |
|
| 829 |
def _addLegacySYSFromVOTableSTC(ctx, tableDef, serManager): |
| 830 |
"""adds COOSYS and TIMESYS elements from votable-stc annotation to |
| 831 |
the enclosing RESOURCE. |
| 832 |
""" |
| 833 |
for ann in tableDef.iterAnnotationsOfType("votable:Coords"): |
| 834 |
if "time" in ann: |
| 835 |
timeFrame = ann["time"].get("frame", {}) |
| 836 |
|
| 837 |
timesysEl = V.TIMESYS( |
| 838 |
timescale=timeFrame.get("timescale", "UNKNOWN"), |
| 839 |
refposition=timeFrame.get("refPosition", "UNKNOWN"), |
| 840 |
timeorigin=_guessTimeOrigin(timeFrame, ann["time"].get("location"))) |
| 841 |
timesysId = serManager.makeIdFor(timesysEl, "ts") |
| 842 |
timesysEl(ID=timesysId) |
| 843 |
ctx.getEnclosingResource()[ |
| 844 |
timesysEl] |
| 845 |
if "location" in ann["time"]: |
| 846 |
_addStupidRefByAnnotation( |
| 847 |
ctx, |
| 848 |
ann["time"]["location"], |
| 849 |
serManager, |
| 850 |
timesysId) |
| 851 |
|
| 852 |
if "space" in ann: |
| 853 |
spaceFrame = ann["space"]["frame"] |
| 854 |
coosys = None |
| 855 |
if "astid" in ann: |
| 856 |
# the annotation was built from an <stc> declaration, and |
| 857 |
# _iterSTC may already have created the coosys element, in |
| 858 |
# which case we want to re-use it. |
| 859 |
coosys = ctx.coosysByAST.get(str(ann["astid"])) |
| 860 |
|
| 861 |
if coosys is None: |
| 862 |
# no such coosys created yet |
| 863 |
coosys = V.COOSYS() |
| 864 |
ctx.getEnclosingResource()[coosys] |
| 865 |
|
| 866 |
sysId = serManager.getOrMakeIdFor(coosys, "system") |
| 867 |
# we probably should be more careful with literals vs. references |
| 868 |
# for the orientation, too |
| 869 |
coosys(ID=sysId, |
| 870 |
system=STC_FRAMES_TO_COOSYS[spaceFrame.get("orientation")], |
| 871 |
refposition=spaceFrame.get("refPosition")) |
| 872 |
epVal = spaceFrame.get("epoch") |
| 873 |
if isinstance(epVal, str): |
| 874 |
coosys(epoch=epVal) |
| 875 |
elif epVal: |
| 876 |
coosys[_makeLegacyRefForAnn( |
| 877 |
ctx, epVal, "votable:CustomRefLocation-epoch")] |
| 878 |
|
| 879 |
for child in ann["space"].iterChildRoles(): |
| 880 |
_addStupidRefByAnnotation(ctx, child, serManager, sysId) |
| 881 |
if (child.name in _STC_UTYPE_MAPPING and |
| 882 |
isinstance(child, dm.ParamLikeAnnotation)): |
| 883 |
coosys[_makeLegacyRefForAnn( |
| 884 |
ctx, child, _STC_UTYPE_MAPPING[child.name])] |
| 885 |
|
| 886 |
|
| 887 |
_PHOT_CAL_PARAMS = { |
| 888 |
"filterIdentifier": dict(name="filterIdentifier", datatype="char", |
| 889 |
ucd="meta.id;instr.filter", arraysize="*", |
| 890 |
utype="photDM:PhotometryFilter.identifier"), |
| 891 |
"zeroPointFlux": dict(name="zeroPointFlux", |
| 892 |
ucd="phot.mag;arith.zp", utype="photDM:PhotCal.zeroPoint.flux.value", |
| 893 |
unit="Jy", datatype="double"), |
| 894 |
"magnitudeSystem": dict(name="magnitudeSystem", ucd="meta.code", |
| 895 |
utype="photDM:PhotCal.magnitudeSystem.type", datatype="char", |
| 896 |
arraysize="*"), |
| 897 |
"effectiveWavelength": dict(name="effectiveWavelength", |
| 898 |
ucd="em.wl.effective", unit="m", datatype="double", |
| 899 |
utype="photDM:PhotometryFilter.spectralLocation.value"), |
| 900 |
} |
| 901 |
|
| 902 |
def _addLegacyPhotCal(ctx, tableDef, serManager): |
| 903 |
"""adds PhotCal groups to the enclosing RESOURCE. |
| 904 |
""" |
| 905 |
for ann in tableDef.iterAnnotationsOfType("phot:PhotCal"): |
| 906 |
photGroup = V.GROUP(name="photcal") |
| 907 |
photGroup(ID=serManager.makeIdFor(photGroup, "phot_def")) |
| 908 |
for child in ann.iterChildRoles(): |
| 909 |
if child.name=="value": |
| 910 |
# DaCHS extension: reference the column/param this is for |
| 911 |
photGroup[V.FIELDref(utype="adhoc:location", |
| 912 |
ref=ctx.getOrMakeIdFor(child.value))] |
| 913 |
_addStupidRefByAnnotation(ctx, child, serManager, photGroup.ID) |
| 914 |
|
| 915 |
elif child.name in _PHOT_CAL_PARAMS: |
| 916 |
if hasattr(child.value, "value"): |
| 917 |
# it's a param rather than an immediate value; reference it. |
| 918 |
param = serManager.table.getParamByName(child.value.name) |
| 919 |
photGroup[V.PARAMref( |
| 920 |
utype=_PHOT_CAL_PARAMS[child.name]["utype"], |
| 921 |
ref=ctx.getOrMakeIdFor(param))] |
| 922 |
else: |
| 923 |
photGroup[V.PARAM(**_PHOT_CAL_PARAMS[child.name])( |
| 924 |
value=str(child.value))] |
| 925 |
|
| 926 |
else: |
| 927 |
# just ignore items we don't understand |
| 928 |
pass |
| 929 |
|
| 930 |
ctx.getEnclosingResource()[photGroup] |
| 931 |
|
| 932 |
|
| 933 |
def _iterNotes(serManager): |
| 934 |
"""yields GROUPs for table notes. |
| 935 |
|
| 936 |
The idea is that the note is in the group's description, and the FIELDrefs |
| 937 |
give the columns that the note applies to. |
| 938 |
""" |
| 939 |
# add notes as a group with FIELDrefs, but don't fail on them |
| 940 |
for key, note in serManager.notes.items(): |
| 941 |
noteId = serManager.getOrMakeIdFor(note) |
| 942 |
noteGroup = V.GROUP(name="note-%s"%key, ID=noteId)[ |
| 943 |
V.DESCRIPTION[note.getContent(targetFormat="text")]] |
| 944 |
for col in serManager: |
| 945 |
if col["note"] is note: |
| 946 |
noteGroup[V.FIELDref(ref=col["id"])] |
| 947 |
yield noteGroup |
| 948 |
|
| 949 |
|
| 950 |
def _makeRef(baseType, ref, container, serManager): |
| 951 |
"""returns a new node of baseType reflecting the group.TypedRef |
| 952 |
instance ref. |
| 953 |
|
| 954 |
container is the destination of the reference. For columns, that's |
| 955 |
the table definition, but for parameters, this must be the table |
| 956 |
itself rather than its definition because it's the table's |
| 957 |
params that are embedded in the VOTable. |
| 958 |
""" |
| 959 |
return baseType( |
| 960 |
ref=serManager.getOrMakeIdFor(ref.resolve(container)), |
| 961 |
utype=ref.utype, |
| 962 |
ucd=ref.ucd) |
| 963 |
|
| 964 |
|
| 965 |
def _iterGroups(ctx, container, serManager): |
| 966 |
"""yields GROUPs for the RD groups within container, taking params and |
| 967 |
fields from serManager's table. |
| 968 |
|
| 969 |
container can be a tableDef or a group. |
| 970 |
""" |
| 971 |
for group in container.groups: |
| 972 |
votGroup = V.GROUP(ucd=group.ucd, utype=group.utype, name=group.name) |
| 973 |
votGroup[V.DESCRIPTION[group.description]] |
| 974 |
|
| 975 |
for ref in group.columnRefs: |
| 976 |
votGroup[_makeRef(V.FIELDref, ref, |
| 977 |
serManager.table.tableDef, serManager)] |
| 978 |
|
| 979 |
for ref in group.paramRefs: |
| 980 |
votGroup[_makeRef(V.PARAMref, ref, |
| 981 |
serManager.table, serManager)] |
| 982 |
|
| 983 |
for param in group.params: |
| 984 |
votGroup[_makeVOTParam(ctx, param)] |
| 985 |
|
| 986 |
for subgroup in _iterGroups(ctx, group, serManager): |
| 987 |
votGroup[subgroup] |
| 988 |
|
| 989 |
yield votGroup |
| 990 |
|
| 991 |
|
| 992 |
def makeTable(ctx, table, isMeta=False): |
| 993 |
"""returns a Table node for the table.Table instance table. |
| 994 |
""" |
| 995 |
sm = valuemappers.SerManager(table, mfRegistry=ctx.mfRegistry, |
| 996 |
idManager=ctx, acquireSamples=ctx.acquireSamples) |
| 997 |
|
| 998 |
# this must happen before FIELDs and such are serialised to ensure |
| 999 |
# referenced things have IDs. |
| 1000 |
|
| 1001 |
result = V.TABLE() |
| 1002 |
with ctx.activeContainer(result): |
| 1003 |
# start out with VO-DML annotation so everything that needs |
| 1004 |
# an id has one. |
| 1005 |
if ctx.produceVODML: |
| 1006 |
for ann in table.tableDef.annotations: |
| 1007 |
try: |
| 1008 |
ctx.addVODMLMaterial(ann.getVOT(ctx, table)) |
| 1009 |
except Exception as msg: |
| 1010 |
# never fail just because stupid DM annotation doesn't work out |
| 1011 |
base.ui.notifyError("%s-typed DM annotation failed: %s"%( |
| 1012 |
ann.type, msg)) |
| 1013 |
|
| 1014 |
# iterate STC before serialising the columns so the columns |
| 1015 |
# have the stupid ref to COOSYS |
| 1016 |
result[_iterSTC(ctx, table.tableDef, sm)] |
| 1017 |
|
| 1018 |
# same for votable-STC (except here the FIELDs need reliable IDs) |
| 1019 |
try: |
| 1020 |
_addLegacySYSFromVOTableSTC(ctx, table.tableDef, sm) |
| 1021 |
except Exception as ex: |
| 1022 |
base.ui.notifyError(f"Could not serialise VOTable COOSYS/TIMESYS: {ex}") |
| 1023 |
|
| 1024 |
# photometry hack |
| 1025 |
_addLegacyPhotCal(ctx, table.tableDef, sm) |
| 1026 |
|
| 1027 |
result( |
| 1028 |
name=base.getMetaText(table, "name", table.tableDef.id), |
| 1029 |
utype=base.getMetaText(table, "utype", macroPackage=table.tableDef, |
| 1030 |
propagate=False))[ |
| 1031 |
# _iterGroups must run before _iterFields and _iterParams since it |
| 1032 |
# may need to add ids to the respective items. XSD-correct ordering of |
| 1033 |
# the elements is done by xmlstan. |
| 1034 |
V.DESCRIPTION[base.getMetaText(table, "description", |
| 1035 |
macroPackage=table.tableDef, propagate=False)], |
| 1036 |
_iterGroups(ctx, table.tableDef, sm), |
| 1037 |
_iterFields(ctx, sm), |
| 1038 |
_iterTableParams(ctx, sm), |
| 1039 |
_iterNotes(sm), |
| 1040 |
_linkBuilder.build(table.tableDef), |
| 1041 |
] |
| 1042 |
|
| 1043 |
if isMeta: |
| 1044 |
# we take the "should not contain data" from the spec as "will not". |
| 1045 |
# That is, we will simply drop any data on resources declared as meta |
| 1046 |
return result |
| 1047 |
|
| 1048 |
else: |
| 1049 |
return votable.DelayedTable(result, |
| 1050 |
sm.getMappedTuples(), |
| 1051 |
tableEncoders[ctx.tablecoding], |
| 1052 |
overflowElement=ctx.overflowElement) |
| 1053 |
|
| 1054 |
|
| 1055 |
def _makeResource(ctx, data): |
| 1056 |
"""returns a Resource node for the rsc.Data instance data. |
| 1057 |
""" |
| 1058 |
resType = base.getMetaText(data, "_type") |
| 1059 |
res = V.RESOURCE() |
| 1060 |
|
| 1061 |
# For now, DaCHS will only have one RESOURCE that can contain VODML |
| 1062 |
# annotation. In case that ever changes, ctx will have to keep track |
| 1063 |
# of what "top-level" RESOURCE we're annotating (unless MIVOT gets |
| 1064 |
# sanitised). |
| 1065 |
if ctx.produceVODML: |
| 1066 |
res[V.RESOURCE(type="meta")[ctx.rootVODML]] |
| 1067 |
|
| 1068 |
with ctx.activeContainer(res): |
| 1069 |
res(type=resType, |
| 1070 |
utype=base.getMetaText(data, "utype"))[ |
| 1071 |
_iterResourceMeta(ctx, data), [ |
| 1072 |
_makeVOTParam(ctx, param) for param in data.iterParams()], |
| 1073 |
_linkBuilder.build(data.dd), |
| 1074 |
] |
| 1075 |
for table in data: |
| 1076 |
with ctx.buildingFromTable(table): |
| 1077 |
res[makeTable(ctx, table, isMeta=resType=="meta")] |
| 1078 |
res[ctx.overflowElement] |
| 1079 |
return res |
| 1080 |
|
| 1081 |
############################# Toplevel/User-exposed code |
| 1082 |
|
| 1083 |
makeResource = _makeResource |
| 1084 |
|
| 1085 |
|
| 1086 |
def makeVOTable(data, ctx=None, **kwargs): |
| 1087 |
"""returns a votable.V.VOTABLE object representing data. |
| 1088 |
|
| 1089 |
data can be an rsc.Data or an rsc.Table. data can be a data or a table |
| 1090 |
instance, tablecoding any key in votable.tableEncoders. |
| 1091 |
|
| 1092 |
You may pass a VOTableContext object; if you don't a context |
| 1093 |
with all defaults will be used. |
| 1094 |
|
| 1095 |
A deprecated alternative is to directly pass VOTableContext constructor |
| 1096 |
arguments as additional keyword arguments. Don't do this, though, |
| 1097 |
we'll probably remove the option to do so at some point. |
| 1098 |
|
| 1099 |
You will usually pass the result to votable.write. The object returned |
| 1100 |
contains DelayedTables, i.e., most of the content will only be realized at |
| 1101 |
render time. |
| 1102 |
""" |
| 1103 |
ctx = ctx or VOTableContext(**kwargs) |
| 1104 |
|
| 1105 |
data = rsc.wrapTable(data) |
| 1106 |
if ctx.version==(1,1): |
| 1107 |
vot = V.VOTABLE11() |
| 1108 |
elif ctx.version==(1,2): |
| 1109 |
vot = V.VOTABLE12() |
| 1110 |
elif ctx.version==(1,3): |
| 1111 |
raise votable.VOTableError("Cannot write VOTable 1.3 any more" |
| 1112 |
" (and you shouldn't have reason to).") |
| 1113 |
elif ctx.version==(1,4): |
| 1114 |
vot = V.VOTABLE() |
| 1115 |
elif ctx.version==(1,5): |
| 1116 |
vot = V.VOTABLE() |
| 1117 |
elif ctx.version==(1,6): |
| 1118 |
vot = V.VOTABLE() |
| 1119 |
else: |
| 1120 |
raise votable.VOTableError("No toplevel element for VOTable version %s"% |
| 1121 |
repr(ctx.version)) |
| 1122 |
|
| 1123 |
dlResources = list(_iterDatalinkResources(ctx, data)) |
| 1124 |
vot[_iterToplevelMeta(ctx, data)] |
| 1125 |
vot[_makeResource(ctx, data)] |
| 1126 |
vot[dlResources] |
| 1127 |
|
| 1128 |
if ctx.produceVODML: |
| 1129 |
vot._fixedTagMaterial += ' xmlns:mivot="{}"'.format( |
| 1130 |
utils.getPrefixInfo("mivot")[0]) |
| 1131 |
|
| 1132 |
if ctx.suppressNamespace: |
| 1133 |
# use this for "simple" table with nice element names |
| 1134 |
vot._fixedTagMaterial = "" |
| 1135 |
|
| 1136 |
# What follows is a hack around the insanity of stuffing |
| 1137 |
# unused namespaces and similar detritus into VOTable's roots. |
| 1138 |
rootAttrs = data.getMeta("_votableRootAttributes") |
| 1139 |
if rootAttrs: |
| 1140 |
rootHacks = [vot._fixedTagMaterial]+[ |
| 1141 |
item.getContent() for item in rootAttrs] |
| 1142 |
vot._fixedTagMaterial = " ".join(s for s in rootHacks if s) |
| 1143 |
|
| 1144 |
return vot |
| 1145 |
|
| 1146 |
|
| 1147 |
def writeAsVOTable(data, outputFile, ctx=None, **kwargs): |
| 1148 |
"""writes ``data`` to the ``outputFile``. |
| 1149 |
|
| 1150 |
data can be a table or ``Data`` item. |
| 1151 |
|
| 1152 |
``ctx`` can be a ``VOTableContext`` instance; alternatively, |
| 1153 |
``VOTableContext`` constructor arguments can be passed in as |
| 1154 |
``kwargs``. |
| 1155 |
""" |
| 1156 |
ctx = ctx or VOTableContext(**kwargs) |
| 1157 |
vot = makeVOTable(data, ctx) |
| 1158 |
votable.write(vot, outputFile) |
| 1159 |
|
| 1160 |
|
| 1161 |
def getAsVOTable(data, ctx=None, **kwargs): |
| 1162 |
"""returns a string containing a VOTable representation of data. |
| 1163 |
|
| 1164 |
``kwargs`` can be constructor arguments for VOTableContext. |
| 1165 |
""" |
| 1166 |
ctx = ctx or VOTableContext(**kwargs) |
| 1167 |
dest = io.BytesIO() |
| 1168 |
writeAsVOTable(data, dest, ctx) |
| 1169 |
return dest.getvalue() |
| 1170 |
|
| 1171 |
|
| 1172 |
def format(data, outputFile, **ctxargs): |
| 1173 |
# used for construction of the formats.common interface |
| 1174 |
return writeAsVOTable(data, outputFile, VOTableContext(**ctxargs)) |
| 1175 |
|
| 1176 |
common.registerDataWriter("votable", format, |
| 1177 |
base.votableType, "Default VOTable", ".vot", |
| 1178 |
tapId="ivo://ivoa.net/std/TAPRegExt#output-votable-binary") |
| 1179 |
common.registerDataWriter("votableb2", functools.partial( |
| 1180 |
format, tablecoding="binary2"), |
| 1181 |
"application/x-votable+xml;serialization=BINARY2", |
| 1182 |
"Binary2 VOTable", |
| 1183 |
".votb2", |
| 1184 |
"votable/b2", |
| 1185 |
tapId="ivo://ivoa.net/std/TAPRegExt#output-votable-binary2") |
| 1186 |
common.registerDataWriter("votabletd", functools.partial( |
| 1187 |
format, tablecoding="td"), |
| 1188 |
"application/x-votable+xml;serialization=TABLEDATA", "Tabledata VOTable", |
| 1189 |
".vottd", |
| 1190 |
"text/xml", |
| 1191 |
"votable/td", |
| 1192 |
tapId="ivo://ivoa.net/std/TAPRegExt#output-votable-td") |
| 1193 |
common.registerDataWriter("votabletd1.1", functools.partial( |
| 1194 |
format, tablecoding="td", version=(1,1)), |
| 1195 |
"application/x-votable+xml;serialization=TABLEDATA;version=1.1", |
| 1196 |
"Tabledata VOTable version 1.1", |
| 1197 |
".vot1", |
| 1198 |
"text/xml") |
| 1199 |
common.registerDataWriter("votable1.1", functools.partial( |
| 1200 |
format, tablecoding="binary", version=(1,1)), |
| 1201 |
"application/x-votable+xml;version=1.1", |
| 1202 |
"Tabledata VOTable version 1.1", |
| 1203 |
".vot1", |
| 1204 |
"text/xml") |
| 1205 |
common.registerDataWriter("votabletd1.2", functools.partial( |
| 1206 |
format, tablecoding="td", version=(1,2)), |
| 1207 |
"application/x-votable+xml;serialization=TABLEDATA;version=1.2", |
| 1208 |
"Tabledata VOTable version 1.2", |
| 1209 |
".vot2", |
| 1210 |
"text/xml") |
| 1211 |
common.registerDataWriter("vodml", functools.partial( |
| 1212 |
format, tablecoding="td", version=(1,6)), |
| 1213 |
"application/x-votable+xml;serialization=TABLEDATA;version=1.6", |
| 1214 |
"VOTable version 1.6 beta, tabledata", |
| 1215 |
".vot6") |
| 1216 |
common.registerDataWriter("vodmlb", functools.partial( |
| 1217 |
format, version=(1,6)), |
| 1218 |
"application/x-votable+xml;version=1.6", |
| 1219 |
"VOTable version 1.6 beta", |
| 1220 |
".vot6") |