Debian Codegraph @

astropy_healpix/high_level.py

raw
1 # Licensed under a 3-clause BSD style license - see LICENSE.rst
2 import inspect
3 import os
4
5 from astropy.coordinates import (BaseCoordinateFrame, frame_transform_graph,
6 SkyCoord, UnitSphericalRepresentation)
7
8 from .core import (nside_to_pixel_area, nside_to_pixel_resolution,
9 nside_to_level, nside_to_npix, npix_to_nside,
10 healpix_to_lonlat, lonlat_to_healpix,
11 healpix_to_xyz, xyz_to_healpix,
12 bilinear_interpolation_weights, interpolate_bilinear_lonlat,
13 ring_to_nested, nested_to_ring, healpix_cone_search,
14 boundaries_lonlat, neighbours, _validate_order,
15 _NUMPY_COPY_IF_NEEDED)
16 from .utils import parse_input_healpix_data
17
18 __all__ = ['HEALPix']
19
20
21 NO_FRAME_MESSAGE = """
22 No frame was specified when initializing HEALPix, so SkyCoord objects cannot be
23 returned. Either specify a frame when initializing HEALPix or use the {0}
24 method.
25 """.replace(os.linesep, ' ').strip()
26
27
28 class NoFrameError(Exception):
29 def __init__(self, alternative_method):
30 super().__init__(NO_FRAME_MESSAGE.format(alternative_method))
31
32
33 def _get_frame(frame):
34 """
35 Get a frame instance or None, from the input `frame`, which could be a
36 frame name string, frame instance, or frame class.
37
38 Adapted from
39 :meth:`astropy.coordinates.sky_coordinate_parsers._get_frame_class`.
40 """
41
42 if frame is None or isinstance(frame, BaseCoordinateFrame):
43 return frame
44
45 elif isinstance(frame, str):
46 frame_cls = frame_transform_graph.lookup_name(frame)
47 if frame_cls is None:
48 frame_names = frame_transform_graph.get_names()
49 raise ValueError('Coordinate frame name "{}" is not a known '
50 'coordinate frame ({})'
51 .format(frame, sorted(frame_names)))
52 return frame_cls()
53
54 elif inspect.isclass(frame) and issubclass(frame, BaseCoordinateFrame):
55 return frame()
56
57 else:
58 raise ValueError("Coordinate frame must be a frame name, frame "
59 "instance, frame class, or None, not a '{}'"
60 .format(frame.__class__.__name__))
61
62
63 class HEALPix:
64 """
65 A HEALPix pixellization.
66
67 Parameters
68 ----------
69 nside : int
70 Number of pixels along the side of each of the 12 top-level HEALPix tiles
71 order : { 'nested' | 'ring' }, optional
72 Order of HEALPix pixels. Input string can be lower or upper case.
73 frame : str or :class:`~astropy.coordinates.BaseCoordinateFrame`, optional
74 The celestial coordinate frame of the pixellization. This can be
75 ommitted, in which case the pixellization will not be attached to any
76 particular celestial frame, and the methods ending in _skycoord will
77 not work (but the _lonlat methods will still work and continue to
78 return generic longitudes/latitudes). The frame may be passed as a
79 string (such as ``galactic``), as a frame class, or as an instance of
80 a frame class.
81
82 Raises
83 ------
84 ValueError
85 If 'order' is not one of the allowed options.
86 """
87
88 def __init__(self, nside=None, order='ring', frame=None):
89 if nside is None:
90 raise ValueError('nside has not been set')
91 self.nside = nside
92 self.order = _validate_order(order)
93 self.frame = _get_frame(frame)
94
95 @classmethod
96 def from_header(cls, input_data, field=0, hdu_in=None, nested=None):
97 """
98 Parameters
99 ----------
100 input_data : str or `~astropy.io.fits.TableHDU` or `~astropy.io.fits.BinTableHDU` or tuple
101 The input data to reproject. This can be:
102
103 * The name of a HEALPIX FITS file
104 * A `~astropy.io.fits.TableHDU` or `~astropy.io.fits.BinTableHDU`
105 instance
106 * A tuple where the first element is a `~numpy.ndarray` and the
107 second element is a `~astropy.coordinates.BaseCoordinateFrame`
108 instance or a string alias for a coordinate frame.
109
110 hdu_in : int or str, optional
111 If ``input_data`` is a FITS file, specifies the HDU to use.
112 (the default HDU for HEALPIX data is 1, unlike with image files where
113 it is generally 0)
114 nested : bool, optional
115 The order of the healpix_data, either nested (True) or ring (False).
116 If a FITS file is passed in, this is determined from the header.
117
118 Returns
119 -------
120 healpix : `~astropy_healpix.HEALPix`
121 A HEALPix pixellization corresponding to the input data.
122 """
123 array_in, frame, nested = parse_input_healpix_data(
124 input_data, field=field, hdu_in=hdu_in, nested=nested)
125 nside = npix_to_nside(len(array_in))
126 order = 'nested' if nested else 'ring'
127 return cls(nside=nside, order=order, frame=frame)
128
129 @property
130 def pixel_area(self):
131 """
132 The area of a single HEALPix pixel.
133 """
134 return nside_to_pixel_area(self.nside)
135
136 @property
137 def pixel_resolution(self):
138 """
139 The resolution of a single HEALPix pixel.
140 """
141 return nside_to_pixel_resolution(self.nside)
142
143 @property
144 def npix(self):
145 """
146 The number of pixels in the pixellization of the sphere.
147 """
148 return nside_to_npix(self.nside)
149
150 @property
151 def level(self):
152 """
153 The HEALPix level.
154 """
155 return nside_to_level(self.nside)
156
157 def healpix_to_lonlat(self, healpix_index, dx=None, dy=None):
158 """
159 Convert HEALPix indices (optionally with offsets) to longitudes/latitudes
160
161 Parameters
162 ----------
163 healpix_index : `~numpy.ndarray`
164 1-D array of HEALPix indices
165 dx, dy : `~numpy.ndarray`, optional
166 1-D arrays of offsets inside the HEALPix pixel, which must be in
167 the range [0:1] (0.5 is the center of the HEALPix pixels). If not
168 specified, the position at the center of the pixel is used.
169
170 Returns
171 -------
172 lon : :class:`~astropy.coordinates.Longitude`
173 The longitude values
174 lat : :class:`~astropy.coordinates.Latitude`
175 The latitude values
176 """
177 return healpix_to_lonlat(healpix_index, self.nside, dx=dx, dy=dy, order=self.order)
178
179 def lonlat_to_healpix(self, lon, lat, return_offsets=False):
180 """
181 Convert longitudes/latitudes to HEALPix indices (optionally with offsets)
182
183 Parameters
184 ----------
185 lon, lat : :class:`~astropy.units.Quantity`
186 The longitude and latitude values as :class:`~astropy.units.Quantity` instances
187 with angle units.
188 return_offsets : bool
189 If `True`, the returned values are the HEALPix pixel as well as
190 ``dx`` and ``dy``, the fractional positions inside the pixel. If
191 `False` (the default), only the HEALPix pixel is returned.
192
193 Returns
194 -------
195 healpix_index : `~numpy.ndarray`
196 1-D array of HEALPix indices
197 dx, dy : `~numpy.ndarray`
198 1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
199 is the center of the HEALPix pixels). This is returned if
200 ``return_offsets`` is `True`.
201 """
202 return lonlat_to_healpix(lon, lat, self.nside,
203 return_offsets=return_offsets, order=self.order)
204
205 def healpix_to_xyz(self, healpix_index, dx=None, dy=None):
206 """
207 Convert HEALPix indices (optionally with offsets) to Cartesian coordinates
208
209 Parameters
210 ----------
211 healpix_index : `~numpy.ndarray`
212 1-D array of HEALPix indices
213 dx, dy : `~numpy.ndarray`, optional
214 1-D arrays of offsets inside the HEALPix pixel, which must be in
215 the range [0:1] (0.5 is the center of the HEALPix pixels). If not
216 specified, the position at the center of the pixel is used.
217
218 Returns
219 -------
220 x : :class:`~numpy.ndarray`
221 The x coordinates
222 y : :class:`~numpy.ndarray`
223 The y coordinates
224 z : :class:`~numpy.ndarray`
225 The z coordinates
226 """
227 return healpix_to_xyz(healpix_index, self.nside, dx=dx, dy=dy, order=self.order)
228
229 def xyz_to_healpix(self, x, y, z, return_offsets=False):
230 """
231 Convert Cartesian coordinates to HEALPix indices (optionally with offsets)
232
233 Parameters
234 ----------
235 x : :class:`~numpy.ndarray`
236 The x coordinates
237 y : :class:`~numpy.ndarray`
238 The y coordinates
239 z : :class:`~numpy.ndarray`
240 The z coordinates
241 return_offsets : bool
242 If `True`, the returned values are the HEALPix pixel as well as
243 ``dx`` and ``dy``, the fractional positions inside the pixel. If
244 `False` (the default), only the HEALPix pixel is returned.
245
246 Returns
247 -------
248 healpix_index : `~numpy.ndarray`
249 1-D array of HEALPix indices
250 dx, dy : `~numpy.ndarray`
251 1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
252 is the center of the HEALPix pixels). This is returned if
253 ``return_offsets`` is `True`.
254 """
255 return xyz_to_healpix(x, y, z, self.nside,
256 return_offsets=return_offsets, order=self.order)
257
258 def nested_to_ring(self, nested_index):
259 """
260 Convert a healpix 'nested' index to a healpix 'ring' index
261
262 Parameters
263 ----------
264 nested_index : `~numpy.ndarray`
265 Healpix index using the 'nested' ordering
266
267 Returns
268 -------
269 ring_index : `~numpy.ndarray`
270 Healpix index using the 'ring' ordering
271 """
272 return nested_to_ring(nested_index, self.nside)
273
274 def ring_to_nested(self, ring_index):
275 """
276 Convert a healpix 'ring' index to a healpix 'nested' index
277
278 Parameters
279 ----------
280 ring_index : `~numpy.ndarray`
281 Healpix index using the 'ring' ordering
282
283 Returns
284 -------
285 nested_index : `~numpy.ndarray`
286 Healpix index using the 'nested' ordering
287 """
288 return ring_to_nested(ring_index, self.nside)
289
290 def bilinear_interpolation_weights(self, lon, lat):
291 """
292 Get the four neighbours for each (lon, lat) position and the weight
293 associated with each one for bilinear interpolation.
294
295 Parameters
296 ----------
297 lon, lat : :class:`~astropy.units.Quantity`
298 The longitude and latitude values as
299 :class:`~astropy.units.Quantity` instances with angle units.
300
301 Returns
302 -------
303 indices : `~numpy.ndarray`
304 2-D array with shape (4, N) giving the four indices to use for the
305 interpolation
306 weights : `~numpy.ndarray`
307 2-D array with shape (4, N) giving the four weights to use for the
308 interpolation
309 """
310 return bilinear_interpolation_weights(lon, lat, self.nside, order=self.order)
311
312 def interpolate_bilinear_lonlat(self, lon, lat, values):
313 """
314 Interpolate values at specific longitudes/latitudes using bilinear interpolation
315
316 If a position does not have four neighbours, this currently returns NaN.
317
318 Parameters
319 ----------
320 lon, lat : :class:`~astropy.units.Quantity`
321 The longitude and latitude values as :class:`~astropy.units.Quantity` instances
322 with angle units.
323 values : `~numpy.ndarray`
324 1-D array with the values in each HEALPix pixel. This must have a
325 length of the form 12 * nside ** 2 (and nside is determined
326 automatically from this).
327
328 Returns
329 -------
330 result : `~numpy.ndarray`
331 1-D array of interpolated values
332 """
333 if len(values) != self.npix:
334 raise ValueError('values must be an array of length {} (got {})'
335 .format(self.npix, len(values)))
336 return interpolate_bilinear_lonlat(lon, lat, values, order=self.order)
337
338 def cone_search_lonlat(self, lon, lat, radius):
339 """
340 Find all the HEALPix pixels within a given radius of a longitude/latitude.
341
342 Note that this returns all pixels that overlap, including partially, with
343 the search cone. This function can only be used for a single lon/lat pair at
344 a time, since different calls to the function may result in a different
345 number of matches.
346
347 Parameters
348 ----------
349 lon, lat : :class:`~astropy.units.Quantity`
350 The longitude and latitude to search around
351 radius : :class:`~astropy.units.Quantity`
352 The search radius
353
354 Returns
355 -------
356 healpix_index : `~numpy.ndarray`
357 1-D array with all the matching HEALPix pixel indices.
358 """
359 if not lon.isscalar or not lat.isscalar or not radius.isscalar:
360 raise ValueError('The longitude, latitude and radius must be '
361 'scalar Quantity objects')
362 return healpix_cone_search(lon, lat, radius, self.nside, order=self.order)
363
364 def boundaries_lonlat(self, healpix_index, step):
365 """
366 Return the longitude and latitude of the edges of HEALPix pixels
367
368 This returns the longitude and latitude of points along the edge of each
369 HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
370 so setting ``step`` to 1 returns just the corners.
371
372 Parameters
373 ----------
374 healpix_index : `~numpy.ndarray`
375 1-D array of HEALPix pixels
376 step : int
377 The number of steps to take along each edge.
378
379 Returns
380 -------
381 lon, lat : :class:`~astropy.units.Quantity`
382 The longitude and latitude, as 2-D arrays where the first dimension is
383 the same as the ``healpix_index`` input, and the second dimension has
384 size ``4 * step``.
385 """
386 return boundaries_lonlat(healpix_index, step, self.nside, order=self.order)
387
388 def neighbours(self, healpix_index):
389 """
390 Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
391
392 Parameters
393 ----------
394 healpix_index : `~numpy.ndarray`
395 Array of HEALPix pixels
396
397 Returns
398 -------
399 neigh : `~numpy.ndarray`
400 Array giving the neighbours starting SW and rotating clockwise. This has
401 one extra dimension compared to ``healpix_index`` - the first dimension -
402 which is set to 8. For example if healpix_index has shape (2, 3),
403 ``neigh`` has shape (8, 2, 3).
404
405 Notes
406 -----
407 Some HEALPix pixels do not have all 8 neighbours. In these cases, the
408 corresponding entry in the returned array has the value of -1 and Numpy
409 may print an invalid value warning. To suppress the warning, use
410 :class:`numpy.errstate`.
411 """
412 return neighbours(healpix_index, self.nside, order=self.order)
413
414 def healpix_to_skycoord(self, healpix_index, dx=None, dy=None):
415 """
416 Convert HEALPix indices (optionally with offsets) to celestial coordinates.
417
418 Note that this method requires that a celestial frame was specified when
419 initializing HEALPix. If you don't know or need the celestial frame, you
420 can instead use :meth:`~astropy_healpix.HEALPix.healpix_to_lonlat`.
421
422 Parameters
423 ----------
424 healpix_index : `~numpy.ndarray`
425 1-D array of HEALPix indices
426 dx, dy : `~numpy.ndarray`, optional
427 1-D arrays of offsets inside the HEALPix pixel, which must be in
428 the range [0:1] (0.5 is the center of the HEALPix pixels). If not
429 specified, the position at the center of the pixel is used.
430
431 Returns
432 -------
433 coord : :class:`~astropy.coordinates.SkyCoord`
434 The resulting celestial coordinates
435 """
436 if self.frame is None:
437 raise NoFrameError("healpix_to_skycoord")
438 lon, lat = self.healpix_to_lonlat(healpix_index, dx=dx, dy=dy)
439 representation = UnitSphericalRepresentation(lon, lat, copy=_NUMPY_COPY_IF_NEEDED)
440 return SkyCoord(self.frame.realize_frame(representation))
441
442 def skycoord_to_healpix(self, skycoord, return_offsets=False):
443 """
444 Convert celestial coordinates to HEALPix indices (optionally with offsets).
445
446 Note that this method requires that a celestial frame was specified when
447 initializing HEALPix. If you don't know or need the celestial frame, you
448 can instead use :meth:`~astropy_healpix.HEALPix.lonlat_to_healpix`.
449
450 Parameters
451 ----------
452 skycoord : :class:`~astropy.coordinates.SkyCoord`
453 The celestial coordinates to convert
454 return_offsets : bool
455 If `True`, the returned values are the HEALPix pixel as well as
456 ``dx`` and ``dy``, the fractional positions inside the pixel. If
457 `False` (the default), only the HEALPix pixel is returned.
458
459 Returns
460 -------
461 healpix_index : `~numpy.ndarray`
462 1-D array of HEALPix indices
463 dx, dy : `~numpy.ndarray`
464 1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
465 is the center of the HEALPix pixels). This is returned if
466 ``return_offsets`` is `True`.
467 """
468 if self.frame is None:
469 raise NoFrameError("skycoord_to_healpix")
470 skycoord = skycoord.transform_to(self.frame)
471 representation = skycoord.represent_as(UnitSphericalRepresentation)
472 lon, lat = representation.lon, representation.lat
473 return self.lonlat_to_healpix(lon, lat, return_offsets=return_offsets)
474
475 def interpolate_bilinear_skycoord(self, skycoord, values):
476 """
477 Interpolate values at specific celestial coordinates using bilinear interpolation.
478
479 If a position does not have four neighbours, this currently returns NaN.
480
481 Note that this method requires that a celestial frame was specified when
482 initializing HEALPix. If you don't know or need the celestial frame, you
483 can instead use :meth:`~astropy_healpix.HEALPix.interpolate_bilinear_lonlat`.
484
485 Parameters
486 ----------
487 skycoord : :class:`~astropy.coordinates.SkyCoord`
488 The celestial coordinates at which to interpolate
489 values : `~numpy.ndarray`
490 1-D array with the values in each HEALPix pixel. This must have a
491 length of the form 12 * nside ** 2 (and nside is determined
492 automatically from this).
493
494 Returns
495 -------
496 result : `~numpy.ndarray`
497 1-D array of interpolated values
498 """
499 if self.frame is None:
500 raise NoFrameError("interpolate_bilinear_skycoord")
501 skycoord = skycoord.transform_to(self.frame)
502 representation = skycoord.represent_as(UnitSphericalRepresentation)
503 lon, lat = representation.lon, representation.lat
504 return self.interpolate_bilinear_lonlat(lon, lat, values)
505
506 def cone_search_skycoord(self, skycoord, radius):
507 """
508 Find all the HEALPix pixels within a given radius of a celestial position.
509
510 Note that this returns all pixels that overlap, including partially,
511 with the search cone. This function can only be used for a single
512 celestial position at a time, since different calls to the function may
513 result in a different number of matches.
514
515 This method requires that a celestial frame was specified when
516 initializing HEALPix. If you don't know or need the celestial frame,
517 you can instead use :meth:`~astropy_healpix.HEALPix.cone_search_lonlat`.
518
519 Parameters
520 ----------
521 skycoord : :class:`~astropy.coordinates.SkyCoord`
522 The celestial coordinates to use for the cone search
523 radius : :class:`~astropy.units.Quantity`
524 The search radius
525
526 Returns
527 -------
528 healpix_index : `~numpy.ndarray`
529 1-D array with all the matching HEALPix pixel indices.
530 """
531 if self.frame is None:
532 raise NoFrameError("cone_search_skycoord")
533 skycoord = skycoord.transform_to(self.frame)
534 representation = skycoord.represent_as(UnitSphericalRepresentation)
535 lon, lat = representation.lon, representation.lat
536 return self.cone_search_lonlat(lon, lat, radius)
537
538 def boundaries_skycoord(self, healpix_index, step):
539 """
540 Return the celestial coordinates of the edges of HEALPix pixels
541
542 This returns the celestial coordinates of points along the edge of each
543 HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
544 so setting ``step`` to 1 returns just the corners.
545
546 This method requires that a celestial frame was specified when
547 initializing HEALPix. If you don't know or need the celestial frame,
548 you can instead use :meth:`~astropy_healpix.HEALPix.boundaries_lonlat`.
549
550 Parameters
551 ----------
552 healpix_index : `~numpy.ndarray`
553 1-D array of HEALPix pixels
554 step : int
555 The number of steps to take along each edge.
556
557 Returns
558 -------
559 skycoord : :class:`~astropy.coordinates.SkyCoord`
560 The celestial coordinates of the HEALPix pixel boundaries
561 """
562 if self.frame is None:
563 raise NoFrameError("boundaries_skycoord")
564 lon, lat = self.boundaries_lonlat(healpix_index, step)
565 representation = UnitSphericalRepresentation(lon, lat, copy=_NUMPY_COPY_IF_NEEDED)
566 return SkyCoord(self.frame.realize_frame(representation))