-
Notifications
You must be signed in to change notification settings - Fork 0
/
localization.py
1445 lines (1213 loc) · 54.4 KB
/
localization.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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# localization.py: HEALPix and associated localization classes
#
# Authors: William Cleveland (USRA),
# Adam Goldstein (USRA) and
# Daniel Kocevski (NASA)
#
# Portions of the code are Copyright 2020 William Cleveland and
# Adam Goldstein, Universities Space Research Association
# All rights reserved.
#
# Written for the Fermi Gamma-ray Burst Monitor (Fermi-GBM)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
import os, re
from copy import deepcopy
import astropy.io.fits as fits
import numpy as np
from scipy.stats import chi2, norm
from warnings import warn
import warnings
import healpy as hp
from collections import OrderedDict
from matplotlib.pyplot import contour as Contour
from matplotlib.patches import Polygon
from .lal_post_subs import make_circle_poly
from .gbmhealpy.coords import get_sun_loc, geocenter_in_radec, spacecraft_to_radec
from .gbmhealpy.coords import latitude_from_geocentric_coords_complex, haversine
from .gbmhealpy.coords import latitude_from_geocentric_coords_simple
from .detectors import Detector
from .data import DataFile
from .headers import healpix_primary, healpix_image
class HealPix(DataFile):
"""Base class for HEALPix localization files.
Attributes:
centroid (float, float): The RA and Dec of the highest probability pixel
datatype (str): The datatype of the file
detector (str): The GBM detector the file is associated with
directory (str): The directory the file is located in
filename (str): The filename
full_path (str): The full path+filename
headers (dict): The headers for each extension
id (str): The GBM file ID
is_gbm_file (bool): True if the file is a valid GBM standard file,
False if it is not.
is_trigger (bool): True if the file is a GBM trigger file, False if not
npix (int): Number of pixels in the HEALPix map
nside (int): The HEALPix resolution
pixel_area (float): The area of each pixel in square degrees
trigtime (float): The time corresponding to the localization
"""
def __init__(self):
self._headers = OrderedDict()
self._prob = np.array([], dtype=float)
self._sig = np.array([], dtype=float)
super().__init__()
@property
def headers(self):
return self._headers
@property
def trigtime(self):
try:
return self._headers['PRIMARY']['TRIGTIME']
except:
return None
@property
def npix(self):
return len(self._prob)
@property
def nside(self):
return hp.npix2nside(self.npix)
@property
def pixel_area(self):
return 4.0 * 180.0 ** 2 / (np.pi * self.npix)
@property
def centroid(self):
pix = np.argmax(self._prob)
theta, phi = hp.pix2ang(self.nside, pix)
return (self._phi_to_ra(phi), self._theta_to_dec(theta))
@classmethod
def from_data(cls, prob_arr, sig_arr, trigtime=None):
"""Create a HealPix object from healpix arrays
Args:
prob_arr (np.array): The HEALPix array containing the probability/pixel
sig_arr (np.array): The HEALPix array containing the signficance
trigtime (float, optional): The time corresponding to the localization
Returns:
:class:`HealPix`: The HEALPix localization
"""
obj = cls()
obj._prob = obj._assert_prob(prob_arr)
obj._sig = obj._assert_sig(sig_arr)
# set file properties
if trigtime is None:
trigtime = 0.0
obj.set_properties(trigtime=trigtime, datatype='healpix',
extension='fit')
return obj
@classmethod
def from_annulus(cls, center_ra, center_dec, radius, sigma, nside=None,
**kwargs):
"""Create a HealPix object of a Gaussian-width annulus
Args:
center_ra (float): The RA of the center of the annulus
center_dec (float): The Dec of the center of the annulus
radius (float): The radius of the annulus, in degrees, measured to
the center of the of the annulus
sigma (float): The Gaussian standard deviation width of the annulus,
in degrees
nside (int, optional): The nside of the HEALPix to make. By default,
the nside is automatically determined by the
`sigma` width. Set this argument to
override the default.
**kwargs: Options to pass to :meth:`from_data`
Return:
:class:`HealPix`: The HEALPix annulus
"""
# Automatically calculate appropriate nside by taking the closest nside
# with an average resolution that matches 0.2*sigma
if nside is None:
nsides = 2**np.arange(15)
pix_res = hp.nside2resol(nsides, True)/60.0
idx = np.abs(pix_res-sigma/5.0).argmin()
nside = nsides[idx]
# get everything in the right units
center_phi = cls._ra_to_phi(center_ra)
center_theta = cls._dec_to_theta(center_dec)
radius_rad = np.deg2rad(radius)
sigma_rad = np.deg2rad(sigma)
# number of points in the circle based on the approximate arclength
# and resolution
res = hp.nside2resol(nside)
# calculate normal distribution about annulus radius with sigma width
x = np.linspace(0.0, np.pi, int(10.0*np.pi/res))
pdf = norm.pdf(x, loc=radius_rad, scale=sigma_rad)
# cycle through annuli of radii from 0 to 180 degree with the
# appropriate amplitude and fill the probability map
probmap = np.zeros(hp.nside2npix(nside))
for i in range(x.size):
# no need to waste time on pixels that will have ~0 probability...
if pdf[i]/pdf.max() < 1e-10:
continue
# approximate arclength determines number of points in each annulus
arclength = 2.0*np.pi*x[i]
numpts = int(np.ceil(arclength/res))*10
circ = make_circle_poly(x[i], center_theta, center_phi, numpts)
theta = np.pi / 2.0 - circ[:, 1]
phi = circ[:, 0]
# convert to pixel indixes and fill the map
idx = hp.ang2pix(nside, theta, phi)
probmap[idx] = pdf[i]
mask = (probmap[idx] > 0.0)
probmap[idx[~mask]] = pdf[i]
probmap[idx[mask]] = (probmap[idx[mask]] + pdf[i])/2.0
probmap /= probmap.sum()
# signficance map
sigmap = 1.0 - find_greedy_credible_levels(probmap)
obj = cls.from_data(probmap, sigmap, **kwargs)
return obj
@classmethod
def from_gaussian(cls, center_ra, center_dec, sigma, nside=None, **kwargs):
"""Create a HealPix object of a Gaussian
Args:
center_ra (float): The RA of the center of the Gaussian
center_dec (float): The Dec of the center of the Gaussian
sigma (float): The Gaussian standard deviation, in degrees
nside (int, optional): The nside of the HEALPix to make. By default,
the nside is automatically determined by the
`sigma` of the Gaussian. Set this argument
to override the default.
**kwargs: Options to pass to :meth:`from_data`
Returns:
:class:`HealPix`: The HEALPix Gaussian
"""
# Automatically calculate appropriate nside by taking the closest nside
# with an average resolution that matches 0.2*sigma
if nside is None:
nsides = 2**np.arange(15)
pix_res = hp.nside2resol(nsides, True)/60.0
idx = np.abs(pix_res-sigma/10.0).argmin()
nside = nsides[idx]
# get everything in the right units
center_phi = cls._ra_to_phi(center_ra)
center_theta = cls._dec_to_theta(center_dec)
sigma_rad = np.deg2rad(sigma)
# point probability
npix = hp.nside2npix(nside)
probmap = np.zeros(npix)
probmap[hp.ang2pix(nside, center_theta, center_phi)] = 1.0
# then smooth out using appropriate gaussian kernel
probmap = hp.smoothing(probmap, sigma=sigma_rad, verbose=False)
# significance map
sigmap = 1.0 - find_greedy_credible_levels(probmap)
obj = cls.from_data(probmap, sigmap, **kwargs)
return obj
@classmethod
def from_vertices(cls, ra_pts, dec_pts, nside=64, **kwargs):
"""Create a HealPix object from a list of RA, Dec vertices.
The probability within the vertices will be distributed uniformly and
zero probability outside the vertices.
Args:
ra_pts (np.array): The array of RA coordinates
dec_pts (np.array): The array of Dec coordinates
nside (int, optional): The nside of the HEALPix to make. Default is 64.
**kwargs: Options to pass to :meth:`from_data`
Returns:
:class:`HealPix`: The HEALPix object
"""
poly = Polygon(np.vstack((ra_pts, dec_pts)).T, closed=True)
npix = hp.nside2npix(nside)
theta, phi = hp.pix2ang(nside, np.arange(npix))
ra = cls._phi_to_ra(phi)
dec = cls._theta_to_dec(theta)
mask = poly.contains_points(np.vstack((ra, dec)).T)
probmap = np.zeros(npix)
probmap[mask] = 1.0
probmap /= probmap.sum()
# significance map
sigmap = 1.0 - find_greedy_credible_levels(probmap)
obj = cls.from_data(probmap, sigmap, **kwargs)
return obj
@classmethod
def multiply(cls, healpix1, healpix2, primary=1, output_nside=128):
"""Multiply two HealPix maps and return a new HealPix object
Args:
healpix1 (:class:`HealPix`): One of the HEALPix maps to multiply
healpix2 (:class:`HealPix`): The other HEALPix map to multiply
primary (int, optional): If 1, use the first map header information,
or if 2, use the second map header
information. Default is 1.
output_nside (int, optional): The nside of the multiplied map.
Default is 128.
Returns
:class:`HealPix`: The multiplied map
"""
# if different resolutions, upgrade the lower res, then multiply
if healpix1.nside > healpix2.nside:
prob = healpix1._prob * hp.ud_grade(healpix2._prob,
nside_out=healpix1.nside)
elif healpix1.nside < healpix2.nside:
prob = healpix2._prob * hp.ud_grade(healpix1._prob,
nside_out=healpix2.nside)
else:
prob = healpix1._prob * healpix2._prob
# output resolution and normalize
prob = hp.ud_grade(prob, output_nside)
prob = prob / np.sum(prob)
sig = 1.0 - find_greedy_credible_levels(prob)
# copy header info
if primary == 1:
headers = healpix1.headers
trigtime = healpix1.trigtime
else:
headers = healpix2.headers
trigtime = healpix2.trigtime
if 'HEALPIX' in headers:
headers['HEALPIX']['NSIDE'] = output_nside
obj = cls.from_data(prob, sig, trigtime=trigtime)
obj._headers = headers
return obj
def probability(self, ra, dec, per_pixel=False):
"""Calculate the localization probability at a given point. This
function interpolates the map at the requested point rather than
providing the vale at the nearest pixel center.
Args:
ra (float): The RA
dec (float): The Dec
per_pixel (bool, optional):
If True, return probability per pixel, otherwise return
probability per square degree. Default is False.
Returns:
float: The localization probability
"""
phi = self._ra_to_phi(ra)
theta = self._dec_to_theta(dec)
prob = hp.get_interp_val(self._prob, theta, phi)
if not per_pixel:
prob /= self.pixel_area
return prob
def confidence(self, ra, dec):
"""Calculate the localization confidence level for a given point.
This function interpolates the map at the requested point rather than
providing the value at the nearest pixel center.
Args:
ra (float): The RA
dec (float): The Dec
Returns:
float: The localization confidence level
"""
phi = self._ra_to_phi(ra)
theta = self._dec_to_theta(dec)
return 1.0 - hp.get_interp_val(self._sig, theta, phi)
def area(self, clevel):
"""Calculate the sky area contained within a given confidence region
Args:
clevel (float): The localization confidence level (valid range 0-1)
Returns:
float: The area contained in square degrees
"""
numpix = np.sum((1.0 - self._sig) <= clevel)
return numpix * self.pixel_area
def prob_array(self, numpts_ra=360, numpts_dec=180, sqdegrees=True,
sig=False):
"""Return the localization probability mapped to a grid on the sky
Args:
numpts_ra (int, optional): The number of grid points along the RA
axis. Default is 360.
numpts_dec (int, optional): The number of grid points along the Dec
axis. Default is 180.
sqdegrees (bool, optional):
If True, the prob_array is in units of probability per square
degrees, otherwise in units of probability per pixel.
Default is True
sig (bool, optional): Set True to retun the significance map on a
grid instead of the probability. Default is False.
Returns:
3-tuple containing:
- *np.array*: The probability (or significance) array with shape \
(``numpts_dec``, ``numpts_ra``)
- *np.array*: The RA grid points
- *np.array*: The Dec grid points
"""
grid_pix, phi, theta = self._mesh_grid(numpts_ra, numpts_dec)
if sig:
sqdegrees = False
prob_arr = self._sig[grid_pix]
else:
prob_arr = self._prob[grid_pix]
if sqdegrees:
prob_arr /= self.pixel_area
return (prob_arr, self._phi_to_ra(phi), self._theta_to_dec(theta))
def confidence_region_path(self, clevel, numpts_ra=360, numpts_dec=180):
"""Return the bounding path for a given confidence region
Args:
clevel (float): The localization confidence level (valid range 0-1)
numpts_ra (int, optional): The number of grid points along the RA
axis. Default is 360.
numpts_dec (int, optional): The number of grid points along the Dec
axis. Default is 180.
Returns:
[(np.array, np.array), ...]: A list of RA, Dec points, where each \
item in the list is a continuous closed path.
"""
# create the grid and integrated probability array
grid_pix, phi, theta = self._mesh_grid(numpts_ra, numpts_dec)
sig_arr = 1.0 - self._sig[grid_pix]
ra = self._phi_to_ra(phi)
dec = self._theta_to_dec(theta)
# use matplotlib contour to produce a path object
contour = Contour(ra, dec, sig_arr, [clevel])
# get the contour path, which is made up of segments
paths = contour.collections[0].get_paths()
# extract all the vertices
pts = [path.vertices for path in paths]
# unfortunately matplotlib will plot this, so we need to remove
for c in contour.collections:
c.remove()
return pts
def source_probability(self, ra, dec, prior=0.5):
r"""The probability that the HealPix localization is associated with
a known point location. This is calculated against the null hypothesis
that the HealPix localization originates from an unassociated random
source that has equal probability of origination anywhere in the sky:
:math:`P(A | \mathcal{I}) =
\frac{P(\mathcal{I} | A) \ P(A)}
{P(\mathcal{I} | A) \ P(A) + P(\mathcal{I} | \neg A) \ P(\neg A)}`
where
* :math:`P(\mathcal{I} | A)` is the probability of the localization at
the point source once
* :math:`P(\mathcal{I} | \neg A)` is the probability per pixel assuming
a uniform distribution on the sky (i.e. the probability the
localization is associated with a random point on the sky)
* :math:`P(A)` is the prior probability that the localization is
associated with the point source
Args:
ra (float): The RA of the known source location
dec (float): The Dec of the known source location
prior (float, optional): The prior probability that the localization
is associated with the source.
Default is 0.5
Returns:
float: The probability that the HealPix localization is spatially \
associated with the point source
"""
if (prior < 0.0) or (prior > 1.0):
raise ValueError('Prior probability must be within 0-1, inclusive')
# convert uniform prob/sr to prob/pixel
u = 1.0 / (4.0 * np.pi)
u *= hp.nside2resol(self.nside) ** 2
# the pixel probability of the skymap at the location of the point source
p = self.probability(ra, dec, per_pixel=True)
# null hypothesis is that they are not associated, therefore the sky map
# is result of some source that has uniform probability on the sky
prob = (p*prior) / ((p*prior) + (u*(1.0-prior)))
return prob
def region_probability(self, healpix, prior=0.5):
r"""The probability that the HealPix localization is associated with
another HealPix map. This is calculated against the null hypothesis
that the two HealPix maps are unassociated:
:math:`P(A | \mathcal{I}) =
\frac{P(\mathcal{I} | A) \ P(A)}
{P(\mathcal{I} | A) \ P(A) + P(\mathcal{I} | \neg A) \ P(\neg A)}`
where
* :math:`P(\mathcal{I} | A)` is the integral over the overlap of the two
maps once the Earth occultation has been removed for *this* map.
* :math:`P(\mathcal{I} | \neg A)` is the integral over the overlap of
*this* map with a uniform distribution on the sky (i.e. the probability
the localization is associated with a random point on the sky)
* :math:`P(A)` is the prior probability that *this* localization is
associated with the *other* HEALPix map.
Args:
healpix (:class:`HealPix`): The healpix map for which to calculate
the spatial association
prior (float, optional): The prior probability that the localization
is associated with the source.
Default is 0.5
Returns:
float: The probability that this HealPix localization is
associated with the input HealPix map
"""
if (prior < 0.0) or (prior > 1.0):
raise ValueError('Prior probability must be within 0-1, inclusive')
# convert uniform prob/sr to prob/pixel
u = 1.0 / (4.0 * np.pi)
# ensure maps are the same resolution
probmap1 = self._prob
probmap2 = healpix._prob
if self.nside > healpix.nside:
probmap2 = hp.ud_grade(probmap2, nside_out=self.nside)
probmap2 = self._assert_prob(probmap2)
u *= hp.nside2resol(self.nside) ** 2
elif self.nside < healpix.nside:
probmap1 = hp.ud_grade(probmap1, nside_out=healpix.nside)
probmap1 = self._assert_prob(probmap1)
u *= hp.nside2resol(healpix.nside) ** 2
else:
u *= hp.nside2resol(self.nside) ** 2
# alternative hypothesis: they are related
alt_hyp = np.sum(probmap1 * probmap2)
# null hypothesis: one of the maps is from an unassociated source
# (uniform spatial probability)
null_hyp = np.sum(probmap1 * u)
# since we have an exhaustive and complete list of possibilities, we can
# easily calculate the probability
prob = (alt_hyp*prior) / ((alt_hyp*prior) + (null_hyp*(1.0-prior)))
return prob
def convolve(self, model, *args):
"""Convolve the map with a model kernel. The model can be a Gaussian
kernel or any mixture of Gaussian kernels. Uses `healpy.smoothing
<https://healpy.readthedocs.io/en/latest/generated/healpy.sphtfunc.smoothing.html>`_.
An example of a model kernel with a 50%/50% mixture of two Gaussians,
one with a 1-deg width, and the other with a 3-deg width::
def gauss_mix_example():
sigma1 = np.deg2rad(1.0)
sigma2 = np.deg2rad(3.0)
frac1 = 0.50
return ([sigma1, sigma2], [frac1])
Args:
model (<function>): The function representing the model kernel
*args: Arguments to be passed to the model kernel function
Returns:
:class:`HealPix`: A new HealPix object that is a result of the \
convolution with the model kernel
"""
# evaluate model
sigmas, fracs = model(*args)
# determine number of gaussians, and ensure that they match the
# number of fractional weights
num_sigmas = len(sigmas)
if len(fracs) != num_sigmas:
if len(fracs) + 1 != num_sigmas:
raise ValueError(
'Number of mixture fraction parameters is incorrect')
fracs.append(1.0 - np.sum(fracs))
# for each gaussian, apply the smoothing at the prescribed weight
new_prob = np.zeros(self._prob.shape)
for i in range(num_sigmas):
new_prob += fracs[i] * hp.smoothing(self._prob, sigma=sigmas[i],
verbose=False)
# make the object
new_sig = 1.0 - find_greedy_credible_levels(new_prob)
new_obj = deepcopy(self)
new_obj._prob = new_obj._assert_prob(new_prob)
new_obj._sig = new_obj._assert_sig(new_sig)
return new_obj
@staticmethod
def _ra_to_phi(ra):
return np.deg2rad(ra)
@staticmethod
def _phi_to_ra(phi):
return np.rad2deg(phi)
@staticmethod
def _dec_to_theta(dec):
return np.deg2rad(90.0 - dec)
@staticmethod
def _theta_to_dec(theta):
return np.rad2deg(np.pi / 2.0 - theta)
def _ang_to_pix(self, ra, dec):
# convert RA/Dec to healpixels
theta = self._dec_to_theta(dec)
phi = self._ra_to_phi(ra)
pix = hp.ang2pix(self.nside, theta, phi)
return pix
def _mesh_grid(self, num_phi, num_theta):
# create the mesh grid in phi and theta
theta = np.linspace(np.pi, 0.0, num_theta)
phi = np.linspace(0.0, 2 * np.pi, num_phi)
phi_grid, theta_grid = np.meshgrid(phi, theta)
grid_pix = hp.ang2pix(self.nside, theta_grid, phi_grid)
return (grid_pix, phi, theta)
def _assert_prob(self, prob):
# ensure that the pixels have valid probability:
# each pixel must be > 0 and sum == 1.
prob[prob < 0.0] = 0.0
prob /= prob.sum()
return prob
def _assert_sig(self, sig):
# ensure that the pixels have valid significance:
# each pixel must have significance [0, 1]
if sig is not None:
sig[sig < 0.0] = 0.0
sig[sig > 1.0] = 1.0
return sig
class GbmHealPix(HealPix):
"""Class for GBM HEALPix localization files.
Attributes:
<detector_name>_pointing (float, float):
The RA, Dec of the detector pointing (e.g. ``GbmHealPix.n0_pointing``)
centroid (float, float): The RA and Dec of the highest probability pixel
datatype (str): The datatype of the file
detector (str): The GBM detector the file is associated with
directory (str): The directory the file is located in
filename (str): The filename
full_path (str): The full path+filename
geo_location (float, float): The geocenter RA, Dec at trigtime
geo_probability (float): The amount of localization probability on the Earth
geo_radius (float): The apparent Earth radius as observed by Fermi
headers (dict): The headers for each extension
id (str): The GBM file ID
is_gbm_file (bool): True if the file is a valid GBM standard file,
False if it is not.
is_trigger (bool): True if the file is a GBM trigger file, False if not
npix (int): Number of pixels in the HEALPix map
nside (int): The HEALPix resolution
quaternion (np.array): The spacecraft attitude quaternion
pixel_area (float): The area of each pixel in square degrees
scpos (np.array): The spacecraft position in Earth inertial coordinates
sun_location (float, float): The Sun RA, Dec at trigtime
trigtime (float): The time corresponding to the localization
"""
def __init__(self):
super().__init__()
@property
def sun_location(self):
try:
return (self._headers['HEALPIX']['SUN_RA'],
self._headers['HEALPIX']['SUN_DEC'])
except:
return None
@property
def geo_location(self):
try:
return (self._headers['HEALPIX']['GEO_RA'],
self._headers['HEALPIX']['GEO_DEC'])
except:
return None
@property
def geo_radius(self):
# if the radius isn't known, use the average 67.5 deg radius
try:
return self._headers['HEALPIX']['GEO_RAD']
except:
return 67.5
@property
def scpos(self):
if 'COMMENT' not in self.headers['HEALPIX']:
return None
scpos = [c for c in self.headers['HEALPIX']['COMMENT'] if 'SCPOS' in c]
if len(scpos) != 1:
return None
else:
scpos = scpos[0].split('[')[1].split(']')[0]
scpos = np.array([float(el) for el in scpos.split()])
return scpos
@property
def quaternion(self):
if 'COMMENT' not in self.headers['HEALPIX']:
return None
quat = [c for c in self.headers['HEALPIX']['COMMENT'] if 'QUAT' in c]
if len(quat) != 1:
return None
else:
quat = quat[0].split('[')[1].split(']')[0]
quat = np.array([float(el) for el in quat.split()])
return quat
@property
def geo_probability(self):
if self.geo_location is None:
return None
prob_mask, geo_mask = self._earth_mask()
return np.sum(self._prob[prob_mask][geo_mask])
@classmethod
def open(cls, filename):
"""Open a GBM HEALPix FITS file and return the GbmHealPix object
Args:
filename (str): The filename of the FITS file
Returns:
:class:`GbmHealPix`: The GBM HEALPix localization
"""
warnings.filterwarnings("ignore", category=UserWarning)
obj = cls()
obj._file_properties(filename)
# open FITS file
with fits.open(filename, mmap=False) as hdulist:
for hdu in hdulist:
obj._headers.update({hdu.name: hdu.header})
# the healpix arrays
prob, sig = hp.read_map(filename, field=(0, 1), memmap=False,
verbose=False)
obj._prob = obj._assert_prob(prob)
obj._sig = obj._assert_sig(sig)
# set the detector pointing attributes
try:
obj._set_det_attr()
except:
pass
return obj
@classmethod
def from_data(cls, prob_arr, sig_arr, tcat=None, trigtime=None,
quaternion=None, scpos=None):
"""Create a HealPix object from healpix arrays and optional metadata
Args:
prob_arr (np.array): The HEALPix array containing the probability/pixel
sig_arr (np.array): The HEALPix array containing the signficance
tcat (:class:`.Tcat`, optional): The associated Tcat to fill out
the primary header info
trigtime (float, optional): The time corresponding to the localization
quaternion (np.array, optional):
The associated spacecraft quaternion used to determine the
detector pointings in equatorial coordinates
scpos (np.array, optional):
The associated spacecraft position in Earth inertial coordinates
used to determine the geocenter location in equatorial coordinates
Returns:
:class:`GbmHealPix`: The HEALPix localization
"""
obj = cls()
obj._prob = obj._assert_prob(prob_arr)
obj._sig = obj._assert_sig(sig_arr)
if tcat is not None:
trigtime = tcat.trigtime
if trigtime is None:
trigtime = 0.0
comments = []
# if we have a trigtime, calculate sun position
sun_key = []
if trigtime is not None:
sun_loc = get_sun_loc(trigtime)
sun_key = [('SUN_RA', sun_loc[0], 'RA of Sun'),
('SUN_DEC', sun_loc[1], 'Dec of Sun')]
# if we have a scpos, calculate geocenter position, radius
geo_key = []
if scpos is not None:
comments.append(('COMMENT', 'SCPOS: ' + np.array2string(scpos)))
geo = geocenter_in_radec(scpos)
try:
_, alt = latitude_from_geocentric_coords_complex(scpos)
except:
warn('Using simple spheroidal Earth approximation')
_, alt = latitude_from_geocentric_coords_simple(scpos)
r = 6371.0 * 1000.0
geo_radius = np.rad2deg(np.arcsin(r / (r + alt)))
geo_key = [
('GEO_RA', float(geo[0]), 'RA of Geocenter relative to Fermi'),
('GEO_DEC', float(geo[1]),
'Dec of Geocenter relative to Fermi'),
('GEO_RAD', geo_radius, 'Radius of the Earth')]
# if we have a quaternion, calculate detector pointings
det_keys = []
if quaternion is not None:
comments.append(
('COMMENT', 'QUAT: ' + np.array2string(quaternion)))
keys = []
for det in Detector:
detname = det.short_name
ra, dec = spacecraft_to_radec(det.azimuth, det.zenith,
quaternion)
ra_key = (detname + '_RA', float(ra),
'RA pointing for detector ' + detname)
dec_key = (detname + '_DEC', float(dec),
'Dec pointing for detector ' + detname)
keys.append([ra_key, dec_key])
det_keys = [key for det in keys for key in det]
# put the additional keys together, and create the headers
keys = sun_key
keys.extend(geo_key)
keys.extend(det_keys)
keys.extend(comments)
prihdr = healpix_primary(tcat=tcat, trigtime=trigtime)
obj._headers['PRIMARY'] = prihdr
obj._headers['HEALPIX'] = healpix_image(nside=obj.nside,
extra_keys=keys,
object=prihdr['OBJECT'])
# set the detector pointing attributes
try:
obj._set_det_attr()
except:
pass
# set file properties
obj.set_properties(trigtime=obj.trigtime, datatype='healpix',
extension='fit')
return obj
@classmethod
def from_chi2grid(cls, chi2grid, nside=128, tcat=None):
"""Create a GbmHealPix object from a chi2grid object
Args:
chi2grid (class:`Chi2Grid`): The chi2grid object containing the
chi-squared/log-likelihood info
nside (int, optional): The nside resolution to use. Default is 128
tcat (:class:`.Tcat`, optional): The associated Tcat to fill out
the primary header info
Returns:
:class:`GbmHealPix`: The GBM HEALPix localization
"""
# fill up a low-resolution healpix map with significance
lores_nside = 64
lores_npix = hp.nside2npix(lores_nside)
lores_array = np.zeros((lores_npix))
theta = cls._dec_to_theta(chi2grid.dec)
phi = cls._ra_to_phi(chi2grid.ra)
idx = hp.ang2pix(lores_nside, theta, phi)
lores_array[idx] = chi2grid.significance
# upscale to high-resolution
hires_nside = nside
hires_npix = hp.nside2npix(hires_nside)
theta, phi = hp.pix2ang(hires_nside, np.arange(hires_npix))
sig_array = hp.get_interp_val(lores_array, theta, phi)
sig_array[sig_array < 0.0] = 0.0
# convert chisq map to probability map
loglike = -chi2grid.chisq / 2.0
probs = np.exp(loglike - np.max(loglike))
lores_array = np.zeros(lores_npix)
lores_array[idx] = probs
prob_array = hp.get_interp_val(lores_array, theta, phi)
prob_array[prob_array < 0.0] = 0.0
prob_array /= np.sum(prob_array)
obj = cls.from_data(prob_array, sig_array, tcat=tcat,
trigtime=chi2grid.trigtime, scpos=chi2grid.scpos,
quaternion=chi2grid.quaternion)
return obj
@classmethod
def multiply(cls, healpix1, healpix2, primary=1, output_nside=128):
"""Multiply two GbmHealPix maps and return a new GbmHealPix object
Note:
Either `healpix1` *or* healpix2 can be a non-GbmHealPix object,
however at least one of them must be a GbmHealPix object **and**
the `primary` argument must be set to the appropriate GbmHealPix
object otherwise a TypeError will be raised.
Args:
healpix1 (:class:`HealPix` or :class:`GbmHealPix`):
One of the HEALPix maps to multiply
healpix2 (:class:`HealPix` or :class:`GbmHealPix`):
The other HEALPix map to multiply
primary (int, optional): If 1, use the first map header information,
or if 2, use the second map header
information. Default is 1.
output_nside (int, optional): The nside of the multiplied map.
Default is 128.
Returns
:class:`GbmHealPix`: The multiplied map
"""
if primary == 1:
if not isinstance(healpix1, cls):
raise TypeError('Primary HealPix (healpix1) is not of class {}. '
'Perhaps try setting healpix2 as the primary'.format(cls.__name__))
else:
if not isinstance(healpix2, cls):
raise TypeError('Primary HealPix (healpix2) is not of class {}. '
'Perhaps try setting healpix1 as the primary'.format(cls.__name__))
obj = super().multiply(healpix1, healpix2, primary=primary,
output_nside=output_nside)
obj._set_det_attr()
return obj
def write(self, directory, filename=None):
"""Write the GbmHealPix object to a FITS file
Args:
directory (str): The directory to write to
filename (str, optional): The filename of the FITS file
"""
if filename is None:
filename = self.filename
self.headers['PRIMARY']['FILENAME'] = filename
out_file = os.path.join(directory, filename)
# get arrays in proper order, and write the healpix data to disk
prob_arr = hp.reorder(self._prob, r2n=True)
sig_arr = hp.reorder(self._sig, r2n=True)
columns = ['PROBABILITY', 'SIGNIFICANCE']
hp.write_map(out_file, (prob_arr, sig_arr), nest=True, coord='C',
overwrite=True, \
column_names=columns,
extra_header=self.headers['HEALPIX'].cards)
# healpy doesn't allow direct input into the primary header on writing,
# so we have to open the written file, add the primary header, rename
# the tables in the HEALPIX extension and write a new file
hdulist = fits.open(out_file)
hdulist[0].header.extend(self.headers['PRIMARY'])
hdulist[1].name = 'HEALPIX'
hdulist[1].header['TTYPE1'] = (
'PROBABILITY', 'Differential probability per pixel')
hdulist[1].header['TTYPE2'] = (
'SIGNIFICANCE', 'Integrated probability')
hdulist.writeto(out_file, clobber=True, checksum=True)
@classmethod
def remove_earth(cls, healpix):
"""Return a new GbmHealPix with the probability on the Earth masked out.
The remaining probability on the sky is renormalized.
Note:
The :attr:`geo_location` attribute must be available to use this function
Args:
healpix (:class:`GbmHealPix`): The map for which the Earth will be
removed
Returns:
:class:`GbmHealPix`: GBM HEALPix localization
"""
if healpix.geo_location is None:
raise ValueError('Location of geocenter is not known')
# get the non-zero probability and earth masks
prob_mask, geo_mask = healpix._earth_mask()
# zero out the probabilities behind the earth
new_prob = np.copy(healpix._prob)
temp = new_prob[prob_mask]
temp[geo_mask] = 0.0
new_prob[prob_mask] = temp
# renormalize
new_prob /= np.sum(new_prob)