-
Notifications
You must be signed in to change notification settings - Fork 14
/
healpix.py
422 lines (371 loc) · 12.4 KB
/
healpix.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
import sys
import distutils.sysconfig as sysconfig
import ctypes
import ctypes.util
from numpy.ctypeslib import ndpointer
import numpy as np
from pathlib import Path
# healpy number to represent bad numbers
UNSEEN = -1.6375e+30
# Find and load the library
_lib = None
_libname = ctypes.util.find_library("healpix_c")
_ext_suffix = sysconfig.get_config_var("EXT_SUFFIX")
if _libname:
_lib = ctypes.CDLL(_libname)
if _lib is None:
# Add top-level mwdust repository directory for pip install (-e) .,
# just becomes site-packages for regular install
paths = sys.path
paths.append(str(Path(__file__).parent.parent.parent.absolute()))
for path in [Path(p) for p in paths]:
if not path.is_dir():
continue
try:
_lib = ctypes.CDLL(str(path / f"healpix_c{_ext_suffix}"))
except OSError:
_lib = None
else:
break
if _lib is None:
raise IOError("healpix/C module not found")
# useful utilities: http:https://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
def check_nside(nside, nest=False):
"""
Utility function
Check if healpix map with nside is valid in general
"""
# nside can only be a power of 2 for nest, but generally less than 2**29
nside_arr = np.array(nside).astype(np.int64)
is_ok = True
if np.all(np.logical_and(np.logical_and(nside == nside_arr, np.all(np.less(0, nside))), nside_arr <= 2**29)):
if nest:
is_ok = (nside_arr & (nside_arr - 1)) == 0
else:
is_ok = False
if not is_ok:
raise ValueError(f"{nside} is not valid")
def check_npix(npix):
"""
Utility function
Check if total pixel number of a healpix map are valid in general
"""
# check if npix is a valid value for healpix map size
nside = np.sqrt(np.asarray(npix) / 12.0)
if nside != np.floor(nside):
raise ValueError(f"{npix} is not a valid value for healpix map size")
def check_ipix_nside(ipix, nside):
"""
Utility function
Check if pixel number(s) are valid in a healpix map with nside
"""
# check if all ipix are valid for a healpix map size
if not np.all(ipix <= nside2npix(nside)):
raise ValueError(f"Not all ipix are valid for such healpix map size")
def npix2nside(npix):
"""
Utility function
Give the nside parameter for the given number of pixels.
"""
check_npix(npix)
return int(np.sqrt(npix / 12.0))
def lonlat2thetaphi(lon, lat):
"""
NAME:
lonlat2thetaphi
PURPOSE:
Angular coordinates convsrion: longitude and latitude (deg) to colatitude/longitude (rad)
INPUT:
lon, lat - longitude and latitude (deg)
OUTPUT:
HISTORY:
2023-03-01 - Written - Henry Leung (Toronto)
"""
return np.pi / 2.0 - np.radians(lat), np.radians(lon)
def thetaphi2lonlat(theta, phi):
"""
NAME:
thetaphi2lonlat
PURPOSE:
Angular coordinates convsrion: colatitude/longitude (rad) to longitude and latitude (deg)
INPUT:
theta, phi - colatitude/longitude (rad)
OUTPUT:
lon, lat - longitude and latitude (deg)
HISTORY:
2023-03-01 - Written - Henry Leung (Toronto)
"""
return np.degrees(phi), 90.0 - np.degrees(theta)
def ang2pix(nside, theta, phi, nest=False, lonlat=False):
"""
NAME:
ang2pix
PURPOSE:
Angular coordinates to healpix map pixel number
INPUT:
nside - a integer of healpix map nside
theta - colatitude
phi - longitude
nest - is using NEST?
lonlat - input in longitude and latitude (deg)?
OUTPUT:
ipix - pixel numbers
HISTORY:
2023-03-01 - Written - Henry Leung (Toronto)
"""
check_nside(nside)
theta, phi = np.atleast_1d(np.asarray(theta)), np.atleast_1d(np.asarray(phi))
nstars = len(theta)
if lonlat:
theta, phi = lonlat2thetaphi(theta, phi)
if nest is False:
raise NotImplementedError("RING scheme is not avaliable for now")
# ang2pix_c = _lib.ang2pix_ring
else:
ang2pix_c = _lib.ang2pix_nest
ndarrayFlags = ("C_CONTIGUOUS", "WRITEABLE")
ang2pix_c.argtypes = [
ctypes.c_long,
ndpointer(dtype=np.float64, flags=ndarrayFlags),
ndpointer(dtype=np.float64, flags=ndarrayFlags),
ctypes.c_long,
]
ang2pix_c.restype = ctypes.POINTER(ctypes.c_longlong)
# Array requirements, first store old order
f_cont = [theta.flags["F_CONTIGUOUS"], phi.flags["F_CONTIGUOUS"]]
theta = np.require(theta, dtype=np.float64, requirements=["C", "W"])
phi = np.require(phi, dtype=np.float64, requirements=["C", "W"])
res = ang2pix_c(
ctypes.c_long(nside),
theta.astype(np.float64, order="C", copy=False),
phi.astype(np.float64, order="C", copy=False),
ctypes.c_long(nstars),
)
result = np.fromiter(res, dtype=np.int32, count=nstars)
# Reset input arrays
if f_cont[0]:
theta = np.asfortranarray(theta)
if f_cont[1]:
phi = np.asfortranarray(phi)
return result
def ang2vec(theta, phi, lonlat=False):
"""
NAME:
ang2vec
PURPOSE:
Angular coordinates to unit 3-vector direction
INPUT:
theta - colatitude
phi - longitude
lonlat - input in longitude and latitude (deg)?
OUTPUT:
x, y, z - unit 3-vector direction
HISTORY:
2023-03-01 - Written - Henry Leung (Toronto)
"""
theta, phi = np.atleast_1d(np.asarray(theta)), np.atleast_1d(np.asarray(phi))
nstars = len(theta)
if lonlat:
theta, phi = lonlat2thetaphi(theta, phi)
ang2vec_c = _lib.ang2vec
ndarrayFlags = ("C_CONTIGUOUS", "WRITEABLE")
ang2vec_c.argtypes = [
ndpointer(dtype=np.float64, flags=ndarrayFlags),
ndpointer(dtype=np.float64, flags=ndarrayFlags),
ctypes.c_long,
]
ang2vec_c.restype = ctypes.POINTER(ctypes.c_double)
# Array requirements, first store old order
f_cont = [theta.flags["F_CONTIGUOUS"], phi.flags["F_CONTIGUOUS"]]
theta = np.require(theta, dtype=np.float64, requirements=["C", "W"])
phi = np.require(phi, dtype=np.float64, requirements=["C", "W"])
res = ang2vec_c(
theta.astype(np.float64, order="C", copy=False),
phi.astype(np.float64, order="C", copy=False),
ctypes.c_long(nstars),
)
result = np.fromiter(res, dtype=np.float64, count=nstars*3)
result = result.reshape(nstars, 3)
# Reset input arrays
if f_cont[0]:
theta = np.asfortranarray(theta)
if f_cont[1]:
phi = np.asfortranarray(phi)
return result
def pix2vec(nside, ipix, nest=False):
"""
NAME:
pix2vec
PURPOSE:
Pixel number to unit 3-vector direction
INPUT:
nside - a integer of healpix map nside
ipix - a (list) of integer of pixel number
nest - is using NEST?
OUTPUT:
x, y, z - unit 3-vector direction
HISTORY:
2023-03-01 - Written - Henry Leung (Toronto)
"""
ipix = np.asarray(ipix)
check_nside(nside, nest=nest)
check_ipix_nside(ipix, nside)
ipix = np.atleast_1d(ipix)
npix = len(ipix)
if nest:
pix2vec_c = _lib.pix2vec_nest
else:
raise NotImplementedError("RING scheme is not avaliable for now")
# _lib.pix2ang_ring
ndarrayFlags = ("C_CONTIGUOUS", "WRITEABLE")
# (int nside, int npix, long long int *ipix)
pix2vec_c.argtypes = [
ctypes.c_long,
ctypes.c_long,
ndpointer(dtype=np.int64, flags=ndarrayFlags),
]
pix2vec_c.restype = ctypes.POINTER(ctypes.c_double)
# Array requirements, first store old order
f_cont = [ipix.flags["F_CONTIGUOUS"]]
ipix = np.require(ipix, dtype=np.int64, requirements=["C", "W"])
res = pix2vec_c(
nside,
npix,
ipix.astype(np.int64, order="C", copy=False),
)
result = np.fromiter(res, dtype=np.float64, count=npix*3)
result = result.reshape(npix, 3)
# Reset input arrays
if f_cont[0]:
ipix = np.asfortranarray(ipix)
x, y, z = result[:, 0], result[:, 1], result[:, 2]
return x, y, z
def pix2ang(nside, ipix, nest=False, lonlat=False):
"""
NAME:
pix2ang
PURPOSE:
Pixel number to angular coordinates
INPUT:
nside - a integer of healpix map nside
ipix - a (list) of integer of pixel number
nest - is using NEST?
lonlat - output in longitude and latitude (deg)?
OUTPUT:
theta, phi - angular coordinates
HISTORY:
2023-03-01 - Written - Henry Leung (Toronto)
"""
ipix = np.asarray(ipix)
check_nside(nside, nest=nest)
check_ipix_nside(ipix, nside)
ipix = np.atleast_1d(ipix)
npix = len(ipix)
if nest:
pix2ang_c = _lib.pix2ang_nest
else:
raise NotImplementedError("RING scheme is not avaliable for now")
# _lib.pix2ang_ring
ndarrayFlags = ("C_CONTIGUOUS", "WRITEABLE")
# (int nside, int npix, long long int *ipix)
pix2ang_c.argtypes = [
ctypes.c_long,
ctypes.c_long,
ndpointer(dtype=np.int64, flags=ndarrayFlags),
]
pix2ang_c.restype = ctypes.POINTER(ctypes.c_double)
# Array requirements, first store old order
f_cont = [ipix.flags["F_CONTIGUOUS"]]
ipix = np.require(ipix, dtype=np.int64, requirements=["C", "W"])
res = pix2ang_c(
nside,
npix,
ipix.astype(np.int64, order="C", copy=False),
)
result = np.fromiter(res, dtype=np.float64, count=npix*2)
result = result.reshape(npix, 2)
# Reset input arrays
if f_cont[0]:
ipix = np.asfortranarray(ipix)
theta, phi = result[:, 0], result[:, 1]
if lonlat:
return thetaphi2lonlat(theta, phi)
else:
return theta, phi
def nside2pixarea(nside):
"""
NAME:
nside2pixarea
PURPOSE:
Get area of a pixel for a healpix map with nside
INPUT:
nside - a integer of healpix map nside
OUTPUT:
pixarea - a float of healpix map pixel area
HISTORY:
2023-03-01 - Written - Henry Leung (Toronto)
"""
return np.pi / (3 * nside ** 2)
def nside2npix(nside):
"""
NAME:
nside2npix
PURPOSE:
Get how many pixel for a healpix map with nside
INPUT:
nside - a integer of healpix map nside
OUTPUT:
npix - a integer of number of healpix map pixel
HISTORY:
2023-03-01 - Written - Henry Leung (Toronto)
"""
return 12 * nside * nside
def ud_grade(map_in, nside_plot, pess=False, order_in="RING", order_out=None, power=None, dtype=None):
"""
NAME:
dust_vals_disk
PURPOSE:
Upgrade or degrade healpix map
INPUT:
map_in - healpix map to be upgraded or degraded
nside_plot - nside of the output map wanted
OUTPUT:
map_out - arrays of upgraded or degraded map(s)
HISTORY:
2023-03-01 - Written - Henry Leung (Toronto)
"""
# check if arguements are implemented
if order_in != "NEST" or (order_out is not None and order_out != "NEST"):
raise NotImplementedError("order_in and order_out for RING scheme is not implemented for now")
if power is not None:
raise NotImplementedError("power is not implemented for now")
if pess is not False:
raise NotImplementedError("pess=True is not implemented for now")
if dtype is not False:
raise NotImplementedError("dtype is implemented for now, output map always has the same dtype as input map")
check_nside(nside_plot, nest=order_in != "RING")
map_in = np.asarray(map_in)
num_of_map = len(np.atleast_2d(map_in))
if num_of_map != 1:
raise ValueError("This function only support one map at each time")
nside_in = npix2nside(len(map_in))
npix_in = nside2npix(nside_in)
npix_out = nside2npix(nside_in)
if nside_plot > nside_in: # upgrade
rat2 = npix_out // npix_in
fact = np.ones(rat2, dtype=map_in.dtype)
map_out = np.outer(map_in, fact).reshape(npix_out)
elif nside_plot < nside_in: # degrade
rat2 = npix_in // npix_out
mr = map_in.reshape(npix_out, rat2)
goods = ~(np.isclose(mr, UNSEEN) | (~np.isfinite(mr)) | (~np.isnan(mr)))
map_out = np.sum(mr * goods, axis=1)
nhit = goods.sum(axis=1)
map_out[nhit != 0] = map_out[nhit != 0] / nhit[nhit != 0]
try:
map_out[nhit == 0] = UNSEEN
except OverflowError:
pass
else:
map_out = map_in
return map_out