-
Notifications
You must be signed in to change notification settings - Fork 1
/
grb.py
1819 lines (1462 loc) · 65.2 KB
/
grb.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
"""
This module contains the classes and tools to handle a GRB object, i.e.
a collection of lightcurve bins for each of which is given an energy spectrum,
an explosion (trigger) time and physical characteristics.
Created on Tue Jan 22 11:41:34 2019
@author: Stolar
"""
import os
import sys
import pickle
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
from matplotlib import cm
import astropy
import astropy.units as u
from astropy.table import Table, QTable
from astropy.io import fits
from astropy.time import Time
from astropy.coordinates import SkyCoord
from astropy.coordinates import AltAz
from astropy.visualization import quantity_support
import observatory as obs
from visibility import Visibility
from niceprint import warning, failure
from niceplot import single_legend
from utilities import get_filename
from gammapy.modeling.models import Models
from gammapy.modeling.models import PointSpatialModel, SkyModel
from gammapy.modeling.models import EBLAbsorptionNormSpectralModel
from gammapy.modeling.models import TemplateSpectralModel
# Transform warnings into errors - useful to find who is guilty !
import warnings
#warnings.filterwarnings('error')
warnings.filterwarnings('ignore')
__all__ = ["GammaRayBurst"]
###############################################################################
class GammaRayBurst(object):
"""
A class to store GRB properties.
The GRB information is read from files.
A GRB is composed of several parameters among which, a name, a redshift,
a position in the sky, and measurement points in time at which
an energy spectrum is given.
Each energy spectrum is given as a series of flux measurements but is then
stored as an interpolated spectrum* (i.e. the energy bin width has a modest
importance).
The GRB properties like `z` and `Eiso` connect the afterglow and prompt
emissions together.
The original energy bins can be limited by a maximal maximal energy
(Limitation in time can be obtained from the visibility computation).
The spectra are usually modified for an EBL absorption, or the absorbed
flux is given in the file in some cases.
The afterglow flux can be adjusted by a multiplicative factor for
various tests.
If requested, the associated prompt spectrum is read and added to the
afterglow spectra to give the total contribution.
**Note:**
Following a question on the `Slack gammapy` channel on November 27 :sup:`th` ,
and the answer by Axel Donath:
The following statement later in the code gave an error
(:code:`dlist_onoff` is a collection of `Dataset`)
:code:`dlist_onoff.write(datapath,prefix="cls",overwrite=True)`
gives:
.. code-block:: python
..\\gammapy\\modeling\\models\\spectral.py",
line 989, in to_dict "data": self.energy.data.tolist(),
NotImplementedError: memoryview: unsupported format >f
This error comes from the fact that the energy list as to be
explicitely passed as a float as done below: :code:`cls.Eval.astype(float)`
(A `Quantity` is passed as requested but the underlying numpy
dtype is not supported by :code:`energy.data.tolist()`)
"""
ignore = ["id","filename", "Eval","tval", "tstart", "tstop", "fluxval",
"spec_afterglow", "prompt", "id90", "E_prompt", "flux_prompt",
"spec_prompt", "models", "vis"]
""" Ignore these members when dumping the class out."""
###------------------------------------------------------------------------
def __init__(self):
"""
This initializes a default GRB.
Returns
-------
None.
"""
self.id = 'dummy'
self.filename = None # File with the spectral and lightcurve data
self.z = 0 # Redshift
self.eblmodel = None
# GRB properties - Dummy default values
self.radec = SkyCoord(ra=100*u.deg, dec= -15*u.deg, frame="icrs")
self.Eiso = 0.*u.erg
self.Liso = 0.*u.Unit("erg/s")
self.Epeak = 0.*u.keV
self.t90 = 0.*u.s
self.G0H = 0.*u.dimensionless_unscaled
self.G0W = 0.*u.dimensionless_unscaled
self.Fpeak = 0.*u.erg
self.Fpeak_GBM = 0.*u.erg
self.gamle = 0.*u.dimensionless_unscaled
self.gamhe = 0.*u.dimensionless_unscaled
# GRB explosion time
self.t_trig = Time('2020-01-01T02:00:00', format="isot", scale='utc')
#------------
### Afterglow
#------------
# Afterglow Flux table - Spectra at a series of points in time
self.Eval = [0]*u.GeV # Energy values
self.tval = [0]*u.s # Time values
self.tstart = 0*u.s # Start time
self.tstop = 0*u.s # Stop time
# Raw flux arrays
self.fluxval = [0]*u.Unit("1 / (cm2 GeV s)")
# Afterglow interpolated arrays
self.spec_afterglow = []
#-------------------
### Prompt component
#-------------------
# Default : no prompt
self.prompt = False
# Afterglow Slice id at which the prompt stops
self.id90 = -1
# Prompt energy bins
self.E_prompt = [0]*u.GeV
# Prompt raw flux value
self.flux_prompt = 1*u.Unit("1 / (cm2 GeV s)")
# One Interpolated, non attenuated E-spectrum
self.spec_prompt = None
#-------------
### Total flux
#-------------
# If the prompt flux exist, this the sum of both flux until the
# last time bin of the afterglow flux below t90 of the prompt.
# Gammapy Skymodel models (one per t slice)
self.models = []
#-------------
### Visibility
#-------------
# Visibility - dictionnary with site entries
self.vis = dict()
###------------------------------------------------------------------------
@classmethod
def from_fits(cls,
filename,
prompt = None,
ebl = None,
emax = None,
tmax = None,
dt = 0.0,
magnify = 1,
debug = False):
"""
Read the GRB data from a `fits` file.
Fluxes are given for a series of (t,E) values
So far no flux exists beyond the last point (no extrapolation).
The spectrum is stored as a table, :obj:`TemplateSpectralModel`, that takes
as an input a series of flux values as a function of the energy.
The model will return values interpolated in log-space with
:func:`scipy.interpolate.interp1d`, returning zero for energies
outside of the limits of the provided energy array.
In this function, the trigger time (time of the GRB explosion), is
expected to come from the input file, with the possibility to add a
constant time shift in days, or is set randomly over the default year.
Alternatively, the dates can be overwritten by dates stored in
an external file in the `SoHAPPy.py` main process using
:func:`grb.GammaRayBurst.set_visibility` function.
Parameters
----------
cls : GammaRayBurst class
GammaRayBurst class instance.
filename : Path
GRB input file name.
prompt: Boolean
If True, read information from the associated prompt component.
ebl : String, optional
The EBL absorption model considered. If ebl is `built-in`, uses
the absorbed specrum from the data if available. Can be `None`.
Emax : Astropy Quantity, optionnal
Maximal energy considered in the data. The default is `None`.
dt: float, optionnal
A number of Julian days to be added to the present source trigger
time. The default is 0.0.
magnify : float, optional
Flux multiplicative factor to the afterglow model flux for tests.
Default is 1.
debug: Boolean, optional
Debugging flag. The default is False.
Returns
-------
A GammaRayBurst instance.
"""
### -----------------------------------------------------
### Open file, get header, keys, and data fill the class members
### -----------------------------------------------------
hdul = fits.open(get_filename(filename))
hdr = hdul[0].header
keys_0 = list(hdul[0].header.keys())
cls = GammaRayBurst() # Default constructor
cls.filename = filename
cls.z = hdr['Z']
cls.eblmodel = ebl
# Get identifier by removing all extensions
cls.id = str(filename.name).rstrip(''.join(filename.suffixes))
cls.radec = SkyCoord(ra = hdr['RA']*u.deg, dec = hdr['DEC']*u.deg,
frame="icrs")
cls.Eiso = hdr['EISO']*u.erg
if "LISO" in keys_0:
cls.Liso = hdr["LISO"]*u.Unit("erg/s") # New large prod. files
else:
cls.Liso = 0*u.Unit("erg/s")
cls.Epeak = hdr['EPEAK']*u.keV
cls.t90 = hdr['Duration']*u.s
cls.G0H = hdr['G0H']
if "G0W" in keys_0: # Not in SHORTFITS
cls.G0W = hdr['G0W']
if "PHFLUX" in keys_0:
cls.Fpeak = hdr['PHFLUX']*u.Unit("cm-2.s-1")
elif "PHFX" in keys_0:
cls.Fpeak = hdr['PHFX']*u.Unit("cm-2.s-1")
cls.gamle = hdr['LOWSP']
cls.gamhe = hdr['HIGHSP']
if "PHFX_GBM" in keys_0:
cls.Fpeak_GBM = hdr['PHFX_GBM']*u.Unit("cm-2.s-1")
else:
cls.Fpeak_GBM = 0*u.Unit("cm-2.s-1")
###--------------------------
### GRB trigger time
###--------------------------
# If the input file does not contain a trigger date, then set a date
# by default. It is very likely that this source belongs to a set
# for which a list of explosion (trigger) times should be generated.
if "GRBJD" in keys_0: # Not in SHORTFITS
cls.t_trig = Time(hdr['GRBJD']*u.day + dt*u.day,
format="jd",scale="utc")
elif "GRBTIME" in keys_0: # Add start date
cls.t_trig = Time(hdr['GRBTIME'] + dt*u.day,
format="jd",scale="utc")
else:
warning(f"{__name__:}.py: Trigger time absent from file, using random value")
import random
cls.t_trig += random.uniform(0, 365)*u.day
###--------------------------
### Time intervals - so far common to afterglow and prompt
###--------------------------
tval = QTable.read(hdul["TIMES (AFTERGLOW)"])
# Temporary : in short GRB fits file, unit is omitted
# The flux value is given on an interval ("col0", "col1°°.
# The default is to consider that the flux is valid at the end of the
# interval.
if isinstance(tval[0][0], astropy.units.quantity.Quantity):
cls.tval = np.array(tval[tval.colnames[0]].value)*tval[0][0].unit
else: # In SHORT GRB, the time bin is given, [t1, t2].
cls.tval = np.array(tval["col1"])*u.s
# Select point up to tmax. Force last point to be tmax.
if tmax is not None:
ninit = len(cls.tval)
cls.tval = cls.tval[(tmax - cls.tval)>0]
cls.tval[-1] = tmax.to(u.s)
print(f" GRB {cls.id:}: slices {ninit:} -> {len(cls.tval):}")
cls.tstart = cls.t_trig
cls.tstop = cls.t_trig + cls.tval[-1]
###--------------------------
### Afterglow Energies - Limited to Emax if defined
###--------------------------
tab_key = "Energies (afterglow)"
col_key = Table.read(hdul[tab_key]).colnames[0]
cls.Eval = Table.read(hdul[tab_key])[col_key].quantity
cls.Eval = np.array(cls.Eval)*cls.Eval[0].unit
if emax is not None and emax <= cls.Eval[-1]:
warning(" Data up to {:5.3f} restricted to {:5.3f}"
.format(cls.Eval[-1],emax))
cls.Eval = cls.Eval[cls.Eval<= emax]
###--------------------------
### Afterglow flux
###--------------------------
# Get flux, possibly already absorbed
if ebl == "in-file": # Read default absorbed model
flux = QTable.read(hdul["EBL-ABS. SPECTRA (AFTERGLOW)"])
else:
flux = QTable.read(hdul["SPECTRA (AFTERGLOW)"])
flux_unit = u.Unit(flux.meta["UNITS"])
if str(flux_unit).find("ph") > -1:
flux_unit = flux_unit/u.Unit("ph") # Removes ph
# Store the flux. Note the transposition
itmax = len(cls.tval)-1
jEmax = len(cls.Eval) - 1
cls.fluxval = np.zeros( (itmax+1,jEmax+1) )*flux_unit
for i in range(0,itmax+1):
for j in range(0,jEmax+1):
cls.fluxval[i][j] = magnify* flux[j][i]*flux_unit # transp!
# Build time series of interpolated spectra - limited to dtmax
for i in range(len(cls.tval)):
glow = TemplateSpectralModel(energy = cls.Eval.astype(float),
values = cls.fluxval[i],
interp_kwargs={"values_scale": "log"})
cls.spec_afterglow.append(glow)
###--------------------------
### Prompt - a unique energy spectrum
###--------------------------
# Get the prompt if potentially visible and if requested
cls.prompt = False # No prompt component was found
if prompt is not None:
if Path(prompt).is_dir():
# if cls.vis["North"].vis_prompt or cls.vis["South"].vis_prompt:
# Deduce prompt folder from GRB path name
cls.spec_prompt = cls.get_prompt(folder = prompt,
debug = debug)
if cls.spec_prompt is not None:
cls.prompt = True
else:
sys.exit(" {} is not a valid data folder :".format(prompt))
###--------------------------
### Total attenuated spectra
###--------------------------
for i,t in enumerate(cls.tval):
spec_tot = cls.spec_afterglow[i]
if cls.prompt:
if i<=cls.id90: spec_tot += cls.spec_prompt[i]
m = SkyModel(spectral_model= cls.EBLabsorbed(spec_tot,ebl),
spatial_model = PointSpatialModel(lon_0=cls.radec.ra,
lat_0=cls.radec.dec,
frame="icrs"),
name="model_"+str(i))
cls.models.append(m)
### Close fits file
hdul.close()
return cls
###------------------------------------------------------------------------
@classmethod
def historical_from_yaml(cls, item,
ebl = None,
magnify = 1):
"""
Read the characteristics of a parameterised GRB from a `yaml` file.
It is assumed that the energy and time decays are not correlated and
follow two independent power laws.
The function associates spectra to a list of time intervals
in order to comply with the more general case in this class.
Note that the spectra are considered to be from the afterglow only.
Returns
-------
A `GammaRayBurst` instance.
"""
cls = GammaRayBurst() # This calls the constructor
cls.filename = Path(Path(__file__).absolute().parent,
"data/historical/GRB_"+item+".yml")
with open(cls.filename) as f:
import yaml
from yaml.loader import SafeLoader
data = yaml.load(f, Loader=SafeLoader)
cls.z = data["z"]
cls.eblmodel = ebl
cls.id = data["name"]
cls.radec = SkyCoord(data["ra"], data["dec"], frame='icrs')
cls.Eiso = u.Quantity(data["Eiso"])
# self.Liso = 0.*u.Unit("erg/s")
cls.Epeak = u.Quantity(data['Epeak'])
cls.t90 = u.Quantity(data['t90'])
cls.G0H = data['G0H']
cls.G0W = data['G0W']
cls.Fpeak = u.Quantity(data['Fluxpeak'])
# self.Fpeak_GBM = 0.*u.erg
cls.gamle = data['gamma_le']
cls.gamhe = data['gamma_he']
###--------------------------
### GRB trigger time
###--------------------------
cls.t_trig = Time(data["t_trig"],format="datetime",scale="utc")
###--------------------------
### Time intervals
###--------------------------
tmin = max(u.Quantity(data["tmin"]),1*u.s) # Cannot be zero
tmax = u.Quantity(data["tmax"])
ntbin = data["ntbin"]
if ntbin != 1:
cls.tval = np.logspace(np.log10(tmin.to(u.s).value),
np.log10(tmax.to(u.s).value),
ntbin)*u.s
else: # A single time window
cls.tval = np.array([tmin.value,tmax.to(tmin.unit).value])*tmin.unit
cls.tstart = cls.t_trig
cls.tstop = cls.t_trig + cls.tval[-1]
###--------------------------
### Afterglow Energies - Limited to Emin, Emax
###--------------------------
Emin = u.Quantity(data["Emin"])
Emax = u.Quantity(data["Emax"])
cls.Eval = np.asarray([Emin.value,
Emax.to(Emin.unit).value])*Emin.unit
###--------------------------
### Afterglow flux
###--------------------------
flux_unit = u.Unit("1/(cm2 GeV s)")
cls.fluxval = np.zeros( (len(cls.tval),len(cls.Eval)) )*flux_unit
for i,t in enumerate(cls.tval):
for j,E in enumerate(cls.Eval):
dnde = (u.Quantity(data["K"])*(E/data["E0"])**-data["gamma"]
*(t/data["t0"])**-data["beta"])
#print(i,j,dnde)
cls.fluxval[i][j] = magnify* dnde.to(flux_unit)
###--------------------------
### Prompt - No prompt foreseen in this case
###--------------------------
cls.prompt = False
###--------------------------
### Total attenuated spectra
###--------------------------
# See note in from_fits for explanatins on some parameters
for i,t in enumerate(cls.tval):
tab = TemplateSpectralModel(energy = cls.Eval.astype(float),
values = cls.fluxval[i],
interp_kwargs={"values_scale": "log"})
cls.spec_afterglow.append(tab) # Needed for display
m = SkyModel(spectral_model= cls.EBLabsorbed(tab),
spatial_model = PointSpatialModel(lon_0=cls.radec.ra,
lat_0=cls.radec.dec,
frame="icrs"),
name="model_"+str(i))
cls.models.append(m)
return cls
###------------------------------------------------------------------------
@classmethod
def prompt(cls, filename, glowname= None, ebl= None,
z=0*u.dimensionless_unscaled, magnify=1):
"""
This function is for tests using time-resolved spectra.
It reads prompt data from a file and associate the prompt to the
afterglow if requested (or keep the default from the constructor
otherwise, with possibility to supersede the redshift and the flux
multiplicative factor). It does not add the two spectra as this would
require to work on the energy and time binnings that are different and
this is not implemented yet.
Parameters
----------
filename : Path
Prompt file path.
glowname : Path, optional
Afterglow file path. The default is None.
ebl : string, optional
Name of the EBL model. The default is None.
z : Quantity, optional
redshift. The default is 0*u.dimensionless_unscaled.
magnify : float, optional
Multiplicative factor of the flux. The default is 1.
Returns
-------
GammaRayBurst
New instance.
"""
if not filename.exists():
sys.exit(f"File {filename:} not found")
# Read prompt data -supersede defaults
cls = GammaRayBurst()
cls. z = z
cls.magnifiy = magnify
cls.eblmodel = ebl
# Copy missing data from the corresponding afterglow
if glowname is not None:
glow = GammaRayBurst.from_fits(glowname)
# print(glow)
cls.z = glow.z
cls.radec = glow.radec
cls.Eiso = glow.Eiso
cls.Liso = glow.Liso
cls.Epeak = glow.Epeak
cls.Fpeak = glow.Fpeak
cls.t90 = glow.t90
cls.G0H = glow.G0H
cls.G0W = glow.G0W
cls.gamle = glow.gamle
cls.gamhe = glow.gamhe
cls.Fpeak_GBM = glow.Fpeak_GBM
cls.t_trig = glow.t_trig
# Reads prompt data
hdul = fits.open(filename)
cls.id = Path(filename.name).stem
cls.Eval = Table.read(hdul,hdu=1)["energy"].quantity*u.TeV
cls.tval = Table.read(hdul,hdu=2)["time"].quantity*u.s
cls.tstart = cls.t_trig
cls.tstop = cls.t_trig + cls.tval[-1]
flux = Table.read(hdul,hdu=3)
flux_unit = u.Unit("1/(cm2 TeV s)")
icol_t = len(flux.colnames) # column number - time
jrow_E = len(flux[flux.colnames[0]]) # row number
# Note the transposition from flux to fluxval
cls.fluxval = np.zeros( (icol_t,jrow_E) )*flux_unit
for i in range(0,icol_t):
for j in range(0,jrow_E):
f = flux[j][i]
if f>1:
# print(i,j,f)
f =0 # Correct a bug in event #172 - to be removed
cls.fluxval[i][j] = magnify*f*flux_unit # transp!
for i in range(len(cls.tval)):
# Note that TableModel makes an interpolation
prpt = TemplateSpectralModel(energy = cls.Eval.astype(float),
values = cls.fluxval[i],
interp_kwargs={"values_scale": "log"})
# Use the afterglow place holder to store the prompt
cls.spec_afterglow.append(prpt)
m = SkyModel(spectral_model= cls.EBLabsorbed(prpt,ebl),
spatial_model = PointSpatialModel(lon_0=cls.radec.ra,
lat_0=cls.radec.dec,
frame="icrs"),
name="model_"+str(i))
cls.models.append(m)
# Not adding the averaged on time prompt
cls.prompt = False
hdul.close()
return cls
###------------------------------------------------------------------------
def EBLabsorbed(self, tab, debug=False):
"""
Returns the EBL-absorbed model of the current instance.
Absorption data are either obtained from the Gammapy datasets or from
external proprietary files. Data are unchanged if the GRB has
already attenuated spectra or if no absorption is considered.
Parameters
----------
tab : Gammapy TemplateSpectralModel
A flux versus energy as an interpolated table.
model : String
An EBL model name among those available.
debug : Boolean, optional
If True let's talk a bit. The default is False.
Returns
-------
attflux : TemplateSpectralModel
An attenuated flux versus energy as an interpolated table.
"""
attflux = tab # Initialise to the unabsorbed flux
if self.eblmodel is None or self.eblmodel == 'in-file':
return attflux
if self.eblmodel != "gilmore":
eblabs = EBLAbsorptionNormSpectralModel.read_builtin(self.eblmodel,
redshift=self.z)
attflux = tab*eblabs
else:
from ebl import EBL_from_file
eblabs = EBL_from_file("data/ebl/others/ebl_gilmore12-10GeV.dat")
# Change flux for absorption, recreate model
# I di not fine a clever way
attenuated = []
for E in self.Eval:
attenuated.append(tab(E).value*eblabs(E,self.z))
attenuated *= tab(np.mean(self.Eval)).unit
attflux = TemplateSpectralModel(energy = self.Eval.astype(float),
values = attenuated,
interp_kwargs={"values_scale": "log"})
return attflux
###------------------------------------------------------------------------
def set_visibility(self, item, loc,
info = None, n_night = None, n_skip = None,
status="", dbg = False):
"""
Attach a visibility to a GRB instance.
Either recompute it if a keyword has been given and a dictionnary
retrieved or read it from the specified folder or dictionnary.
* If a dictionnary is given, it can be:
1. From the :obj:`visibility.yaml` file - the visibility is
computed on the fly.
2. Not from the :obj:`visibility.yaml` file, the dictionnary
contains a computed visibility from a `json` file.
* The keyword is among those:
* **built-in**, the visibility is read from the fits file.
* **forced**, the visibility is build assuming one infinite
night.
* **permanent**, the visibility is permanent, i.e. the night is
infinite and the GRB is above the horizon. In that case it
can be useful to force the zenith angle to be fixed at a
certain value.
"""
### Update the default - At this stage the visibility is maximal
self.vis[loc] = Visibility(pos = self.radec,
site = obs.xyz["CTA"][loc],
window = [self.tstart, self.tstop],
name = self.id+"_"+loc,
status = status)
if info == "permanent":
self.vis[loc].status = info # Keep track of that special case
return self
if isinstance(info,dict): # A dictionnary not a keyword
if "altmin" in info.keys(): # Compute from dictionnary
# Supersede max. number of nights and nights to be skipped
if n_night is not None:
info["depth"] = n_night
if n_skip is not None:
info["skip"] = n_skip
# Compute from dictionnary elements
self.vis[loc] = self.vis[loc].compute(param = info,debug = dbg)
else: # A dictionnary of all visibilities (from a .json file)
self.vis[loc] = Visibility.from_dict(info[str(item)+"_"+loc])
# Not a dictionnary
elif info == "built-in":
# sys.exit("{}.py : built-in vis. reading to be reimplemented"
# .format(__name__))
# infolder is not passed
self.vis[loc] = Visibility.from_fits(self, loc=loc)
else: # Special or from disk
if info == "forced": # Infinitite nights
self.vis[loc] = self.vis[loc].force_night()
else: # Binary - Obsolete - Archived bin files might be not valid
import pickle
with open(Path(info,self.id+"_"+loc+"_vis.bin"),"r") as f:
self.vis[loc] = pickle.load(f)
###------------------------------------------------------------------------
def altaz(self,loc="",dt=0*u.s):
"""
Get altitude azimuth for the GRB at a given site at GRB time t (s)
Parameters
----------
location : string
Either `North` or `South`.
dt : Quantity (time)
The time elapsed since the trigger time
Returns
-------
altaz : astropy.coordinates.AltAz
The GRB poistion in the sky at the given time and site.
"""
if type(dt) is not astropy.units.quantity.Quantity:
sys.exit("Time has to be a quantity (weird behaviour otherwise")
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
altaz = self.radec.transform_to(AltAz(obstime = dt + self.t_trig,
location = self.vis[loc].site))
return altaz
###------------------------------------------------------------------------
def get_prompt(self, folder = None, strict=False, debug = False):
"""
Get the time averaged prompt component associated to the afterglow.
The prompt spectra are produced so that they correspond to the values
of the physical parameters from the population (Lorentz Factor,
peak energy, photon flux, and redshift).
A single set of spectra is given spanning over the `T90` GRB duration.
The flux is an "average" prompt spectrum over `T90`.
Parameters
----------
folder : String, optional
Where to find the prompt data below the 'lightcurves/prompt'
folder. The default is None.
strict : Boolean, optional
If True, requires that the density profile agrees between the
prompt and the afterglow.
debug : Boolean, optional
If True, let's talk a bit. The default is False.
Returns
-------
List of Models
List of `Gammapy` models for the Prompt component.
"""
# Find back the source id number from the id (assumes only the id has digits)
gid = ""
for s in self.id:
if s.isdigit():
gid += s
if strict:
if gid in [6, 30 ,191]:
failure(f" GRB prompt {gid:} simulated with a Wind profile")
failure(" It cannot be associated to the current afterglow !")
return -1, None
###----------------------------
### Compute weihts to "Mask" the time interval beyond t90
###----------------------------
# Find the closest time bin at t90 in the Afterglow
# id90 is the index of the time following the t90 value
# t90 is therefore between the index id90-1 and id90
self.id90 = np.where(self.tval >= self.t90)[0][0]
if self.id90 == 0:
warning(f"{self.id:} : t90 = {self.t90:} "\
"is before the first afterglow time bin")
return None
# The given flux is per unit of time.
# In order to take into account that the last time bin is not completely
# covered, it is corrected by the fraction in time in this bin.
dtprompt = self.t90 - self.tval[self.id90-1] # Prompt is active
dtslice = self.tval[self.id90]-self.tval[self.id90-1] # Total slice duration
fraction = dtprompt/dtslice
# All slices have weight 1 before the slice containing t90, the
# fraction above for the slice containing t90, and zero beyond
weight = np.concatenate( (np.ones(self.id90),
[fraction],
np.zeros(len(self.tval)-self.id90-1)))
###----------------------------
### Read prompt data
###----------------------------
# Open file - read the lines
filename = Path(folder,gid+"-spec.dat")
if not filename.exists():
failure("{} does no exist".format(filename))
return None
file = open(filename,"r")
lines = file.readlines()
# get Gamma and z
data = lines[0].split()
gamma_prompt = float(data[2])
redshift = float(data[5])
# Consistency check - Zeljka data are rounded at 2 digits
if np.abs(self.z - redshift)>0.01 or np.abs(self.G0H - gamma_prompt)>0.01:
failure(f" {self.id:10s}: "\
f"Afterglow / prompt : z= {self.z:4.2f} / {redshift:4.2f}"\
f" G0H/gamma= {self.G0H:5.2f} / {gamma_prompt:5.2f}"\
f" (G0W= {self.G0W:5.2f})")
# Get units - omit "ph" in flux unit
data = lines[1].split()
unit_e = data[0][1:-1]
unit_flx = ''.join([ x + " " for x in data[2:]])[1:-2]
# Get flux points - assign units to data, use afterglow units
data = lines
Eval = []
fluxval = []
for line in lines[4:]:
data = line.split()
Eval.append(float(data[0]))
fluxval.append(float(data[1]))
self.E_prompt = Eval*u.Unit(unit_e)
self.flux_prompt = fluxval*u.Unit(unit_flx)
if unit_e != self.Eval.unit:
if debug:
warning(f"Converting energy units from {unit_e:}"\
f" to {self.Eval[0].unit:}")
self.E_prompt = self.E_prompt.to(self.Eval[0].unit)
if unit_flx != self.fluxval[0].unit:
if debug:
warning("Converting flux units from {} to {}"
.format(unit_flx, self.fluxval[0][0].unit))
self.flux_prompt = self.flux_prompt.to(self.fluxval[0][0].unit)
###----------------------------
### Create a list of weighted models for non-zero weights
###----------------------------
models = []
for i in range(self.id90+1):
flux_w = self.flux_prompt*weight[i]
models.append(TemplateSpectralModel(energy = self.E_prompt,
values = flux_w,
interp_kwargs={"values_scale": "log"}))
if debug:
print("Prompt associated to ",self.id)
print("Gamma = ",gamma_prompt," redshift =",redshift)
print(" {:8} : {:10}".format(unit_e, unit_flx))
for E, flux in zip(self.E_prompt,self.flux_prompt):
print(" {:8.2f} : {:10.2e} "
.format(E.value,flux.value))
islice=0
print(" {:>8} - {:>5} ".format("Time","Weight"),end="")
for t, w in zip(self.tval, weight):
print(" {:8.2f} - {:5.2f} ".format(t,w),end="")
print("*") if islice== self.id90 else print("")
islice+=1
print("Prompt is between: ",self.tval[self.id90-1],self.tval[self.id90])
return models
###------------------------------------------------------------------------
### INPUT/OUPUT
###------------------------------------------------------------------------
def __str__(self):
"""
Printout the GRB properties (Not the visibilities).
"""
txt=""
if self.filename is not None:
txt += ' Read from : {}\n'.format(self.filename)
txt += ' RA, DEC : {:6.2f} {:6.2f}\n' \
.format(self.radec.ra.value, self.radec.dec.value)
txt += ' Redshift : {:6.2f}\n'.format(self.z)
txt += ' EBL model : "{:}"\n'.format(self.eblmodel)
txt += ' Eiso : {:6.2e}\n'.format(self.Eiso)
txt += ' Epeak : {:6.2f}\n'.format(self.Epeak)
txt += ' t90 : {:6.2f}\n'.format(self.t90)
txt += ' G0H / G0W : {:6.2f} / {:6.2f}\n' \
.format(self.G0H,self.G0W)
txt += ' Flux peak : {:6.2f}\n'.format(self.Fpeak)
txt += ' Flux peak (GBM): {:6.2f}\n'.format(self.Fpeak_GBM)
txt += ' gamma LE / HE : {:6.2f} / {:6.2f}\n' \
.format(self.gamle,self.gamhe)
txt += ' t_trig : {}\n'.format(Time(self.t_trig,format="iso"))
txt += ' Duration : {:6.2f} {:10.2f}\n' \
.format( (self.tval[-1]-self.tval[0]).to(u.d),
(self.tval[-1]-self.tval[0]).to(u.s))
# txt += ' Bins : E, t, dt : {:4d} {:4d} {:4d} \n' \
# .format(len(self.Eval), len(self.tval), len(self.time_interval))
txt += ' Bins : E, t : {:4d} {:4d} \n' \
.format(len(self.Eval), len(self.tval))
if self.prompt:
txt += ' Prompt component : \n'
txt += ' Up to slice : {:3d}\n'.format(self.id90)
txt += " Bins : E : {:3d}\n".format(len(self.E_prompt))
else:
txt += ' Prompt component not considered\n'
if self.vis is None:
txt += ' Visibility not available\n'
return txt
###------------------------------------------------------------------------
def write_to_bin(self, folder, debug=True):
"""
Write current instance to a binary file for further
reuse.
Parameters
----------
folder : String
Folder name.
debug : Boolean, optional
If True, talks bit. The default is True.
Returns
-------
None.
"""
filename = Path(folder,self.id+".bin")
outfile = open(filename,"wb")
pickle.dump(self,outfile)
outfile.close()