| 1 |
""" |
| 2 |
Helper functions for SODA manipulators. |
| 3 |
|
| 4 |
This primarily comprises various WCS helpers. It is built on base.coords, |
| 5 |
which is where you'll get the wcsFields. |
| 6 |
|
| 7 |
Note that this must not use things from protocols.datalink, as it |
| 8 |
is imported from there. Essentially, use this space for helpers |
| 9 |
for SODA manipulations that are generic enough to be kept outside of |
| 10 |
the RD but not generic enough to go do base.coords. |
| 11 |
""" |
| 12 |
|
| 13 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 14 |
#c |
| 15 |
#c This program is free software, covered by the GNU GPL. See the |
| 16 |
#c COPYING file in the source distribution. |
| 17 |
|
| 18 |
|
| 19 |
from gavo import base |
| 20 |
from gavo import rscdef |
| 21 |
from gavo import svcs |
| 22 |
from gavo import utils |
| 23 |
from gavo.base import coords |
| 24 |
from gavo.utils import fitstools |
| 25 |
|
| 26 |
from gavo.base import makeStruct as MS |
| 27 |
|
| 28 |
|
| 29 |
DEFAULT_SEMANTICS = "http://dc.g-vo.org/datalink#other" |
| 30 |
|
| 31 |
|
| 32 |
class EmptyData(base.ExecutiveAction): |
| 33 |
"""raise this when you notice you won't have any data to return. |
| 34 |
""" |
| 35 |
responseCode = 204 |
| 36 |
# SODA and HTTP say no bytes are allowed in empty responses. |
| 37 |
responsePayload = "" |
| 38 |
|
| 39 |
|
| 40 |
class DatalinkFault(object): |
| 41 |
"""A datalink error ("fault", as it's called in the spec). |
| 42 |
|
| 43 |
These are usually constructed using one of the classmethods |
| 44 |
|
| 45 |
* AuthenticationFault -- Not authenticated (and authentication required) |
| 46 |
* AuthorizationFault -- Not authorized (to access the resource) |
| 47 |
* NotFoundFault -- Unknown ID value |
| 48 |
* UsageFault -- Invalid input (e.g. no ID values) |
| 49 |
* TransientFault -- Service is not currently able to function |
| 50 |
* FatalFault -- Service cannot perform requested action |
| 51 |
* Fault -- General error (not covered above) |
| 52 |
|
| 53 |
all of which take the pubDID that caused the failure and a human-oriented |
| 54 |
error message. |
| 55 |
""" |
| 56 |
def __init__(self, code, pubDID, message, exceptionClass, semantics, |
| 57 |
description=None): |
| 58 |
self.code, self.pubDID, self.message = code, pubDID, message |
| 59 |
self.semantics = semantics |
| 60 |
self.exceptionClass = exceptionClass |
| 61 |
self.description = description |
| 62 |
|
| 63 |
@classmethod |
| 64 |
def _addErrorMaker(cls, errCode, exceptionClass): |
| 65 |
def meth(inner, pubDID, message, semantics=DEFAULT_SEMANTICS, |
| 66 |
description=None): |
| 67 |
return inner(errCode, pubDID, message, exceptionClass, semantics, |
| 68 |
description) |
| 69 |
setattr(cls, errCode, classmethod(meth)) |
| 70 |
|
| 71 |
def asDict(self): |
| 72 |
"""returns an error row for the datalink response. |
| 73 |
""" |
| 74 |
return {"ID": self.pubDID, "error_message": |
| 75 |
"%s: %s"%(self.code, self.message), |
| 76 |
"semantics": self.semantics, |
| 77 |
"description": self.description} |
| 78 |
|
| 79 |
def raiseException(self): |
| 80 |
raise self.exceptionClass(self.message+" (pubDID: %s)"%self.pubDID) |
| 81 |
|
| 82 |
for errName, exClass in [ |
| 83 |
("AuthenticationFault", svcs.ForbiddenURI), |
| 84 |
("AuthorizationFault", svcs.ForbiddenURI), |
| 85 |
("NotFoundFault", svcs.UnknownURI), |
| 86 |
("UsageFault", svcs.BadMethod), |
| 87 |
("TransientFault", svcs.BadMethod), |
| 88 |
("FatalFault", svcs.Error), |
| 89 |
("Fault", svcs.Error)]: |
| 90 |
DatalinkFault._addErrorMaker(errName, exClass) |
| 91 |
del errName, exClass |
| 92 |
|
| 93 |
|
| 94 |
class FormatNow(base.ExecutiveAction): |
| 95 |
"""can be raised by data functions to abort all further processing |
| 96 |
and format the current descriptor.data. |
| 97 |
""" |
| 98 |
|
| 99 |
|
| 100 |
class DeliverNow(base.ExecutiveAction): |
| 101 |
"""can be raised by data functions to abort all further processing |
| 102 |
and return the current descriptor.data to the client. |
| 103 |
""" |
| 104 |
|
| 105 |
|
| 106 |
def ensureSkyWCS(descriptor): |
| 107 |
"""furnishes a soda fits descriptor with skyWCS and spatialAxes attributes |
| 108 |
if necessary. |
| 109 |
|
| 110 |
This is usually called by the functions needing this automatically, and |
| 111 |
it's a no-op if it has already run. |
| 112 |
|
| 113 |
skyWCS will be None after this function as run if no usable WCS is found; |
| 114 |
otherwise, it will be a astropy.wcs.WCS instance. Additionally, spatialAxes |
| 115 |
will be a sequence of 1-based axis indices, and an empty dictionary |
| 116 |
axisNames is available to be filled by metaMakers. It will then map |
| 117 |
the SODA parameter name to either a FITS axis index or to the special |
| 118 |
WCSLONG, WCSLAT values. |
| 119 |
""" |
| 120 |
if hasattr(descriptor, "skyWCS"): |
| 121 |
return |
| 122 |
|
| 123 |
descriptor.skyWCS, descriptor.spatialAxes = coords.getSkyWCS(descriptor.hdr) |
| 124 |
descriptor.axisNames = {} |
| 125 |
|
| 126 |
|
| 127 |
def iterSpatialAxisKeys(descriptor, axisMetaOverrides): |
| 128 |
"""yields SODA inputKeys for spatial cutouts along the spatial |
| 129 |
coordinate axes. |
| 130 |
|
| 131 |
This can be nothing if descriptor doesn't have a skyWCS attribute |
| 132 |
or if it's None. |
| 133 |
""" |
| 134 |
ensureSkyWCS(descriptor) |
| 135 |
if descriptor.skyWCS is None: |
| 136 |
return |
| 137 |
|
| 138 |
footprint = descriptor.skyWCS.calcFootprint(descriptor.hdr) |
| 139 |
wcsprm = descriptor.skyWCS.wcs |
| 140 |
|
| 141 |
# FIXME: UCD inference! |
| 142 |
for name, colInd, description, baseUCD, cutoutName in [ |
| 143 |
(wcsprm.lattyp.strip(), wcsprm.lat, "The latitude coordinate", |
| 144 |
"pos.eq.dec", "WCSLAT"), |
| 145 |
(wcsprm.lngtyp.strip(), wcsprm.lng, "The longitude coordinate", |
| 146 |
"pos.eq.ra", "WCSLONG")]: |
| 147 |
if name: |
| 148 |
vertexCoos = footprint[:,colInd] |
| 149 |
paramArgs = {"name": name, "unit": "deg", |
| 150 |
"description": description, |
| 151 |
"ucd": baseUCD} |
| 152 |
|
| 153 |
minCoo, maxCoo = min(vertexCoos), max(vertexCoos) |
| 154 |
# for RA, we need to move the stitching line out |
| 155 |
# of the way (and go to negative longitudes) if |
| 156 |
# 0 is on the image; we're doing a little heuristic |
| 157 |
# there assuming that images are smaller than 180 deg. |
| 158 |
if cutoutName=="WCSLONG": |
| 159 |
if coords.straddlesStitchingLine(minCoo, maxCoo): |
| 160 |
minCoo, maxCoo = maxCoo-360, minCoo |
| 161 |
|
| 162 |
if name in axisMetaOverrides: |
| 163 |
paramArgs.update(axisMetaOverrides[name]) |
| 164 |
|
| 165 |
yield MS(svcs.InputKey, multiplicity="single", |
| 166 |
type="double precision[2]", xtype="interval", |
| 167 |
values=MS(rscdef.Values, min=minCoo, max=maxCoo), |
| 168 |
**paramArgs) |
| 169 |
descriptor.axisNames[name] = cutoutName |
| 170 |
|
| 171 |
|
| 172 |
def iterOtherAxisKeys(descriptor, axisMetaOverrides): |
| 173 |
"""yields inputKeys for all non-spatial WCS axes. |
| 174 |
|
| 175 |
descriptor must be a FITSDescriptor. |
| 176 |
|
| 177 |
Note that this will not generate params unless the fits axis index |
| 178 |
is mentioned in axisMetaOverrides. This is because typically, there |
| 179 |
are pre-defined SODA parameters for such other axes. |
| 180 |
""" |
| 181 |
ensureSkyWCS(descriptor) |
| 182 |
if descriptor.skyWCS is None: |
| 183 |
return |
| 184 |
|
| 185 |
axesLengths = fitstools.getAxisLengths(descriptor.hdr) |
| 186 |
for axIndex, length in enumerate(axesLengths): |
| 187 |
fitsAxis = axIndex+1 |
| 188 |
if fitsAxis in descriptor.spatialAxes: |
| 189 |
continue |
| 190 |
if fitsAxis not in axisMetaOverrides: |
| 191 |
continue |
| 192 |
if length==1: |
| 193 |
# no cutouts along degenerate axes |
| 194 |
continue |
| 195 |
|
| 196 |
try: |
| 197 |
ax = fitstools.WCSAxis.fromHeader( |
| 198 |
descriptor.hdr, |
| 199 |
fitsAxis, |
| 200 |
forceSeparable=True) |
| 201 |
except ValueError: |
| 202 |
# probably botched WCS, or an inseparable axis. |
| 203 |
# Just ignore this axis, operators can add it manually |
| 204 |
# using forceSeparable |
| 205 |
continue |
| 206 |
|
| 207 |
descriptor.axisNames[ax.name] = fitsAxis |
| 208 |
minPhys, maxPhys = ax.getLimits() |
| 209 |
|
| 210 |
# FIXME: ucd inference |
| 211 |
paramArgs = {"name": ax.name, "unit": ax.cunit, |
| 212 |
"description": "Coordinate along axis number %s"%fitsAxis, |
| 213 |
"ucd": None} |
| 214 |
paramArgs.update(axisMetaOverrides[fitsAxis]) |
| 215 |
|
| 216 |
yield MS(svcs.InputKey, multiplicity="single", |
| 217 |
type="double precision[2]", xtype="interval", |
| 218 |
values=MS(rscdef.Values, min=minPhys, max=maxPhys), |
| 219 |
**paramArgs) |
| 220 |
|
| 221 |
|
| 222 |
def addPolygonSlices(descriptor, poly, srcPar="Unknown"): |
| 223 |
"""adds slicings in descriptor.slices for a pgsphere.SPoly poly. |
| 224 |
|
| 225 |
srcPar is the name of the parameter that generated the polygon |
| 226 |
(for making error messages) |
| 227 |
""" |
| 228 |
for axisInd, lower, upper in coords.getPixelLimits( |
| 229 |
poly.asCooPairs(), descriptor.skyWCS): |
| 230 |
descriptor.changingAxis(axisInd, srcPar) |
| 231 |
descriptor.slices.append((axisInd, lower, upper)) |
| 232 |
|
| 233 |
|
| 234 |
def doAxisCutout(descriptor, args): |
| 235 |
"""updates descriptor.data on a FITS descriptor, interpreting the |
| 236 |
parameters defined by iter*AxisKeys, passed in in args. |
| 237 |
|
| 238 |
This is the main implementation of //soda#fits_doWCSCutout |
| 239 |
""" |
| 240 |
ensureSkyWCS(descriptor) |
| 241 |
slices = descriptor.slices |
| 242 |
|
| 243 |
# limits: [minRA, maxRA], [minDec, maxDec]] |
| 244 |
footprint = descriptor.skyWCS.calcFootprint(descriptor.hdr) |
| 245 |
limits = [[min(footprint[:,0]), max(footprint[:,0])], |
| 246 |
[min(footprint[:,1]), max(footprint[:,1])]] |
| 247 |
if coords.straddlesStitchingLine(limits[0][0], limits[0][1]): |
| 248 |
limits[0] = [limits[0][1]-360, limits[0][0]] |
| 249 |
limitsChangedName = None |
| 250 |
|
| 251 |
for parName, fitsAxis in descriptor.axisNames.items(): |
| 252 |
if args[parName] is None: |
| 253 |
continue |
| 254 |
limitsChangedName = parName |
| 255 |
|
| 256 |
if not isinstance(fitsAxis, int): |
| 257 |
# some sort of spherical axis |
| 258 |
if fitsAxis=="WCSLAT": |
| 259 |
cooLimits = limits[1] |
| 260 |
elif fitsAxis=="WCSLONG": |
| 261 |
cooLimits = limits[0] |
| 262 |
else: |
| 263 |
assert False |
| 264 |
|
| 265 |
cooLimits[0] = max(cooLimits[0], args[parName][0]) |
| 266 |
cooLimits[1] = min(cooLimits[1], args[parName][1]) |
| 267 |
|
| 268 |
else: |
| 269 |
# 1-d axis |
| 270 |
transform = fitstools.WCSAxis.fromHeader(descriptor.hdr, fitsAxis) |
| 271 |
limits1 = [transform.physToPix(v) for v in args[parName]] |
| 272 |
descriptor.changingAxis(fitsAxis, parName) |
| 273 |
slices.append((fitsAxis, |
| 274 |
utils.floorInt(min(limits1)), |
| 275 |
utils.ceilInt(max(limits1)))) |
| 276 |
|
| 277 |
if limitsChangedName: |
| 278 |
for axisInd, lower, upper in coords.getPixelLimits([ |
| 279 |
(limits[0][0], limits[1][0]), |
| 280 |
(limits[0][1], limits[1][1])], descriptor.skyWCS): |
| 281 |
descriptor.changingAxis(axisInd, limitsChangedName) |
| 282 |
slices.append((axisInd, lower, upper)) |
| 283 |
|
| 284 |
if descriptor.data==["This is test instrumentation"]: |
| 285 |
return |
| 286 |
|
| 287 |
if slices: |
| 288 |
for axis, lower, upper in slices: |
| 289 |
if lower==upper: # Sentinel for empty data |
| 290 |
raise EmptyData() |
| 291 |
descriptor.data[descriptor.imageExtind] = fitstools.cutoutFITS( |
| 292 |
descriptor.data[descriptor.imageExtind], |
| 293 |
*slices) |
| 294 |
descriptor.dataIsPristine = False |