Blame view

src/distribution.py 13.8 KB
627ed999   Thomas Fitoussi   1. Reorganized fi...
1
from numpy import histogram, log10,logspace, shape, arange, pi, r_, diff, sqrt, correlate
4d2bede0   Thomas Fitoussi   add script for me...
2
from numpy import append, zeros, sin, size
627ed999   Thomas Fitoussi   1. Reorganized fi...
3
4
5
6
7
from matplotlib.pyplot import figure, show, setp, legend, gca
from matplotlib import gridspec, rcParams
from read import ReadProfile, ReadTiming, ReadSpectrum, ReadSourceSpectrum, ReadElmag, ReadTaylor
from read import ReadRadial, ReadAngleVsEnergy
from analytic import Ethreshold_gg, Analytic_flux, Eic, Analytic_dNdt, Analytic_dNdtheta
4d2bede0   Thomas Fitoussi   add script for me...
8
from constants import yr , degre
627ed999   Thomas Fitoussi   1. Reorganized fi...
9
10
11
12
13
14
15
16
17
18
19
20
21

label_size = 20
rcParams['xtick.labelsize'] = label_size
rcParams['ytick.labelsize'] = label_size

#====================================================================================
#       Compute distributions (dN/dE, dN/dtheta, dN/dt)
#====================================================================================
def distribution(x,weight,nbBins=100,x_range=[]):
   '''
      Compute distribution dN/dx vs x (x could be E, theta or time)
      Input: events x and weight
             (optional: number of bins and x range)
4d2bede0   Thomas Fitoussi   add script for me...
22
      Output: mean x [x_unit], dN/dx [x_unit^-1]
627ed999   Thomas Fitoussi   1. Reorganized fi...
23
24
25
26
   '''
   if x_range==[]:
      x_range[0]=min(x)
      x_range[1]=max(x)
4d2bede0   Thomas Fitoussi   add script for me...
27
   dN,xi = histogram(log10(x[x>0]),nbBins,range=log10(x_range),weights=weight[x>0])
627ed999   Thomas Fitoussi   1. Reorganized fi...
28
29
30
31
32
33
34
35
   xi = 10**xi
   xc = (xi[1:nbBins+1]+xi[0:nbBins])/2
   dx = xi[1:nbBins+1]-xi[0:nbBins]
   return xc, dN/dx

#====================================================================================
#       Draw distributions (dN/dE, dN/dtheta, dN/dt)
#====================================================================================
4d2bede0   Thomas Fitoussi   add script for me...
36
37
38
39
40
41
42
43
44
45
46
47
def which_label(fileId):
      if "Gamma" in fileId:
         return "$\\"+fileId+"$"
      elif "lambda" in fileId:
         return "$\\"+fileId+"$"
      elif "theta" in fileId:
         return "$\\"+fileId+"^\circ$"
      elif "tobs" in fileId:
         return "$\\theta_{obs}="+fileId.split("tobs=")[1]+"^\circ$"
      else:
         return fileId

627ed999   Thomas Fitoussi   1. Reorganized fi...
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def drawSpectrum(files,plot_analytic=False,plot_other_codes=False,plot="",Erange=[1e0,1e5],yrange=[1e-4,1e0],colors=['k','b','g','r','c','m','y']):
   '''
      Plot flux versus energy
      Input: list of directories
      Input (optional, default=False): plot analytic expression
      Output: graph spectrum normalize to 1 source photon
   '''
   fig = figure(figsize=(12,9))
   #gs = gridspec.GridSpec(2, 1, height_ratios=[3,1]) 
   #fig.subplots_adjust(hspace=0.001)
   #ax1 = fig.add_subplot(gs[0])
   #ax2 = fig.add_subplot(gs[1],sharex=ax1)
   ax1 = fig.add_subplot(111)
   i=0

4d2bede0   Thomas Fitoussi   add script for me...
63

627ed999   Thomas Fitoussi   1. Reorganized fi...
64
   for fileId in files:
4d2bede0   Thomas Fitoussi   add script for me...
65
      lab = which_label(fileId)
627ed999   Thomas Fitoussi   1. Reorganized fi...
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

      if plot=="1month":
         ener,dNdE = ReadSpectrum(fileId,[0,8])
         ax1.plot(ener,ener**2*dNdE,drawstyle='steps-mid',color=colors[i],linewidth=2,label=lab)
      else:
         # draw full spectrum
         ener,dNdE = ReadSpectrum(fileId,[0,1])
         z = ReadProfile(fileId,[3])
         if plot=="cascade contribution":
            p, = ax1.plot(ener,ener**2*dNdE *(1+z),drawstyle='steps-mid',linewidth=2,color=colors[i],label=lab)
            ener,dNdE0,dNdE1,dNdE2,dNdE3,dNdE4 = ReadSpectrum(fileId,[0,2,3,4,5,6])
            p1,=ax1.plot(ener,ener**2 *(dNdE1+dNdE2+dNdE3+dNdE4) *(1+z),color=p.get_color(),linewidth=1,linestyle='--')
            p2,=ax1.plot(ener,ener**2 *dNdE0 *(1+z),color=p.get_color(),linewidth=1,linestyle=':')
            leg1 = legend([p,p1,p2], ["all photons","cascade photons","source photons"],fontsize=label_size, loc=3)
         elif plot=="generation":
4d2bede0   Thomas Fitoussi   add script for me...
81
            p, = ax1.plot(ener,ener**2*dNdE *(1+z),drawstyle='steps-mid',linewidth=2,color=colors[i],label=lab)#"all")
627ed999   Thomas Fitoussi   1. Reorganized fi...
82
            ener,dNdE1,dNdE2,dNdE3 = ReadSpectrum(fileId,[0,3,4,5])  
4d2bede0   Thomas Fitoussi   add script for me...
83
84
85
            ax1.plot(ener,ener**2*dNdE1 *(1+z),color=p.get_color(),drawstyle='steps-mid',linestyle='--',linewidth=2)#,label="gen=1")
            ax1.plot(ener,ener**2*dNdE2 *(1+z),color=p.get_color(),drawstyle='steps-mid',linestyle='-.',linewidth=2)#,label="gen=2")
            ax1.plot(ener,ener**2*dNdE3 *(1+z),color=p.get_color(),drawstyle='steps-mid',linestyle=':',linewidth=2)#,label="gen=3")
627ed999   Thomas Fitoussi   1. Reorganized fi...
86
87
88
         elif plot=="obs time":
            p, = ax1.plot(ener,ener**2 *dNdE *(1+z),drawstyle='steps-mid',linewidth=2,color='k',label="$t_{obs}=\infty$")
            ener,dNdE1,dNdE2,dNdE3,dNdE4,dNdE5 = ReadSpectrum(fileId,[0,7,8,9,10,11])
4d2bede0   Thomas Fitoussi   add script for me...
89
90
            ax1.plot(ener,ener**2 *dNdE5 *(1+z),drawstyle='steps-mid',linestyle='-',linewidth=2,label="$t_{obs}$=$10^6$ yr")
            ax1.plot(ener,ener**2 *dNdE4 *(1+z),drawstyle='steps-mid',linestyle='-',linewidth=2,label="$t_{obs}$=$10^3$ yr")
627ed999   Thomas Fitoussi   1. Reorganized fi...
91
            ax1.plot(ener,ener**2 *dNdE3 *(1+z),drawstyle='steps-mid',linestyle='-',linewidth=2,label="$t_{obs}$=1 yr")
4d2bede0   Thomas Fitoussi   add script for me...
92
93
            ax1.plot(ener,ener**2 *dNdE2 *(1+z),drawstyle='steps-mid',linestyle='-',linewidth=2,label="$t_{obs}$=1 month")
            ax1.plot(ener,ener**2 *dNdE1 *(1+z),drawstyle='steps-mid',linestyle='-',linewidth=2,label="$t_{obs}$=1 day")
627ed999   Thomas Fitoussi   1. Reorganized fi...
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
         else:
            p, = ax1.plot(ener,ener**2 *dNdE *(1+z),drawstyle='steps-mid',linewidth=2,color=colors[i],label=lab)

      i+=1
         
   #minEner=min(ener)
   #maxEner=100e3
   #Ec = 309e3
   #alpha = (1-(4*ener*Ec/maxEner**2)**0.1) *3e-2 #dNdE[ener==minEner]*minEner**3*(1+z)/(minEner**(2-1.6))
   #ax1.plot(ener,alpha*ener**(2-1.6),'--m',linewidth=2)
   #alpha=2e-2 #dNdE[ener==minEner]*minEner**2*(1+z)/(minEner**(2-1.8))
   #ax1.plot(ener,alpha*ener**(2-1.8),'-.m',linewidth=2)

   if plot_analytic:
      #minEner=min(ener)
      #alpha=flux[ener==minEner]/sqrt(minEner)
      #ax1.plot(ener,alpha*sqrt(ener),'--m')
      #=== Gen=2 ===
      #ax1.plot(ener,2*Analytic_flux(ener),'--g')
      #=== Gen=4 ===
      Elim= Eic(Ethreshold_gg()/2)
      alpha = 0.75*9.262e3/Elim**(1/4.)
      alpha = dNdE[0]*ener[0]**2/sqrt(ener[0])
      ax1.plot(ener,2*ener**2*Analytic_flux(ener,fileId),'--b',linewidth=2)
      #alpha = 2*29.29e3
      #ax1.plot(ener,alpha*(ener/100)**(1/4.),'--m',linewidth=1)
      #ax1.plot(ener,ener**(0)*max(flux)*0.95,'--m',linewidth=2)
      #ax1.axvline(x=Ethreshold_gg(), ymin=0., ymax = 1., color='r', linewidth=2)
      #ax1.axvline(x=1e4, ymin=0., ymax = 1., color='g', linewidth=2)
        
   if plot_other_codes:
      coef = max(ener**2*dNdE)
      ener,E2dNdE,ener_PSF,E2dNdE_PSF = ReadElmag(fileId)
      E2dNdE *= coef/max(E2dNdE)
      E2dNdE_PSF *= coef/max(E2dNdE_PSF)
4d2bede0   Thomas Fitoussi   add script for me...
129
      ax1.plot(ener,E2dNdE*(1+z),"k-.",linewidth=2,label="Elmag")
627ed999   Thomas Fitoussi   1. Reorganized fi...
130
131
132
      #ax1.plot(ener_PSF,E2dNdE_PSF,"b.",label="Elmag - Fermi/LAT PSF")
      ener,E2dNdE = ReadTaylor(fileId)
      E2dNdE *= coef/max(E2dNdE)
4d2bede0   Thomas Fitoussi   add script for me...
133
      ax1.plot(ener,E2dNdE*(1+z),"k:",linewidth=2,label="Taylor 2011")
627ed999   Thomas Fitoussi   1. Reorganized fi...
134
135
136
137
138
139
140
141
142

   ax1.legend(loc="best",fontsize=label_size)
   #ax1.legend(loc=3,fontsize=label_size)
   ax1.set_xscale('log')
   ax1.set_yscale('log')
   ax1.grid(b=True,which='major')
   if "simple case" in fileId:
       ax1.set_ylabel("$E^2 dN/dE$ [GeV]",fontsize=label_size)
   else:
4d2bede0   Thomas Fitoussi   add script for me...
143
144
       ax1.set_ylabel("$E^2 dN/dE / L_{0}$",fontsize=label_size)
   ax1.set_xlabel("$E$ [GeV]",fontsize=label_size)
627ed999   Thomas Fitoussi   1. Reorganized fi...
145
146
147
148
149
150
151
152
153
154
155
156
   ax1.set_xlim(Erange)
   ax1.set_ylim(yrange)
   #ax2.set_xscale('log')
   #ax2.grid(b=True,which='major')
   #ax2.set_xlabel("energy [GeV]",fontsize=label_size)
   #xticklabels = ax1.get_xticklabels()
   #setp(xticklabels, visible=False)
   if plot=="cascade contribution":
      ax1 = gca().add_artist(leg1)

   show()

4d2bede0   Thomas Fitoussi   add script for me...
157
def drawArrivalAngle(files,plot_analytic=False,plot="",colors=['k','b','g','r','c','m','y'],yrange=[1e0,1e7]):
627ed999   Thomas Fitoussi   1. Reorganized fi...
158
159
160
161
162
163
164
165
166
   '''
      Plot flux versus arrival angle
      Input: list of directories
      Output: graph of flux versus angle
   '''
   fig = figure(figsize=(12,9))
   ax = fig.add_subplot(111)
   i=0 
   for fileId in files:
4d2bede0   Thomas Fitoussi   add script for me...
167
      lab = which_label(fileId)
627ed999   Thomas Fitoussi   1. Reorganized fi...
168
169
170

      if plot=="generation":
         theta,dNdtheta,dNdtheta1,dNdtheta2,dNdtheta3 = ReadRadial(fileId,[0,1,3,4,5])
4d2bede0   Thomas Fitoussi   add script for me...
171
172
173
174
175
         theta /= degre
         p,=ax.plot(theta,theta*dNdtheta*degre,drawstyle='steps-mid',color=colors[i],linewidth=2,label=lab)#,label="all gen")
         ax.plot(theta,theta*dNdtheta1*degre,color=p.get_color(),drawstyle='steps-mid',linestyle='--',linewidth=2)#,label="gen=1")
         ax.plot(theta,theta*dNdtheta2*degre,color=p.get_color(),drawstyle='steps-mid',linestyle='-.',linewidth=2)#,label="gen=2")
         ax.plot(theta,theta*dNdtheta3*degre,color=p.get_color(),drawstyle='steps-mid',linestyle=':',linewidth=2)#,label="gen=3")
627ed999   Thomas Fitoussi   1. Reorganized fi...
176
177
178

      elif plot=="obs time":
         theta,dNdtheta,dNdtheta1,dNdtheta2,dNdtheta3,dNdtheta4 = ReadRadial(fileId,[0,1,7,8,9,10])
4d2bede0   Thomas Fitoussi   add script for me...
179
180
181
182
183
184
         theta /= degre
         ax.plot(theta,theta*dNdtheta1*degre,drawstyle='steps-mid',linestyle='--',label="$t_{obs}$=1 day")
         ax.plot(theta,theta*dNdtheta2*degre,drawstyle='steps-mid',linestyle='--',label="$t_{obs}$=10 days")
         ax.plot(theta,theta*dNdtheta3*degre,drawstyle='steps-mid',linestyle='--',label="$t_{obs}$=1 month")
         ax.plot(theta,theta*dNdtheta3*degre,drawstyle='steps-mid',linestyle='--',label="$t_{obs}$=1 yr")
         ax.plot(theta,theta*dNdtheta*degre,color="k",drawstyle='steps-mid',linewidth=2,label="$t_{obs}$=\\infty")
627ed999   Thomas Fitoussi   1. Reorganized fi...
185
186
187
        
      else:
         theta,dndtheta = ReadRadial(fileId,[0,1])
4d2bede0   Thomas Fitoussi   add script for me...
188
189
         theta /= degre
         ax.plot(theta,theta*dndtheta*degre,drawstyle='steps-mid',linewidth=2,color=colors[i],label=lab)
627ed999   Thomas Fitoussi   1. Reorganized fi...
190
191
192
193

      i+=1   
        
   if plot_analytic:         
4d2bede0   Thomas Fitoussi   add script for me...
194
      ax.plot(theta,2*theta*Analytic_dNdtheta(theta,fileId),'--b',linewidth=2) 
627ed999   Thomas Fitoussi   1. Reorganized fi...
195
196
197
198
199

   ax.legend(loc="best",fontsize=label_size)
   ax.set_xscale('log')
   ax.set_yscale('log')
   ax.set_xlim([1e-5,180])
4d2bede0   Thomas Fitoussi   add script for me...
200
   ax.set_ylim(yrange)
627ed999   Thomas Fitoussi   1. Reorganized fi...
201
202
   ax.grid(b=True,which='major')
   ax.set_xlabel("$\\theta$ [deg]",fontsize=label_size)
4d2bede0   Thomas Fitoussi   add script for me...
203
   ax.set_ylabel("$\\theta dN/d\\theta$ [/ primary phot.]",fontsize=label_size)
627ed999   Thomas Fitoussi   1. Reorganized fi...
204
205
206
   
   show()

4d2bede0   Thomas Fitoussi   add script for me...
207
def drawTiming(files,plot_analytic=False,plot="",colors=['k','b','g','r','c','m','y'],yrange=[1e0,5e3]):
627ed999   Thomas Fitoussi   1. Reorganized fi...
208
209
210
211
212
213
214
215
216
   '''
      Plot flux versus time delay
      Input: list of directories
      Output: graph of flux versus time delay 
   '''
   fig = figure(figsize=(12,9))
   ax = fig.add_subplot(111)
   i=0
   for fileId in files:
4d2bede0   Thomas Fitoussi   add script for me...
217
      lab = which_label(fileId)
627ed999   Thomas Fitoussi   1. Reorganized fi...
218
219
220

      if plot=="generation":
         delta_t,dNdt,dNdt1,dNdt2,dNdt3 = ReadTiming(fileId,[0,1,3,4,5])
4d2bede0   Thomas Fitoussi   add script for me...
221
222
223
224
         p,=ax.plot(delta_t/yr,delta_t*dNdt,linestyle="steps-mid",color=colors[i],linewidth=2,label=lab)#"all gen")
         ax.plot(delta_t/yr,delta_t*dNdt1,color=p.get_color(),drawstyle='steps-mid',linestyle='--',linewidth=2)#,label="gen=1")
         ax.plot(delta_t/yr,delta_t*dNdt2,color=p.get_color(),drawstyle='steps-mid',linestyle='-.',linewidth=2)#,label="gen=2")
         ax.plot(delta_t/yr,delta_t*dNdt3,color=p.get_color(),drawstyle='steps-mid',linestyle=':',linewidth=2)#,label="gen=3")
627ed999   Thomas Fitoussi   1. Reorganized fi...
225
226
227
228
229
230
231
         #i=5
         #for gen in ReadGeneration(fileId,[0]):
         #   delta_t,dNdt = ReadTiming(fileId,[0,i])
         #   ax.plot(delta_t,dNdt,drawstyle='steps-mid',linestyle='--',label="gen=%.0f"%gen)
         #   i+=1
      else:
         delta_t,dNdt = ReadTiming(fileId,[0,1])
4d2bede0   Thomas Fitoussi   add script for me...
232
         p,=ax.plot(delta_t/yr,delta_t*dNdt,linestyle="steps-mid",linewidth=2,color=colors[i],label=lab)
627ed999   Thomas Fitoussi   1. Reorganized fi...
233
234
235
236
237
238
239
240
241

      i+=1   
        
   if plot_analytic:         
      ax.plot(delta_t,2*Analytic_dNdt(delta_t,fileId),'--b',linewidth=2) 
            
   ax.set_xscale('log')
   ax.set_yscale('log')
   ax.set_xlim([1e-4,1e10])
4d2bede0   Thomas Fitoussi   add script for me...
242
   ax.set_ylim(yrange)
627ed999   Thomas Fitoussi   1. Reorganized fi...
243
244
   ax.grid(b=True,which='major')
   ax.legend(loc="best",fontsize=label_size)
4d2bede0   Thomas Fitoussi   add script for me...
245
246
   ax.set_xlabel("$\\Delta t$ [yr]",fontsize=label_size)
   ax.set_ylabel("$\\Delta t\  dN/dt$ [/ primary phot.]",fontsize=label_size)
627ed999   Thomas Fitoussi   1. Reorganized fi...
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

   show()

def drawConvolveTiming(files):
   fig = figure(figsize=(12,9))
   ax = fig.add_subplot(111)
   for fileId in files:
      #print fileId, " ====================================="
      dt,N_MeV,N_GeV,N_TeV = ReadTiming(fileId,[0,2,3,4]) # MeV GeV TeV band
      delta_t = -dt[::-1]
      delta_t = append(delta_t,dt)
      dNdt_MeV = zeros(shape(dt)[0])
      dNdt_MeV = append(dNdt_MeV,N_MeV)
      dNdt_GeV = zeros(shape(dt)[0]) 
      dNdt_GeV = append(dNdt_GeV,N_GeV)
      dNdt_TeV = zeros(shape(dt)[0]) 
      dNdt_TeV = append(dNdt_TeV,N_TeV)
      #fft_MeV = rfft(dNdt_MeV)
      #fft_GeV = rfft(dNdt_GeV)
      #fft_TeV = rfft(dNdt_TeV)
      #CC_MeV_GeV = irfft(conj(fft_MeV) * fft_GeV)
      #CC_GeV_TeV = irfft(conj(fft_GeV) * fft_TeV)
      #CC_MeV_TeV = irfft(conj(fft_MeV) * fft_TeV)
      ac_MeV = correlate(dNdt_MeV,dNdt_MeV)[0]
      ac_GeV = correlate(dNdt_GeV,dNdt_GeV)[0]
      ac_TeV = correlate(dNdt_TeV,dNdt_TeV)[0]
      autocorr_MeV = correlate(dNdt_MeV,dNdt_MeV,'same')[0]
      autocorr_GeV = correlate(dNdt_GeV,dNdt_GeV,'same')[0] 
      autocorr_TeV = correlate(dNdt_TeV,dNdt_TeV,'same')[0]
      CC_MeV_GeV = correlate(dNdt_MeV,dNdt_GeV,'same')/sqrt(ac_GeV*ac_MeV)
      CC_GeV_TeV = correlate(dNdt_GeV,dNdt_TeV,'same')/sqrt(ac_TeV*ac_GeV)
      CC_MeV_TeV = correlate(dNdt_MeV,dNdt_TeV,'same')/sqrt(ac_TeV*ac_MeV)
      if shape(files)[0]==1:
         #ax.plot(delta_t,autocorr_MeV/ac_MeV,linestyle="steps-mid",label="MeV band")
         #ax.plot(delta_t,autocorr_GeV/ac_GeV,linestyle="steps-mid",label="GeV band")
         #ax.plot(delta_t,autocorr_TeV/ac_TeV,linestyle="steps-mid",label="TeV band")
         ax.plot(delta_t,CC_MeV_GeV,linestyle="steps-mid",label="MeV VS GeV band")
         #print "   MeV - GeV band: ",delta_t[r_[True, conv1[1:] > conv1[:-1]] & r_[conv1[:-1] > conv1[1:], True]] 
         ax.plot(delta_t,CC_GeV_TeV,linestyle="steps-mid",label="GeV VS TeV band")
         #print("   GeV - TeV band: ",delta_t[r_[True, conv2[1:] > conv2[:-1]] & r_[conv2[:-1] >   conv2[1:], True]])
         ax.plot(delta_t,CC_MeV_TeV,linestyle="steps-mid",label="MeV VS TeV band")
         #print "   MeV - TeV band: ",delta_t[r_[True, conv3[1:] > conv3[:-1]] & r_[conv3[:-1] > conv3[1:], True]]
      else:
         ax.plot(delta_t,CC_GeV_TeV,linestyle="steps-mid",label=fileId)

   #ax.set_xscale('log')
   #ax.set_yscale('log')
   ax.set_xlim([-1e16,1e16])
   ax.legend(loc="best",fontsize=label_size)
   ax.grid(b=True,which='major')
   ax.set_xlabel("Time delay [s]",fontsize=label_size)
   ax.set_ylabel("cross correlation [normalized]",fontsize=label_size)

   show()