observables.py 8.06 KB
import matplotlib.cm as colormap
from matplotlib.pyplot     import figure, show, legend, gca
from numpy                 import sort, log10, histogram, pi, arange, where, ma
from numpy                 import rot90, flipud, histogram2d, logspace, size, loadtxt
from mpl_toolkits.mplot3d  import Axes3D
from modules.read          import ReadResults
from modules.analytic      import Analytic_delay_vs_theta, Analytic_observables_vs_energy
from modules.constants     import degre, yr

#=========================== CORELATION BETWEEN OBSERVABLES ===========================#
def observables_vs_energy(energy,theta,delay,weight,Erange=[1e-3,1e3],nbBins=20):
   #Erange=[1e-1,1e5],nbBins=16 <=> Arlen 2014 (energy binning)
   bins=logspace(log10(Erange[0]),log10(Erange[1]),nbBins+1)
   ener = (bins[1:nbBins+1]*bins[0:nbBins])**0.5
   dtheta, dE = histogram(energy,bins,weights=weight*theta)
   dt,     dE = histogram(energy,bins,weights=weight*delay)
   dN,     dE = histogram(energy,bins,weights=weight)
   return ener, dtheta/dN, dt/dN

def observables_vs_delay(energy,theta,delay,weight,time_range=[10**-0.5,10**8.5],nbBins=9): 
   # <=> Taylor 2011 (time binning)
   bins=logspace(log10(time_range[0]),log10(time_range[1]),nbBins+1)
   time = (bins[1:nbBins+1]*bins[0:nbBins])**0.5
   dtheta, dt = histogram(delay,bins,weights=weight*theta)
   dE,     dt = histogram(delay,bins,weights=weight*energy)
   dN,     dt = histogram(delay,bins,weights=weight)
   return time, dtheta/dN, dE/dN

def drawObservables(fileId,psf=180,plot_generation=True,plot_others_codes=False):
   #ax = figure(figsize=(12,9)).add_subplot(111,projection='3d')
   ax1 = figure(figsize=(12,9)).add_subplot(111)
   ax2 = figure(figsize=(12,9)).add_subplot(111)
   ax3 = figure(figsize=(12,9)).add_subplot(111)

   fileId = "Simulations/"+fileId

   i=0
   nbBins = 100
   generation, weight, energy, delay, pos, theta = ReadResults(fileId,cols=[0,1,2,3,4,8])
   theta *= degre

   cond = (theta>1e-7*degre) & (delay>1e4) & (pos < psf)
   generation = generation[cond]
   energy = energy[cond]
   weight = weight[cond]
   delay = delay[cond]/yr
   theta = theta[cond]

   theta_range = [min(theta),max(theta)]
   delay_range = [min(delay),max(delay)]
   #energy_range = [min(energy),max(energy)]
   energy_range = [1e-3,1e4]
    
   weight /= sum(weight)
 
   if plot_generation: 
      cmaps=[colormap.Blues,colormap.Greens,colormap.Reds]
      colors=['b','g']
      for gen in [2,4,6]:#sort(list(set(generation))):
         cond = (generation==gen)
         H, xedges, yedges = histogram2d(log10(energy[cond]),log10(delay[cond]),bins=nbBins,weights=weight[cond])
         H = flipud(rot90(ma.masked_where(H==0,H)))
         im1 = ax1.pcolormesh(10**xedges,10**yedges,log10(H),cmap=cmaps[i]) 
           
         H, xedges, yedges = histogram2d(log10(energy[cond]),log10(theta[cond]),bins=nbBins,weights=weight[cond])
         H = flipud(rot90(ma.masked_where(H==0,H)))
         im2 = ax2.pcolormesh(10**xedges,10**yedges,log10(H),cmap=cmaps[i])    
              
         H, xedges, yedges = histogram2d(log10(delay[cond]),log10(theta[cond]),bins=nbBins,weights=weight[cond])
         H = flipud(rot90(ma.masked_where(H==0,H)))
         im3 = ax3.pcolormesh(10**xedges,10**yedges,log10(H),cmap=cmaps[i])
       
         if gen < 5:
            ener,angle,dt = observables_vs_energy(energy[cond],theta[cond],delay[cond],weight[cond])
            ax1.plot(ener,dt,color=colors[i],linewidth=2,label="gen = %.0f"%(i+1))
            ax2.plot(ener,angle,color=colors[i],linewidth=2,label="gen = %.0f"%(i+1))
            dt,angle,ener = observables_vs_delay(energy[cond],theta[cond],delay[cond],weight[cond])
            ax3.plot(dt,angle,color=colors[i],linewidth=2,label="gen = %.0f"%(i+1))

         i+=1

   ener,angle,dt = observables_vs_energy(energy,theta,delay,weight)
   ax1.plot(ener,dt,color='m',linewidth=2)
   ax2.plot(ener,angle,color='m',linewidth=2)
   dt,angle,ener = observables_vs_delay(energy,theta,delay,weight)
   ax3.plot(dt,angle,color='m',linewidth=2)

   nE = 5000 
   Emin = 1.e-3
   Emax = 1e4
   E = Emin*(Emax/Emin)**(arange(nE)/(nE-1.))
   theta_fit, delay_fit = Analytic_observables_vs_energy(E,"../"+fileId)
   ax1.plot(E,delay_fit/yr,'--k',linewidth=2)
   ax2.plot(E,theta_fit,'--k',linewidth=2)
   ax3.scatter(delay_fit/yr,theta_fit,color='k',marker="+")
    
   if plot_others_codes:
      # Results from Arlen 2014 - fig. 2a, 2b
      # =====================================
      #   - binning in energy : log, 16 bins between 1e-1 et 1e3 GeV
      #   - PSF = 10 deg
      data = loadtxt(fileId+'/Arlen2014-fig2a.csv', delimiter=',')
      ax1.plot(data[:,0],data[:,1],color="m",linestyle='--',linewidth=2,label="Arlen 2014 -no  EBL")
      data = loadtxt(fileId+'/Arlen2014-fig2b.csv', delimiter=',')
      ax1.plot(data[:,0],data[:,1],color="m",linestyle='-.',linewidth=2,label="Arlen 2014 - EBL")

      # Results from Taylor 2011 - fig. 2
      # =================================
      data = loadtxt(fileId+'/Taylor2011-fig2.csv', delimiter=',')
      ax1.plot(data[:,0]*1e-9,data[:,1],color="m",linestyle=':',linewidth=2,label="Taylor 2011")  

   #ax.legend(loc="best")
   #ax.set_xlabel("energy [GeV]")
   #ax.set_ylabel("$\\theta$ [deg]")
   #ax.set_zlabel("Time delay [s]")

   ax1.grid(b=True,which='major')
   ax1.legend(loc="best")   
   ax1.set_xscale('log')
   ax1.set_yscale('log')
   ax1.set_xlim(energy_range)
   ax1.set_ylim(delay_range)
   ax1.set_xlabel("energy [GeV]")
   ax1.set_ylabel("Time delay [yrs]")

   ax2.grid(b=True,which='major')
   ax2.legend(loc="best")
   ax2.set_xscale('log')
   ax2.set_yscale('log')
   ax2.set_xlim(energy_range)
   ax2.set_ylim(theta_range)
   ax2.set_xlabel("energy [GeV]")
   ax2.set_ylabel("$\\theta$ [deg]")

   ax3.grid(b=True,which='major')
   ax3.legend(loc="best")
   ax3.set_xscale('log')
   ax3.set_yscale('log')
   ax3.set_xlim(delay_range)
   ax3.set_ylim(theta_range)
   ax3.set_xlabel("Time delay [yrs]")
   ax3.set_ylabel("$\\theta$ [deg]")

   show()

def drawDelays_vs_energy(files,psf=180,plot_others_codes=False):
   ax1 = figure(figsize=(12,9)).add_subplot(111)
   nbBins = 100

   for fileId0 in files:
      fileId = "Simulations/simple case/"+fileId0
      gen, weight, energy, delay, pos, arrival_angle = ReadResults(fileId,cols=[0,1,2,3,4,8])
      cond = (gen==2) & (pos < psf) #PSF_Taylor2011(energy) 
      #energy = energy[cond]
      #arrival_angle = arrival_angle[cond]
      #delay = delay[cond]
      #weight = weight[cond]
      ener,dtheta,dt = observables_vs_energy(energy,arrival_angle*degre,delay/yr,weight)
      p0, =ax1.plot(ener,dt,marker='*',linewidth=2,label=fileId0) 
      
      nth = 5000
      thmin = 0.1
      thmax = 1e4
      E = thmin*(thmax/thmin)**(arange(nth)/(nth-1.))
      delay_fit = Analytic_observables_vs_energy(E,fileId)[1]
      ax1.plot(E,delay_fit/yr,color=p0.get_color(),linestyle="-")
                                                     
      if plot_others_codes:
         # Results from Arlen 2014 - fig. 2a, 2b
         # =====================================
         #   - binning in energy : log, 16 bins between 1e-1 et 1e3 GeV
         #   - PSF = 10 deg
         data = loadtxt(fileId+'/Arlen2014-fig2a.csv', delimiter=',')
         p1,= ax1.plot(data[:,0],data[:,1],color=p0.get_color(),linestyle='--',linewidth=2)
         data = loadtxt(fileId+'/Arlen2014-fig2b.csv', delimiter=',')
         p2,= ax1.plot(data[:,0],data[:,1],color=p0.get_color(),linestyle='-.',linewidth=2)

         # Results from Taylor 2011 - fig. 2
         # =================================
         data = loadtxt(fileId+'/Taylor2011-fig2.csv', delimiter=',')
         p3,= ax1.plot(data[:,0]*1e-9,data[:,1],color=p0.get_color(),linestyle=':',linewidth=2)

         leg1 = legend([p0,p1,p2,p3], ["our code","Arlen 2014 - fig 2a",
            "Arlen 2014 - fig 2b","Taylor 2011"], loc=1)
                                                               
   ax1.grid(b=True,which='major')  
   ax1.set_xscale('log')
   ax1.set_yscale('log')
   ax1.set_ylim([1,1e8])
   ax1.set_xlim([1e-1,1e3])
   ax1.set_xlabel("energy [GeV]")
   ax1.set_ylabel("Time delay [yrs]") 
   ax1.legend(loc=2)
   ax1 = gca().add_artist(leg1)

   show()