Debian Codegraph @

gavo/protocols/scs.py

raw
1 """
2 IVOA cone search: Helper functions, a core, and misc.
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 from gavo import base
12 from gavo import svcs
13 from gavo.protocols import simbadinterface #noflake: for registration
14 from gavo.svcs import outputdef
15
16
17 def getRadialCondition(td, ra, dec, sr,
18 raColName=None, decColName=None):
19 """returns a sql literal for building a spatial query over the tableDef
20 td.
21
22 ra, dec, and sr are as in SCS. While this function does some mild
23 last-resort checking in case things break, you must not pass in
24 untrusted content in there. It's ok to pass in columns or expressions,
25 though.
26
27 raCol and decCol are determined through UCDs if not given. This
28 will preferentially use q3c and fall back to pgsphere if no q3c indices
29 can be discerned on the columns.
30
31 In case no SCS UCDs are present, the function will also accept
32 spoints with pos.eq;meta.main. This, of course, will not work
33 with SCS itself (out of the box).
34 """
35 if (isinstance(ra, str) and ";" in ra
36 ) or (isinstance(dec, str) and ";" in dec
37 ) or (isinstance(sr, str) and ";" in sr):
38 raise base.ReportableError(
39 "getRadialCondition's last resort alarm triggered.")
40
41 try:
42 if raColName is None:
43 raCol = td.getColumnByUCD("pos.eq.ra;meta.main")
44 else:
45 raCol = td.getColumnByName(raColName)
46
47 if decColName is None:
48 decCol = td.getColumnByUCD("pos.eq.dec;meta.main")
49 else:
50 decCol = td.getColumnByName(decColName)
51 except base.StructureError:
52 # presumably a UCD location failure
53 pointCols = td.getColumnsByUCD("pos.eq")
54 if pointCols:
55 return ("{ptname} <@ scircle("
56 "spoint(radians({constra}), radians({constdec})),"
57 " radians({sr}))").format(ptname=pointCols[0].name,
58 constra=ra, constdec=dec, sr=sr)
59 else:
60 raise
61
62 if "q3c" in (raCol.isIndexed() or []):
63 pattern = ("q3c_radial_query({varra}, {vardec},"
64 " {constra}, {constdec}, {sr})")
65 else:
66 pattern = ("spoint(radians({varra}), radians({vardec})) "
67 " <@ scircle("
68 "spoint(radians({constra}), radians({constdec})),"
69 " radians({sr}))")
70
71 return pattern.format(
72 varra=raCol.name, vardec=decCol.name,
73 constra=ra, constdec=dec, sr=sr)
74
75
76 def findNClosest(alpha, delta, tableDef, n, fields, searchRadius=5):
77 """returns the n objects closest around alpha, delta in table.
78
79 n is the number of items returned, with the closest ones at the
80 top, fields is a sequence of desired field names, searchRadius
81 is a radius for the initial q3c search and will need to be
82 lowered for dense catalogues and possibly raised for sparse ones.
83
84 The last item of each row is the distance of the object from
85 the query center in degrees.
86 """
87 with base.getTableConn() as conn:
88 raField = tableDef.getColumnByUCDs("pos.eq.ra;meta.main",
89 "POS_EQ_RA_MAIN").name
90 decField = tableDef.getColumnByUCDs("pos.eq.dec;meta.main",
91 "POS_EQ_RA_MAIN").name
92 res = list(conn.query("SELECT %s,"
93 " (spoint(radians(%s), radians(%s)) <->"
94 " spoint(radians(%%(alpha)s), radians(%%(delta)s))) as dist_"
95 " FROM %s WHERE"
96 " q3c_radial_query(%s, %s, %%(alpha)s, %%(delta)s,"
97 " %%(searchRadius)s)"
98 " ORDER BY dist_ LIMIT %%(n)s"%
99 (",".join(fields), raField, decField, tableDef.getQName(),
100 raField, decField),
101 locals()))
102 return res
103
104
105 def parseHumanSpoint(cooSpec, colName=None):
106 """tries to interpret cooSpec as some sort of cone center.
107
108 Attempted interpretations include various forms of coordinate pairs
109 and simbad objects; hence, this will in general cause network traffic.
110
111 If no sense can be made, a ValidationError on colName is raised.
112 """
113 try:
114 cooPair = base.parseCooPair(cooSpec)
115 except ValueError:
116 simbadData = base.caches.getSesame("web").query(cooSpec)
117 if not simbadData:
118 raise base.ValidationError("%s is neither a RA,DEC"
119 " pair nor a simbad resolvable object."%cooSpec, colName)
120 cooPair = simbadData["RA"], simbadData["dec"]
121 return cooPair
122
123
124 def getConeColumns(td):
125 """returns the columns the cone search will use as positions in a
126 tableDef.
127
128 This will raise an error if these are not present or not unique.
129 Both new-style and old-style UCDs are accepted.
130 """
131 raColumn = td.getColumnByUCDs(
132 "pos.eq.ra;meta.main", "POS_EQ_RA_MAIN")
133 decColumn = td.getColumnByUCDs(
134 "pos.eq.dec;meta.main", "POS_EQ_DEC_MAIN")
135 return raColumn, decColumn
136
137
138 class SCSCore(svcs.DBCore):
139 """A core performing cone searches.
140
141 This will, if it finds input parameters it can make out a position from,
142 add a _r column giving the distance between the match center and
143 the columns that a cone search will match against.
144
145 If any of the conditions for adding _r aren't met, this will silently
146 degrade to a plain DBCore.
147
148 You will almost certainly want a::
149
150 <FEED source="//scs#coreDescs"/>
151
152 in the body of this (in addition to whatever other custom conditions
153 you may have).
154 """
155 name_ = "scsCore"
156
157 def onElementComplete(self):
158 super().onElementComplete()
159 # raColumn and decColumn must be from the queriedTable (rather than
160 # the outputTable, as it would be preferable), since we're using
161 # them to build database queries.
162 self.raColumn, self.decColumn = getConeColumns(self.queriedTable)
163 try:
164 self.idColumn = self.outputTable.getColumnByUCDs(
165 "meta.id;meta.main", "ID_MAIN")
166 except base.StructureError:
167 base.ui.notifyWarning("SCS core at %s: Output table has no unique"
168 " meta.id;meta.main column. This service will be invalid."%
169 self.getSourcePosition())
170
171 self.distCol = base.resolveCrossId("//scs#distCol")
172 # let me indulge in this ugly hack -- outputTable belongs to
173 # us anyway, and saving a copy is totally not worth it
174 self.outputTable.columns[0:0] = [self.distCol]
175 self.outputTable.columns.redoIndex()
176
177 if not self.hasProperty("defaultSortKey"):
178 self.setProperty("defaultSortKey", self.distCol.name)
179
180 def _guessDestPos(self, inputTable):
181 """returns RA and Dec for a cone search possibly contained in inputTable.
182
183 If no positional query is discernible, this returns None.
184 """
185 pars = inputTable.getParamDict()
186 if pars.get("RA") is not None and pars.get("DEC") is not None:
187 return pars["RA"], pars["DEC"]
188 elif pars.get("hscs_pos") is not None:
189 try:
190 return parseHumanSpoint(pars["hscs_pos"], "hscs_pos")
191 except (ValueError, base.ValidationError):
192 # We do not want to fail for this fairly unimportant thing.
193 # If the core actually needs the position, it should fail itself.
194 return None
195 else:
196 return None
197
198 def _getDistColumn(self, destPos):
199 """returns an outputField selecting the distance of the match
200 object to the cone center.
201 """
202 if destPos is None:
203 select = "NULL"
204 else:
205 select = "degrees(spoint(radians(%s), radians(%s)) <-> %s)"%(
206 self.raColumn.name, self.decColumn.name,
207 "spoint '(%fd,%fd)'"%destPos)
208
209 return self.distCol.change(select=select)
210
211 def _fixupQueryColumns(self, destPos, baseColumns):
212 """returns the output columns from baseColumns for a query
213 centered at destPos.
214
215 In particular, the _r column is primed so it yields the right result
216 if destPos is given.
217 """
218 res = []
219 for col in baseColumns:
220 if col.name=="_r":
221 res.append(self._getDistColumn(destPos))
222 else:
223 res.append(col)
224 return res
225
226 def _makeResultTableDef(self, service, inputTable, queryMeta):
227 destPos = self._guessDestPos(inputTable)
228
229 outCols = self._fixupQueryColumns(destPos,
230 self.getQueryCols(service, queryMeta))
231
232 return base.makeStruct(outputdef.OutputTableDef,
233 parent_=self.queriedTable.parent,
234 id="result",
235 onDisk=False,
236 columns=outCols,
237 params=self.queriedTable.params)