pl_simulations.py

Acharyya Atreya, 12/10/2019 07:01 PM

Download (7.79 KB)

 
1
import numpy
2
import os, sys
3
import random
4
import matplotlib.pyplot as plt
5
from matplotlib import rc
6

    
7
import gammalib
8
import ctools
9
import cscripts
10

    
11

    
12
data=numpy.genfromtxt('pl_4lac_with_redshift_v2.dat', dtype='string')
13

    
14

    
15
Source_Name=[]
16
RAJ2000=[]
17
DECJ2000=[]
18
Redshift=[]
19
Pivot_Energy=[]
20
PL_Flux_Density=[]#units ph / (cm2 MeV s)
21
PL_Index=[]
22

    
23
for i in range(1,len(data)):
24
    if(0<float(data[i][3])<4):
25
        Source_Name.append(data[i][0])
26
        RAJ2000.append(float(data[i][1]))
27
        DECJ2000.append(float(data[i][2]))
28
        Redshift.append(float(data[i][3]))
29
        Pivot_Energy.append(float(data[i][4]))
30
        PL_Flux_Density.append(float(data[i][5]))
31
        PL_Index.append(float(data[i][6]))
32

    
33

    
34

    
35
caldb = 'prod3b-v2'
36
tmin = 0.0
37
tmax= 18000
38
emin  = 0.03   # TeV
39
emax  = 30.0 # TeV
40

    
41

    
42

    
43
for i in range(len(DECJ2000)):
44
    ra=RAJ2000[i]
45
    dec=DECJ2000[i]
46
    source=Source_Name[i]
47
    if(25>dec>0):
48
        irf   = 'North_z20_50h'
49
    if(45>dec>25):
50
        irf   = 'North_z40_50h'
51
    if(65>dec>45):
52
        irf   = 'North_z60_50h'
53
    if(-25<dec<0):
54
        irf   = 'South_z20_50h'
55
    if(-45<dec<-25):
56
        irf   = 'South_z40_50h'
57
    if(-65<dec<-45):
58
        irf   = 'South_z60_50h'
59

    
60
    print dec,irf
61
    
62
    
63
    for j in range(10):
64
        s1=random.randint(1,1000)
65
        evfile = '/Volumes/mac_ext/egal_pop/PL_events_file/%s/events_%f.fits'%(source,j)
66
        obssim = ctools.ctobssim()
67
        obssim['ra']        = ra
68
        obssim['dec']       = dec
69
        obssim['rad']       = 3.0
70
        obssim['tmin']      = tmin#'2020-01-01T00:00:00'
71
        obssim['tmax']      = tmax
72
        obssim['seed'] = s1 # Any integer value you like
73
        obssim['emin']      = emin
74
        obssim['emax']      = emax
75
        obssim['caldb']     = caldb
76
        obssim['irf']       = irf
77
        obssim['inmodel']   = '/Volumes/mac_ext/egal_pop/PL_input_model/input_loglaw_pl_%s.xml'%(source)
78
        obssim['outevents'] = evfile
79
        obssim.execute()
80
    '''
81

82

83

84
    
85

86

87
    
88

89

90
 
91
    
92
    
93

94

95
    like = ctools.ctlike()
96
    like['inobs']   = evfile
97
    like['caldb']   = caldb
98
    like['irf']     = irf
99
    like['inmodel'] = '%s.xml'%(source_name)
100
    like['outmodel'] = 'results_%s_0.03_%s.xml'%(source_name,s)
101
    like.execute()
102

103

104
#print (like.obs().models()[0])
105

106
    import re
107
    import sys
108
    import os
109
    import glob
110
    
111
    orig_stdout = sys.stdout
112
    f = open('results_%s_0.03_%s.txt'%(source_name,s),'w')
113
    sys.stdout = f 
114
    print(like.obs().models()[0])
115
    print s1
116
    
117
    sys.stdout = orig_stdout
118
    f.close()
119

120

121

122
    text_file = open('results_%s_0.03_%s.txt'%(source_name,s))
123
#print text_file
124
    lines = text_file.readlines()
125
    #print lines
126
    if (numpy.float(re.findall("\d+\.\d+", lines[3])[0])>10):
127
        ts.append(numpy.float(re.findall("\d+\.\d+", lines[3])[0]))
128

129
print ts
130

131
plt.hist(ts, bins=10)
132
plt.xlabel('TS')
133
plt.ylabel('Number')
134
plt.xlim(numpy.min(ts),numpy.max(ts)+10)
135
plt.savefig('ts_hist.png')
136
#plt.show()
137

138
maxt=0
139
for t in range(len(ts)):
140
    if (ts[t]==numpy.max(ts)):
141
        maxt= t
142

143
s=maxt
144
butterfly = 'butterfly_%s_0.03_%s.txt'%(source_name,s) # text file where the butterfly plot is stored
145

146
bttflmk = ctools.ctbutterfly()
147
    
148
bttflmk['inobs'] = 'events.fits'
149
bttflmk['inmodel'] = 'results_%s_0.03_%s.xml'%(source_name,s)
150
bttflmk['srcname'] = '%s'%(source_name)
151
bttflmk['emin'] = emin
152
bttflmk['emax'] = emax
153
bttflmk['caldb']     = caldb
154
bttflmk['irf']       = irf
155
bttflmk['statistic'] = 'WSTAT'
156
bttflmk['outfile'] = butterfly
157
bttflmk.execute()
158

159

160
sed = "sed.fits"
161

162
sedmkr = cscripts.csspec()
163

164
sedmkr['inobs'] = 'events.fits'
165
sedmkr['inmodel'] = 'results_%s_0.03_%s.xml'%(source_name,s)
166
sedmkr['srcname'] = '%s'%(source_name)
167
sedmkr['outfile'] = sed
168
sedmkr['statistic'] = 'WSTAT'
169
sedmkr['method'] = "AUTO"
170
sedmkr['emin'] = emin
171
sedmkr['emax'] = emax
172
sedmkr['caldb']     = caldb
173
sedmkr['irf']       = irf
174
sedmkr['enumbins'] = 10
175
sedmkr['ebinalg'] = 'LOG'
176

177
sedmkr.execute()
178

179

180

181
def plot_butterfly(filename,ax,color,label):
182
    #this snippet is extracted from
183
    #$CTOOLS/examples/show_butterfly.py
184
    
185
    # Read butterfly file
186
        csv = gammalib.GCsv(filename)
187
    
188
    # Initialise arrays to be filled
189
        butterfly_x = []
190
        butterfly_y = []
191
        line_x      = []
192
        line_y      = []
193
    
194
    # Loop over rows of the file
195
        nrows = csv.nrows()
196
        for row in range(nrows):
197
        
198
        # Get conversion coefficient
199
            conv = csv.real(row,0) * csv.real(row,0) * gammalib.MeV2erg
200
        
201
        # Compute upper edge of confidence band
202
            butterfly_x.append(csv.real(row,0)/1.0e6) # TeV
203
            butterfly_y.append(csv.real(row,2)*conv)
204
        
205
        # Set line values
206
            line_x.append(csv.real(row,0)/1.0e6) # TeV
207
            line_y.append(csv.real(row,1)*conv)
208
    
209
    # Loop over the rows backwards to compute the lower edge of the
210
    # confidence band
211
        for row in range(nrows):
212
            index = nrows - 1 - row
213
            conv  = csv.real(index,0) * csv.real(index,0) * gammalib.MeV2erg
214
            butterfly_x.append(csv.real(index,0)/1.0e6)
215
            low_error = max(csv.real(index,3)*conv, 1e-26)
216
            butterfly_y.append(low_error)
217
            
218
    # Plot
219
        ax.plot(line_x,line_y,color=color,ls='--',alpha=0.5,label=label)
220
            #ax.fill(butterfly_x,butterfly_y,color=color,alpha=0.2)
221

222
def plot_sed(filename,ax,color,ts_thresh=9):
223
    #this snippet is extracted from
224
    #$CTOOLS/examples/show_spectrum.py
225
    
226
    fits     = gammalib.GFits(filename)
227
    table    = fits.table(1)
228
    c_energy = table['Energy']
229
    c_ed     = table['ed_Energy']
230
    c_eu     = table['eu_Energy']
231
    c_flux   = table['Flux']
232
    c_eflux  = table['e_Flux']
233
    c_ts     = table['TS']
234
    c_upper  = table['UpperLimit']
235
    
236
    # Initialise arrays to be filled
237
    energies    = []
238
    flux        = []
239
    ed_engs     = []
240
    eu_engs     = []
241
    e_flux      = []
242
    ul_energies = []
243
    ul_ed_engs  = []
244
    ul_eu_engs  = []
245
    ul_flux     = []
246
    
247
    # Loop over rows of the file
248
    nrows = table.nrows()
249
    for row in range(nrows):
250
        
251
        # Get Test Statistic, flux and flux error
252
        ts    = c_ts.real(row)
253
        flx   = c_flux.real(row)
254
        e_flx = c_eflux.real(row)
255
        
256
        # If Test Statistic is larger than threshold and flux error is smaller than
257
        # flux then append flux plots ...
258
        if ts > ts_thresh and e_flx < flx:
259
            energies.append(c_energy.real(row))
260
            flux.append(c_flux.real(row))
261
            ed_engs.append(c_ed.real(row))
262
            eu_engs.append(c_eu.real(row))
263
            e_flux.append(c_eflux.real(row))
264
        
265
        # ... otherwise append upper limit
266
        else:
267
            ul_energies.append(c_energy.real(row))
268
            ul_flux.append(c_upper.real(row))
269
            ul_ed_engs.append(c_ed.real(row))
270
            ul_eu_engs.append(c_eu.real(row))
271

272
# Set upper limit errors
273
    yerr = [0.6 * x for x in ul_flux]
274

275
    # Plot
276
    ax.errorbar(energies, flux, yerr=e_flux, xerr=[ed_engs, eu_engs],
277
                fmt='o'+color,alpha=0.4)
278
    ax.errorbar(ul_energies, ul_flux, xerr=[ul_ed_engs, ul_eu_engs],
279
                            yerr=yerr, uplims=True, fmt='o'+color,alpha=0.4)
280

281

282

283
fig6 = plt.figure()
284
ax = plt.subplot()
285

286
# define axes properties
287
ax.set_xscale('log')
288
ax.set_yscale('log')
289
ax.set_xlabel('Energy (TeV)')
290
ax.set_ylabel(r'E$^2$ $\times$ dN/dE (erg cm$^{-2}$ s$^{-1}$)')
291

292
# plot results
293
plot_butterfly(butterfly,ax,color='b',label='%s'%(source_name))
294
plot_sed(sed,ax,color='g')
295

296

297

298
# legend
299
ax.legend(loc='best')
300
pylab.xlim([0.03,30])
301
#pylab.ylim([10**(-10),10**(-9)])
302
plt.savefig('butterfly_%s_0.03_%s.png'%(source_name,s))
303
#plt.show()
304

305
ulimit=ctools.ctulimit()
306
ulimit['inobs']   = evfile
307
ulimit['emin']      = emin
308
ulimit['emax']      = emax
309
ulimit['caldb']     = caldb
310
ulimit['irf']       = irf
311
ulimit['srcname'] = '%s'%(source_name)
312
ulimit['inmodel']   = 'input_loglaw.xml'
313
ulimit.execute()
314

315

316
'''