| 1 |
""" |
| 2 |
"User" defined functions, i.e., ADQL functions defined only on this |
| 3 |
system. |
| 4 |
|
| 5 |
See the userFunction docstring on how to use these. |
| 6 |
""" |
| 7 |
|
| 8 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 9 |
#c |
| 10 |
#c This program is free software, covered by the GNU GPL. See the |
| 11 |
#c COPYING file in the source distribution. |
| 12 |
|
| 13 |
|
| 14 |
from gavo import base |
| 15 |
from gavo import stc |
| 16 |
from gavo import utils |
| 17 |
from gavo.adql import common |
| 18 |
from gavo.adql import fieldinfo |
| 19 |
from gavo.adql import morphhelpers |
| 20 |
from gavo.adql import nodes |
| 21 |
from gavo.base import sqlsupport |
| 22 |
|
| 23 |
if sqlsupport.DaCHSConnection.extensionFunctions is None: |
| 24 |
raise ImportError("Early import of adql.ufunctions:" |
| 25 |
" sqlsupport not initialised yet") |
| 26 |
|
| 27 |
UFUNC_REGISTRY = {} |
| 28 |
|
| 29 |
|
| 30 |
def userFunction(name, |
| 31 |
signature, |
| 32 |
doc, |
| 33 |
returntype="double precision", |
| 34 |
unit="", |
| 35 |
ucd="", |
| 36 |
polymorphism=(), |
| 37 |
additionalNames=[], |
| 38 |
depends=None): |
| 39 |
"""a decorator adding some metadata to python functions to make |
| 40 |
them suitable as ADQL user defined functions. |
| 41 |
|
| 42 |
name is the name the function will be visible under in ADQL; signature is a |
| 43 |
signature not including the name of the form '(parName1 type1, parName1 |
| 44 |
type2) -> resulttype'; doc is preformatted ASCII documentation. The |
| 45 |
indentation of the second line will be removed from all lines. |
| 46 |
|
| 47 |
returntype is the SQL return type, which defaults to double |
| 48 |
precision. While ADQL 2.0 appears to say that UDFs must be |
| 49 |
numeric, in practice nobody cares; so, return whatever you see fit. |
| 50 |
|
| 51 |
unit and ucd are optional for when you actually have a good guess what's |
| 52 |
coming back from your ufunc. They can also be callable; in that |
| 53 |
case, they'll be passed the (annotated) arguments, and whatever |
| 54 |
they return will be the unit/ucd. |
| 55 |
|
| 56 |
polymorphism, if given, must be a sequence of pairs of |
| 57 |
(signature, documentation) for alternative signatures of the |
| 58 |
UDF. |
| 59 |
|
| 60 |
additionalNames, if given, is a list of names the function can |
| 61 |
also be used as. This is intended for when you started with |
| 62 |
gavo_somefunc and then want to move on to ivo_somefunc without |
| 63 |
functional change and want to keep legacy queries working. |
| 64 |
|
| 65 |
depends if non-None, is a name of a postgres function that this UDF |
| 66 |
needs. This is for when UDF should disappear when an extension is |
| 67 |
missing. This is not evaluated right away because we do not have |
| 68 |
a database connection during import. Host code has to arrange |
| 69 |
for calling cleanForConn(conn). |
| 70 |
|
| 71 |
The python function receives a list of arguments; this will in |
| 72 |
general be ADQL expression trees. It must return either |
| 73 |
|
| 74 |
* a string that will go literally into the eventual serialised SQL |
| 75 |
string (so take care to quote; in general, you will use |
| 76 |
nodes.flatten(arg) to flatten individual args); |
| 77 |
* or they may return None, in which case the expression tree |
| 78 |
remains unchanged. This is for when the actual implementation is |
| 79 |
in the database. |
| 80 |
* or they may raise nodes.ReplaceNode(r), where r is a nodes.ADQLNode |
| 81 |
instance, which then replaces the user defined function in the parse |
| 82 |
tree and will be annotated as usual |
| 83 |
* or they may return a node with a flatten method, which then will |
| 84 |
be used instead of the normal FunctionNode flattener. This is often |
| 85 |
the preferred way, because it lets DaCHS do the normal annotation work |
| 86 |
on the arguments; the arguments are not yet annotated when these |
| 87 |
functions see them. |
| 88 |
|
| 89 |
If you receive bad arguments or something else goes awry, raise |
| 90 |
a UfuncError. |
| 91 |
""" |
| 92 |
def deco(f): |
| 93 |
f.adqlUDF_name = name |
| 94 |
f.adqlUDF_signature = f.adqlUDF_name+signature.strip() |
| 95 |
f.adqlUDF_doc = utils.fixIndentation(doc, "", 1).strip() |
| 96 |
f.adqlUDF_returntype = returntype |
| 97 |
f.adqlUDF_unit = unit |
| 98 |
f.adqlUDF_ucd = ucd |
| 99 |
f.adqlUDF_additionalSignatures = [ |
| 100 |
{"signature": f.adqlUDF_name+signature.strip(), "doc": doc} |
| 101 |
for signature, doc in polymorphism] |
| 102 |
|
| 103 |
if depends: |
| 104 |
if depends not in sqlsupport.DaCHSConnection.extensionFunctions: |
| 105 |
# don't register if the function would be broken because of |
| 106 |
# missing dependencies. |
| 107 |
return f |
| 108 |
|
| 109 |
UFUNC_REGISTRY[f.adqlUDF_name.upper()] = f |
| 110 |
for alias in additionalNames: |
| 111 |
UFUNC_REGISTRY[alias.upper()] = f |
| 112 |
|
| 113 |
return f |
| 114 |
return deco |
| 115 |
|
| 116 |
|
| 117 |
def _makeTwoArgBooleanizer(funcName, booleanExpr): |
| 118 |
"""makes and registers a 2-argument booleanizer for funcName. |
| 119 |
|
| 120 |
That's where 1=some_pred(x) should become some [not] op1 opr op2 expression. |
| 121 |
|
| 122 |
booleanExpr is the postgres expression the function should be booleanized |
| 123 |
to. Refer to the two arguments as %(1)s and %(2)s |
| 124 |
""" |
| 125 |
def _booleanizeThis(node, operator, operand): |
| 126 |
if len(node.args)!=2: |
| 127 |
raise common.UfuncError("%s takes exactly two arguments"%funcName) |
| 128 |
return morphhelpers.addNotToBooleanized( |
| 129 |
booleanExpr%{ |
| 130 |
'1': nodes.flatten(node.args[0]), |
| 131 |
'2': nodes.flatten(node.args[1])}, |
| 132 |
operator, operand) |
| 133 |
|
| 134 |
morphhelpers.registerBooleanizer(funcName.upper(), _booleanizeThis) |
| 135 |
|
| 136 |
|
| 137 |
def _makeOneArgBooleanizer(funcName): |
| 138 |
"""makes and registers a one-argument booleanizer for funcName. |
| 139 |
|
| 140 |
That's for when the morphed ADQL would just be [not] expr, and |
| 141 |
expr is what the udf code has returned. |
| 142 |
""" |
| 143 |
morphhelpers.registerBooleanizer(funcName.upper(), |
| 144 |
morphhelpers.addNotToBooleanized) |
| 145 |
|
| 146 |
|
| 147 |
@userFunction("gavo_match", |
| 148 |
"(pattern TEXT, string TEXT) -> INTEGER", |
| 149 |
""" |
| 150 |
gavo_match returns 1 if the POSIX regular expression pattern |
| 151 |
matches anything in string, 0 otherwise. |
| 152 |
""", |
| 153 |
"integer") |
| 154 |
def _match(args): |
| 155 |
if len(args)!=2: |
| 156 |
raise common.UfuncError("gavo_match takes exactly two arguments") |
| 157 |
return "(CASE WHEN %s ~ %s THEN 1 ELSE 0 END)"%( |
| 158 |
nodes.flatten(args[1]), nodes.flatten(args[0])) |
| 159 |
|
| 160 |
|
| 161 |
@userFunction("ivo_hasword", |
| 162 |
"(haystack TEXT, needle TEXT) -> INTEGER", |
| 163 |
""" |
| 164 |
gavo_hasword returns 1 if needle shows up in haystack, 0 otherwise. This |
| 165 |
is for "google-like"-searches in text-like fields. In word, you can |
| 166 |
actually employ a fairly complex query language; see |
| 167 |
https://www.postgresql.org/docs/current/textsearch.html |
| 168 |
for details. |
| 169 |
""", |
| 170 |
"integer") |
| 171 |
def _hasword(args): |
| 172 |
if len(args)!=2: |
| 173 |
raise common.UfuncError("ivo_hasword takes exactly two arguments") |
| 174 |
return None |
| 175 |
|
| 176 |
_makeTwoArgBooleanizer("ivo_hasword", |
| 177 |
"(to_tsvector('english', %(1)s) @@ plainto_tsquery('english', %(2)s))") |
| 178 |
|
| 179 |
|
| 180 |
@userFunction("ivo_nocasematch", |
| 181 |
"(value TEXT, pattern TEXT) -> INTEGER", |
| 182 |
""" |
| 183 |
ivo_nocasematch returns 1 if pattern matches value, 0 otherwise. |
| 184 |
pattern is defined as for the SQL LIKE operator, but the |
| 185 |
match is performed case-insensitively. This function in effect |
| 186 |
provides a surrogate for the ILIKE SQL operator that is missing from |
| 187 |
ADQL. |
| 188 |
|
| 189 |
On this site, this is actually implemented using python's and SQL's |
| 190 |
LOWER, so for everything except ASCII, your mileage will vary. |
| 191 |
""", |
| 192 |
"integer") |
| 193 |
def _nocasematch(args): |
| 194 |
if len(args)!=2: |
| 195 |
raise common.UfuncError("ivo_nocasematch takes exactly two arguments") |
| 196 |
if args[1].type=='characterStringLiteral': |
| 197 |
args[1].value = args[1].value.lower() |
| 198 |
else: |
| 199 |
args[1] = "LOWER(%s)"%nodes.flatten(args[1]) |
| 200 |
return None |
| 201 |
|
| 202 |
_makeTwoArgBooleanizer("ivo_nocasematch", "(LOWER(%(1)s) like %(2)s)") |
| 203 |
|
| 204 |
|
| 205 |
@userFunction("ivo_hashlist_has", |
| 206 |
"(hashlist TEXT, item TEXT) -> INTEGER", |
| 207 |
""" |
| 208 |
The function takes two strings; the first is a list of words not |
| 209 |
containing the hash sign (#), concatenated by hash signs, the second is |
| 210 |
a word not containing the hash sign. It returns 1 if, compared |
| 211 |
case-insensitively, the second argument is in the list of words coded in |
| 212 |
the first argument. The behaviour in case the the second |
| 213 |
argument contains a hash sign is unspecified. |
| 214 |
""", |
| 215 |
"integer") |
| 216 |
def _hashlist_has(args): |
| 217 |
if len(args)!=2: |
| 218 |
raise common.UfuncError("ivo_haslist_has takes exactly two arguments") |
| 219 |
return None |
| 220 |
|
| 221 |
_makeTwoArgBooleanizer("ivo_hashlist_has", |
| 222 |
"lower(%(2)s) = ANY(string_to_array(lower(%(1)s), '#'))") |
| 223 |
|
| 224 |
@userFunction("ivo_interval_overlaps", |
| 225 |
"(l1 NUMERIC, h1 NUMERIC, l2 NUMERIC, h2 NUMERIC) -> INTEGER", |
| 226 |
""" |
| 227 |
The function returns 1 if the interval [l1...h1] overlaps with |
| 228 |
the interval [l2...h2]. For the purposes of this function, |
| 229 |
the case l1=h2 or l2=h1 is treated as overlap. The function |
| 230 |
returns 0 for non-overlapping intervals. |
| 231 |
""") |
| 232 |
def _interval_overlaps(args): |
| 233 |
if len(args)!=4: |
| 234 |
raise common.UfuncError( |
| 235 |
"ivo_interval_overlaps takes exactly four arguments") |
| 236 |
l1, h1, l2, h2 = args |
| 237 |
return nodes.TransparentNode(children=[ |
| 238 |
nodes.Comparison(op1=h1, opr='>=', op2=l2), |
| 239 |
"AND", nodes.Comparison(op1=h2, opr='>=', op2=l1), |
| 240 |
"AND", nodes.Comparison(op1=l1, opr='<=', op2=h1), |
| 241 |
"AND", nodes.Comparison(op1=l2, opr='<=', op2=h2)]) |
| 242 |
# return "((%s)>=(%s) AND (%s)>=(%s) AND (%s)<=(%s) AND (%s)<=(%s))::INTEGER"%( |
| 243 |
# h1, l2, h2, l1, |
| 244 |
# l1, h1, l2, h2) |
| 245 |
|
| 246 |
_makeOneArgBooleanizer("ivo_interval_overlaps") |
| 247 |
|
| 248 |
|
| 249 |
@userFunction("ivo_interval_has", |
| 250 |
"(val NUMERIC, iv INTERVAL) -> INTEGER", |
| 251 |
""" |
| 252 |
The function returns 1 if the interval iv contains val, 0 otherwise. |
| 253 |
The lower limit is always included in iv, behaviour on the upper |
| 254 |
limit is column-specific. |
| 255 |
""") |
| 256 |
def _interval_has(args): |
| 257 |
if len(args)!=2: |
| 258 |
raise common.UfuncError( |
| 259 |
"ivo_interval_has takes exactly two arguments") |
| 260 |
return None |
| 261 |
|
| 262 |
_makeTwoArgBooleanizer("ivo_interval_has", "((%(1)s) <@ (%(2)s))") |
| 263 |
|
| 264 |
|
| 265 |
@userFunction("ivo_to_mjd", |
| 266 |
"(d TIMESTAMP) -> DOUBLE PRECISION", |
| 267 |
""" |
| 268 |
The function converts a postgres timestamp to modified julian date. |
| 269 |
This is naive; no corrections for timezones, let alone time |
| 270 |
scales or the like are done; you can thus not expect this to be |
| 271 |
good to second-precision unless you are careful in the construction |
| 272 |
of the timestamp. |
| 273 |
""", |
| 274 |
additionalNames=["gavo_to_mjd"]) |
| 275 |
def _to_mjd(args): |
| 276 |
if len(args)!=1: |
| 277 |
raise common.UfuncError("gavo_to_mjd takes exactly one timestamp argument") |
| 278 |
return "ts_to_mjd(%s)"%nodes.flatten(args[0]) |
| 279 |
|
| 280 |
|
| 281 |
@userFunction("ivo_to_jd", |
| 282 |
"(d TIMESTAMP) -> DOUBLE PRECISION", |
| 283 |
""" |
| 284 |
The function converts a postgres timestamp to julian date. |
| 285 |
This is naive; no corrections for timezones, let alone time |
| 286 |
scales or the like are done; you can thus not expect this to be |
| 287 |
good to second-precision unless you are careful in the construction |
| 288 |
of the timestamp. |
| 289 |
""", |
| 290 |
additionalNames=["gavo_to_jd"]) |
| 291 |
def _to_jd(args): |
| 292 |
if len(args)!=1: |
| 293 |
raise common.UfuncError("gavo_to_jd takes exactly one timestamp argument") |
| 294 |
return "ts_to_jd(%s)"%nodes.flatten(args[0]) |
| 295 |
|
| 296 |
|
| 297 |
class HistogramNode(nodes.FunctionNode): |
| 298 |
def addFieldInfo(self, context): |
| 299 |
ucd = "stat.histogram" |
| 300 |
baseUCD = self.args[0].fieldInfo.ucd |
| 301 |
if baseUCD: |
| 302 |
ucd = f"{ucd};{baseUCD}" |
| 303 |
|
| 304 |
self.fieldInfo = fieldinfo.FieldInfo("integer[]", |
| 305 |
"", ucd, *nodes.collectUserData(self._getInfoChildren())) |
| 306 |
|
| 307 |
|
| 308 |
@userFunction("ivo_histogram", |
| 309 |
"(val REAL, lower REAL, upper REAL, nbins INTEGER) -> INTEGER[]", |
| 310 |
""" |
| 311 |
The aggregate function returns a histogram of val with nbins+2 elements. |
| 312 |
Assuming 0-based arrays, result[0] contains the number of underflows (i.e., |
| 313 |
val<lower), result[nbins+1] the number of overflows. Elements 1..nbins |
| 314 |
are the counts in nbins bins of width (upper-lower)/nbins. Clients |
| 315 |
will have to convert back to physical units using some external |
| 316 |
communication, there currently is no (meta-) data as lower and upper in |
| 317 |
the TAP response. |
| 318 |
""", |
| 319 |
returntype="integer[]", |
| 320 |
additionalNames=["gavo_histogram"]) |
| 321 |
def _ivo_histogram(args): |
| 322 |
if len(args)!=4: |
| 323 |
raise common.UfuncError( |
| 324 |
"ivo_histogram takes exactly four arguments (the column to aggregate," |
| 325 |
" a lower and upper limit of values to tabulate, and the number" |
| 326 |
" of bins desired).") |
| 327 |
raise nodes.ReplaceNode( |
| 328 |
HistogramNode(funName="GAVO_HISTOGRAM", args=args)) |
| 329 |
|
| 330 |
|
| 331 |
@userFunction("gavo_ipix", |
| 332 |
"(long REAL, lat REAL) -> BIGINT", |
| 333 |
""" |
| 334 |
gavo_ipix returns the q3c ipix for a long/lat pair (it simply wraps |
| 335 |
the 13c_ang2ipix function). |
| 336 |
|
| 337 |
This is probably only relevant when you play tricks with indices or |
| 338 |
PPMXL ids. |
| 339 |
""", |
| 340 |
returntype="bigint", |
| 341 |
ucd="pos", |
| 342 |
depends="q3c_ang2ipix") |
| 343 |
def _gavo_ipix(args): |
| 344 |
if len(args)!=2: |
| 345 |
raise common.UfuncError( |
| 346 |
"gavo_ipix takes exactly two arguments.") |
| 347 |
|
| 348 |
int, lat = [nodes.flatten(a) for a in args] |
| 349 |
return "q3c_ang2ipix(%s, %s)"%(int, lat) |
| 350 |
|
| 351 |
|
| 352 |
class _TransformNode(nodes.FunctionNode): |
| 353 |
"""a node representing a gavo_transform call. |
| 354 |
|
| 355 |
This has a proper node mainly because of type inference. |
| 356 |
""" |
| 357 |
name = "gavo_transform" |
| 358 |
_a_trans = None |
| 359 |
_a_toSys = None |
| 360 |
|
| 361 |
ucdMap = { |
| 362 |
'ICRS': "pos.eq", |
| 363 |
'FK5': "pos.eq", |
| 364 |
'FK4': "pos.eq", |
| 365 |
'GALACTIC': "pos.galactic", |
| 366 |
} |
| 367 |
|
| 368 |
def flatten(self): |
| 369 |
return "(%s)%s"%(nodes.flatten(self.args[0]), self.trans) |
| 370 |
|
| 371 |
def addFieldInfo(self, context): |
| 372 |
if hasattr(self.args[0], "fieldInfo"): |
| 373 |
self.fieldInfo = self.args[0].fieldInfo |
| 374 |
|
| 375 |
else: |
| 376 |
# go for an STC-S string |
| 377 |
self.fieldInfo = fieldinfo.FieldInfo("text", "", "", tainted=True) |
| 378 |
self.fieldInfo.properties["xtype"] = "adql:REGION" |
| 379 |
|
| 380 |
# We discard the existing UCD, as that may change depending on the |
| 381 |
# the frame. We should probably look at the type, too, and not |
| 382 |
# call circles, polygons, or MOCs positions. Let's see when we want |
| 383 |
# that. |
| 384 |
self.fieldInfo.ucd = self.ucdMap.get(self.toSys, "pos") |
| 385 |
|
| 386 |
|
| 387 |
@userFunction("ivo_geom_transform", |
| 388 |
"(from_sys TEXT, to_sys TEXT, geo GEOMETRY) -> GEOMETRY", |
| 389 |
""" |
| 390 |
The function transforms ADQL geometries between various reference systems. |
| 391 |
geo can be a POINT, a CIRCLE, or a POLYGON, and the function will return a |
| 392 |
geometry of the same type. In the current implementation, from_sys and |
| 393 |
to_sys must be literal strings (i.e., they cannot be computed through |
| 394 |
expressions or be taken from database columns). |
| 395 |
|
| 396 |
All transforms are just simple rotations, which is only a rough |
| 397 |
approximation to the actual relationships between reference systems |
| 398 |
(in particular between FK4 and ICRS-based ones). Note that, in particular, |
| 399 |
the epoch is not changed (i.e., no proper motions are applied). |
| 400 |
|
| 401 |
We currently support the following reference frames: ICRS, FK5 (which |
| 402 |
is treated as ICRS), FK4 (for B1950. without epoch-dependent corrections), |
| 403 |
GALACTIC. Reference frame names are case-sensitive. |
| 404 |
""", |
| 405 |
returntype="GEOMETRY", |
| 406 |
additionalNames=["gavo_transform"]) |
| 407 |
def _gavo_transform(args): |
| 408 |
if len(args)!=3: |
| 409 |
raise common.UfuncError( |
| 410 |
"gavo_transform takes exactly three arguments") |
| 411 |
|
| 412 |
fromSys = nodes.getStringLiteral(args[0], "source reference system") |
| 413 |
toSys = nodes.getStringLiteral(args[1], "target reference system") |
| 414 |
|
| 415 |
try: |
| 416 |
trans = stc.getPGSphereTrafo(fromSys, toSys) |
| 417 |
except stc.STCValueError as msg: |
| 418 |
raise common.UfuncError( |
| 419 |
"Cannot compute transformation between %s and %s: %s"%( |
| 420 |
fromSys, toSys, msg)) |
| 421 |
|
| 422 |
if trans is None: |
| 423 |
return args[2] |
| 424 |
else: |
| 425 |
raise nodes.ReplaceNode(_TransformNode( |
| 426 |
funName="gavo_transform", |
| 427 |
args=(args[2],), |
| 428 |
trans=trans, |
| 429 |
toSys=toSys)) |
| 430 |
|
| 431 |
|
| 432 |
@userFunction("ivo_normal_random", |
| 433 |
"(mu REAL, sigma REAL) -> REAL", |
| 434 |
"""The function returns a random number drawn from a normal distribution |
| 435 |
with mean mu and width sigma. |
| 436 |
|
| 437 |
Implementation note: Right now, the Gaussian is approximated by |
| 438 |
summing up and scaling ten calls to random. This, hence, is not |
| 439 |
very precise or fast. It might work for some use cases, and we |
| 440 |
will provide a better implementation if this proves inadequate. |
| 441 |
""", |
| 442 |
returntype="real", |
| 443 |
additionalNames=["gavo_normal_random"]) |
| 444 |
def _gavo_normal_random(args): |
| 445 |
if len(args)!=2: |
| 446 |
raise common.UfuncError( |
| 447 |
"gavo_normal_random takes mu, sigma arguments.") |
| 448 |
|
| 449 |
return ("(((random()+random()+random()+random()+random()" |
| 450 |
"+random()+random()+random()+random()+random()-5)*(%s)" |
| 451 |
")+(%s))")%(nodes.flatten(args[1]), nodes.flatten(args[0])) |
| 452 |
|
| 453 |
|
| 454 |
@userFunction("gavo_mocunion", |
| 455 |
"(moc1 MOC, moc2 MOC) -> MOC", |
| 456 |
"""returns the union of two MOCs. |
| 457 |
""", |
| 458 |
returntype="smoc", |
| 459 |
depends="smoc_union") |
| 460 |
def _gavo_mocunion(args): |
| 461 |
if len(args)!=2: |
| 462 |
raise common.UfuncError( |
| 463 |
"gavo_mocunion only has two arguments.") |
| 464 |
|
| 465 |
return "%s | %s"%( |
| 466 |
nodes.flatten(args[0]), |
| 467 |
nodes.flatten(args[1])) |
| 468 |
|
| 469 |
|
| 470 |
@userFunction("gavo_mocintersect", |
| 471 |
"(moc1 MOC, moc2 MOC) -> MOC", |
| 472 |
"""returns the intersection of two MOCs. |
| 473 |
""", |
| 474 |
returntype="smoc", |
| 475 |
depends="smoc_union") |
| 476 |
def _gavo_mocintersect(args): |
| 477 |
if len(args)!=2: |
| 478 |
raise common.UfuncError( |
| 479 |
"gavo_mocintersect only has two arguments.") |
| 480 |
|
| 481 |
return "%s & %s"%( |
| 482 |
nodes.flatten(args[0]), |
| 483 |
nodes.flatten(args[1])) |
| 484 |
|
| 485 |
|
| 486 |
@userFunction("ivo_string_agg", |
| 487 |
"(expression TEXT, delimiter TEXT) -> TEXT", |
| 488 |
""" |
| 489 |
An aggregate function returning all values of |
| 490 |
expression within a GROUP contcatenated with delimiter |
| 491 |
""", |
| 492 |
"text") |
| 493 |
def _string_agg(args): |
| 494 |
if len(args)!=2: |
| 495 |
raise common.UfuncError("ivo_string_agg takes exactly two arguments") |
| 496 |
return "string_agg(%s, %s)"%( |
| 497 |
nodes.flatten(args[0]), nodes.flatten(args[1])) |
| 498 |
|
| 499 |
|
| 500 |
@userFunction("gavo_apply_pm", |
| 501 |
"(ra DOUBLE PRECISION, dec DOUBLE PRECISION, pmra DOUBLE PRECISION, pmde DOUBLE PRECISION, epdist DOUBLE PRECISION) -> POINT", |
| 502 |
"""Returns a POINT (in the UNDEFINED reference frame) for the position |
| 503 |
an object at ra/dec with proper motion pmra/pmde has after epdist years. |
| 504 |
|
| 505 |
positions must be in degrees, PMs in should be in julian years (i.e., proper |
| 506 |
motions are expected in degrees/year). pmra is assumed to contain |
| 507 |
cos(delta). |
| 508 |
|
| 509 |
This function goes through the tangential plane. Since it does not have |
| 510 |
information on distance and radial velocity, it cannot reconstruct |
| 511 |
the true space motion, and hence its results will degrade over time. |
| 512 |
|
| 513 |
This function should not be used in new queries; use ivo_epoch_prop |
| 514 |
instead. |
| 515 |
""", |
| 516 |
returntype="spoint", |
| 517 |
additionalNames=["ivo_apply_pm"], |
| 518 |
depends="epoch_prop") |
| 519 |
def _gavo_apply_pm(args): |
| 520 |
# we need to make sure we eventually flatten to ivo_apply_pm, as |
| 521 |
# that's what is defined in //adql. For that, we have to manipulate |
| 522 |
# our node, which UserFunction below somewhat stupidly does not allow. |
| 523 |
# We simply steal its self: |
| 524 |
utils.stealVar("self").funName = "IVO_APPLY_PM" |
| 525 |
|
| 526 |
if len(args)==5: |
| 527 |
# there's no indexing or anything to gain here; drop through to an |
| 528 |
# implementation in the database. |
| 529 |
# |
| 530 |
# This is the legacy ("gavo") implementation that we probably |
| 531 |
# want to drop. |
| 532 |
return None |
| 533 |
elif len(args)==6: |
| 534 |
# This is the ESAC-compliant ("ivo") implementation that we probably |
| 535 |
# want to keep. |
| 536 |
return None |
| 537 |
else: |
| 538 |
raise common.UfuncError( |
| 539 |
"gavo_apply_pm requires exactly ra, dec, pmra, pmdec, epdist.") |
| 540 |
|
| 541 |
|
| 542 |
# epoch_prop will bomb out at the postgres level unless you have a |
| 543 |
# pgsphere later than 1.2 or so |
| 544 |
|
| 545 |
class EpochPropagation(nodes.FunctionNode): |
| 546 |
def flatten(self): |
| 547 |
kws = dict((label, nodes.flatten(self.args[ind])) |
| 548 |
for ind, label in enumerate( |
| 549 |
"ra dec parallax pmra pmdec radial_velocity ref_epoch out_epoch".split())) |
| 550 |
|
| 551 |
if self.funName=="ivo_epoch_prop_pos": |
| 552 |
kws["selectClause"] = "spoint(t[1], t[2])" |
| 553 |
elif self.funName=="ivo_epoch_prop": |
| 554 |
kws["selectClause"] = ("array[DEGREES(t[1]), DEGREES(t[2]), t[3]," |
| 555 |
" DEGREES(t[4]*3.6e6), DEGREES(t[5]*3.6e6), t[6]]") |
| 556 |
else: |
| 557 |
raise common.UfuncError( |
| 558 |
f"Unknown epoch propagation mode: {self.funName}") |
| 559 |
|
| 560 |
return ("(SELECT {selectClause} FROM" |
| 561 |
" epoch_prop(spoint(RADIANS({ra}), RADIANS({dec}))," |
| 562 |
" {parallax}, RADIANS(({pmra})/3.6e6), RADIANS(({pmdec})/3.6e6)," |
| 563 |
" {radial_velocity}, ({out_epoch})-({ref_epoch})) as t)" |
| 564 |
.format(**kws)) |
| 565 |
|
| 566 |
|
| 567 |
@userFunction("ivo_epoch_prop", |
| 568 |
"(ra DOUBLE PRECISION, dec DOUBLE PRECISION, parallax DOUBLE PRECISION," |
| 569 |
" pmra DOUBLE PRECISION, pmdec DOUBLE PRECISION," |
| 570 |
" radial_velocity DOUBLE PRECISION," |
| 571 |
" ref_epoch DOUBLE PRECISION, out_epoch DOUBLE PRECISION)" |
| 572 |
" -> DOUBLE PRECISION[6]", |
| 573 |
"""Returns a 6-vector of (ra, dec, parallax, pmra, pmdec, rv) |
| 574 |
at out_epoch for these quantities at ref_epoch. |
| 575 |
|
| 576 |
Essentially, it will apply the proper motion under the assumption of |
| 577 |
linear motion. Despite the name of the positional parameters, this is |
| 578 |
not restricted to equatorial systems, as long as positions and proper |
| 579 |
motions are expressed in the same reference frames. |
| 580 |
|
| 581 |
Units on input and output are degrees for ra and dec, mas for parallax, |
| 582 |
mas/yr for pmra and pmdec, and km/s for the radial velocity. |
| 583 |
|
| 584 |
ref_epoch and out_epoch are given in Julian years. |
| 585 |
|
| 586 |
parallax, pmra, pmdec, and radial_velocity may be None and will enter |
| 587 |
the computations as 0 then, except in the case of parallax, which |
| 588 |
will be some small value. When abs(parallax) is smaller or equal |
| 589 |
to that small value, parallax and radial velocity will be NULL on |
| 590 |
output. |
| 591 |
|
| 592 |
In daily use, you probably want to use the ivo_epoch_prop_pos functions. |
| 593 |
""", |
| 594 |
returntype="double precision[6]", |
| 595 |
depends="epoch_prop") |
| 596 |
def _epoch_prop(args): |
| 597 |
if len(args)!=8: |
| 598 |
raise common.UfuncError("ivo_epoch_prop gets ra, dec [deg], parallax" |
| 599 |
" [mas], pmra, pmdec [mas/yr], radial_velocity [km/s], ref_epoch," |
| 600 |
" out_epoch [yr] arguments") |
| 601 |
return EpochPropagation( |
| 602 |
funName="ivo_epoch_prop", |
| 603 |
args=args) |
| 604 |
|
| 605 |
|
| 606 |
@userFunction("ivo_epoch_prop_pos", |
| 607 |
"(ra DOUBLE PRECISION, dec DOUBLE PRECISION, parallax DOUBLE PRECISION," |
| 608 |
" pmra DOUBLE PRECISION, pmdec DOUBLE PRECISION," |
| 609 |
" radial_velocity DOUBLE PRECISION," |
| 610 |
" ref_epoch DOUBLE PRECISION, out_epoch DOUBLE PRECISION)" |
| 611 |
" -> POINT", |
| 612 |
"""Returns a POINT giving the position at out_epoch for an object |
| 613 |
with the six parameters at ref_epoch. |
| 614 |
|
| 615 |
Essentially, it will apply the proper motion under the assumption of |
| 616 |
linear motion. Despite the name of the positional parameters, this is |
| 617 |
not restricted to equatorial systems, as long as positions and proper |
| 618 |
motions are expressed in the same reference frames. |
| 619 |
|
| 620 |
Units on input are degrees for ra and dec, mas for parallax, |
| 621 |
mas/yr for pmra and pmdec, and km/s for the radial velocity. |
| 622 |
ref_epoch and out_epoch are given in Julian years. |
| 623 |
|
| 624 |
parallax, pmra, pmdec, and radial_velocity may be None and will enter |
| 625 |
the computations as 0 then, except in the case of parallax, which |
| 626 |
will be some small value. |
| 627 |
""", |
| 628 |
returntype="spoint", |
| 629 |
polymorphism=[ |
| 630 |
("(ra DOUBLE PRECISION, dec DOUBLE PRECISION," |
| 631 |
" pmra DOUBLE PRECISION, pmdec DOUBLE PRECISION," |
| 632 |
" ref_epoch DOUBLE PRECISION, out_epoch DOUBLE PRECISION)" |
| 633 |
" -> POINT", |
| 634 |
"""A variant of ivo_epoch_prop_pos that behave as if parallax |
| 635 |
and radial_velocity were both passed as NULL.""")], |
| 636 |
ucd="pos", |
| 637 |
depends="epoch_prop") |
| 638 |
def _epoch_prop_pos(args): |
| 639 |
if len(args)==6: |
| 640 |
# fill in NULL literals for parallax (arg 3) and radial_velocity (arg 6) |
| 641 |
args[4:4] = [nodes.makeValueExpression(["NULL"])] |
| 642 |
args[2:2] = [nodes.makeValueExpression(["NULL"])] |
| 643 |
|
| 644 |
elif len(args)==8: |
| 645 |
pass |
| 646 |
|
| 647 |
else: |
| 648 |
raise common.UfuncError("ivo_epoch_prop_pos gets ra, dec [deg], parallax" |
| 649 |
" [mas], pmra, pmdec [mas/yr], radial_velocity [km/s], ref_epoch," |
| 650 |
" out_epoch [yr] arguments, where you may leave out parallax and" |
| 651 |
" radial_velocity.") |
| 652 |
|
| 653 |
return EpochPropagation( |
| 654 |
funName="ivo_epoch_prop_pos", |
| 655 |
args=args) |
| 656 |
|
| 657 |
|
| 658 |
# the healpix functions require a fairly recent pgspsphere (available |
| 659 |
# as of Debian bullseye) |
| 660 |
|
| 661 |
@userFunction("ivo_healpix_index", |
| 662 |
"(order INTEGER, ra DOUBLE PRECISION, dec DOUBLE PRECISION) -> BIGINT", |
| 663 |
"""Returns the index of the (nest) healpix with order containing the |
| 664 |
spherical point (ra, dec). |
| 665 |
|
| 666 |
An alternative, 2-argument form |
| 667 |
|
| 668 |
ivo_healpix_index(order INTEGER, p POINT) -> BIGINT |
| 669 |
|
| 670 |
is also available. |
| 671 |
""", |
| 672 |
returntype="bigint", |
| 673 |
depends="healpix_nest") |
| 674 |
def _ivo_healpix_index(args): |
| 675 |
if len(args)==2: |
| 676 |
return "healpix_nest(%s, %s)"%( |
| 677 |
nodes.flatten(args[0]), nodes.flatten(args[1])) |
| 678 |
elif len(args)==3: |
| 679 |
return "healpix_nest(%s, spoint(RADIANS(%s), RADIANS(%s)))"%( |
| 680 |
nodes.flatten(args[0]), nodes.flatten(args[1]), nodes.flatten(args[2])) |
| 681 |
else: |
| 682 |
raise common.UfuncError("ivo_healpix_index takes either (ra, dec, order)" |
| 683 |
" or (point, order) arguments") |
| 684 |
|
| 685 |
|
| 686 |
@userFunction("ivo_healpix_center", |
| 687 |
"(hpxOrder INTEGER, hpxIndex BIGINT) -> POINT", |
| 688 |
"""returns a POINT corresponding to the center of the healpix with |
| 689 |
the given index at the given order. |
| 690 |
""", |
| 691 |
returntype="spoint", |
| 692 |
depends="healpix_nest") |
| 693 |
def _ivo_healpix_center(args): |
| 694 |
if len(args)!=2: |
| 695 |
raise common.UfuncError("ivo_healpix_center only takes (index, order)" |
| 696 |
" arguments") |
| 697 |
return "center_of_healpix_nest(%s, %s)"%( |
| 698 |
nodes.flatten(args[0]), nodes.flatten(args[1])) |
| 699 |
|
| 700 |
|
| 701 |
@userFunction("gavo_getauthority", |
| 702 |
"(ivoid TEXT) -> TEXT", |
| 703 |
"""returns the authority part of an ivoid (or, more generally a URI). |
| 704 |
So, ivo://org.gavo.dc/foo/bar#baz becomes org.gavo.dc. |
| 705 |
|
| 706 |
The behaviour for anything that's not a full URI is undefined. |
| 707 |
""", |
| 708 |
returntype="text") |
| 709 |
def _gavo_getauthority(args): |
| 710 |
if len(args)!=1: |
| 711 |
raise common.UfuncError("gavo_getauthority only takes an ivoid" |
| 712 |
" argument.") |
| 713 |
return None |
| 714 |
|
| 715 |
|
| 716 |
@userFunction("gavo_vocmatch", |
| 717 |
"(vocname TEXT, term TEXT, matchagainst TEXT) -> INTEGER", |
| 718 |
"""returns 1 if matchagainst is term or narrower in the IVOA vocabulary |
| 719 |
vocname, 0 otherwise. |
| 720 |
|
| 721 |
This is intended for semantic querying. For instance, |
| 722 |
gavo_vocmatch('datalink/core', 'calibration', semantics) would be 1 |
| 723 |
if semantics is any of calibration, bias, dark, or flat. |
| 724 |
|
| 725 |
For RDF-flavoured vocabularies (strict trees), term will expand to the |
| 726 |
entire branch rooted in term. For SKOS-flavoured vocabularies (where |
| 727 |
narrower is not transitive), only directly narrower terms will be included. |
| 728 |
|
| 729 |
Both the term and the vocabulary name must be string literals (i.e., |
| 730 |
constants). matchagainst can be any string-valued expression. |
| 731 |
""", |
| 732 |
returntype="integer") |
| 733 |
def _gavo_vocmatch(args): |
| 734 |
if len(args)!=3: |
| 735 |
raise common.UfuncError("gavo_getauthority takes three" |
| 736 |
" arguments.") |
| 737 |
|
| 738 |
from gavo.protocols import vocabularies |
| 739 |
voc = vocabularies.get_vocabulary( |
| 740 |
nodes.getStringLiteral(args[0], "vocabulary name")) |
| 741 |
term = nodes.getStringLiteral(args[1], "term") |
| 742 |
if term not in voc["terms"]: |
| 743 |
raise common.UfuncError("'%s' is not a term in the vocabulary %s"%( |
| 744 |
term, voc["uri"])) |
| 745 |
|
| 746 |
expanded = [args[1]] |
| 747 |
for narrower in voc["terms"][term]["narrower"]: |
| 748 |
expanded.append( |
| 749 |
nodes.CharacterStringLiteral(value=narrower)) |
| 750 |
|
| 751 |
args[1] = "(%s)"%(", ".join(nodes.flatten(n) for n in expanded)) |
| 752 |
raise nodes.ReplaceNode(nodes.FunctionNode( |
| 753 |
funName='GAVO_VOCMATCH', |
| 754 |
args=(args[2], args[1]))) |
| 755 |
|
| 756 |
_makeTwoArgBooleanizer("gavo_vocmatch", |
| 757 |
"%(1)s IN %(2)s") |
| 758 |
|
| 759 |
|
| 760 |
class _SpecconvNode(nodes.FieldInfoedNode): |
| 761 |
"""A node left by gavo_specconv. |
| 762 |
|
| 763 |
It is constructed with the target unit and the expression to |
| 764 |
convert. During annotation, it will mutate its children so they |
| 765 |
are in the target unit. |
| 766 |
|
| 767 |
We have this complication because at UDF creation time, the columns |
| 768 |
are not annotated and hence we may not know the unit to convert from. |
| 769 |
If forceUnit is given (three-argument form), we could do the |
| 770 |
transformation immediately, but we still use the code in |
| 771 |
addFieldInfo to avoid too many code paths. The price is the |
| 772 |
stupid exprReplaced hack. |
| 773 |
""" |
| 774 |
_a_targetUnit = None |
| 775 |
_a_forceUnit = None |
| 776 |
_a_expr = None |
| 777 |
exprReplaced = False |
| 778 |
|
| 779 |
def _getFromUnit(self, context): |
| 780 |
"""returns the unit we transform from. |
| 781 |
|
| 782 |
This needs the context because it might produce warnings. |
| 783 |
""" |
| 784 |
fromUnit = None |
| 785 |
try: |
| 786 |
fromUnit = self.expr.fieldInfo.unit |
| 787 |
if not fromUnit: |
| 788 |
raise AttributeError("Empty from Unit") |
| 789 |
except AttributeError: |
| 790 |
pass # handle missing fromUnit below |
| 791 |
|
| 792 |
if self.forceUnit: |
| 793 |
if fromUnit: |
| 794 |
context.warnings.append("Warning in specconv: overriding" |
| 795 |
f" unit {fromUnit} with {self.forceUnit}") |
| 796 |
fromUnit = self.forceUnit |
| 797 |
|
| 798 |
if not fromUnit: |
| 799 |
raise common.UfuncError("specconv: Cannot infer unit of first" |
| 800 |
" argument. Perhaps use the three-argument specconv?") |
| 801 |
|
| 802 |
return fromUnit |
| 803 |
|
| 804 |
def _replaceExpr(self, sentinelName, newExpr): |
| 805 |
"""replaces self.expr with newExpr, where a (fake) column |
| 806 |
reference named sentinelName is replaced by the previous expression. |
| 807 |
""" |
| 808 |
def replaceTarget(nodes): |
| 809 |
for ind, child in enumerate(nodes): |
| 810 |
if getattr(child, "name", None)==sentinelName: |
| 811 |
nodes[ind] = self.expr |
| 812 |
return True |
| 813 |
if hasattr(child, "children"): |
| 814 |
if replaceTarget(child.children): |
| 815 |
return True |
| 816 |
|
| 817 |
if replaceTarget(newExpr.children): |
| 818 |
self.expr = newExpr |
| 819 |
else: |
| 820 |
raise common.UfuncError("specconv: Internal Error: No sentinel found.") |
| 821 |
|
| 822 |
def addFieldInfo(self, context): |
| 823 |
try: |
| 824 |
nodes.FieldInfoedNode.addFieldInfo(self, context) |
| 825 |
|
| 826 |
fromUnit = self._getFromUnit(context) |
| 827 |
|
| 828 |
exprLit = base.getSpecExpr(fromUnit, self.targetUnit |
| 829 |
).format("REPLACE_ME") |
| 830 |
exprNode = nodes.getTreeBuildingGrammar()[0][ |
| 831 |
"userDefinedFunctionParam" |
| 832 |
].parseString(exprLit, parseAll=True)[0] |
| 833 |
|
| 834 |
self._replaceExpr("REPLACE_ME", exprNode) |
| 835 |
self.exprReplaced = True |
| 836 |
|
| 837 |
self.fieldInfo = self.fieldInfo.change( |
| 838 |
unit=self.targetUnit, |
| 839 |
type="double precision") |
| 840 |
# TODO: We should probably fix the description to indicate |
| 841 |
# it's some sort of different thing. |
| 842 |
except base.IncompatibleUnits as msg: |
| 843 |
raise common.UfuncError(str(msg)) |
| 844 |
|
| 845 |
def flatten(self): |
| 846 |
if not self.exprReplaced: |
| 847 |
raise ValueError("You cannot use ivo_specconv here. Complain" |
| 848 |
" to the operators.") |
| 849 |
return self.expr.flatten() |
| 850 |
|
| 851 |
|
| 852 |
@userFunction("gavo_specconv", |
| 853 |
"(expr DOUBLE PRECISION, dest_unit TEXT) -> DOUBLE PRECISION", |
| 854 |
"""returns the spectral value expr converted to dest_unit. |
| 855 |
|
| 856 |
expr has to be in either energy, wavelength, or frequency, and dest_unit |
| 857 |
must be a VOUnit giving another spectral unit (e.g., MHz, keV, nm, or |
| 858 |
Angstrom). This is intended to let users express spectral constraints |
| 859 |
in their preferred unit independently of the choice of unit in the |
| 860 |
database. Examples:: |
| 861 |
|
| 862 |
gavo_specconv(obscore.em_min, "keV") > 300 |
| 863 |
gavo_specconv(obscore.em_max, "MHz") > 30 |
| 864 |
gavo_specconv(spectral_start, "Angstrom") > 4000 |
| 865 |
|
| 866 |
There is a variant of gavo_specconv accepting expr's unit in a third |
| 867 |
argument. |
| 868 |
""", |
| 869 |
polymorphism=[( |
| 870 |
"(expr NUMERIC, expr_unit TEXT, dest_unit TEXT) -> NUMERIC", |
| 871 |
"""returns expr assumed to be in expr_unit expressed in dest_unit. |
| 872 |
|
| 873 |
This is a variant of the two-argument gavo_specconv for when |
| 874 |
the unit of expr is not known to the ADQL translator, either because |
| 875 |
it because it is a literal or because it does not look like |
| 876 |
a spectral unit. Examples:: |
| 877 |
|
| 878 |
gavo_specconv(656, 'nm', 'J') BETWEEN spectral_start AND spectral_end |
| 879 |
gavo_specconv(arccos(phi)*incidence, 'Hz', 'eV') |
| 880 |
|
| 881 |
Clearly, overriding known units is likely to yield bad results; |
| 882 |
the translator therefore warns if an existing unit is overridden |
| 883 |
with a different unit.""")], |
| 884 |
additionalNames=["ivo_specconv"]) |
| 885 |
def _gavo_specconv(args): |
| 886 |
try: |
| 887 |
if len(args)==2: |
| 888 |
newNode = _SpecconvNode(expr=args[0], |
| 889 |
targetUnit=nodes.getStringLiteral(args[1])) |
| 890 |
|
| 891 |
elif len(args)==3: |
| 892 |
newNode = _SpecconvNode(expr=args[0], |
| 893 |
targetUnit=nodes.getStringLiteral(args[2]), |
| 894 |
forceUnit=nodes.getStringLiteral(args[1])) |
| 895 |
|
| 896 |
else: |
| 897 |
raise common.UfuncError("gavo_specconv takes two or three arguments") |
| 898 |
except base.IncompatibleUnits as msg: |
| 899 |
raise common.UfuncError(msg) |
| 900 |
|
| 901 |
raise nodes.ReplaceNode(newNode) |
| 902 |
|
| 903 |
|
| 904 |
class UserFunction(nodes.FunctionNode): |
| 905 |
"""A node processing user defined functions. |
| 906 |
|
| 907 |
See the userFunction docstring for how ADQL user defined functions |
| 908 |
are defined. |
| 909 |
""" |
| 910 |
type = "userDefinedFunction" |
| 911 |
|
| 912 |
def _getFunc(self): |
| 913 |
try: |
| 914 |
return UFUNC_REGISTRY[self.funName.upper()] |
| 915 |
except: |
| 916 |
raise common.UfuncError("No such function: %s"%self.funName) |
| 917 |
|
| 918 |
def _polish(self): |
| 919 |
if self.args: |
| 920 |
self.args = list(self.args) |
| 921 |
self.processedExpression = self._getFunc()(self.args) |
| 922 |
|
| 923 |
def flatten(self): |
| 924 |
if self.processedExpression is None: |
| 925 |
return nodes.FunctionNode.flatten(self) |
| 926 |
else: |
| 927 |
return nodes.flatten(self.processedExpression) |
| 928 |
|
| 929 |
def addFieldInfo(self, context): |
| 930 |
ufunc = self._getFunc() |
| 931 |
|
| 932 |
unit = (ufunc.adqlUDF_unit(self.args) if callable(ufunc.adqlUDF_unit) |
| 933 |
else ufunc.adqlUDF_unit) |
| 934 |
ucd = (ufunc.adqlUDF_ucd(self.args) if callable(ufunc.adqlUDF_ucd) |
| 935 |
else ufunc.adqlUDF_ucd) |
| 936 |
|
| 937 |
self.fieldInfo = fieldinfo.FieldInfo( |
| 938 |
ufunc.adqlUDF_returntype, |
| 939 |
unit, |
| 940 |
ucd) |
| 941 |
|
| 942 |
|
| 943 |
nodes.registerNode(UserFunction) |