Debian Codegraph @

astropy_healpix/core.py

raw
1 # Licensed under a 3-clause BSD style license - see LICENSE.rst
2 import math
3
4 import numpy as np
5
6 from astropy import units as u
7 from astropy.coordinates import Longitude, Latitude
8
9 from . import _core
10
11 __all__ = [
12 'nside_to_pixel_area',
13 'nside_to_pixel_resolution',
14 'pixel_resolution_to_nside',
15 'nside_to_npix',
16 'npix_to_nside',
17 'level_to_nside',
18 'nside_to_level',
19 'level_ipix_to_uniq',
20 'uniq_to_level_ipix',
21 'lonlat_to_healpix',
22 'healpix_to_lonlat',
23 'xyz_to_healpix',
24 'healpix_to_xyz',
25 'bilinear_interpolation_weights',
26 'interpolate_bilinear_lonlat',
27 'boundaries_lonlat',
28 'neighbours',
29 ]
30
31 _NUMPY_COPY_IF_NEEDED = False if np.__version__.startswith("1.") else None
32
33
34 def _validate_order(order):
35 # We also support upper-case, to support directly the values
36 # ORDERING = {'RING', 'NESTED'} in FITS headers
37 # This is currently undocumented in the docstrings.
38 if order == 'nested' or order == 'NESTED':
39 return 'nested'
40 elif order == 'ring' or order == 'RING':
41 return 'ring'
42 else:
43 raise ValueError("order must be 'nested' or 'ring'")
44
45
46 def _validate_offset(label, offset):
47 offset = np.asarray(offset)
48 if np.any((offset < 0) | (offset > 1)):
49 raise ValueError(f'd{label} must be in the range [0:1]')
50
51
52 def _validate_level(level):
53 if np.any(level < 0):
54 raise ValueError('level must be positive')
55
56
57 def _validate_nside(nside):
58 log_2_nside = np.round(np.log2(nside))
59 if not np.all(2 ** log_2_nside == nside):
60 raise ValueError('nside must be a power of two')
61
62
63 def _validate_npix(level, ipix):
64 if not np.all(ipix < (3 << 2*(level + 1))):
65 raise ValueError('ipix for a specific level must be inferior to npix')
66
67
68 def level_to_nside(level):
69 """
70 Find the pixel dimensions of the top-level HEALPix tiles.
71
72 This is given by ``nside = 2**level``.
73
74 Parameters
75 ----------
76 level : int
77 The resolution level
78
79 Returns
80 -------
81 nside : int
82 The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
83 """
84 level = np.asarray(level, dtype=np.int64)
85
86 _validate_level(level)
87 return 2 ** level
88
89
90 def nside_to_level(nside):
91 """
92 Find the HEALPix level for a given nside.
93
94 This is given by ``level = log2(nside)``.
95
96 This function is the inverse of `level_to_nside`.
97
98 Parameters
99 ----------
100 nside : int
101 The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
102 Must be a power of two.
103
104 Returns
105 -------
106 level : int
107 The level of the HEALPix cells
108 """
109 nside = np.asarray(nside, dtype=np.int64)
110
111 _validate_nside(nside)
112 return np.log2(nside).astype(np.int64)
113
114
115 def uniq_to_level_ipix(uniq):
116 """
117 Convert a HEALPix cell uniq number to its (level, ipix) equivalent.
118
119 A uniq number is a 64 bits integer equaling to : ipix + 4*(4**level). Please read
120 this `paper <http://ivoa.net/documents/MOC/20140602/REC-MOC-1.0-20140602.pdf>`_
121 for more details about uniq numbers.
122
123 Parameters
124 ----------
125 uniq : int
126 The uniq number of a HEALPix cell.
127
128 Returns
129 -------
130 level, ipix: int, int
131 The level and index of the HEALPix cell computed from ``uniq``.
132 """
133 uniq = np.asarray(uniq, dtype=np.int64)
134
135 level = (np.log2(uniq//4)) // 2
136 level = level.astype(np.int64)
137 _validate_level(level)
138
139 ipix = uniq - (1 << 2*(level + 1))
140 _validate_npix(level, ipix)
141
142 return level, ipix
143
144
145 def level_ipix_to_uniq(level, ipix):
146 """
147 Convert a level and HEALPix index into a uniq number representing the cell.
148
149 This function is the inverse of `uniq_to_level_ipix`.
150
151 Parameters
152 ----------
153 level : int
154 The level of the HEALPix cell
155 ipix : int
156 The index of the HEALPix cell
157
158 Returns
159 -------
160 uniq : int
161 The uniq number representing the HEALPix cell.
162 """
163 level = np.asarray(level, dtype=np.int64)
164 ipix = np.asarray(ipix, dtype=np.int64)
165
166 _validate_level(level)
167 _validate_npix(level, ipix)
168
169 return ipix + (1 << 2*(level + 1))
170
171
172 def nside_to_pixel_area(nside):
173 """
174 Find the area of HEALPix pixels given the pixel dimensions of one of
175 the 12 'top-level' HEALPix tiles.
176
177 Parameters
178 ----------
179 nside : int
180 The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
181
182 Returns
183 -------
184 pixel_area : :class:`~astropy.units.Quantity`
185 The area of the HEALPix pixels
186 """
187 nside = np.asanyarray(nside, dtype=np.int64)
188 _validate_nside(nside)
189 npix = 12 * nside * nside
190 pixel_area = 4 * math.pi / npix * u.sr
191 return pixel_area
192
193
194 def nside_to_pixel_resolution(nside):
195 """
196 Find the resolution of HEALPix pixels given the pixel dimensions of one of
197 the 12 'top-level' HEALPix tiles.
198
199 Parameters
200 ----------
201 nside : int
202 The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
203
204 Returns
205 -------
206 resolution : :class:`~astropy.units.Quantity`
207 The resolution of the HEALPix pixels
208
209 See also
210 --------
211 pixel_resolution_to_nside
212 """
213 nside = np.asanyarray(nside, dtype=np.int64)
214 _validate_nside(nside)
215 return (nside_to_pixel_area(nside) ** 0.5).to(u.arcmin)
216
217
218 def pixel_resolution_to_nside(resolution, round='nearest'):
219 """Find closest HEALPix nside for a given angular resolution.
220
221 This function is the inverse of `nside_to_pixel_resolution`,
222 for the default rounding scheme of ``round='nearest'``.
223
224 If you choose ``round='up'``, you'll get HEALPix pixels that
225 have at least the requested resolution (usually a bit better
226 due to rounding).
227
228 Pixel resolution is defined as square root of pixel area.
229
230 Parameters
231 ----------
232 resolution : `~astropy.units.Quantity`
233 Angular resolution
234 round : {'up', 'nearest', 'down'}
235 Which way to round
236
237 Returns
238 -------
239 nside : int
240 The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
241 Always a power of 2.
242
243 Examples
244 --------
245 >>> from astropy import units as u
246 >>> from astropy_healpix import pixel_resolution_to_nside
247 >>> pixel_resolution_to_nside(13 * u.arcmin)
248 256
249 >>> pixel_resolution_to_nside(13 * u.arcmin, round='up')
250 512
251 """
252 resolution = resolution.to(u.rad).value
253 pixel_area = resolution * resolution
254 npix = 4 * math.pi / pixel_area
255 nside = np.sqrt(npix / 12)
256
257 # Now we have to round to the closest ``nside``
258 # Since ``nside`` must be a power of two,
259 # we first compute the corresponding ``level = log2(nside)`
260 # round the level and then go back to nside
261 level = np.log2(nside)
262
263 if round == 'up':
264 level = np.ceil(level)
265 elif round == 'nearest':
266 level = np.round(level)
267 elif round == 'down':
268 level = np.floor(level)
269 else:
270 raise ValueError(f'Invalid value for round: {round!r}')
271
272 # For very low requested resolution (i.e. large angle values), we
273 # return ``level=0``, i.e. ``nside=1``, i.e. the lowest resolution
274 # that exists with HEALPix
275 level = np.clip(level.astype(int), 0, None)
276
277 return level_to_nside(level)
278
279
280 def nside_to_npix(nside):
281 """
282 Find the number of pixels corresponding to a HEALPix resolution.
283
284 Parameters
285 ----------
286 nside : int
287 The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
288
289 Returns
290 -------
291 npix : int
292 The number of pixels in the HEALPix map.
293 """
294 nside = np.asanyarray(nside, dtype=np.int64)
295 _validate_nside(nside)
296 return 12 * nside ** 2
297
298
299 def npix_to_nside(npix):
300 """
301 Find the number of pixels on the side of one of the 12 'top-level' HEALPix
302 tiles given a total number of pixels.
303
304 Parameters
305 ----------
306 npix : int
307 The number of pixels in the HEALPix map.
308
309 Returns
310 -------
311 nside : int
312 The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
313 """
314
315 npix = np.asanyarray(npix, dtype=np.int64)
316
317 if not np.all(npix % 12 == 0):
318 raise ValueError('Number of pixels must be divisible by 12')
319
320 square_root = np.sqrt(npix / 12)
321 if not np.all(square_root ** 2 == npix / 12):
322 raise ValueError('Number of pixels is not of the form 12 * nside ** 2')
323
324 return np.round(square_root).astype(int)
325
326
327 def healpix_to_lonlat(healpix_index, nside, dx=None, dy=None, order='ring'):
328 """
329 Convert HEALPix indices (optionally with offsets) to longitudes/latitudes.
330
331 If no offsets (``dx`` and ``dy``) are provided, the coordinates will default
332 to those at the center of the HEALPix pixels.
333
334 Parameters
335 ----------
336 healpix_index : int or `~numpy.ndarray`
337 HEALPix indices (as a scalar or array)
338 nside : int or `~numpy.ndarray`
339 Number of pixels along the side of each of the 12 top-level HEALPix tiles
340 dx, dy : float or `~numpy.ndarray`, optional
341 Offsets inside the HEALPix pixel, which must be in the range [0:1],
342 where 0.5 is the center of the HEALPix pixels (as scalars or arrays)
343 order : { 'nested' | 'ring' }, optional
344 Order of HEALPix pixels
345
346 Returns
347 -------
348 lon : :class:`~astropy.coordinates.Longitude`
349 The longitude values
350 lat : :class:`~astropy.coordinates.Latitude`
351 The latitude values
352 """
353
354 _validate_nside(nside)
355
356 if _validate_order(order) == 'ring':
357 func = _core.healpix_ring_to_lonlat
358 else: # _validate_order(order) == 'nested'
359 func = _core.healpix_nested_to_lonlat
360
361 if dx is None:
362 dx = 0.5
363 else:
364 _validate_offset('x', dx)
365 if dy is None:
366 dy = 0.5
367 else:
368 _validate_offset('y', dy)
369
370 nside = np.asarray(nside, dtype=np.intc)
371
372 lon, lat = func(healpix_index, nside, dx, dy)
373
374 lon = Longitude(lon, unit=u.rad, copy=_NUMPY_COPY_IF_NEEDED)
375 lat = Latitude(lat, unit=u.rad, copy=_NUMPY_COPY_IF_NEEDED)
376
377 return lon, lat
378
379
380 def lonlat_to_healpix(lon, lat, nside, return_offsets=False, order='ring'):
381 """
382 Convert longitudes/latitudes to HEALPix indices
383
384 Parameters
385 ----------
386 lon, lat : :class:`~astropy.units.Quantity`
387 The longitude and latitude values as :class:`~astropy.units.Quantity`
388 instances with angle units.
389 nside : int or `~numpy.ndarray`
390 Number of pixels along the side of each of the 12 top-level HEALPix tiles
391 order : { 'nested' | 'ring' }
392 Order of HEALPix pixels
393 return_offsets : bool, optional
394 If `True`, the returned values are the HEALPix pixel indices as well as
395 ``dx`` and ``dy``, the fractional positions inside the pixels. If
396 `False` (the default), only the HEALPix pixel indices is returned.
397
398 Returns
399 -------
400 healpix_index : int or `~numpy.ndarray`
401 The HEALPix indices
402 dx, dy : `~numpy.ndarray`
403 Offsets inside the HEALPix pixel in the range [0:1], where 0.5 is the
404 center of the HEALPix pixels
405 """
406
407 if _validate_order(order) == 'ring':
408 func = _core.lonlat_to_healpix_ring
409 else: # _validate_order(order) == 'nested'
410 func = _core.lonlat_to_healpix_nested
411
412 nside = np.asarray(nside, dtype=np.intc)
413
414 lon = lon.to_value(u.rad)
415 lat = lat.to_value(u.rad)
416
417 healpix_index, dx, dy = func(lon, lat, nside)
418
419 if return_offsets:
420 return healpix_index, dx, dy
421 else:
422 return healpix_index
423
424
425 def healpix_to_xyz(healpix_index, nside, dx=None, dy=None, order='ring'):
426 """
427 Convert HEALPix indices (optionally with offsets) to Cartesian coordinates.
428
429 If no offsets (``dx`` and ``dy``) are provided, the coordinates will default
430 to those at the center of the HEALPix pixels.
431
432 Parameters
433 ----------
434 healpix_index : int or `~numpy.ndarray`
435 HEALPix indices (as a scalar or array)
436 nside : int or `~numpy.ndarray`
437 Number of pixels along the side of each of the 12 top-level HEALPix tiles
438 dx, dy : float or `~numpy.ndarray`, optional
439 Offsets inside the HEALPix pixel, which must be in the range [0:1],
440 where 0.5 is the center of the HEALPix pixels (as scalars or arrays)
441 order : { 'nested' | 'ring' }, optional
442 Order of HEALPix pixels
443
444 Returns
445 -------
446 x, y, z : float or `~numpy.ndarray`
447 The Cartesian coordinate components
448 """
449
450 _validate_nside(nside)
451
452 if _validate_order(order) == 'ring':
453 func = _core.healpix_ring_to_xyz
454 else: # _validate_order(order) == 'nested'
455 func = _core.healpix_nested_to_xyz
456
457 if dx is None:
458 dx = 0.5
459 else:
460 _validate_offset('x', dx)
461 if dy is None:
462 dy = 0.5
463 else:
464 _validate_offset('y', dy)
465
466 nside = np.asarray(nside, dtype=np.intc)
467
468 return func(healpix_index, nside, dx, dy)
469
470
471 def xyz_to_healpix(x, y, z, nside, return_offsets=False, order='ring'):
472 """
473 Convert longitudes/latitudes to HEALPix indices
474
475 Parameters
476 ----------
477 x, y, z : float or `~numpy.ndarray`
478 The Cartesian coordinate components
479 nside : int or `~numpy.ndarray`
480 Number of pixels along the side of each of the 12 top-level HEALPix tiles
481 order : { 'nested' | 'ring' }
482 Order of HEALPix pixels
483 return_offsets : bool, optional
484 If `True`, the returned values are the HEALPix pixel indices as well as
485 ``dx`` and ``dy``, the fractional positions inside the pixels. If
486 `False` (the default), only the HEALPix pixel indices is returned.
487
488 Returns
489 -------
490 healpix_index : int or `~numpy.ndarray`
491 The HEALPix indices
492 dx, dy : `~numpy.ndarray`
493 Offsets inside the HEALPix pixel in the range [0:1], where 0.5 is the
494 center of the HEALPix pixels
495 """
496
497 if _validate_order(order) == 'ring':
498 func = _core.xyz_to_healpix_ring
499 else: # _validate_order(order) == 'nested'
500 func = _core.xyz_to_healpix_nested
501
502 nside = np.asarray(nside, dtype=np.intc)
503
504 healpix_index, dx, dy = func(x, y, z, nside)
505
506 if return_offsets:
507 return healpix_index, dx, dy
508 else:
509 return healpix_index
510
511
512 def nested_to_ring(nested_index, nside):
513 """
514 Convert a HEALPix 'nested' index to a HEALPix 'ring' index
515
516 Parameters
517 ----------
518 nested_index : int or `~numpy.ndarray`
519 Healpix index using the 'nested' ordering
520 nside : int or `~numpy.ndarray`
521 Number of pixels along the side of each of the 12 top-level HEALPix tiles
522
523 Returns
524 -------
525 ring_index : int or `~numpy.ndarray`
526 Healpix index using the 'ring' ordering
527 """
528
529 nside = np.asarray(nside, dtype=np.intc)
530
531 return _core.nested_to_ring(nested_index, nside)
532
533
534 def ring_to_nested(ring_index, nside):
535 """
536 Convert a HEALPix 'ring' index to a HEALPix 'nested' index
537
538 Parameters
539 ----------
540 ring_index : int or `~numpy.ndarray`
541 Healpix index using the 'ring' ordering
542 nside : int or `~numpy.ndarray`
543 Number of pixels along the side of each of the 12 top-level HEALPix tiles
544
545 Returns
546 -------
547 nested_index : int or `~numpy.ndarray`
548 Healpix index using the 'nested' ordering
549 """
550
551 nside = np.asarray(nside, dtype=np.intc)
552
553 return _core.ring_to_nested(ring_index, nside)
554
555
556 def bilinear_interpolation_weights(lon, lat, nside, order='ring'):
557 """
558 Get the four neighbours for each (lon, lat) position and the weight
559 associated with each one for bilinear interpolation.
560
561 Parameters
562 ----------
563 lon, lat : :class:`~astropy.units.Quantity`
564 The longitude and latitude values as :class:`~astropy.units.Quantity`
565 instances with angle units.
566 nside : int
567 Number of pixels along the side of each of the 12 top-level HEALPix tiles
568 order : { 'nested' | 'ring' }
569 Order of HEALPix pixels
570
571 Returns
572 -------
573 indices : `~numpy.ndarray`
574 2-D array with shape (4, N) giving the four indices to use for the
575 interpolation
576 weights : `~numpy.ndarray`
577 2-D array with shape (4, N) giving the four weights to use for the
578 interpolation
579 """
580
581 lon = lon.to_value(u.rad)
582 lat = lat.to_value(u.rad)
583
584 _validate_nside(nside)
585
586 nside = np.asarray(nside, dtype=np.intc)
587
588 result = _core.bilinear_interpolation_weights(lon, lat, nside)
589 indices = np.stack(result[:4])
590 weights = np.stack(result[4:])
591
592 if _validate_order(order) == 'nested':
593 indices = ring_to_nested(indices, nside)
594
595 return indices, weights
596
597
598 def interpolate_bilinear_lonlat(lon, lat, values, order='ring'):
599 """
600 Interpolate values at specific longitudes/latitudes using bilinear interpolation
601
602 Parameters
603 ----------
604 lon, lat : :class:`~astropy.units.Quantity`
605 The longitude and latitude values as :class:`~astropy.units.Quantity` instances
606 with angle units.
607 values : `~numpy.ndarray`
608 Array with the values in each HEALPix pixel. The first dimension should
609 have length 12 * nside ** 2 (and nside is determined automatically from
610 this).
611 order : { 'nested' | 'ring' }
612 Order of HEALPix pixels
613
614 Returns
615 -------
616 result : float `~numpy.ndarray`
617 The interpolated values
618 """
619 nside = npix_to_nside(values.shape[0])
620 indices, weights = bilinear_interpolation_weights(lon, lat, nside, order=order)
621 values = values[indices]
622 # At this point values has shape (N, M) where both N and M might be several
623 # dimensions, and weights has shape (N,), so we need to transpose in order
624 # to benefit from broadcasting, then transpose back so that the dimension
625 # with length 4 is at the start again, ready for summing.
626 result = (values.T * weights.T).T
627 return result.sum(axis=0)
628
629
630 def neighbours(healpix_index, nside, order='ring'):
631 """
632 Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
633
634 Parameters
635 ----------
636 healpix_index : `~numpy.ndarray`
637 Array of HEALPix pixels
638 nside : int
639 Number of pixels along the side of each of the 12 top-level HEALPix tiles
640 order : { 'nested' | 'ring' }
641 Order of HEALPix pixels
642
643 Returns
644 -------
645 neigh : `~numpy.ndarray`
646 Array giving the neighbours starting SW and rotating clockwise. This has
647 one extra dimension compared to ``healpix_index`` - the first dimension -
648 which is set to 8. For example if healpix_index has shape (2, 3),
649 ``neigh`` has shape (8, 2, 3).
650
651 Notes
652 -----
653 Some HEALPix pixels do not have all 8 neighbours. In these cases, the
654 corresponding entry in the returned array has the value of -1 and Numpy
655 may print an invalid value warning. To suppress the warning, use
656 :class:`numpy.errstate`.
657 """
658
659 _validate_nside(nside)
660
661 nside = np.asarray(nside, dtype=np.intc)
662
663 if _validate_order(order) == 'ring':
664 func = _core.neighbours_ring
665 else: # _validate_order(order) == 'nested'
666 func = _core.neighbours_nested
667
668 return np.stack(func(healpix_index, nside))
669
670
671 def healpix_cone_search(lon, lat, radius, nside, order='ring'):
672 """
673 Find all the HEALPix pixels within a given radius of a longitude/latitude.
674
675 Note that this returns all pixels that overlap, including partially, with
676 the search cone. This function can only be used for a single lon/lat pair at
677 a time, since different calls to the function may result in a different
678 number of matches.
679
680 Parameters
681 ----------
682 lon, lat : :class:`~astropy.units.Quantity`
683 The longitude and latitude to search around
684 radius : :class:`~astropy.units.Quantity`
685 The search radius
686 nside : int
687 Number of pixels along the side of each of the 12 top-level HEALPix tiles
688 order : { 'nested' | 'ring' }
689 Order of HEALPix pixels
690
691 Returns
692 -------
693 healpix_index : `~numpy.ndarray`
694 1-D array with all the matching HEALPix pixel indices.
695 """
696
697 lon = lon.to_value(u.deg)
698 lat = lat.to_value(u.deg)
699 radius = radius.to_value(u.deg)
700
701 _validate_nside(nside)
702 order = _validate_order(order)
703
704 return _core.healpix_cone_search(lon, lat, radius, nside, order)
705
706
707 def boundaries_lonlat(healpix_index, step, nside, order='ring'):
708 """
709 Return the longitude and latitude of the edges of HEALPix pixels
710
711 This returns the longitude and latitude of points along the edge of each
712 HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
713 so setting ``step`` to 1 returns just the corners.
714
715 Parameters
716 ----------
717 healpix_index : `~numpy.ndarray`
718 1-D array of HEALPix pixels
719 step : int
720 The number of steps to take along each edge.
721 nside : int
722 Number of pixels along the side of each of the 12 top-level HEALPix tiles
723 order : { 'nested' | 'ring' }
724 Order of HEALPix pixels
725
726 Returns
727 -------
728 lon, lat : :class:`~astropy.units.Quantity`
729 The longitude and latitude, as 2-D arrays where the first dimension is
730 the same as the ``healpix_index`` input, and the second dimension has
731 size ``4 * step``.
732 """
733
734 healpix_index = np.asarray(healpix_index, dtype=np.int64)
735 step = int(step)
736
737 if step < 1:
738 raise ValueError('step must be at least 1')
739
740 # PERF: this could be optimized by writing a Cython routine to do this to
741 # avoid allocating temporary arrays
742
743 frac = np.linspace(0., 1., step + 1)[:-1]
744 dx = np.hstack([1 - frac, np.repeat(0, step), frac, np.repeat(1, step)])
745 dy = np.hstack([np.repeat(1, step), 1 - frac, np.repeat(0, step), frac])
746
747 healpix_index, dx, dy = np.broadcast_arrays(healpix_index.reshape(-1, 1), dx, dy)
748
749 lon, lat = healpix_to_lonlat(healpix_index.ravel(), nside, dx.ravel(), dy.ravel(), order=order)
750
751 lon = lon.reshape(-1, 4 * step)
752 lat = lat.reshape(-1, 4 * step)
753
754 return lon, lat