| 1 |
""" |
| 2 |
Support code for the Simple Image Access Protocol. |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import math |
| 12 |
import re |
| 13 |
import urllib.request, urllib.parse, urllib.error |
| 14 |
|
| 15 |
from gavo import base |
| 16 |
from gavo import svcs |
| 17 |
from gavo import utils |
| 18 |
from gavo.base import coords |
| 19 |
from gavo.protocols import products |
| 20 |
from gavo.utils import fitstools |
| 21 |
from gavo.utils import pgsphere |
| 22 |
|
| 23 |
MS = base.makeStruct |
| 24 |
|
| 25 |
####################### SIAPv2 magic |
| 26 |
|
| 27 |
def parseSIAP2Geometry(aString, fieldName="POS"): |
| 28 |
"""parses a SIAPv2 geometry spec to a pgsphere object. |
| 29 |
|
| 30 |
Parse errors raise validation errors for fieldName. |
| 31 |
""" |
| 32 |
mat = re.match("(CIRCLE|RANGE|POLYGON) (.*)", aString) |
| 33 |
if not mat: |
| 34 |
raise base.ValidationError("Invalid SIAPv2 geometry: '%s'" |
| 35 |
" (expected a SIAPv2 shape name)"%utils.makeEllipsis(aString, 20), |
| 36 |
fieldName) |
| 37 |
|
| 38 |
geoName = mat.group(1) |
| 39 |
try: |
| 40 |
args = [float(s) for s in mat.group(2).split()] |
| 41 |
except ValueError: |
| 42 |
raise base.ValidationError("Invalid SIAPv2 coordinates: '%s'" |
| 43 |
" (bad floating point literal)"%( |
| 44 |
utils.makeEllipsis(mat.group(2), 40)), |
| 45 |
fieldName) |
| 46 |
|
| 47 |
if geoName=="CIRCLE": |
| 48 |
if len(args)!=3: |
| 49 |
raise base.ValidationError("Invalid SIAPv2 CIRCLE: '%s'" |
| 50 |
" (need exactly three numbers)"%( |
| 51 |
utils.makeEllipsis(aString, 20)), |
| 52 |
fieldName) |
| 53 |
return pgsphere.SCircle.fromDALI(args[:3]) |
| 54 |
|
| 55 |
elif geoName=="RANGE": |
| 56 |
# SBox isn't really RANGE, but RANGE shouldn't have been |
| 57 |
# part of the standard and people that use it deserve |
| 58 |
# to get bad results. |
| 59 |
if len(args)!=4: |
| 60 |
raise base.ValidationError("Invalid SIAPv2 RANGE: '%s'" |
| 61 |
" (need exactly four numbers)"%( |
| 62 |
utils.makeEllipsis(aString, 20)), |
| 63 |
fieldName) |
| 64 |
if args[0]>args[1] or args[2]>args[3]: |
| 65 |
raise base.ValidationError("Invalid SIAPv2 RANGE: '%s'" |
| 66 |
" (lower limits must be smaller than upper limits)"%( |
| 67 |
utils.makeEllipsis(aString, 20)), |
| 68 |
fieldName) |
| 69 |
return pgsphere.SBox( |
| 70 |
pgsphere.SPoint.fromDegrees(args[0], args[2]), |
| 71 |
pgsphere.SPoint.fromDegrees(args[1], args[3])) |
| 72 |
|
| 73 |
elif geoName=="POLYGON": |
| 74 |
if len(args)<6 or len(args)%2: |
| 75 |
raise base.ValidationError("Invalid SIAPv2 POLYGON: '%s'" |
| 76 |
" (need more than three coordinate *pairs*)"%( |
| 77 |
utils.makeEllipsis(mat.group(2), 20)), |
| 78 |
fieldName) |
| 79 |
return pgsphere.SPoly([ |
| 80 |
pgsphere.SPoint.fromDegrees(*pair) |
| 81 |
for pair in utils.iterConsecutivePairs(args)]) |
| 82 |
|
| 83 |
else: # pragma: no cover |
| 84 |
assert False |
| 85 |
|
| 86 |
|
| 87 |
####################### pgsSIAP mixin |
| 88 |
|
| 89 |
# expressions as used in getPGSQuery |
| 90 |
_PGS_OPERATORS = { |
| 91 |
"COVERS": "coverage ~ %%(%s)s", |
| 92 |
"ENCLOSED": "%%(%s)s ~ coverage", |
| 93 |
"CENTER": None, # special handling below |
| 94 |
"OVERLAPS": "%%(%s)s && coverage", |
| 95 |
} |
| 96 |
|
| 97 |
def getPGSQuery(intersect, ra, dec, sizes, prefix, sqlPars): |
| 98 |
"""returns SQL for a SIAP query on pgsSIAP tables. |
| 99 |
""" |
| 100 |
if intersect=='CENTER': |
| 101 |
return "%%(%s)s @ coverage"%(base.getSQLKey( |
| 102 |
prefix+"center", pgsphere.SPoint.fromDegrees(ra, dec), sqlPars)) |
| 103 |
|
| 104 |
expr = _PGS_OPERATORS[intersect] |
| 105 |
try: |
| 106 |
targetBox = pgsphere.SBox.fromSIAPPars(ra, dec, sizes[0], sizes[1]) |
| 107 |
return expr%base.getSQLKey(prefix+"area", targetBox, sqlPars) |
| 108 |
except pgsphere.TwoSBoxes as ex: |
| 109 |
# Fold-over at pole, return a disjunction |
| 110 |
return "( %s OR %s )"%( |
| 111 |
expr%base.getSQLKey(prefix+"area1", ex.box1, sqlPars), |
| 112 |
expr%base.getSQLKey(prefix+"area2", ex.box2, sqlPars)) |
| 113 |
|
| 114 |
|
| 115 |
####################### SIAP service helpers, cores, etc. |
| 116 |
|
| 117 |
def dissectPositions(posStr): |
| 118 |
"""tries to infer RA and DEC from posStr. |
| 119 |
|
| 120 |
In contrast to base.parseCooPair, we are quite strict here and just |
| 121 |
try to cope with some bad clients that leave out the comma. |
| 122 |
""" |
| 123 |
try: |
| 124 |
ra, dec = [float(v) for v in posStr.split(",")] |
| 125 |
except ValueError: # maybe a sign as separator? |
| 126 |
if '+' in posStr: |
| 127 |
ra, dec = [float(v) for v in posStr.split("+")] |
| 128 |
elif '-' in posStr: |
| 129 |
ra, dec = [float(v) for v in posStr.split("-")] |
| 130 |
dec = -dec |
| 131 |
else: |
| 132 |
raise ValueError("No pos") |
| 133 |
return ra, dec |
| 134 |
|
| 135 |
|
| 136 |
def _getQueryMaker(queriedTable): |
| 137 |
"""returns a query making function for SIAP appropriate for queriedTable. |
| 138 |
|
| 139 |
This used to have a function when we had different backends for SIAP. |
| 140 |
Currently, we no longer have that, so this always returns getPGSQuery. |
| 141 |
""" |
| 142 |
return getPGSQuery |
| 143 |
|
| 144 |
|
| 145 |
def getQuery(queriedTable, parameters, sqlPars, prefix="sia"): |
| 146 |
"""returns an SQL fragment for a SIAP query for bboxes. |
| 147 |
|
| 148 |
The SQL is returned as a WHERE-fragment in a string. The parameters |
| 149 |
are added in the sqlPars dictionary. |
| 150 |
|
| 151 |
parameters is a dictionary that maps the SIAP keywords to the |
| 152 |
values in the query. Parameters not defined by SIAP are ignored. |
| 153 |
""" |
| 154 |
posStr = urllib.parse.unquote(parameters["POS"]) |
| 155 |
try: |
| 156 |
ra, dec = dissectPositions(posStr) |
| 157 |
except (ValueError, TypeError): |
| 158 |
raise base.ui.logOldExc(base.ValidationError( |
| 159 |
"%s is not a RA,DEC pair."%posStr, "POS", posStr)) |
| 160 |
|
| 161 |
try: |
| 162 |
sizes = [float(v) for v in parameters["SIZE"].split(",")] |
| 163 |
except ValueError: |
| 164 |
raise base.ui.logOldExc(base.ValidationError("Size specification" |
| 165 |
" has to be <degs> or <degs>,<degs>", "SIZE", parameters["SIZE"])) |
| 166 |
if len(sizes)==1: |
| 167 |
sizes = sizes*2 |
| 168 |
intersect = parameters.get("INTERSECT", "OVERLAPS") |
| 169 |
query = _getQueryMaker(queriedTable)( |
| 170 |
intersect, ra, dec, sizes, prefix, sqlPars) |
| 171 |
# the following are for the benefit of cutout queries. |
| 172 |
sqlPars["_ra"], sqlPars["_dec"] = ra, dec |
| 173 |
sqlPars["_sra"], sqlPars["_sdec"] = sizes |
| 174 |
return query |
| 175 |
|
| 176 |
|
| 177 |
class SIAPCutoutCore(svcs.DBCore): |
| 178 |
"""A core doing SIAP plus cutouts. |
| 179 |
|
| 180 |
It has, by default, an additional column specifying the desired size of |
| 181 |
the image to be retrieved. Based on this, the cutout core will tweak |
| 182 |
its output table such that references to cutout images will be retrieved. |
| 183 |
|
| 184 |
The actual process of cutting out is performed by the product core and |
| 185 |
renderer. |
| 186 |
""" |
| 187 |
name_ = "siapCutoutCore" |
| 188 |
|
| 189 |
# This should become a property or something once we |
| 190 |
# compress the stuff or have images with bytes per pixel != 2 |
| 191 |
copiedCols = ["centerAlpha", "centerDelta", "imageTitle", "instId", |
| 192 |
"dateObs", "nAxes", "pixelSize", "pixelScale", "mime", |
| 193 |
"refFrame", "wcs_equinox", "wcs_projection", "wcs_refPixel", |
| 194 |
"wcs_refValues", "wcs_cdmatrix", "bandpassId", "bandpassUnit", |
| 195 |
"bandpassHi", "bandpassLo", "pixflags"] |
| 196 |
|
| 197 |
def getQueryCols(self, service, queryMeta): |
| 198 |
cols = svcs.DBCore.getQueryCols(self, service, queryMeta) |
| 199 |
for name in self.copiedCols: |
| 200 |
cols.append(svcs.OutputField.fromColumn( |
| 201 |
self.queriedTable.getColumnByName(name))) |
| 202 |
d = self.queriedTable.getColumnByName("accsize").copy(self) |
| 203 |
d.tablehead = "Est. file size" |
| 204 |
cols.append(svcs.OutputField.fromColumn(d)) |
| 205 |
return cols |
| 206 |
|
| 207 |
def _fixRecord(self, record, centerAlpha, centerDelta, sizeAlpha, sizeDelta): |
| 208 |
"""inserts estimates for WCS values into a cutout record. |
| 209 |
""" |
| 210 |
origWCS = coords.getWCS({ |
| 211 |
"CUNIT1": "deg", "CUNIT2": "deg", "CTYPE1": "RA---TAN", |
| 212 |
"CTYPE2": "DEC--TAN", |
| 213 |
"CRVAL1": record["wcs_refValues"][0], |
| 214 |
"CRVAL2": record["wcs_refValues"][1], |
| 215 |
"CRPIX1": record["wcs_refPixel"][0], |
| 216 |
"CRPIX2": record["wcs_refPixel"][1], |
| 217 |
"CD1_1": record["wcs_cdmatrix"][0], |
| 218 |
"CD1_2": record["wcs_cdmatrix"][1], |
| 219 |
"CD2_1": record["wcs_cdmatrix"][2], |
| 220 |
"CD2_2": record["wcs_cdmatrix"][3], |
| 221 |
"LONPOLE": 180., |
| 222 |
"NAXIS": 2, |
| 223 |
"NAXIS1": record["pixelSize"][0], |
| 224 |
"NAXIS2": record["pixelSize"][1], |
| 225 |
}) |
| 226 |
limits = coords.getPixelLimits( |
| 227 |
((centerAlpha-sizeAlpha/2, centerDelta-sizeDelta/2), |
| 228 |
(centerAlpha+sizeAlpha/2, centerDelta+sizeDelta/2)), |
| 229 |
origWCS) |
| 230 |
_, newHeader = fitstools.cutoutHeader(origWCS._dachs_header, *limits) |
| 231 |
|
| 232 |
if newHeader["NAXIS1"]<3 or newHeader["NAXIS2"]<3: |
| 233 |
# these typically result from crazy calibrations or very marginal |
| 234 |
# matches that nobody wants to see |
| 235 |
raise utils.SkipThis("Too marginal a match") |
| 236 |
|
| 237 |
record["wcs_refPixel"] = [newHeader["CRPIX1"], newHeader["CRPIX2"]] |
| 238 |
record["wcs_refValues"] = [newHeader["CRVAL1"], newHeader["CRVAL2"]] |
| 239 |
record["pixelSize"] = [newHeader["NAXIS1"], newHeader["NAXIS2"]] |
| 240 |
|
| 241 |
record["accref"] = products.RAccref(record["accref"], { |
| 242 |
"ra": centerAlpha, "dec": centerDelta, |
| 243 |
"sra": sizeAlpha, "sdec": sizeDelta}) |
| 244 |
record["centerAlpha"] = centerAlpha |
| 245 |
record["centerDelta"] = centerDelta |
| 246 |
|
| 247 |
newWCS = coords.getWCS(newHeader) |
| 248 |
corners = newWCS.calcFootprint() |
| 249 |
record["coverage"] = pgsphere.SPoly.fromDALI([ |
| 250 |
corners[0][0], corners[0][1], |
| 251 |
corners[1][0], corners[1][1], |
| 252 |
corners[2][0], corners[2][1], |
| 253 |
corners[3][0], corners[3][1]]) |
| 254 |
# Aw, fix this already. |
| 255 |
bytesPerPixel = 2 |
| 256 |
record["accsize"] = min(record["accsize"], |
| 257 |
int(bytesPerPixel*newHeader["NAXIS1"]*newHeader["NAXIS2"])) |
| 258 |
|
| 259 |
def run(self, service, inputData, queryMeta): |
| 260 |
res = svcs.DBCore.run(self, service, inputData, queryMeta) |
| 261 |
sqlPars = queryMeta["sqlQueryPars"] |
| 262 |
try: |
| 263 |
sra = sdec = float(queryMeta.ctxArgs["cutoutSize"]) |
| 264 |
except (KeyError, ValueError): |
| 265 |
try: |
| 266 |
sra, sdec = sqlPars["_sra"], sqlPars["_sdec"] |
| 267 |
except KeyError: |
| 268 |
sra, sdec = 0.5, 0.5 |
| 269 |
|
| 270 |
if "_dec" in sqlPars: |
| 271 |
cosD = math.cos(sqlPars["_dec"]/180*math.pi) |
| 272 |
if abs(cosD)>1e-5: |
| 273 |
sra = sra/cosD |
| 274 |
else: |
| 275 |
sra = 360 |
| 276 |
|
| 277 |
newRows = [] |
| 278 |
for record in res: |
| 279 |
try: |
| 280 |
self._fixRecord(record, |
| 281 |
sqlPars.get("_ra", record["centerAlpha"]), |
| 282 |
sqlPars.get("_dec", record["centerDelta"]), sra, sdec) |
| 283 |
newRows.append(record) |
| 284 |
except base.SkipThis: |
| 285 |
pass |
| 286 |
except ValueError as msg: |
| 287 |
# Old pywcs signified troublesome WCS with a ValueError-derived |
| 288 |
# thing. Let's see how this works out for astropy. |
| 289 |
base.ui.notifyWarning("Botched WCS (%s) in the record %s"%( |
| 290 |
msg, record)) |
| 291 |
|
| 292 |
res.rows = newRows |
| 293 |
|
| 294 |
return res |
| 295 |
|
| 296 |
|
| 297 |
def _test(): # pragma: no cover |
| 298 |
import doctest |
| 299 |
doctest.testmod() |