Debian Codegraph @

tests/siaptest.py

raw
1 """
2 Some plausibility testing for our siap infrastructure.
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 unittest
12
13 from gavo.helpers import testhelpers
14
15 from gavo import base
16 from gavo import rsc
17 from gavo import rscdesc #noflake: for registration
18 from gavo.base import coords
19 from gavo.helpers import trialhelpers
20 from gavo.formats import votablewrite
21 from gavo.protocols import siap
22 from gavo.utils import fitstools
23
24 import tresc
25
26
27 class TestWCSTrafos(unittest.TestCase):
28 """Tests for transformations between WCS and pixel coordinates.
29 """
30 wcs = {
31 "CRVAL1": 0, "CRVAL2": 0,
32 "CRPIX1": 50, "CRPIX2": 50,
33 "CD1_1": 0.01, "CD1_2": 0,
34 "CD2_1": 0, "CD2_2": 0.01,
35 "NAXIS1": 100, "NAXIS2": 100,
36 "CUNIT1": "deg", "CUNIT2": "deg",
37 "CTYPE1": 'RA---TAN-SIP', "CTYPE2": 'DEC--TAN-SIP',
38 "LONPOLE": 180.,
39 "NAXIS": 2,
40 }
41
42 def _testInvertibilityReal(self):
43 for crvals in [(0,0), (40,60), (125,-60), (238,80)]:
44 self.wcs["CRVAL1"], self.wcs["CRVAL2"] = crvals
45 for crpixs in [(0,0), (50,50), (100,100), (150,0)]:
46 self.wcs["CRPIX1"], self.wcs["CRPIX2"] = crpixs
47 for pixpos in [(0,0), (50, 50), (0, 100), (100, 0)]:
48 fwTrafo = coords.getWCSTrafo(self.wcs)
49 bwTrafo = coords.getInvWCSTrafo(self.wcs)
50 x, y = bwTrafo(*fwTrafo(*pixpos))
51 self.assertAlmostEqual(x, pixpos[0], 5)
52 self.assertAlmostEqual(y, pixpos[1], 5)
53
54 def testInvertibility(self):
55 self._testInvertibilityReal()
56 self.wcs["CD2_1"] = 0.001
57 self._testInvertibilityReal()
58 self.wcs["CD1_2"] = -0.001
59 self._testInvertibilityReal()
60
61
62 class PixelScaleTest(testhelpers.VerboseTest):
63 wcs = {
64 "CRPIX1": 50, "CRPIX2": 50,
65 "CD1_1": 1E-04, "CD1_2": -1E-06,
66 "CD2_1": -1E-06, "CD2_2": -1E-04,
67 "CTYPE1": 'RA---TAN', "CTYPE2": 'DEC--TAN',
68 "CRVAL1": None, "CRVAL2": None,
69 "NAXIS1": 100, "NAXIS2": 100,
70 "CUNIT1": "deg", "CUNIT2": "deg",}
71
72 def testEquator(self):
73 wcs = self.wcs.copy()
74 wcs["CRVAL1"], wcs["CRVAL2"] = 0, 0
75 self.assertAlmostEqualVector(coords.getPixelSizeDeg(wcs), (1e-4, 1e-4))
76
77 def testStitch(self):
78 wcs = self.wcs.copy()
79 wcs["CRVAL1"], wcs["CRVAL2"] = -1e-3, 0
80 self.assertAlmostEqualVector(coords.getPixelSizeDeg(wcs), (1e-4, 1e-4))
81
82 def testNorth(self):
83 wcs = self.wcs.copy()
84 wcs["CRVAL1"], wcs["CRVAL2"] = 359.99, 70
85 self.assertAlmostEqualVector(coords.getPixelSizeDeg(wcs), (1e-4, 1e-4))
86
87 def testPole(self):
88 wcs = self.wcs.copy()
89 wcs["CRVAL1"], wcs["CRVAL2"] = 10, -90
90 rasz, decsz = coords.getPixelSizeDeg(wcs)
91 self.assertAlmostEqual(decsz, 1e-4, 5)
92 self.assertFalse(rasz>1)
93
94
95 class CooQueryTestBase(testhelpers.VerboseTest):
96 """base class for functional testing of the SIAP code.
97 """
98 data = None
99
100 # queries with expected numbers of returned items
101 _testcases = [
102 ("0,0", "1", (1, 0, 1, 1)),
103 ("45,-45.6", "1", (0, 0, 0, 1)),
104 ("1,45", "3,1", (1, 0, 3, 3)),
105 ("1,46", "1.1", (0, 0, 0, 3)),
106 ("161,45", "3,1", (1, 0, 3, 3)),
107 ("161,46", "1.1", (0, 0, 0, 3)),
108 ("0,90", "360,2", (0, 1, 1, 1)),
109 # XXX TODO: do some more here
110 ]
111 _intersectionIndex = {
112 "COVERS": 0,
113 "ENCLOSED": 1,
114 "CENTER": 2,
115 "OVERLAPS": 3,
116 }
117
118 def _runTests(self, type):
119 if self.data is None: # only do something if given data (see below)
120 return
121 table = self.data.getPrimaryTable()
122 for center, size, expected in self._testcases:
123 pars = {}
124 fragment = siap.getQuery(table.tableDef, {
125 "POS": center,
126 "SIZE": size,
127 "INTERSECT": type}, pars)
128 res = list(table.connection.query(
129 "SELECT * FROM %s WHERE %s"%(table.tableName, fragment),
130 pars))
131 self.assertEqual(len(res), expected[self._intersectionIndex[type]],
132 "%d instead of %d matched when queriying for %s %s"%(len(res),
133 expected[self._intersectionIndex[type]], type, (center, size)))
134
135 # queries with expected numbers of returned items
136 _testcases = [
137 ("0,0", "1", (1, 0, 1, 1)),
138 ("45,-45.6", "1", (0, 0, 0, 1)),
139 ("1,45", "3,1", (1, 0, 3, 3)),
140 ("1,46", "1.1", (0, 0, 0, 3)),
141 ("161,45", "3,1", (1, 0, 3, 3)),
142 ("161,46", "1.1", (0, 0, 0, 3)),
143 ("0,90", "360,2", (0, 1, 1, 1)),
144 # XXX TODO: do some more here
145 ]
146
147 def testCOVERS(self):
148 self._runTests("COVERS")
149
150 def testENCLOSED(self):
151 self._runTests("ENCLOSED")
152
153 def testCENTER(self):
154 self._runTests("CENTER")
155
156 def testOVERLAPS(self):
157 self._runTests("OVERLAPS")
158
159
160 class PgSphereQueriesTest(CooQueryTestBase):
161 """tests for actual queries on the sphere with trivial WCS data.
162 """
163 resources = [("data", tresc.siapTestTable)]
164
165
166 class CutoutQueriesTest(testhelpers.VerboseTest):
167 resources = [("data", tresc.siapTestTable)]
168
169 def _runQuery(self, params):
170 svc = testhelpers.getTestRD().getById("siapcutout")
171 return trialhelpers.runSvcWith(svc, "siap.xml", params
172 ).getPrimaryTable().rows
173
174 def testWCSFixedSimple(self):
175 row = self._runQuery({"POS": ["1,2"], "SIZE": ["0.1,0.2"]})[0]
176 self.assertAlmostEqual(row["wcs_cdmatrix"][0], 0.01)
177 self.assertAlmostEqual(row["wcs_cdmatrix"][1], 0)
178 self.assertEqual(row["pixelSize"], [11, 21])
179 self.assertEqual(row["coverage"].asSTCS("Unknown"),
180 "Polygon Unknown 0.9499129572 1.8990431715 0.9499129572 2.0987721868 1.0498824794 2.0987083322 1.0498824794 1.8989853842")
181
182 def testWCSFixedCrop(self):
183 row = self._runQuery({"POS": ["5,5"], "SIZE": ["1,2"]})[0]
184 self.assertEqual(row["pixelSize"], [50, 99])
185 self.assertEqual(row["coverage"].asSTCS("Unknown"),
186 "Polygon Unknown 4.5007198987 4.0010872016 4.5007198987 4.9720632011 4.9873652888 4.9685772926 4.9873652888 3.9982770726")
187
188
189 class ImportTest(testhelpers.VerboseTest):
190 resources = [("conn", tresc.dbConnection)]
191 setupCost = 0.5
192 noWCSRec = {
193 "imageTitle": "uncalibrated image",
194 "NAXIS1": 1000,
195 "NAXIS2": 100,
196 "NAXIS": 2,
197 "dateObs": None,
198 "accref": "uu",
199 "accsize": None,
200 "embargo": None,
201 "owner": None,}
202
203 def testPlainPGS(self):
204 dd = testhelpers.getTestRD().getById("pgs_siaptest")
205 data = rsc.makeData(dd, connection=self.conn, forceSource=[
206 testhelpers.computeWCSKeys((34, 67), (0.3, 0.4))])
207 try:
208 table = data.tables["pgs_siaptable"]
209 res = list(table.iterQuery([table.tableDef.getColumnByName(n) for
210 n in ("centerAlpha", "centerDelta")], ""))[0]
211 self.assertEqual(int(res["centerDelta"]), 67)
212 finally:
213 data.dropTables(rsc.parseNonValidating)
214 self.conn.commit()
215
216 def testRaisingOnNull(self):
217 dd = testhelpers.getTestRD().getById("pgs_siaptest")
218 self.assertRaises(base.ValidationError,
219 rsc.makeData,
220 dd, connection=self.conn, forceSource=[self.noWCSRec])
221
222 def testNullIncorporation(self):
223 dd = testhelpers.getTestRD().getById("pgs_siapnulltest")
224 data = rsc.makeData(dd, connection=self.conn, forceSource=[
225 self.noWCSRec, testhelpers.computeWCSKeys((34, 67), (0.25, 0.5))])
226 try:
227 table = data.tables["pgs_siaptable"]
228 res = sorted(table.iterQuery(
229 [table.tableDef.getColumnByName("accref")], ""),
230 key=lambda d: d["accref"])
231 self.assertEqual(res,
232 [{'accref': 'image/(34, 67)/(0.25, 0.5)'}, {'accref': 'uu'}])
233 finally:
234 data.dropTables(rsc.parseNonValidating)
235 self.conn.commit()
236
237
238 class SIAPTestResponse(testhelpers.TestResource):
239 resources = [("siapTable", tresc.siapTestTable)]
240
241 def make(self, deps):
242 svc = testhelpers.getTestRD().getById("pgsiapsvc")
243 data = trialhelpers.runSvcWith(svc, "siap.xml",
244 {"POS": "0, 0", "SIZE": "180,180"})
245 vot = votablewrite.getAsVOTable(data,
246 tablecoding="td", suppressNamespace=True)
247 return vot, testhelpers.getXMLTree(vot, debug=False)
248
249 _siapTestResponse = SIAPTestResponse()
250
251
252 class SIAPResponseTest(testhelpers.VerboseTest):
253
254 resources = [("siapResp", _siapTestResponse)]
255
256 def _getSTCGroup(self):
257 try:
258 return _siapTestResponse._stcGroup
259 except AttributeError:
260 _siapTestResponse._stcGroup = self.siapResp[1].find(
261 ".//GROUP[@utype='stc:CatalogEntryLocation']")
262 return _siapTestResponse._stcGroup
263
264 def _getFieldForUtype(self, utype):
265 ref = self._getSTCGroup().find(
266 "FIELDref[@utype='%s']"%utype).get("ref")
267 return self.siapResp[1].find(".//FIELD[@ID='%s']"%ref)
268
269 def testSTCDefined(self):
270 self.assertTrue(len(self._getSTCGroup()))
271
272 def testCoverageDefined(self):
273 self.assertEqual(
274 self._getFieldForUtype("stc:AstroCoordArea.Polygon").get("name"),
275 "coverage")
276
277 def testSpectralDefined(self):
278 self.assertEqual(
279 self._getFieldForUtype("stc:AstroCoordArea.SpectralInterval.HiLimit"
280 ).get("name"),
281 "bandpassHi")
282
283 def testPositionDefined(self):
284 self.assertEqual(
285 self._getFieldForUtype("stc:AstroCoords.Position2D.Value2.C1",
286 ).get("name"),
287 "centerAlpha")
288
289 def testRefsysDefined(self):
290 self.assertEqual(self._getSTCGroup().find(
291 "PARAM[@utype='stc:AstroCoordSystem.SpaceFrame.CoordRefFrame']").get(
292 "value"), "ICRS")
293
294 def testTimesys(self):
295 timesysEls = self.siapResp[1].xpath("RESOURCE[@type='results']/TIMESYS")
296 timesysEl = testhelpers.pickSingle(timesysEls)
297 self.assertEqual(timesysEl.get("refposition"), "UNKNOWN")
298 self.assertEqual(timesysEl.get("timeorigin"), "MJD-origin")
299 self.assertEqual(timesysEl.get("timescale"), "TT")
300
301
302 class ScaleHeaderTest(testhelpers.VerboseTest):
303 # This is a test for fitstricks.shrinkWCSHeader.
304 # It's here just because we already deal with wcs in this module
305 def _assertCoordsMatch(self, pair1, pair2):
306 self.assertAlmostEqual(pair1[0], pair2[0])
307 self.assertAlmostEqual(pair1[1], pair2[1])
308
309 def testSimple(self):
310 fullHdr = fitstools.headerFromDict(
311 testhelpers.computeWCSKeys((23, 27), (1, 2), cutCrap=True))
312 halfHdr = fitstools.shrinkWCSHeader(fullHdr, 2)
313
314 self.assertEqual(halfHdr["IMSHRINK"], 'Image scaled down 2-fold by DaCHS')
315 self.assertEqual(fullHdr["NAXIS2"]/2, halfHdr["NAXIS1"])
316
317 toPhysOld = coords.getWCSTrafo(fullHdr)
318 toPhysNew = coords.getWCSTrafo(halfHdr)
319
320 self._assertCoordsMatch(
321 toPhysOld(fullHdr["CRPIX1"],fullHdr["CRPIX2"]),
322 toPhysNew(halfHdr["CRPIX1"],halfHdr["CRPIX2"]))
323
324 self._assertCoordsMatch(
325 toPhysOld(1, 1), toPhysNew(1, 1))
326
327 self._assertCoordsMatch(
328 toPhysOld(fullHdr["NAXIS1"]+1,fullHdr["NAXIS2"]+1),
329 toPhysNew(halfHdr["NAXIS1"]+1,halfHdr["NAXIS2"]+1))
330
331 def testTypesFixed(self):
332 fullHdr = fitstools.headerFromDict(
333 testhelpers.computeWCSKeys((23, 27), (1, 2), cutCrap=True))
334 fullHdr.set("BZERO", 32768)
335 fullHdr.set("BSCALE", 1)
336 fullHdr.set("BITPIX", 8)
337 halfHdr = fitstools.shrinkWCSHeader(fullHdr, 2)
338 self.assertFalse("BZERO" in halfHdr)
339 self.assertFalse("BSCALE" in halfHdr)
340 self.assertEqual(halfHdr["BITPIX"], -32)
341
342
343 if __name__=="__main__":
344 testhelpers.main(ImportTest)