| 1 |
""" |
| 2 |
Infrastructure for obtaining metadata about on tables and |
| 3 |
columns controlled by DaCHS. |
| 4 |
|
| 5 |
This has the command line interface for dachs info, and the annotation |
| 6 |
machinery is also used by dachs limits; the common functionality should |
| 7 |
probably move to rsc at some point (I think it should live with rsc.dbtable). |
| 8 |
|
| 9 |
The core here is annotateDBTable. This will gather various pieces |
| 10 |
of table metadata and fetch column metadata through _annotateColumns. That, |
| 11 |
in turn, constructs a query fetching the metadata from the database. Since |
| 12 |
writing this query is a bit involved, it is done in terms of a sequence |
| 13 |
of AnnotationMakers. These combine SQL making (through OutputFields) |
| 14 |
and then pulling the results out of the database result (in their |
| 15 |
annotate methods). The end result is that keys in the columns' |
| 16 |
annotations dictionaries are added. |
| 17 |
""" |
| 18 |
|
| 19 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 20 |
#c |
| 21 |
#c This program is free software, covered by the GNU GPL. See the |
| 22 |
#c COPYING file in the source distribution. |
| 23 |
|
| 24 |
|
| 25 |
import datetime |
| 26 |
import math |
| 27 |
import time |
| 28 |
|
| 29 |
from gavo import api |
| 30 |
from gavo import base |
| 31 |
from gavo import stc |
| 32 |
from gavo import svcs |
| 33 |
from gavo import utils |
| 34 |
from gavo.protocols import scs |
| 35 |
|
| 36 |
|
| 37 |
def getDefaultSamplePercent(tableSize): |
| 38 |
"""returns a hopefully sensible value for samplePercent depending |
| 39 |
on the tableSize. |
| 40 |
|
| 41 |
This is based on the gut feeling that up to 1e6 rows, we can just scan all, |
| 42 |
whereas for 1e7 50% is fine, and then: 1e8: 20%, 1e9: 10%, 1e10: 5%. |
| 43 |
I *think* there might be a theory for that. |
| 44 |
""" |
| 45 |
if not tableSize: |
| 46 |
return 100 |
| 47 |
sf = (math.log10(tableSize)-6) |
| 48 |
if sf<=0: |
| 49 |
return 100 |
| 50 |
return max(int(100*(1/(1+sf**1.5))), 1) |
| 51 |
|
| 52 |
|
| 53 |
class AnnotationMaker: |
| 54 |
"""A class for producing column annotations. |
| 55 |
|
| 56 |
An annotation simply is a dictionary with some well-known keys. They |
| 57 |
are generated from DB queries, and this class orchestrates that by |
| 58 |
collecting the DB query's result columns pertaining to a column and |
| 59 |
producing the annotation dictionary from them. |
| 60 |
|
| 61 |
To make this happen, it is constructed with the column; then, for |
| 62 |
each property queried, addPropertyKey is called. Finally, addAnnotation |
| 63 |
is called with the DB result row (see annotateDBTable) to actually |
| 64 |
make and attach the dictionary. |
| 65 |
|
| 66 |
colRef is where to find the values of the column to annotate. This |
| 67 |
will generally be the column's name, but you can pass SQL expressions |
| 68 |
there; this is currently done for timestamps, which are turned into |
| 69 |
MJDs. |
| 70 |
""" |
| 71 |
def __init__(self, column, colRef): |
| 72 |
self.column = column |
| 73 |
self.colRef = colRef |
| 74 |
|
| 75 |
if not hasattr(self.column, "annotations"): |
| 76 |
self.column.annotations = {} |
| 77 |
self.propDests = {} |
| 78 |
|
| 79 |
def doesWork(self): |
| 80 |
"""returns a true value if the annotator will contribute a query. |
| 81 |
""" |
| 82 |
return self.propDests |
| 83 |
|
| 84 |
def getOutputFieldFor(self, propName, propFunc, nameMaker, extractor=None): |
| 85 |
"""returns an OutputField that will generate a propName annotation |
| 86 |
from the propFunc function. |
| 87 |
|
| 88 |
propFunc needs to have {colRef} where the column name (or whatever |
| 89 |
was passed in as colRef) must be inserted. |
| 90 |
|
| 91 |
nameMaker is something like a base.VOTNameMaker. |
| 92 |
|
| 93 |
extractor can be a callable receiving the result of propFunc |
| 94 |
and the annotation dictionary; it the must modify the annotation |
| 95 |
dictionary to reflect the result (the default is to just |
| 96 |
add the result under propName). |
| 97 |
""" |
| 98 |
destCol = nameMaker.makeName(propName+"_"+self.column.key) |
| 99 |
self.propDests[destCol] = extractor or propName |
| 100 |
ofield = api.makeStruct(svcs.OutputField, |
| 101 |
name=destCol, |
| 102 |
select=propFunc.format(colRef=self.colRef), |
| 103 |
type=self.column.type) |
| 104 |
return ofield |
| 105 |
|
| 106 |
def annotate(self, resultRow): |
| 107 |
"""builds an annotation of the column from resultRow. |
| 108 |
|
| 109 |
resultRow is a dictionary containing values for all keys registered |
| 110 |
through addPropertyKey. |
| 111 |
|
| 112 |
If the column already has an annotation, only the new keys will be |
| 113 |
overwritten. |
| 114 |
""" |
| 115 |
for srcKey, destKey in self.propDests.items(): |
| 116 |
if resultRow[srcKey] is None: |
| 117 |
continue |
| 118 |
|
| 119 |
if isinstance(destKey, str): |
| 120 |
self.column.annotations[destKey] = resultRow[srcKey] |
| 121 |
else: |
| 122 |
destKey(self.column.annotations, resultRow[srcKey]) |
| 123 |
|
| 124 |
|
| 125 |
def makeScalarExtractor(td, col, destName): |
| 126 |
"""returns an extractor for a single statistics gatherer. |
| 127 |
|
| 128 |
This is an extractor callback for getOutputFieldFor; over just |
| 129 |
entering the result in the right field in annotations, this |
| 130 |
does refuses insane stuff. |
| 131 |
""" |
| 132 |
if col.type not in ("real", "double precision"): |
| 133 |
def _(annotations, dbResult): |
| 134 |
annotations[destName] = dbResult |
| 135 |
|
| 136 |
else: |
| 137 |
def _(annotations, dbResult): |
| 138 |
res = float(dbResult) |
| 139 |
if not math.isfinite(res): |
| 140 |
base.ui.notifyWarning( |
| 141 |
f"Non-finite stat {dbResult}" |
| 142 |
f" in {destName} statistics on {td}.{col.name}") |
| 143 |
return |
| 144 |
annotations[destName] = dbResult |
| 145 |
|
| 146 |
return _ |
| 147 |
|
| 148 |
|
| 149 |
def getAnnotators(td): |
| 150 |
"""returns a pair of output fields and annotators to gather |
| 151 |
column statistcs for td. |
| 152 |
|
| 153 |
The annotators are AnnotationMaker instances that will add the |
| 154 |
relevant annotations to td's columns. |
| 155 |
|
| 156 |
The rules applying are given in annotateDBTable. |
| 157 |
""" |
| 158 |
outputFields, annotators = [], [] |
| 159 |
nameMaker = base.VOTNameMaker() |
| 160 |
|
| 161 |
for col in td: |
| 162 |
if col.getProperty("statistics", None)=="no": |
| 163 |
continue |
| 164 |
|
| 165 |
# TODO: Logic on pre-stat transformations should |
| 166 |
# really be in per-dbtype type objects that we ought to have one day. |
| 167 |
if col.type=="timestamp": |
| 168 |
# PG chose the inverse JD noon convention than MJD, hence the extra 1. |
| 169 |
colRef=f"(EXTRACT(JULIAN FROM {col.name})-2400001)" |
| 170 |
else: |
| 171 |
colRef = col.name |
| 172 |
annotator = AnnotationMaker(col, colRef) |
| 173 |
|
| 174 |
if col.type in base.ORDERED_TYPES or col.type.startswith("char"): |
| 175 |
outputFields.append( |
| 176 |
annotator.getOutputFieldFor( |
| 177 |
"max_value", |
| 178 |
"MAX({colRef})", |
| 179 |
nameMaker, |
| 180 |
extractor=makeScalarExtractor(td, col, "max_value"))) |
| 181 |
outputFields.append( |
| 182 |
annotator.getOutputFieldFor( |
| 183 |
"min_value", |
| 184 |
"MIN({colRef})", |
| 185 |
nameMaker, |
| 186 |
extractor=makeScalarExtractor(td, col, "min_value"))) |
| 187 |
|
| 188 |
if col.type in base.NUMERIC_TYPES or col.type=="timestamp": |
| 189 |
outputFields.append(annotator.getOutputFieldFor("percentiles", |
| 190 |
"percentile_cont(ARRAY[0.03, 0.5, 0.97]) WITHIN GROUP" |
| 191 |
" (ORDER BY {colRef})", nameMaker, |
| 192 |
extractor=lambda annotations, res: |
| 193 |
annotations.update(dict(zip( |
| 194 |
["percentile03", "median", "percentile97"], res))))) |
| 195 |
|
| 196 |
# for now, we only do discrete-value stats for strings, not for |
| 197 |
# integers. If we want to cover integers, too, we'll have to think |
| 198 |
# about a null literal for them. |
| 199 |
if (col.type=='text' and ( |
| 200 |
col.isEnumerated() |
| 201 |
or col.getProperty("statistics", None)=="enumerate")): |
| 202 |
outputFields.append(annotator.getOutputFieldFor("discrete_values", |
| 203 |
"(SELECT jsonb_object_agg(COALESCE(val, 'NULL'), ct) FROM (" |
| 204 |
" SELECT {colRef} AS val, count(*) AS ct" |
| 205 |
" FROM {tableName} GROUP BY {colRef}) AS {subqueryName})".format( |
| 206 |
tableName=td.getQName(), |
| 207 |
subqueryName="subquery_"+col.name, |
| 208 |
colRef=colRef), |
| 209 |
nameMaker, |
| 210 |
extractor=_normalizeDist)) |
| 211 |
|
| 212 |
outputFields.append(annotator.getOutputFieldFor("fill_factor", |
| 213 |
"AVG(CASE WHEN {colRef} IS NULL THEN 0 ELSE 1 END)", |
| 214 |
nameMaker)) |
| 215 |
|
| 216 |
if annotator.doesWork(): |
| 217 |
annotators.append(annotator) |
| 218 |
|
| 219 |
return outputFields, annotators |
| 220 |
|
| 221 |
|
| 222 |
def _normalizeDist(annotations, dist): |
| 223 |
"""stores dist normalized to sum(dist.values())=1 in |
| 224 |
annotations[discrete_values] |
| 225 |
|
| 226 |
This is probably only useful as the extractor for discrete_values |
| 227 |
output fields. |
| 228 |
""" |
| 229 |
normalizer = sum(dist.values(), 0) |
| 230 |
if not normalizer: |
| 231 |
# no metadata detected, which might be benign. |
| 232 |
return |
| 233 |
|
| 234 |
annotations["discrete_values"] = dict((key, val/normalizer) |
| 235 |
for key, val in dist.items()) |
| 236 |
|
| 237 |
|
| 238 |
def _estimateStatRuntime(rowsInspected): |
| 239 |
"""returns some text guessing at how long a stat run will take based |
| 240 |
on now many rows will have to be inspected. |
| 241 |
|
| 242 |
This assumes not too unreasonable hardware of ~2020; adjust secondsScale |
| 243 |
over time |
| 244 |
""" |
| 245 |
secondsScale = 5e5 |
| 246 |
|
| 247 |
if rowsInspected<secondsScale: |
| 248 |
return "seconds" |
| 249 |
|
| 250 |
elif rowsInspected<secondsScale*60: |
| 251 |
return "minutes" |
| 252 |
|
| 253 |
elif rowsInspected<secondsScale*3600: |
| 254 |
return "hours" |
| 255 |
|
| 256 |
elif rowsInspected<secondsScale*3600*24: |
| 257 |
return "days" |
| 258 |
|
| 259 |
else: |
| 260 |
return "too much time" |
| 261 |
|
| 262 |
|
| 263 |
def _noteAndDelay(fullTime): |
| 264 |
"""a delaying iterator also doing the UI of _annotateColumns. |
| 265 |
""" |
| 266 |
startTime = time.time() |
| 267 |
while True: |
| 268 |
elapsed = str(int(time.time()-startTime))+"s of "+fullTime |
| 269 |
api.ui.notifyProgress(elapsed) |
| 270 |
time.sleep(1) |
| 271 |
yield |
| 272 |
|
| 273 |
|
| 274 |
def _annotateColumns(conn, td, samplePercent): |
| 275 |
"""Adds statistics annotations on td. |
| 276 |
|
| 277 |
This usually takes a long time, and thus this will produce progress |
| 278 |
messages to the UI. |
| 279 |
|
| 280 |
The changes the column objects in td. |
| 281 |
""" |
| 282 |
dbtable = api.TableForDef(td, connection=conn) |
| 283 |
|
| 284 |
if samplePercent==100: |
| 285 |
samplePercent = None |
| 286 |
|
| 287 |
outputFields, annotators = getAnnotators(td) |
| 288 |
resultTableDef, query, pars = dbtable.getQuery( |
| 289 |
outputFields, "", samplePercent=samplePercent) |
| 290 |
|
| 291 |
with base.NonBlockingQuery(conn, query, pars) as query: |
| 292 |
try: |
| 293 |
for _ in _noteAndDelay( |
| 294 |
_estimateStatRuntime(td.nrows*(samplePercent or 100)/100.)): |
| 295 |
if query.getResult() is not None: |
| 296 |
break |
| 297 |
except KeyboardInterrupt: |
| 298 |
query.abort() |
| 299 |
raise base.ReportableError("Aborted statistics gathering." |
| 300 |
" You might consider using --sample-percent") |
| 301 |
resultRow = dict((f.name, v) |
| 302 |
for f, v in zip(outputFields, query.getResult()[0])) |
| 303 |
|
| 304 |
for annotator in annotators: |
| 305 |
annotator.annotate(resultRow) |
| 306 |
|
| 307 |
|
| 308 |
def annotateDBTable(td, |
| 309 |
samplePercent=None, |
| 310 |
acquireColumnMeta=True): |
| 311 |
"""returns the TableDef td with domain annotations for its columns. |
| 312 |
|
| 313 |
td must be an existing on-Disk table. If acquireColumnMeta is |
| 314 |
False, only the size of the table is being estimated. |
| 315 |
|
| 316 |
samplePercent uses TABLESAMPLE SYSTEM to only look at about this percentage |
| 317 |
of the rows (which doesn't work for views). |
| 318 |
|
| 319 |
The annotations come in a dictionary-valued attribute annotations on |
| 320 |
the column object. The keys in there correspond to column names |
| 321 |
from //dc_tables. |
| 322 |
|
| 323 |
This will not attempt to annotate columns that already have |
| 324 |
min, max, or options in their values. |
| 325 |
|
| 326 |
This will only look at columns that have appropriate types. |
| 327 |
""" |
| 328 |
api.ui.notifyProcessStarts(f"Getting stats for {td.getQName()}") |
| 329 |
|
| 330 |
try: |
| 331 |
api.ui.notifyProgress("Estimate nrows") |
| 332 |
with base.getTableConn() as conn: |
| 333 |
try: |
| 334 |
td.nrows = estimateTableSize(td.getQName(), conn) |
| 335 |
except base.DBError: |
| 336 |
raise base.ui.logOldExc( |
| 337 |
api.ReportableError(f"Table {td.getQName()} cannot be queried.", |
| 338 |
hint="This could be because it is an in-memory table. Add" |
| 339 |
" onDisk='True' to make tables reside in the database in that" |
| 340 |
" case. Or run dachs imp to import it if it just hasn't been" |
| 341 |
" created.")) |
| 342 |
|
| 343 |
if samplePercent is None: |
| 344 |
samplePercent = getDefaultSamplePercent(td.nrows) |
| 345 |
|
| 346 |
if acquireColumnMeta: |
| 347 |
_annotateColumns(conn, td, samplePercent) |
| 348 |
finally: |
| 349 |
api.ui.notifyProcessEnded() |
| 350 |
|
| 351 |
|
| 352 |
def getSCSCoverageQuery(td, order): |
| 353 |
"""returns a database query for getting a MOC for a table suitable |
| 354 |
for cone search. |
| 355 |
|
| 356 |
This will return None if no such query can be built. |
| 357 |
""" |
| 358 |
try: |
| 359 |
raCol, decCol = scs.getConeColumns(td) |
| 360 |
except (base.StructureError, base.NotFoundError): |
| 361 |
return None |
| 362 |
|
| 363 |
fragments = [ |
| 364 |
"SELECT smoc('%d/' || string_agg(format('%%%%s', hpx), ','))"%order, |
| 365 |
"FROM (", |
| 366 |
" SELECT DISTINCT healpix_nest(%d," |
| 367 |
" spoint(RADIANS(%s), RADIANS(%s))) AS hpx "%( |
| 368 |
order, str(raCol.name), str(decCol.name)), |
| 369 |
"FROM %s"%td.getQName(), |
| 370 |
"WHERE %s IS NOT NULL AND %s IS NOT NULL"%( |
| 371 |
str(raCol.name), str(decCol.name)), |
| 372 |
"GROUP BY hpx", |
| 373 |
") as q"] |
| 374 |
return "\n".join(fragments) |
| 375 |
|
| 376 |
|
| 377 |
def getSSAPCoverageQuery(td, order): |
| 378 |
"""returns a database query for getting a MOC for a table using |
| 379 |
one of our standard SSAP mixins. |
| 380 |
|
| 381 |
This will return None if no such query can be built. |
| 382 |
""" |
| 383 |
mixinsHandled = ["//ssap#hcd", "//ssap#mixc", "//ssap#view"] |
| 384 |
for mixin in mixinsHandled: |
| 385 |
if td.mixesIn(mixin): |
| 386 |
break |
| 387 |
else: |
| 388 |
return None |
| 389 |
|
| 390 |
fragments = [ |
| 391 |
"SELECT SUM(SMOC(%d,"%order, |
| 392 |
" SCIRCLE(ssa_location, RADIANS(COALESCE(ssa_aperture, 1/3600.)))))", |
| 393 |
"FROM %s WHERE ssa_location IS NOT NULL"%td.getQName()] |
| 394 |
return "\n".join(fragments) |
| 395 |
|
| 396 |
|
| 397 |
def getSIAPCoverageQuery(td, order): |
| 398 |
"""returns a database query for getting a MOC for a table using |
| 399 |
//siap#pgs (i.e., SIAv1) |
| 400 |
|
| 401 |
This will return None if no such query can be built. |
| 402 |
|
| 403 |
For SIAv2, no such thing is available yet, the obscore querier |
| 404 |
below should work; however, we don't really have standalone SIAv2 |
| 405 |
resources in DaCHS yet. |
| 406 |
""" |
| 407 |
if not td.mixesIn("//siap#pgs"): |
| 408 |
return None |
| 409 |
|
| 410 |
fragments = [ |
| 411 |
"SELECT SUM(SMOC(%d, coverage))"%order, |
| 412 |
"FROM %s WHERE coverage IS NOT NULL"%td.getQName()] |
| 413 |
return "\n".join(fragments) |
| 414 |
|
| 415 |
|
| 416 |
def getObscoreCoverageQuery(td, order): |
| 417 |
"""returns a database query for getting a MOC for tables with obscore |
| 418 |
columns |
| 419 |
|
| 420 |
This will return None if no such query can be built. |
| 421 |
""" |
| 422 |
geoSources = [] |
| 423 |
|
| 424 |
if "s_region" in td: |
| 425 |
sRegionType = td.getColumnByName("s_region").type |
| 426 |
if sRegionType=="spoly": |
| 427 |
geoSources.append("SMOC(%d, s_region),"%order) |
| 428 |
elif sRegionType=="smoc": |
| 429 |
geoSources.append("smoc_degrade(%d, s_region),"%order) |
| 430 |
else: |
| 431 |
base.ui.notifyWarning("Table has unsupported s_region type %s" |
| 432 |
" when determining coverage."%sRegionType) |
| 433 |
|
| 434 |
if "s_ra" in td and "s_dec" in td and "s_fov" in td: |
| 435 |
geoSources.append( |
| 436 |
"smoc_disc(%s, RADIANS(s_ra), RADIANS(s_dec), RADIANS(s_fov)),"%order) |
| 437 |
|
| 438 |
if not geoSources: |
| 439 |
return None |
| 440 |
|
| 441 |
fragments = [ |
| 442 |
"SELECT SUM(coverage)", |
| 443 |
"FROM (SELECT", |
| 444 |
" COALESCE(", |
| 445 |
" "+(" ".join(geoSources)), |
| 446 |
" NULL) AS coverage", |
| 447 |
" FROM %s"%td.getQName(), |
| 448 |
" ) AS q"] |
| 449 |
return "\n".join(fragments) |
| 450 |
|
| 451 |
|
| 452 |
def getMOCQuery(td, order): |
| 453 |
"""returns a MOC-generating query for a tableDef with standard |
| 454 |
columns. |
| 455 |
|
| 456 |
(this is a helper for getMOCForStdTable) |
| 457 |
""" |
| 458 |
for generatingFunction in [ |
| 459 |
getSIAPCoverageQuery, |
| 460 |
getSSAPCoverageQuery, |
| 461 |
getSCSCoverageQuery, |
| 462 |
getObscoreCoverageQuery, |
| 463 |
]: |
| 464 |
mocQuery = generatingFunction(td, order) |
| 465 |
if mocQuery is not None: |
| 466 |
return mocQuery |
| 467 |
else: |
| 468 |
raise base.ReportableError("Table %s does not have columns DaCHS knows" |
| 469 |
" how to get a coverage from."%td.getFullId()) |
| 470 |
|
| 471 |
|
| 472 |
def getMOCForStdTable(td, order=6): |
| 473 |
"""returns a MOC for a tableDef with one of the standard protocol mixins. |
| 474 |
|
| 475 |
The function knows about SCS and SSAP for now; protocols are tested |
| 476 |
for in this order. |
| 477 |
""" |
| 478 |
s = utils.spinner() |
| 479 |
with base.getTableConn() as conn: |
| 480 |
if not base.UnmanagedQuerier(conn).getTableType(td.getQName()): |
| 481 |
return None |
| 482 |
with base.NonBlockingQuery(conn, getMOCQuery(td, order)) as query: |
| 483 |
while query.getResult() is None: |
| 484 |
base.ui.notifyProgress("space "+next(s)) |
| 485 |
return query.getResult()[0][0] |
| 486 |
|
| 487 |
|
| 488 |
def _getTimeTransformer(col): |
| 489 |
"""returns a function turning values in col to MJDs. |
| 490 |
|
| 491 |
This is very much a matter of heuristics; we build upon what's happening |
| 492 |
in utils.serializers. |
| 493 |
""" |
| 494 |
if col.type in ["timestamp", "date"]: |
| 495 |
return lambda val: stc.dateTimeToMJD(val) |
| 496 |
|
| 497 |
elif stc.isMJD(col): |
| 498 |
return utils.identity |
| 499 |
|
| 500 |
elif col.unit=="yr" or col.unit=="a": |
| 501 |
return lambda val: stc.dateTimeToMJD(stc.jYearToDateTime(val)) |
| 502 |
|
| 503 |
elif col.unit=="d": |
| 504 |
return lambda val: val-stc.JD_MJD |
| 505 |
|
| 506 |
elif col.unit=="s": |
| 507 |
return lambda val: stc.dateTimeToMJD(datetime.utcfromtimestamp(val)) |
| 508 |
|
| 509 |
else: |
| 510 |
raise NotImplementedError("Cannot figure out how to get an MJD" |
| 511 |
" from column %s"%col.name) |
| 512 |
|
| 513 |
|
| 514 |
def _min(s): |
| 515 |
return "MIN(%s)"%s |
| 516 |
def _max(s): |
| 517 |
return "MAX(%s)"%s |
| 518 |
|
| 519 |
|
| 520 |
def getTimeLimitsExprs(td): |
| 521 |
"""returns the names of columns hopefully containing minimal and |
| 522 |
maximal time coverage of each row of a table defined by td. |
| 523 |
|
| 524 |
As required by getScalarLimits, this will also return a function |
| 525 |
that (hopefully) turns the detected columns to julian years, |
| 526 |
|
| 527 |
This tries a couple of known criteria for columns containing times |
| 528 |
in some order, and the first one matching wins. |
| 529 |
|
| 530 |
This will raise a NotFoundError if none of our heuristics work. |
| 531 |
""" |
| 532 |
# obscore and friends |
| 533 |
try: |
| 534 |
return (_min(td.getColumnByName("t_min").name), |
| 535 |
_max(td.getColumnByName("t_max").name), |
| 536 |
_getTimeTransformer(td.getColumnByName("t_min"))) |
| 537 |
except base.NotFoundError: |
| 538 |
pass |
| 539 |
|
| 540 |
# SSAP |
| 541 |
try: |
| 542 |
col = td.columns.getColumnByUtype( |
| 543 |
"ssa:Char.TimeAxis.Coverage.Location.Value" |
| 544 |
) |
| 545 |
return _min(col.name), _max(col.name), utils.identity |
| 546 |
except base.NotFoundError: |
| 547 |
pass |
| 548 |
|
| 549 |
# our SIAP mixins |
| 550 |
try: |
| 551 |
col = td.getColumnByName("dateObs" |
| 552 |
) |
| 553 |
return _min(col.name), _max(col.name), utils.identity |
| 554 |
except base.NotFoundError: |
| 555 |
pass |
| 556 |
|
| 557 |
# Any table with appropriate, sufficiently unique UCDs |
| 558 |
try: |
| 559 |
col = td.getColumnByUCD("time.start") |
| 560 |
# we assume time.start and time.end work the same way and one |
| 561 |
# transformer is enough. |
| 562 |
return (_min(col.name), |
| 563 |
_max(td.getColumnByUCD("time.end").name) |
| 564 |
), _getTimeTransformer(col) |
| 565 |
except base.StructureError: |
| 566 |
pass |
| 567 |
|
| 568 |
for obsUCD in ["time.epoch", "time.epoch;obs"]: |
| 569 |
try: |
| 570 |
for col in td.getColumnsByUCD(obsUCD): |
| 571 |
if not col.isScalar(): |
| 572 |
raise ValueError("Cannot determine scalar coverage from arrays") |
| 573 |
return _min(col.name), _max(col.name), _getTimeTransformer(col) |
| 574 |
except (ValueError, base.StructureError): |
| 575 |
pass |
| 576 |
|
| 577 |
raise base.NotFoundError("temporal coverage", "Columns to figure out", |
| 578 |
"table "+td.getFullId()) |
| 579 |
|
| 580 |
|
| 581 |
def getSpectralLimitsExprs(td): |
| 582 |
"""returns the name of columns hopefully containing minimal and |
| 583 |
maximal spectral coverage. |
| 584 |
|
| 585 |
Right now, we are only looking at spectral columns from various IVOA |
| 586 |
standards. I suppose we could also look at UCDs? |
| 587 |
|
| 588 |
If this doesn't find any, it raises a NotFoundError. |
| 589 |
""" |
| 590 |
# obscore and friends |
| 591 |
try: |
| 592 |
return (_max(td.getColumnByName("em_max").name), |
| 593 |
_min(td.getColumnByName("em_min").name), |
| 594 |
base.getSpecConverter("m", "J")) |
| 595 |
except base.NotFoundError: |
| 596 |
pass |
| 597 |
|
| 598 |
# SSAP |
| 599 |
try: |
| 600 |
return (_max(td.getColumnByName("ssa_specend").name), |
| 601 |
_min(td.getColumnByName("ssa_specstart").name), |
| 602 |
base.getSpecConverter("m", "J")) |
| 603 |
except base.NotFoundError: |
| 604 |
pass |
| 605 |
|
| 606 |
# SIAv1 |
| 607 |
try: |
| 608 |
return (_max(td.getColumnByName("bandpassHi").name), |
| 609 |
_min(td.getColumnByName("bandpassLo").name), |
| 610 |
base.getSpecConverter("m", "J")) |
| 611 |
except base.NotFoundError: |
| 612 |
pass |
| 613 |
|
| 614 |
# LineTAP |
| 615 |
try: |
| 616 |
return (_max(td.getColumnByName("vacuum_wavelength").name), |
| 617 |
_min(td.getColumnByName("vacuum_wavelength").name), |
| 618 |
base.getSpecConverter("Angstrom", "J")) |
| 619 |
except base.NotFoundError: |
| 620 |
pass |
| 621 |
|
| 622 |
raise base.NotFoundError("spectral coverage", "Columns to figure out", |
| 623 |
"table "+td.getFullId()) |
| 624 |
|
| 625 |
|
| 626 |
def iterScalarLimits(td, columnsDeterminer): |
| 627 |
"""yields Internal instances for time or spectral coverage. |
| 628 |
|
| 629 |
ColumnsDeterminer is a function td -> (mincol, maxcol, transformer) expected |
| 630 |
to raise a NotFoundError if no appropriate columns can be found. This is |
| 631 |
either getTimeLimitsExprs or getSpectralLimitsExprs at this |
| 632 |
point. transformer here is a function val -> val turning what's coming |
| 633 |
back from the database to what's expected by the coverage machinery |
| 634 |
(e.g., MJD -> jYear). |
| 635 |
|
| 636 |
It's conceivable that at some point we'll give multiple intervals, |
| 637 |
and hence this is an iterator (that can very well yield nothing for |
| 638 |
a variety of reasons). |
| 639 |
""" |
| 640 |
try: |
| 641 |
minExpr, maxExpr, transformer = columnsDeterminer(td) |
| 642 |
except base.NotFoundError: |
| 643 |
return |
| 644 |
|
| 645 |
query = "SELECT %s, %s FROM %s"%( |
| 646 |
str(minExpr), str(maxExpr), td.getQName()) |
| 647 |
with base.getTableConn() as conn: |
| 648 |
if not base.UnmanagedQuerier(conn).getTableType(td.getQName()): |
| 649 |
return |
| 650 |
|
| 651 |
for res in conn.query(query): |
| 652 |
try: |
| 653 |
if res[0] is not None and res[1] is not None: |
| 654 |
yield [transformer(res[0]), transformer(res[1])] |
| 655 |
except ZeroDivisionError: |
| 656 |
raise base.ReportableError(f"Invalid limits in {td}: {res}") |
| 657 |
|
| 658 |
|
| 659 |
def _format_val(val): |
| 660 |
"""returns a string representation of val for inclusion in our |
| 661 |
info table. |
| 662 |
""" |
| 663 |
return utils.makeEllipsis(utils.safe_str(val), 30) |
| 664 |
|
| 665 |
|
| 666 |
def _format_percent(val): |
| 667 |
"""formats the float val as a percentage. |
| 668 |
""" |
| 669 |
return "%.0f%%"%(val*100) |
| 670 |
|
| 671 |
|
| 672 |
_PROP_SEQ = ( |
| 673 |
("min_value", _format_val), |
| 674 |
("median", _format_val), |
| 675 |
("max_value", _format_val), |
| 676 |
("fill_factor", _format_percent)) |
| 677 |
|
| 678 |
def printTableInfo(td, samplePercent=None): |
| 679 |
"""tries to obtain various information on the properties of the |
| 680 |
database table described by td. |
| 681 |
""" |
| 682 |
annotateDBTable(td, samplePercent=samplePercent) |
| 683 |
propTable = [("col",)+tuple(p[0] for p in _PROP_SEQ)] |
| 684 |
for col in td: |
| 685 |
row = [col.name] |
| 686 |
for prop, formatter in _PROP_SEQ: |
| 687 |
if prop in col.annotations: |
| 688 |
row.append(formatter(col.annotations[prop])) |
| 689 |
else: |
| 690 |
row.append("-") |
| 691 |
propTable.append(tuple(row)) |
| 692 |
print(utils.formatSimpleTable(propTable)) |
| 693 |
|
| 694 |
|
| 695 |
def estimateTableSize(tableName, connection): |
| 696 |
"""returns an estimate for the size of the table tableName. |
| 697 |
|
| 698 |
This is precise for tables postgres guesses are small (currently, 1e6 |
| 699 |
rows); for larger tables, we round up postgres' estimate. |
| 700 |
|
| 701 |
The function will return None for non-existing tables. |
| 702 |
""" |
| 703 |
try: |
| 704 |
estsize = base.UnmanagedQuerier(connection).getRowEstimate(tableName) |
| 705 |
except KeyError: |
| 706 |
return None |
| 707 |
|
| 708 |
if estsize<1e6: |
| 709 |
# for small tables, we can be precise; but this will also kick in |
| 710 |
# for views (which have estsize=0), where this may run forever. |
| 711 |
# I don't think this can be helped. |
| 712 |
res = list(connection.query("SELECT COUNT(*) FROM %s"%tableName)) |
| 713 |
if not res: |
| 714 |
return None |
| 715 |
return res[0][0] |
| 716 |
|
| 717 |
else: |
| 718 |
return utils.roundO2M(estsize) |
| 719 |
|
| 720 |
|
| 721 |
def parseCmdline(): |
| 722 |
from argparse import ArgumentParser |
| 723 |
|
| 724 |
parser = ArgumentParser( |
| 725 |
description="Displays various stats about the table referred to in" |
| 726 |
" the argument.") |
| 727 |
parser.add_argument("tableId", help="Table id (of the form rdId#tableId)") |
| 728 |
parser.add_argument("-m", "--moc-order", type=int, default=None, |
| 729 |
dest="mocOrder", |
| 730 |
help="Also print a MOC giving the coverage at MOC_ORDER (use MOC_ORDER=6" |
| 731 |
" for about 1 deg resolution).", |
| 732 |
metavar="MOC_ORDER") |
| 733 |
parser.add_argument("-s", "--sample-percent", type=float, default=None, |
| 734 |
dest="samplePercent", metavar="P", |
| 735 |
help="Only look at P percent of the table to determine min/max/mean.") |
| 736 |
return parser.parse_args() |
| 737 |
|
| 738 |
|
| 739 |
def main(): |
| 740 |
args = parseCmdline() |
| 741 |
td = api.getReferencedElement(args.tableId, api.TableDef) |
| 742 |
printTableInfo(td, args.samplePercent) |
| 743 |
|
| 744 |
if args.mocOrder: |
| 745 |
print("Computing MOC at order %s..."%args.mocOrder) |
| 746 |
print(getMOCForStdTable(td, args.mocOrder)) |