Debian Codegraph @

tests/statstest.py

raw
1 """
2 Tests to do with obtaining and managing table- and column level
3 metadata (in user.info and vicinity).
4 """
5
6
7 #c Copyright 2008-2025, the GAVO project <[email protected]>
8 #c
9 #c This program is free software, covered by the GNU GPL. See the
10 #c COPYING file in the source distribution.
11
12 import datetime
13
14 from gavo.helpers import testhelpers
15
16 from gavo import api
17 from gavo import base
18 from gavo.helpers import testtricks
19 from gavo.user import info
20 from gavo.user import limits
21
22 import tresc
23
24
25 class LimitsAnnotatorQueryGenTest(testhelpers.VerboseTest,
26 metaclass=testhelpers.SamplesBasedAutoTest):
27 def _runTest(self, sample):
28 colType, expected = sample
29 td = api.parseFromString(api.TableDef,
30 '<table id="c">%s</table>'%colType)
31 td.parent = base.caches.getRD("//tap")
32 ofs, _ = info.getAnnotators(td)
33 self.assertEqual([o.select for o in ofs], expected)
34
35 samples = [('<column name="x" type="double precision"/>', [
36 "MAX(x)",
37 "MIN(x)",
38 'percentile_cont(ARRAY[0.03, 0.5, 0.97]) WITHIN GROUP (ORDER BY x)',
39 'AVG(CASE WHEN x IS NULL THEN 0 ELSE 1 END)']),
40 ('<column name="quoted/yikes" type="bigint" required="True"/>', [
41 'MAX("yikes")',
42 'MIN("yikes")',
43 'percentile_cont(ARRAY[0.03, 0.5, 0.97]) WITHIN GROUP (ORDER BY "yikes")',
44 'AVG(CASE WHEN "yikes" IS NULL THEN 0 ELSE 1 END)']),
45 ('<column name="x" type="char"><values nullLiteral="u"/></column>', [
46 "MAX(x)",
47 "MIN(x)",
48 'AVG(CASE WHEN x IS NULL THEN 0 ELSE 1 END)']),
49 ('<column name="p" type="spoly"/>',
50 ['AVG(CASE WHEN p IS NULL THEN 0 ELSE 1 END)']),
51 ('<column name="x" type="char" required="True"><property key="statistics">'
52 'no</property></column>', []),
53 # 05
54 ('<column name="x" type="text"><property key="statistics">'
55 'enumerate</property></column>', [
56 'MAX(x)',
57 'MIN(x)',
58 "(SELECT jsonb_object_agg(COALESCE(val, 'NULL'), ct) FROM ( SELECT x AS val, count(*) AS ct "
59 'FROM tap_schema.c GROUP BY x) AS subquery_x)',
60 'AVG(CASE WHEN x IS NULL THEN 0 ELSE 1 END)'
61 ]),
62 ('<column name="d" type="timestamp"/>', [
63 'MAX((EXTRACT(JULIAN FROM d)-2400001))',
64 'MIN((EXTRACT(JULIAN FROM d)-2400001))',
65 'percentile_cont(ARRAY[0.03, 0.5, 0.97]) WITHIN GROUP (ORDER BY '
66 '(EXTRACT(JULIAN FROM d)-2400001))',
67 'AVG(CASE WHEN (EXTRACT(JULIAN FROM d)-2400001) IS NULL THEN 0 ELSE 1 END)'
68 ]),
69 ]
70
71
72 class _AnnotatedTable(testhelpers.TestResource):
73 resources = [("inputTable", tresc.ssaTestTable)]
74
75 def make(self, deps):
76 td = deps["inputTable"].tableDef
77 info.annotateDBTable(td)
78 return td
79
80
81 class DefaultSampleSizeTest(testhelpers.VerboseTest,
82 metaclass=testhelpers.SamplesBasedAutoTest):
83 def _runTest(self, sample):
84 nrows, percent = sample
85 self.assertEqual(info.getDefaultSamplePercent(nrows), percent)
86
87 # Yeah, this test is a bit silly given we're just computing an
88 # expression; consider this a representation of my gut feeling on
89 # how the curve ought to look like.
90 samples = [
91 (18, 100),
92 (180, 100),
93 (180000, 100),
94 (1e6, 100),
95 (1e7, 50),
96 (1e8, 26),
97 (1e9, 16),
98 (1e10, 11),
99 (1e100, 1),
100 ]
101
102
103 class LimitsAnnotatorQueryTest(testhelpers.VerboseTest):
104 resources = [("td", _AnnotatedTable())]
105
106 def testNrowsAnnotated(self):
107 self.assertEqual(self.td.nrows, 6)
108
109 def testStringAnnotated(self):
110 ann = self.td.getColumnByName("accref").annotations
111 self.assertEqual(set(ann.keys()),
112 {'max_value', 'min_value', 'fill_factor'})
113 self.assertEqual(ann["max_value"], "data/spec3.ssatest.vot")
114 self.assertEqual(ann["min_value"], "data/spec1.ssatest")
115 self.assertEqual(ann["fill_factor"], 1.0)
116
117 def testIntAnnotated(self):
118 ann = self.td.getColumnByName("accsize").annotations
119 self.assertEqual(set(ann.keys()),
120 {'max_value', 'min_value', 'fill_factor', "percentile03",
121 "median", "percentile97"})
122 self.assertEqual(ann["max_value"], 225)
123 self.assertEqual(ann["percentile03"], 213.0)
124 self.assertEqual(ann["median"], 219.0)
125 self.assertEqual(ann["percentile97"], 225.0)
126
127 def testFillFactor(self):
128 ann = self.td.getColumnByName("ssa_location").annotations
129 self.assertAlmostEqual(ann["fill_factor"], 2/3.)
130
131 def testSpointAnnotated(self):
132 ann = self.td.getColumnByName("ssa_location").annotations
133 self.assertEqual(set(ann.keys()), {'fill_factor'})
134
135 def testAllNull(self):
136 ann = self.td.getColumnByName("ssa_length").annotations
137 self.assertEqual(set(ann.keys()),
138 {'fill_factor'})
139 self.assertEqual(ann["fill_factor"], 0)
140
141 def testStringEnumeration(self):
142 ann = self.td.getColumnByName("ssa_bandpass").annotations
143 self.assertTrue('discrete_values' in ann.keys())
144 self.assertAlmostEqual(ann["discrete_values"]["B"], 1/3)
145 self.assertAlmostEqual(ann["discrete_values"]["R"], 1/3)
146 self.assertAlmostEqual(ann["discrete_values"]["V"], 1/3)
147
148 def testTimestamp(self):
149 currentMJD = api.dateTimeToMJD(datetime.datetime.utcnow())
150 ann = self.td.getColumnByName("ssa_pdate").annotations
151 self.assertAlmostEqual(ann['percentile03'], currentMJD, places=2)
152 self.assertAlmostEqual(ann['min_value'], currentMJD, places=2)
153 self.assertEqual(ann['fill_factor'], 1)
154
155
156 class LimitsTest(testhelpers.VerboseTest):
157 def testLimitsComputing(self):
158 td = testhelpers.getTestRD().getById("valSpec").copy(None)
159 table = api.TableForDef(td,
160 rows=[
161 {"a_num": 13, "enum": None},
162 {"a_num": None, "enum": "bad"},
163 {"a_num": -10, "enum": "horrific"}])
164 lims = table.getLimits()
165
166 self.assertEqual(lims["a_num"].min, -10)
167 self.assertEqual(lims["a_num"].max, 13)
168 self.assertEqual(lims["a_num"].values, None)
169
170 self.assertEqual(lims["enum"].max, None)
171 self.assertEqual(lims["enum"].min, None)
172 self.assertEqual(lims["enum"].values, set(["bad", "horrific"]))
173
174 def testSCSCoverageQuery(self):
175 self.assertEqual(
176 info.getMOCQuery(testhelpers.getTestRD().getById("adql"), 6),
177 "SELECT smoc('6/' || string_agg(format('%%s', hpx), ','))\nFROM (\n SELECT DISTINCT healpix_nest(6, spoint(RADIANS(alpha), RADIANS(delta))) AS hpx \nFROM test.adql\nWHERE alpha IS NOT NULL AND delta IS NOT NULL\nGROUP BY hpx\n) as q")
178
179 def testSSAPCoverageQuery(self):
180 self.assertEqual(
181 info.getMOCQuery(api.resolveCrossId("data/ssatest#mixctest"), 3),
182 "SELECT SUM(SMOC(3,\n SCIRCLE(ssa_location, RADIANS(COALESCE(ssa_aperture, 1/3600.)))))\n"
183 "FROM test.mixctest WHERE ssa_location IS NOT NULL")
184
185 def testSIAPCoverageQuery(self):
186 self.assertEqual(
187 info.getMOCQuery(api.resolveCrossId("data/test#pgs_siaptable"), 9),
188 "SELECT SUM(SMOC(9, coverage))\n"
189 "FROM test.pgs_siaptable WHERE coverage IS NOT NULL")
190
191 def testObscoreCoverageQuery(self):
192 self.assertEqual(
193 info.getMOCQuery(api.resolveCrossId("//obscore#ObsCore"), 6),
194 "SELECT SUM(coverage)\n"
195 "FROM (SELECT\n"
196 " COALESCE(\n"
197 " SMOC(6, s_region),"
198 " smoc_disc(6, RADIANS(s_ra), RADIANS(s_dec), RADIANS(s_fov)),\n"
199 " NULL) AS coverage\n"
200 " FROM ivoa.ObsCore\n"
201 " ) AS q")
202
203 def testNonstandardTableCoverage(self):
204 self.assertRaisesWithMsg(api.ReportableError,
205 "Table data/test#typesTable does not have columns DaCHS"
206 " knows how to get a coverage from.",
207 info.getMOCQuery,
208 (api.resolveCrossId("data/test#typesTable"), 3))
209
210 def testSIAPLimitsColumns(self):
211 td = api.resolveCrossId("data/test#pgs_siaptable")
212 lo, hi, trans = info.getTimeLimitsExprs(td)
213 self.assertEqual(lo, 'MIN(dateObs)')
214 self.assertEqual(hi, 'MAX(dateObs)')
215 self.assertAlmostEqual(trans(54000), 54000)
216
217 lo, hi, trans = info.getSpectralLimitsExprs(td)
218 self.assertEqual(hi, 'MIN(bandpassLo)')
219 self.assertEqual(lo, 'MAX(bandpassHi)')
220 self.assertAlmostEqual(trans(10), 1.9864458241717583e-26)
221
222 def testSSAPLimitsColumns(self):
223 td = api.resolveCrossId("data/ssatest#mixctest")
224 lo, hi, trans = info.getTimeLimitsExprs(td)
225 self.assertEqual(lo, 'MIN(ssa_dateObs)')
226 self.assertEqual(hi, 'MAX(ssa_dateObs)')
227 self.assertAlmostEqual(trans(54000), 54000)
228
229 lo, hi, trans = info.getSpectralLimitsExprs(td)
230 self.assertEqual(hi, 'MIN(ssa_specstart)')
231 self.assertEqual(lo, 'MAX(ssa_specend)')
232 self.assertAlmostEqual(trans(10), 1.9864458241717583e-26)
233
234 def testMissingLimits(self):
235 self.assertRaisesWithMsg(api.NotFoundError,
236 "Columns to figure out 'spectral coverage' could not be located in table data/test#typesTable",
237 info.getSpectralLimitsExprs,
238 (api.resolveCrossId("data/test#typesTable"),))
239
240 self.assertRaisesWithMsg(api.NotFoundError,
241 "Columns to figure out 'temporal coverage' could not be located in table data/test#typesTable",
242 info.getTimeLimitsExprs,
243 (api.resolveCrossId("data/test#typesTable"),))
244
245
246 class _ColstatsContent(testhelpers.TestResource):
247 resources = [("inputTable", tresc.ssaTestTable)]
248
249 def make(self, deps):
250 inputTable = deps["inputTable"]
251 tableName = inputTable.tableDef.getQName()
252
253 # insert an artificial sentinel so we can figure out
254 # if updateTableLevelStats actually dropped existing data.
255 with base.getWritableAdminConn() as conn:
256 conn.execute("INSERT INTO dc.simple_col_stats"
257 " (tableName, column_name)"
258 " VALUES (%(tableName)s, 'sentinel_garbage')",
259 locals())
260 conn.execute("INSERT INTO dc.discrete_string_values"
261 " (tableName, column_name)"
262 " VALUES (%(tableName)s, 'sentinel_garbage')",
263 locals())
264
265 limits.updateTableLevelStats(
266 inputTable.tableDef, inputTable.conn)
267
268 numStats = dict((r["column_name"], r)
269 for r in inputTable.connection.queryToDicts(
270 "SELECT * FROM dc.simple_col_stats"
271 " WHERE tableName='test.hcdtest'"))
272 enumStats = dict((r["column_name"], r)
273 for r in inputTable.connection.queryToDicts(
274 "SELECT * FROM dc.discrete_string_values"
275 " WHERE tableName='test.hcdtest'"))
276
277 return {"num": numStats, "enum": enumStats}
278
279
280 class ColstatsTableTest(testhelpers.VerboseTest):
281 resources = [("colStats", _ColstatsContent())]
282
283 def testPreviousContentsRemoved(self):
284 self.assertFalse("sentinel_garbage" in self.colStats["num"])
285 self.assertFalse("sentinel_garbage" in self.colStats["enum"])
286
287 def testTableDeclared(self):
288 self.assertEqual([r["tablename"] for r in self.colStats["num"].values()],
289 ["test.hcdtest"]*15)
290
291 def testAllNumericColumnsAnnotated(self):
292 self.assertEqual(len(self.colStats["num"]), 15)
293
294 def testFillFactorNonNull(self):
295 self.assertTrue(
296 None not in set(r["fill_factor"] for r in self.colStats["num"].values()))
297
298 def testFillFactorComputed(self):
299 self.assertAlmostEqual(self.colStats["num"]["ssa_snr"]["fill_factor"], 0.)
300 self.assertAlmostEqual(
301 self.colStats["num"]["ssa_dateObs"]["fill_factor"], 1.)
302
303 def testMedianComputation(self):
304 self.assertEqual(self.colStats["num"]["accsize"]["median"], "219.0")
305
306 def testPercentiles(self):
307 self.assertAlmostEqual(
308 float(self.colStats["num"]["ssa_redshift"]["percentile03"]),
309 -0.001),
310 self.assertAlmostEqual(
311 float(self.colStats["num"]["ssa_redshift"]["percentile97"]),
312 0.7)
313
314 def testMinMax(self):
315 self.assertEqual(self.colStats["num"]["accsize"]["min_value"], "213")
316 self.assertEqual(self.colStats["num"]["accsize"]["max_value"], "225")
317
318 def testTimestamp(self):
319 currentMJD = api.dateTimeToMJD(datetime.datetime.utcnow())
320 rec = self.colStats["num"]["ssa_pdate"]
321 self.assertAlmostEqual(float(rec["median"]), currentMJD, places=3)
322
323 def testBandpassDistribution(self):
324 row = self.colStats["enum"]["ssa_bandpass"]
325 self.assertEqual(row["tablename"], "test.hcdtest")
326 self.assertEqual(row["vals"], ["B", "R", "V"])
327 self.assertAlmostEqual(row["freqs"][0], 1/3)
328
329 def testTargetDistribution(self):
330 row = self.colStats["enum"]["ssa_targname"]
331 self.assertEqual(row["vals"],
332 ['big fart nebula', 'booger star', 'rat hole in the yard'])
333
334
335 class _TDWithStats(testhelpers.TestResource):
336 """The stuff from the tstat RD with the in-DB annotations.
337
338 This takes care to tear down the statistics entries again, as
339 they might interfere with other tests.
340 """
341 resources = [("conn", tresc.dbConnection)]
342
343 def make(self, deps):
344 conn = deps["conn"]
345 rdId = "data/tstat"
346 rd = api.getRD(rdId)
347
348 api.makeData(rd.getById("import"), connection=conn)
349 conn.commit()
350 limits.updateTableLevelStats(
351 rd.getById("DoNotMixCase"), conn)
352
353 base.caches.clearForName(rdId)
354 return api.resolveCrossId(rdId+"#DoNotMixCase")
355
356 def clean(self, ignored):
357 with base.getWritableAdminConn() as conn:
358 conn.execute("delete from dc.simple_col_stats where"
359 " tableName='test.DoNotMixCase'")
360
361
362 _tdWithStats = _TDWithStats()
363
364 class ColstatsInjectionTest(testhelpers.VerboseTest):
365 resources = [("statsTD", _tdWithStats)]
366
367 def testFloatAnnotationInValues(self):
368 col = self.statsTD.getColumnByName("plain_float")
369 self.assertEqual(col.values.min, "-1")
370 self.assertEqual(col.values.max, "1.0")
371 self.assertAlmostEqual(float(col.values.median), 0.41666666, places=6)
372
373 def testDelimitedAnnotation(self):
374 col = self.statsTD.getColumnByName(api.QuotedName("gg-/l"))
375 self.assertAlmostEqual(float(col.values.percentile03), 1.27, places=6)
376 self.assertEqual(col.values.median, "6.5")
377 self.assertAlmostEqual(float(col.values.percentile97), 15.37, places=6)
378 self.assertEqual(col.values.fillFactor, "1.0")
379
380 def testManuallyAnnotatedColumn(self):
381 col = self.statsTD.getColumnByName("plain_float")
382 self.assertEqual(col.values.min, "-1")
383 col = self.statsTD.getColumnByName("dontlook")
384 self.assertEqual(col.values.min, "-3.6")
385
386 def testStatisticsSkip(self):
387 col = self.statsTD.getColumnByName("dontlook")
388 self.assertEqual(col.values.fillFactor, None)
389
390 def testNoneIsSkipped(self):
391 col = self.statsTD.getColumnByName("allnull")
392 self.assertEqual(col.values.median, None)
393
394 def testStringSel(self):
395 col = self.statsTD.getColumnByName("hurgel")
396 self.assertEqual(
397 [opt.title for opt in col.values.options],
398 ["nma0", "nma1"])
399
400
401 class _VOSITablesetWithStats(testhelpers.TestResource):
402 """a VOSIDataService tableset over a statistically annotated table.
403 """
404 resources = [("statsTD", _tdWithStats)]
405
406 def make(self, deps):
407 from gavo.registry import tableset
408 from gavo.web.vosi import VTM
409
410 xmlLit = tableset.getTableForTableDef(
411 deps["statsTD"],
412 set(),
413 rootElement=VTM.table).render()
414 tree = testhelpers.getXMLTree(xmlLit, debug=False)
415 return xmlLit, tree
416
417
418 class ColstatsVSTest(testhelpers.VerboseTest, testtricks.XSDTestMixin):
419 resources = [("rt", _VOSITablesetWithStats())]
420
421 def testValid(self):
422 self.assertValidates(self.rt[0])
423
424 def testMinDefinedPlain(self):
425 self.assertEqual(
426 self.rt[1].xpath("column[name='plain_float']/stats/min")[0].text,
427 "-1")
428
429 def testMaxDefinedDelimited(self):
430 self.assertEqual(
431 self.rt[1].xpath("column[name='\"gg-/l\"']/stats/max")[0].text,
432 "16")
433
434 def testMedianDefined(self):
435 self.assertEqual(
436 self.rt[1].xpath("column[name='\"gg-/l\"']/stats/median")[0].text,
437 "6.5")
438
439 def testLowerPercentileDefined(self):
440 self.assertAlmostEqual(
441 float(self.rt[1].xpath(
442 "column[name='plain_float']/stats/percentile03")[0].text),
443 0.2575)
444
445 def testUpperPercentileDefined(self):
446 self.assertAlmostEqual(
447 float(self.rt[1].xpath(
448 "column[name='plain_float']/stats/percentile97")[0].text),
449 0.955)
450
451 def testFillFactorDefined(self):
452 self.assertEqual(
453 self.rt[1].xpath("column[name='plain_float']/stats/fillFactor")[0].text,
454 "1")
455
456 def testOptions(self):
457 opts = self.rt[1].xpath("column[name='hurgel']/stats/option")
458 self.assertEqual(len(opts), 2)
459 self.assertEqual(opts[0].text, "nma0")
460 self.assertEqual(opts[1].get("freq"), "0.5")
461
462 def testIntOption(self):
463 opt = self.rt[1].xpath("column[name='calib']/stats/option")[0]
464 self.assertEqual(opt.text, "0")
465
466
467 class DumpingTest(testhelpers.VerboseTest):
468 resources = [
469 ("conn", tresc.dbConnection),
470 ("adqlgeo", tresc.adqlGeoTable),
471 ("withstats", _tdWithStats)]
472
473 def testUnimportedTable(self):
474 rd = base.parseFromString(api.RD,
475 """<resource schema="test"><table id="dumb" onDisk="True">
476 <column name="x"/></table></resource>""")
477 testtricks.assertHasStrings(
478 testhelpers.captureOutput(
479 limits.dumpTableLevelStats, (rd.getById("dumb"), self.conn))[1],
480 ["Statistics for test.dumb", "No metadata (table not imported)?"])
481
482 def testImportedTable(self):
483 testtricks.assertHasStrings(
484 testhelpers.captureOutput(
485 limits.dumpTableLevelStats, (self.adqlgeo.tableDef, self.conn))[1],
486 ["Statistics for test.ADQLgeo", "|rows| = <Unknown>"])
487
488 def testAnalysedTable(self):
489 testtricks.assertHasStrings(
490 testhelpers.captureOutput(
491 limits.dumpTableLevelStats, (self.withstats, self.conn))[1],
492 ["Statistics for test.DoNotMixCase", "|rows| = 4",
493 "plain_float", '"gg-/l"', " 0.257500000… ", " 0.955", " None "])
494
495 def testRDInfo(self):
496 testtricks.assertHasStrings(
497 testhelpers.captureOutput(
498 limits.dumpStatsForRD, (self.withstats.rd, self.conn))[1],
499 ["Statistics for RD data/tstat", "No RD stats.",
500 "Statistics for test.DoNotMixCase"])
501
502
503 if __name__=="__main__":
504 testhelpers.main(LimitsAnnotatorQueryTest)