Loading [MathJax]/extensions/tex2jax.js
LSST Applications g0fba68d861+05816baf74,g1ec0fe41b4+f536777771,g1fd858c14a+a9301854fb,g35bb328faa+fcb1d3bbc8,g4af146b050+a5c07d5b1d,g4d2262a081+6e5fcc2a4e,g53246c7159+fcb1d3bbc8,g56a49b3a55+9c12191793,g5a012ec0e7+3632fc3ff3,g60b5630c4e+ded28b650d,g67b6fd64d1+ed4b5058f4,g78460c75b0+2f9a1b4bcd,g786e29fd12+cf7ec2a62a,g8352419a5c+fcb1d3bbc8,g87b7deb4dc+7b42cf88bf,g8852436030+e5453db6e6,g89139ef638+ed4b5058f4,g8e3bb8577d+d38d73bdbd,g9125e01d80+fcb1d3bbc8,g94187f82dc+ded28b650d,g989de1cb63+ed4b5058f4,g9d31334357+ded28b650d,g9f33ca652e+50a8019d8c,gabe3b4be73+1e0a283bba,gabf8522325+fa80ff7197,gb1101e3267+d9fb1f8026,gb58c049af0+f03b321e39,gb665e3612d+2a0c9e9e84,gb89ab40317+ed4b5058f4,gcf25f946ba+e5453db6e6,gd6cbbdb0b4+bb83cc51f8,gdd1046aedd+ded28b650d,gde0f65d7ad+941d412827,ge278dab8ac+d65b3c2b70,ge410e46f29+ed4b5058f4,gf23fb2af72+b7cae620c0,gf5e32f922b+fcb1d3bbc8,gf67bdafdda+ed4b5058f4,w.2025.16
LSST Data Management Base Package
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
_healpixPixelization.py
Go to the documentation of this file.
1# This file is part of sphgeom.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
27__all__ = ["HealpixPixelization"]
28
29import hpgeom as hpg
30import numpy as np
31
32from ._sphgeom import Box, Circle, ConvexPolygon, Ellipse, LonLat, RangeSet, Region, UnitVector3d
33from .pixelization_abc import PixelizationABC
34
35
37 """HEALPix pixelization class.
38
39 Parameters
40 ----------
41 level : `int`
42 Pixelization level. HEALPix nside = 2**level
43 """
44
45 MAX_LEVEL = 17
46
47 def __init__(self, level: int):
48 if level < 0:
49 raise ValueError("HealPix level must be >= 0.")
50
51 self._level = level
52 self._nside = 2**level
53
54 self._npix = hpg.nside_to_npixel(self._nside)
55
56 # Values used to do pixel/region intersections
57 self._bit_shift = 8
58 self._nside_highres = self._nside * (2 ** (self._bit_shift // 2))
59
60 @property
61 def nside(self):
62 return self._nside
63
64 def getLevel(self):
65 return self._level
66
67 level = property(getLevel)
68
69 def universe(self) -> RangeSet:
70 return RangeSet(0, self._npix)
71
72 def pixel(self, i) -> Region:
73 # This is arbitrarily returning 4 points on a side
74 # to approximate the pixel shape.
75 varr = hpg.angle_to_vector(*hpg.boundaries(self._nside, i, step=4))
76 return ConvexPolygon([UnitVector3d(*c) for c in varr])
77
78 def index(self, v: UnitVector3d) -> int:
79 return hpg.vector_to_pixel(self._nside, v.x(), v.y(), v.z())
80
81 def toString(self, i: int) -> str:
82 return str(i)
83
84 def envelope(self, region: Region, maxRanges: int = 0):
85 if maxRanges > 0:
86 # If this is important, the rangeset can be consolidated.
87 raise NotImplementedError("HealpixPixelization: maxRanges not implemented")
88 pixels_highres = self._interior_pixels_from_region(self._nside_highres, region)
89
90 # Dilate the high resolution pixels by one to ensure that the full
91 # region is completely covered at high resolution.
92 neighbors = hpg.neighbors(self._nside_highres, pixels_highres).ravel()
93 # Shift back to the original resolution and uniquify
94 pixels = np.unique(np.right_shift(neighbors[neighbors >= 0], self._bit_shift))
95
96 return RangeSet(pixels)
97
98 def interior(self, region: Region, maxRanges: int = 0):
99 if maxRanges > 0:
100 # If this is important, the rangeset can be consolidated.
101 raise NotImplementedError("HealpixPixelization: maxRanges not implemented")
102 pixels = self._interior_pixels_from_region(self._nside, region)
103
104 # Check that the corners of the pixels are entirely enclosed in
105 # the region
106
107 # Returns arrays [npixels, ncorners], where ncorners is 4.
108 corners_lon, corners_lat = hpg.boundaries(self._nside, pixels, step=1, degrees=False)
109
110 corners_int = region.contains(corners_lon.ravel(), corners_lat.ravel()).reshape((len(pixels), 4))
111 interior = np.sum(corners_int, axis=1) == 4
112 pixels = pixels[interior]
113
114 return RangeSet(pixels)
115
116 def _interior_pixels_from_region(self, nside: int, region: Region):
117 """Get interior pixels from a region.
118
119 Parameters
120 ----------
121 nside : `int`
122 Healpix nside to retrieve interior pixels.
123 region : `lsst.sphgeom.Region`
124 Sphgeom region to find interior pixels.
125
126 Returns
127 -------
128 pixels : `np.ndarray`
129 Array of pixels at resolution nside, nest ordering.
130 """
131 if isinstance(region, Circle):
132 center = LonLat(region.getCenter())
133 radius_rad = region.getOpeningAngle().asRadians()
134 if radius_rad > 0:
135 pixels = hpg.query_circle(
136 nside,
137 center.getLon().asRadians(),
138 center.getLat().asRadians(),
139 radius_rad,
140 degrees=False,
141 )
142 elif radius_rad == 0:
143 pixels = hpg.angle_to_pixel(
144 nside,
145 center.getLon().asRadians(),
146 center.getLat().asRadians(),
147 degrees=False,
148 )
149 else:
150 raise ValueError("Invalid circle radius.")
151 elif isinstance(region, ConvexPolygon):
152 vertices = np.array([[v.x(), v.y(), v.z()] for v in region.getVertices()])
153 pixels = hpg.query_polygon_vec(nside, vertices)
154 elif isinstance(region, Box):
155 pixels = hpg.query_box(
156 nside,
157 region.getLon().getA().asRadians(),
158 region.getLon().getB().asRadians(),
159 region.getLat().getA().asRadians(),
160 region.getLat().getB().asRadians(),
161 degrees=False,
162 )
163 elif isinstance(region, Ellipse):
164 # hpgeom supports query_ellipse given center, alpha, beta,
165 # and orientation. However, until we figure out how to get
166 # the orientation out of the Ellipse region, we will use the
167 # bounding circle as was done with healpy.
168 _circle = region.getBoundingCircle()
169 center = LonLat(_circle.getCenter())
170 pixels = hpg.query_circle(
171 nside,
172 center.getLon().asRadians(),
173 center.getLat().asRadians(),
174 _circle.getOpeningAngle().asRadians(),
175 degrees=False,
176 )
177 else:
178 raise ValueError("Invalid region.")
179
180 return pixels
181
182 def __eq__(self, other):
183 if isinstance(other, HealpixPixelization):
184 return self._level == other._level
185
186 def __repr__(self):
187 return f"HealpixPixelization({self._level})"
188
189 def __reduce__(self):
190 return (self.__class__, (self._level,))
ConvexPolygon is a closed convex polygon on the unit sphere.
LonLat represents a spherical coordinate (longitude/latitude angle) pair.
Definition LonLat.h:55
A RangeSet is a set of unsigned 64 bit integers.
Definition RangeSet.h:106
UnitVector3d is a unit vector in ℝ³ with components stored in double precision.