Debian Codegraph @

gavo/protocols/simbadinterface.py

raw
1 """
2 A caching proxy for CDS' Simbad object resolver.
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 json
12 import os
13 import socket
14 from urllib import request, parse
15
16 if __name__=="__main__":
17 # see below on why this doesn't have normal unit tests.
18 os.environ["GAVO_OOTTEST"] = "dontcare"
19 from gavo.helpers import testhelpers
20
21 from gavo import base
22 from gavo.utils import ElementTree
23
24
25
26 class ObjectCache(object):
27 """a cache for simbad queries kept in dc.metastore.
28
29 This used to be file-based, and used different keys for different
30 purposes. The different keys didn't seem to be useful, so they're
31 ignored now.
32
33 This only caches positive responses; there's too much that can
34 go wrong when caching negatives, and the expectation is that negatives
35 are so varying that there's little to win anyway.
36
37 The values passed in are json-encoded (for simbad, these are dictionaries).
38 """
39 def addItem(self, key, value):
40 """adds an item to the cache.
41
42 value is json-encoded before writing it.
43 """
44 with base.getWritableAdminConn() as conn:
45 base.setDBMeta(conn,
46 'simbad:'+key,
47 json.dumps(value))
48
49 def getItem(self, key):
50 """returns a previously stored object of key.
51
52 This raises a KeyError if nothing has been stored before.
53 """
54 return json.loads(base.getDBMeta('simbad:'+key))
55
56
57 class Sesame(object):
58 """is a simple interface to the simbad name resolver.
59 """
60 # we're using several simbad mirrors if we have to, and only give
61 # up if all of them fail.
62 svc_urls = [
63 "http://cdsweb.u-strasbg.fr/cgi-bin/nph-sesame/-ox/SN?",
64 "http://vizier.cfa.harvard.edu/viz-bin/nph-sesame/-ox/SN?"]
65
66 def __init__(self):
67 self.cache = ObjectCache()
68
69 def _parseXML(self, simbadXML):
70 try:
71 et = ElementTree.fromstring(simbadXML)
72 except Exception as msg: # simbad returned weird XML
73 base.ui.notifyWarning("Bad XML from simbad (%s)"%str(msg))
74 return None
75
76 res = {}
77 nameMatch = et.find("Target/name")
78 if nameMatch is None:
79 # no such object, return a negative
80 return None
81
82 res["oname"] = nameMatch.text
83 firstResponse = et.find("Target/Resolver")
84 if not firstResponse:
85 return None
86
87 res["otype"] = getattr(firstResponse.find("otype"), "text", None)
88 try:
89 res["RA"] = float(firstResponse.find("jradeg").text)
90 res["dec"] = float(firstResponse.find("jdedeg").text)
91 except (ValueError, AttributeError):
92 # presumably null position
93 return None
94 return res
95
96 def query(self, ident):
97 try:
98 return self.cache.getItem(ident)
99 except KeyError:
100 # cache miss, fall through to actually querying sesame
101 pass
102
103 for svc_url in self.svc_urls:
104 try:
105 with request.urlopen(svc_url+parse.quote(ident), timeout=2) as f:
106 newOb = self._parseXML(f.read())
107 self.cache.addItem(ident, newOb)
108 return newOb
109 except socket.error:
110 # Try next mirror
111 pass
112 else:
113 # all mirrors fail
114 raise base.ui.logOldExc(base.ValidationError(
115 "Simbad is offline, cannot query.",
116 "hscs_pos", # really, this should be added by the widget
117 hint="If this problem persists, complain to us rather than simbad."))
118
119 def getPositionFor(self, identifier):
120 rec = self.query(identifier)
121 if not rec:
122 raise KeyError(identifier)
123 return float(rec["RA"]), float(rec["dec"])
124
125
126 def getSimbadPositions(identifier):
127 """returns ra and dec from Simbad for identifier.
128
129 It raises a KeyError if Simbad doesn't know identifier.
130 """
131 return base.caches.getSesame("").getPositionFor(identifier)
132
133
134 # This used to accept a "key" to separate different uses of Sesame.
135 # That's not turned out to be useful, so we're now ignoring the
136 # key.
137 base.caches.makeCache("getSesame", lambda key="ignored": Sesame())
138
139
140 ############## ADQL ufunc
141
142 from gavo import adql
143
144 @adql.userFunction("ivo_simbadpoint",
145 "(identifier TEXT) -> POINT",
146 """
147 gavo_simbadpoint queries simbad for an identifier and returns the
148 corresponding point. Note that identifier can only be a literal,
149 i.e., as simple string rather than a column name. This is because
150 our database cannot query simbad, and we probably wouldn't want
151 to fire off millions of simbad queries anyway; use simbad's own
152 TAP service for this kind of application.
153 """,
154 "point", ucd="pos.eq;src",
155 additionalNames=["gavo_simbadpoint"])
156 def _simbadpoint(args):
157 from gavo.adql import nodes
158
159 if len(args)!=1 or args[0].type!="characterStringLiteral":
160 raise adql.UfuncError(
161 "gavo_simbadpoint takes exactly one string literal as argument")
162
163 object = args[0].value
164
165 resolver = base.caches.getSesame("")
166 try:
167 alpha, delta = resolver.getPositionFor(object)
168 except KeyError:
169 raise adql.UfuncError("No simbad position for '%s'"%object)
170
171 raise nodes.ReplaceNode(nodes.Point(cooSys=None,
172 x=nodes.Factor([repr(alpha)]), y=nodes.Factor([repr(delta)])))
173
174
175 def _getTestSuite():
176 import unittest
177
178 with base.getWritableAdminConn() as conn:
179 conn.execute("DELETE FROM dc.metastore WHERE key LIKE 'simbad:%%'")
180
181 sc = base.caches.getSesame("anything")
182
183 # NOTE: all these tests assume the cache has been cleared before
184 # them, and that the configured mirrors are up.
185 # Cache clearing happens a few lines up.
186 class QueryTest(testhelpers.VerboseTest):
187 def testBasic(self):
188 res = getSimbadPositions("Antares")
189 self.assertAlmostEqual(res[0], 247.351915, 5)
190 self.assertAlmostEqual(res[1], -26.432002, 5)
191
192 def testCaching(self):
193 res = getSimbadPositions("M31")
194 self.assertAlmostEqual(res[0], 10.684708, 5)
195 self.assertAlmostEqual(res[1], 41.26875, 5)
196
197 tmp = Sesame.svc_urls
198 Sesame.svcs_urls = []
199 try:
200 res = getSimbadPositions("M31")
201 self.assertAlmostEqual(res[0], 10.684708, 5)
202 self.assertAlmostEqual(res[1], 41.26875, 5)
203 finally:
204 Sesame.svcs_urls = tmp
205
206 def testMirrorFailover(self):
207 tmp = Sesame.svc_urls[0]
208 Sesame.svc_urls[0] = "http://localhost:39293?"
209
210 try:
211 res = getSimbadPositions("epsilon Eri")
212 self.assertAlmostEqual(res[0], 53.232687, 5)
213 self.assertAlmostEqual(res[1], -9.458258, 5)
214 finally:
215 Sesame.svc_urls[0] = tmp
216
217 def testCacheInstallation(self):
218 res = base.caches.getSesame("anything").getPositionFor("ε Eri")
219 self.assertAlmostEqual(res[0], 53.232687, 5)
220 self.assertAlmostEqual(res[1], -9.458258, 5)
221
222 l = locals()
223 tests = [l[name] for name in l
224 if isinstance(l[name], type) and issubclass(l[name], unittest.TestCase)]
225 loader = unittest.TestLoader()
226 suite = unittest.TestSuite([loader.loadTestsFromTestCase(t)
227 for t in tests])
228 return suite
229
230
231 if __name__=="__main__":
232 # we don't want to test this as part of the normal unit tests, as
233 # there's little to sensibly test without a live network connection
234 # (and we don't want to require that for the unit tests).
235 import unittest
236 suite = _getTestSuite()
237 unittest.TextTestRunner().run(suite)
238