-
-
Notifications
You must be signed in to change notification settings - Fork 390
/
conesearch.py
528 lines (411 loc) · 16.5 KB
/
conesearch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Support VO Simple Cone Search capabilities.
.. note:: This maintains a similar API as ``astropy.vo.client``.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
# STDLIB
import warnings
# THIRD-PARTY
import numpy as np
# ASTROPY
from astropy.io.votable.exceptions import vo_warn, W25
from astropy.utils.console import color_print
from astropy.utils.exceptions import AstropyUserWarning
# LOCAL
from . import vos_catalog
from .vo_async import AsyncBase
from .core import ConeSearchClass, _validate_sr
from .exceptions import ConeSearchError, VOSError
from ..utils.timer import timefunc, RunTimePredictor
# Import configurable items declared in __init__.py
from . import conf
__all__ = ['AsyncConeSearch', 'conesearch', 'AsyncSearchAll', 'search_all',
'list_catalogs', 'predict_search', 'conesearch_timer']
# Skip these doctests
__doctest_skip__ = ['AsyncConeSearch', 'AsyncSearchAll']
class AsyncConeSearch(AsyncBase):
"""
Perform a Cone Search asynchronously and returns the result of the
first successful query.
.. note::
See :class:`~astroquery.vo_conesearch.vo_async.AsyncBase`
for more details.
Parameters
----------
args, kwargs
See :func:`conesearch`.
Examples
--------
>>> from astropy import coordinates as coord
>>> from astropy import units as u
>>> from astroquery.vo_conesearch import conesearch
>>> c = coord.ICRS(6.0223 * u.degree, -72.0814 * u.degree)
>>> async_search = conesearch.AsyncConeSearch(
... c, 0.5 * u.degree,
... catalog_db='The PMM USNO-A1.0 Catalogue (Monet 1997) 1')
Check search status:
>>> async_search.running()
True
>>> async_search.done()
False
Get search results after a 30-second wait (not to be
confused with ``astroquery.vo_conesearch.conf.timeout`` that
governs individual Cone Search queries). If search is still not
done after 30 seconds, `TimeoutError` is raised. Otherwise,
Cone Search result is returned and can be manipulated as in
:ref:`Simple Cone Search Examples <vo-sec-scs-examples>`.
If no ``timeout`` keyword given, it waits until completion:
>>> async_result = async_search.get(timeout=30)
>>> cone_arr = async_result.array.data
>>> cone_arr.size
36184
"""
def __init__(self, *args, **kwargs):
super(AsyncConeSearch, self).__init__(conesearch, *args, **kwargs)
def conesearch(center, radius, verb=1, catalog_db=None, pedantic=None,
verbose=True, cache=True, timeout=None, query_all=False):
"""
Perform Cone Search and returns the result of the
first successful query.
Parameters
----------
center : str, `astropy.coordinates` object, list, or tuple
Position of the center of the cone to search.
It may be specified as an object from the
:ref:`astropy:astropy-coordinates` package,
string as accepted by
:func:`~astroquery.utils.parse_coordinates`, or tuple/list.
If given as tuple or list, it is assumed to be ``(RA, DEC)``
in the ICRS coordinate frame, given in decimal degrees.
radius : float or `~astropy.units.quantity.Quantity`
Radius of the cone to search:
- If float is given, it is assumed to be in decimal degrees.
- If astropy quantity is given, it is internally converted
to degrees.
verb : {1, 2, 3}
Verbosity indicating how many columns are to be returned
in the resulting table. Support for this parameter by
a Cone Search service implementation is optional. If the
service supports the parameter:
1. Return the bare minimum number of columns that
the provider considers useful in describing the
returned objects.
2. Return a medium number of columns between the
minimum and maximum (inclusive) that are
considered by the provider to most typically
useful to the user.
3. Return all of the columns that are available for
describing the objects.
If not supported, the service should ignore the parameter
and always return the same columns for every request.
catalog_db
May be one of the following, in order from easiest to
use to most control:
- `None`: A database of
``astroquery.vo_conesearch.conf.conesearch_dbname`` catalogs is
downloaded from ``astroquery.vo_conesearch.conf.vos_baseurl``.
The first catalog in the database to successfully return a
result is used.
- *catalog name*: A name in the database of
``astroquery.vo_conesearch.conf.conesearch_dbname`` catalogs at
``astroquery.vo_conesearch.conf.vos_baseurl`` is used.
For a list of acceptable names, use
:func:`astroquery.vo_conesearch.vos_catalog.list_catalogs`.
- *url*: The prefix of a URL to a IVOA Service for
``astroquery.vo_conesearch.conf.conesearch_dbname``.
Must end in either '?' or '&'.
- `~astroquery.vo_conesearch.vos_catalog.VOSCatalog` object: A
specific catalog manually downloaded and selected from the
database (see :ref:`vo-sec-client-vos`).
- Any of the above 3 options combined in a list, in which case
they are tried in order.
pedantic : bool or `None`
When `True`, raise an error when the result violates the spec,
otherwise issue a warning. Warnings may be controlled using
:py:mod:`warnings` module. When not provided, uses the
configuration setting ``astroquery.vo_conesearch.conf.pedantic``,
which defaults to `False`.
verbose : bool
Verbose output.
cache : bool
Use caching for VO Service database. Access to actual VO
websites referenced by the database still needs internet
connection.
timeout : number or `None`
Timeout limit in seconds for each service being queries.
If `None`, use default.
query_all : bool
This is used by :func:`search_all`.
Returns
-------
obj : `astropy.io.votable.tree.Table`
First table from first successful VO service request.
Raises
------
ConeSearchError
When invalid inputs are passed into Cone Search.
VOSError
If VO service request fails.
"""
# Not using default ConeSearch instance because the attributes are
# tweaked to match user inputs to this function.
cs = ConeSearchClass()
n_timed_out = 0
service_type = conf.conesearch_dbname
catalogs = vos_catalog._get_catalogs(
service_type, catalog_db, cache=cache, verbose=verbose)
if query_all:
result = {}
else:
result = None
if pedantic is not None:
cs.PEDANTIC = pedantic
if timeout is not None:
cs.TIMEOUT = timeout
for name, catalog in catalogs:
if isinstance(catalog, six.string_types):
if catalog.startswith('http'):
url = catalog
else:
remote_db = vos_catalog.get_remote_catalog_db(
service_type, cache=cache, verbose=verbose)
catalog = remote_db.get_catalog(catalog)
url = catalog['url']
else:
url = catalog['url']
cs.URL = url
if verbose: # pragma: no cover
color_print('Trying {0}'.format(url), 'green')
try:
r = cs.query_region(center, radius, verb=verb, cache=cache,
verbose=verbose)
except Exception as e:
err_msg = str(e)
vo_warn(W25, (url, err_msg))
if not query_all and 'ConnectTimeoutError' in err_msg:
n_timed_out += 1
else:
if query_all:
result[r.url] = r
else:
result = r
break
if result is None:
err_msg = 'None of the available catalogs returned valid results.'
if n_timed_out > 0:
err_msg += ' ({0} URL(s) timed out.)'.format(n_timed_out)
raise VOSError(err_msg)
return result
class AsyncSearchAll(AsyncBase):
"""
Perform a Cone Search asynchronously, storing all results
instead of just the result from first successful query.
.. note::
See :class:`~astroquery.vo_conesearch.vo_async.AsyncBase`
for more details.
Parameters
----------
args, kwargs
See :func:`search_all`.
Examples
--------
>>> from astropy import coordinates as coord
>>> from astropy import units as u
>>> from astroquery.vo_conesearch import conesearch
>>> c = coord.ICRS(6.0223 * u.degree, -72.0814 * u.degree)
>>> async_search = conesearch.AsyncSearchAll(c, 0.5 * u.degree)
Check search status:
>>> async_search.running()
True
>>> async_search.done()
False
Get a dictionary of all search results after a 30-second wait (not
to be confused with ``astroquery.vo_conesearch.conf.timeout`` that
governs individual Cone Search queries). If search is still not
done after 30 seconds, `TimeoutError` is raised. Otherwise, a
dictionary is returned and can be manipulated as in
:ref:`Simple Cone Search Examples <vo-sec-scs-examples>`.
If no ``timeout`` keyword given, it waits until completion:
>>> async_allresults = async_search.get(timeout=30)
>>> all_catalogs = list(async_allresults)
>>> first_cone_arr = async_allresults[all_catalogs[0]].array.data
>>> first_cone_arr.size
36184
"""
def __init__(self, *args, **kwargs):
AsyncBase.__init__(self, search_all, *args, **kwargs)
def search_all(*args, **kwargs):
"""
Perform Cone Search and returns the results of
all successful queries.
.. warning::
Could potentially take up significant run time and
computing resources.
Parameters
----------
args, kwargs
Arguments and keywords accepted by :func:`conesearch`.
Returns
-------
result : dict of `astropy.io.votable.tree.Table` objects
A dictionary of tables from successful VO service requests,
with keys being the access URLs. If none is successful,
an empty dictionary is returned.
Raises
------
ConeSearchError
When invalid inputs are passed into Cone Search.
"""
kwargs['query_all'] = True
return conesearch(*args, **kwargs)
def list_catalogs(**kwargs):
"""
Return the available Cone Search catalogs as a list of strings.
These can be used for the ``catalog_db`` argument to
:func:`conesearch`.
Parameters
----------
cache : bool
Use caching for VO Service database. Access to actual VO
websites referenced by the database still needs internet
connection.
verbose : bool
Show download progress bars.
pattern : str or `None`
If given string is anywhere in a catalog name, it is
considered a matching catalog. It accepts patterns as
in :py:mod:`fnmatch` and is case-insensitive.
By default, all catalogs are returned.
sort : bool
Sort output in alphabetical order. If not sorted, the
order depends on dictionary hashing. Default is `True`.
Returns
-------
arr : list of str
List of catalog names.
"""
return vos_catalog.list_catalogs(conf.conesearch_dbname, **kwargs)
def predict_search(url, *args, **kwargs):
"""
Predict the run time needed and the number of objects
for a Cone Search for the given access URL, position, and
radius.
Run time prediction uses `astroquery.utils.timer.RunTimePredictor`.
Baseline searches are done with starting and ending radii at
0.05 and 0.5 of the given radius, respectively.
Extrapolation on good data uses least-square straight line fitting,
assuming linear increase of search time and number of objects
with radius, which might not be accurate for some cases. If
there are less than 3 data points in the fit, it fails.
Warnings (controlled by :py:mod:`warnings`) are given when:
#. Fitted slope is negative.
#. Any of the estimated results is negative.
#. Estimated run time exceeds
``astroquery.vo_conesearch.conf.timeout``.
.. note::
If ``verbose=True``, extra log info will be provided.
But unlike :func:`conesearch_timer`, timer info is suppressed.
The predicted results are just *rough* estimates.
Prediction is done using
:class:`astroquery.vo_conesearch.core.ConeSearchClass`.
Prediction for :class:`AsyncConeSearch` is not supported.
Parameters
----------
url : str
Cone Search access URL to use.
plot : bool
If `True`, plot will be displayed.
Plotting uses `matplotlib <http://matplotlib.sourceforge.net/>`_.
args, kwargs
See :meth:`astroquery.vo_conesearch.core.ConeSearchClass.query_region`.
Returns
-------
t_est : float
Estimated time in seconds needed for the search.
n_est : int
Estimated number of objects the search will yield.
Raises
------
AssertionError
If prediction fails.
ConeSearchError
If input parameters are invalid.
VOSError
If VO service request fails.
"""
if len(args) != 2: # pragma: no cover
raise ConeSearchError('conesearch must have exactly 2 arguments')
plot = kwargs.pop('plot', False)
center, radius = args
sr = _validate_sr(radius)
if sr <= 0:
raise ConeSearchError('Search radius must be > 0 degrees')
# Not using default ConeSearch instance because the attributes are
# tweaked to match user inputs to this function.
cs = ConeSearchClass()
cs.URL = url
cs.PEDANTIC = kwargs.pop('pedantic', conf.pedantic)
cs_pred = RunTimePredictor(cs.query_region, center, **kwargs)
# Search properties for timer extrapolation
num_datapoints = 10 # Number of desired data points for extrapolation
sr_min = 0.05 * sr # Min radius to start the timer
sr_max = 0.5 * sr # Max radius to stop the timer
sr_step = (1.0 / num_datapoints) * (sr_max - sr_min) # Radius step
# Slowly increase radius to get data points for extrapolation
sr_arr = np.arange(sr_min, sr_max + sr_step, sr_step)
cs_pred.time_func(sr_arr)
# Predict run time
t_coeffs = cs_pred.do_fit()
t_est = cs_pred.predict_time(sr)
if t_est < 0 or t_coeffs[1] < 0: # pragma: no cover
warnings.warn(
'Estimated runtime ({0} s) is non-physical with slope of '
'{1}'.format(t_est, t_coeffs[1]), AstropyUserWarning)
elif t_est > cs.TIMEOUT: # pragma: no cover
warnings.warn(
'Estimated runtime is longer than timeout of '
'{0} s'.format(cs.TIMEOUT), AstropyUserWarning)
# Predict number of objects
sr_arr = sorted(cs_pred.results) # Orig with floating point error
n_arr = [cs_pred.results[key].array.size for key in sr_arr]
n_coeffs = np.polyfit(sr_arr, n_arr, 1)
n_fitfunc = np.poly1d(n_coeffs)
n_est = int(round(n_fitfunc(sr)))
if n_est < 0 or n_coeffs[0] < 0: # pragma: no cover
warnings.warn('Estimated #objects ({0}) is non-physical with slope of '
'{1}'.format(n_est, n_coeffs[0]), AstropyUserWarning)
if plot: # pragma: no cover
import matplotlib.pyplot as plt
xlabeltext = 'radius (deg)'
sr_fit = np.append(sr_arr, sr)
n_fit = n_fitfunc(sr_fit)
cs_pred.plot(xlabeltext=xlabeltext)
fig, ax = plt.subplots()
ax.plot(sr_arr, n_arr, 'kx-', label='Actual')
ax.plot(sr_fit, n_fit, 'b--', label='Fit')
ax.scatter([sr], [n_est], marker='o', c='r', label='Predicted')
ax.set_xlabel(xlabeltext)
ax.set_ylabel('#objects')
ax.legend(loc='best', numpoints=1)
plt.draw()
return t_est, n_est
@timefunc(1)
def conesearch_timer(*args, **kwargs):
"""
Time a single Cone Search using `astroquery.utils.timer.timefunc`
with a single try and a verbose timer.
Parameters
----------
args, kwargs
See :func:`conesearch`.
Returns
-------
t : float
Run time in seconds.
obj : `astropy.io.votable.tree.Table`
First table from first successful VO service request.
"""
return conesearch(*args, **kwargs)