def test_igmf(self): EGeV = np.logspace(1., 3.5, 50) pin = np.diag((1., 1., 0.)) * 0.5 source = Source(z=0.116, ra='21h58m52.0s', dec='-30d13m32s') alp = ALP(m=1., g=1e-10) ebl_model = 'dominguez' m = ModuleList(alp, source, pin=pin, EGeV=EGeV) m.add_propagation("IGMF", 0, nsim=10, B0=1e-10, # B field in micro Gauss n0=1e-7, L0=1e3, eblmodel=ebl_model ) # check access to module assert m.modules['MixIGMFCell'] == m.modules[0] # mixing should be so small, that it's the same as EBL attenuation only px, py, pa = m.run(multiprocess=1) pgg = px + py tau = OptDepth.readmodel(model='dominguez') # these numbers are pretty high, # this is reported in a github issue # and needs to be investigated further rtol = 0.2 atol = 0.03 for p in pgg: assert_allclose(p, np.exp(-tau.opt_depth(source.z, EGeV / 1e3)), rtol=rtol, atol=atol)
def get_ebl_absorb(energy_GeV, redshift, EBL_model): """ Compute the EBL absorbtion. Parameters ---------- - energy_GeV (array): photon energy in GeV - redshift (float): object redshift - EBL_model (str): the model to be used Outputs -------- - absorb = the absorbtion, to be multiplied to the spectrum """ tau = OptDepth.readmodel(model=EBL_model) absorb = np.exp(-1. * tau.opt_depth(redshift, energy_GeV*1e-3)) # search for duplicate, because of bug in interpolation at high absorb minabs = np.nanmin(absorb) if minabs <= 1e-4: wmin = (absorb == minabs) absorb[wmin] = 0.0 return absorb
def ComputeExtrapolateSpectrum(sourcename,z,eblmodel = "dominguez",alpha = -1,out="."): try : Cat = FermiCatalogReader.fromName(sourcename,FK5,FERMI_CATALOG_DIR,"dnde","MeV") #read 3FHL except : print 'cannot read 3FHL for some reason, returning' return emin = 5e4 #Mev emax = 100e6 params = Cat.ReadPL("3FHL") print params spec = Spectrum(params,Model="PowerLaw",Emin=emin, Emax=emax,Representation="dnde",escale="MeV", Npt=1000) energy,phi = spec.GetModel() # Cat.MakeSpectrum("3FHL",emin,emax) # _,_,energy,phi = Cat.Plot("3FHL") SpectreWithCutoff = cutoff(energy/1e6,z) #Correct for EBL using Dominguez model tau = OD.readmodel(model = eblmodel) TauEBL = tau.opt_depth(z,energy/1e6) Etau2 = numpy.interp([2.],TauEBL,energy/1e6)*1e6 # Input in TeV -> Get MeV at the end EBL_corrected_phi = phi*numpy.exp(alpha * TauEBL) phi_extrapolated = EBL_corrected_phi*SpectreWithCutoff # phi_extrapolated = EBL_corrected_phi outfile = out+"/"+sourcename.replace(" ","")+"_File.txt" CF.MakeFileFunction(energy,phi_extrapolated+1e-300,outfile) return outfile, Etau2
def _ebl_atten(z, eblmodel, egev): """ Compute EBL attenuation, using ebl-table project By default, using kx=ky=2 as interpolation order Parameters ---------- z : Redshift eblmodel : EBL Model egev : Energy (in GeV) Return ------ atten : attenuation """ # Check if redshift is greater than 1.e-3 # if not, then atten = 1 if z >= 1.e-3: # Initiate instance of OptDepth tau = OptDepth.readmodel(eblmodel) atten = np.exp(-1. * tau.opt_depth(z, egev * 1.e-3)) else: atten = 1.0 # Return return atten
def ComputeExtrapolateSpectrum(sourcename, z, eblmodel="dominguez", alpha=-1, out="."): try: Cat = FermiCatalogReader.fromName(sourcename, FK5, FERMI_CATALOG_DIR, "dnde", "MeV") #read 3FHL except: print 'cannot read 3FHL for some reason, returning' return emin = 5e4 #Mev emax = 100e6 params = Cat.ReadPL("3FHL") print params spec = Spectrum(params, Model="PowerLaw", Emin=emin, Emax=emax, Representation="dnde", escale="MeV", Npt=1000) energy, phi = spec.GetModel() # Cat.MakeSpectrum("3FHL",emin,emax) # _,_,energy,phi = Cat.Plot("3FHL") SpectreWithCutoff = cutoff(energy / 1e6, z) #Correct for EBL using Dominguez model tau = OD.readmodel(model=eblmodel) TauEBL = tau.opt_depth(z, energy / 1e6) Etau2 = numpy.interp( [2.], TauEBL, energy / 1e6) * 1e6 # Input in TeV -> Get MeV at the end EBL_corrected_phi = phi * numpy.exp(alpha * TauEBL) phi_extrapolated = EBL_corrected_phi * SpectreWithCutoff # phi_extrapolated = EBL_corrected_phi outfile = out + "/" + sourcename.replace(" ", "") + "_File.txt" CF.MakeFileFunction(energy, phi_extrapolated + 1e-300, outfile) return outfile, Etau2
thisppfactor = dminterpol.ppfactor_ann(args.sigmav, args.mass) elif args.process == 'decay': thisppfactor = dminterpol.ppfactor_dec(args.sigmav, args.mass) else: print('Unknown process. I assume you mean annihilation') thisppfactor = dminterpol.ppfactor_ann(args.sigmav, args.mass) if args.z > 1.e-3: # Create Optical-Depth instance tau = OptDepth.readmodel(model='franceschini') # Computing EBL attenuation for E_start up to DM mass atten = np.exp(-1. * tau.opt_depth(args.z, xvalues * args.mass * 1.e-3)) else: # Redshift is below minimum value available # Then, attenuation is equal to indentity atten = 1.0 # Computing the gamma-ray flux from dm flux = ewdm_int(args.mass, xvalues) flux_atten = flux[0] * atten * thisppfactor * args.jfactor
#------ Source Id data = numpy.genfromtxt("AGN_Monitoring_list.dat",dtype=str,unpack=True) for i in xrange(len(data[0])): srcname = data[0][i]+data[1][i] if srcname == config["target"]["name"]: redshift = data[-1][i] srcname = config["target"]["name"] ra = config["target"]["ra"] dec = config["target"]["dec"] #------------------ Value of the EBL normalisation and redshift Alpha = numpy.arange(.1,1.5001,.2) ETeV = numpy.logspace(-2,2.5,200) tau = OD.readmodel(model = 'franceschini') Tau_values = tau.opt_depth(redshift,ETeV) #----------------- make the first DC1 selection from ctoolsAnalysis.cscriptClass import CTA_ctools_script Script = CTA_ctools_script.fromConfig(config) Script.csobsselect(obsXml = "$CTADATA/obs/obs_agn_baseline.xml", log = True,debug = False) #------------------- Select the files print 'first selection of the data' Analyse = CTA_ctools_analyser.fromConfig(config) Analyse.ctselect(log = True) loglike_res = open(srcname+"_AlphaScan_DC1.txt","w") for ii in xrange(len(Alpha)):
def __init__(self, alp, source, **kwargs): """ Initialize mixing in the intergalactic magnetic field (IGMF). Parameters ---------- alp: :py:class:`~gammaALPs.ALP` :py:class:`~gammaALPs.ALP` object with ALP parameters source: :py:class:`~gammaALPs.Source` :py:class:`~gammaALPs.Source` object with source parameters EGeV: array-like Gamma-ray energies in GeV dL: array-like Domain lengths. If not given, they will be automatically generated. restore: str or None if str, identifier for files to restore environment. If None, initialize mixing with new B field restore_path: str full path to environment files B0: float IGMF at z = 0 in muG L0: float Coherence length at z = 0 in kpc n0: float electron density of intergalactic medium at z=0 in cm^-3 chi: `~scipy.interpolate.RectBivariateSpline` Spline function in (E [GeV], z) giving values of photon-photon dispersion chi at redshift z. eblmodel: string name of the used EBL model (default: Dominguez et al. 2011 Model) cosmo: `~astropy.cosmology.core.FlatLambdaCDM` chosen cosmology, default is H0 = 70, Om0 = 0.3 nsim: int number of B field realizations """ kwargs.setdefault('EGeV', np.logspace(0., 4., 100)) kwargs.setdefault('restore', None) kwargs.setdefault('restore_path', './') kwargs.setdefault('B0', 1.e-3) kwargs.setdefault('L0', 1.e3) kwargs.setdefault('n0', 1.e-7) kwargs.setdefault('nsim', 1) kwargs.setdefault('dL', None) kwargs.setdefault('chi', None) kwargs.setdefault('cosmo', FlatLambdaCDM(H0=70., Om0=0.3)) kwargs.setdefault('eblmodel', 'dominguez') kwargs.setdefault('seed', None) logger = logging.getLogger('gamma_alps') self._source = source self._t = OptDepth.readmodel(model=kwargs['eblmodel']) self._cosmo = kwargs['cosmo'] if kwargs['restore'] is None: self._Bfield_model = cell.Bcell(kwargs['B0'], kwargs['L0'], seed=kwargs['seed']) B, psi, dL, self._z_step = self._Bfield_model.new_Bcosmo( self._source.z, cosmo=kwargs['cosmo'], nsim=kwargs['nsim']) if kwargs['dL'] is not None: if isinstance(kwargs['dL'], list) or isinstance( kwargs['dL'], np.ndarray): dL = kwargs['dL'] else: raise TypeError("dL kwarg must be list or numpy.ndarray") self._z_mean = self._z_step[:-1] self._nel = kwargs['n0'] * (1. + self._z_mean)**3. dt = self._t.opt_depth(self._z_step[1:], kwargs['EGeV'] / 1.e3) - \ self._t.opt_depth(self._z_step[:-1], kwargs['EGeV'] / 1.e3) # absorption rate in kpc^-1 Gamma = dt.T / dL if type(kwargs['chi']) == RBSpline: Chi = kwargs['chi'](kwargs['EGeV'], self._z_mean) logger.info("Using interpolated chi") elif kwargs['chi'] is not None: logger.info("Using inputted chi") Chi = kwargs['chi'] else: # energy density of the CMB ~ (1+z)^4 Chi = trans.chiCMB * (1. + self._z_mean)**4. # init the transfer function with absorption super(MixIGMFCell, self).__init__(kwargs['EGeV'], B, psi, self._nel, dL, alp, Gamma=Gamma, chi=Chi, Delta=None) self._ee *= (1. + self._z_mean ) # transform energies to comoving frame else: dL, self._z_step = trafo.cosmo_cohlength(self._source.z, kwargs['L0'] * u.kpc, cosmo=self._cosmo) tra = super(MixIGMFCell, self).read_environ( kwargs['restore'], alp, filepath=kwargs['restore_path'], ) super(MixIGMFCell, self).__init__(tra.EGeV, tra.B, tra.psin, tra.nel, tra.dL, tra.alp, Gamma=tra.Gamma, chi=tra.chi, Delta=tra.Delta)
try: #conf file provided config = get_config(sys.argv[-2]) redshift = float(sys.argv[-1]) except : print "usage : python "+sys.argv[0]+" config_file redshift" exit() # #------------------- Analyse = CTA_ctools_analyser.fromConfig(config) #------------------ Value of the EBL ETeV = numpy.logspace(-2,2.5,200) EBL_mod = config["simulation"]["EBL_model"] tau = OD.readmodel(model = EBL_mod) Tau_values = tau.opt_depth(redshift,ETeV) #------------------ Make the XML model for simulations lib,doc = xml.CreateLib() srcname = config["target"]["name"] Model = config["simulation"]["spectrum_model"] #SOURCE SPECTRUM if Model == "PL": spec = xml.addPowerLaw1(lib,srcname,"PointSource", eflux=1e6*numpy.sqrt(Analyse.config["energy"]["emax"]*Analyse.config["energy"]["emin"]),flux_value=1e-10,flux_max=1000.0, flux_min=1e-5) elif Model == "PLEBL": #### EBL filename = config["out"]+"/tau_"+srcname+".txt" filefun = open(filename,"w") for j in xrange(len(ETeV)):
import gammalib import ctools import cscripts import numpy as np from ebltable.tau_from_model import OptDepth from random import randint, uniform import xml_generator as xml from astropy.io import fits from xml.dom import minidom tau = OptDepth.readmodel(model='dominguez') input_model = '3e-9_all.out.alert' imin = 0 gam = 2.19 ep = 100. tobscta = 600. debug = True edisp = True caldb = 'prod3b-v1' irf = 'North_z20_average_30m' declination, redshift, A = np.loadtxt(input_model, unpack=True) imax = len(redshift)
def __init__(self, alp, source, **kwargs): """ Initialize mixing in the intergalactic magnetic field (IGMF). Parameters ---------- alp: `~gammaALPs.ALP` `~gammaALPs.ALP` object with ALP parameters source: `~gammaALPs.Source` `~gammaALPs.Source` object with source parameters kwargs ------ EGeV: `~numpy.ndarray` Gamma-ray energies in GeV dL: `~numpy.ndarray` Domain lengths. If not given, they will be automatically generated. restore: str or None if str, identifier for files to restore environment. If None, initialize mixing with new B field restore_path: str full path to environment files B0: float IGMF at z = 0 in muG L0: float Coherence length at z = 0 in kpc n0: float electron density of intergalactic medium at z=0 in cm^-3 eblmodel: string name of the used EBL model (default: Dominguez et al. 2011 Model) cosmo: `~astropy.cosmology.core.FlatLambdaCDM` chosen cosmology, default is H0 = 70, Om0 = 0.3 nsim: int number of B field realizations """ kwargs.setdefault('EGeV', np.logspace(0., 4., 100)) kwargs.setdefault('restore', None) kwargs.setdefault('restore_path', './') kwargs.setdefault('B0', 1.e-3) kwargs.setdefault('L0', 1.e3) kwargs.setdefault('n0', 1.e-7) kwargs.setdefault('nsim', 1) kwargs.setdefault('dL', 'None') kwargs.setdefault('cosmo', FlatLambdaCDM(H0=70., Om0=0.3)) kwargs.setdefault('eblmodel', 'dominguez') self._source = source self._t = OptDepth.readmodel(model=kwargs['eblmodel']) self._cosmo = kwargs['cosmo'] if kwargs['restore'] == None: self._b = cell.Bcell(kwargs['B0'], kwargs['L0']) B, psi, dL, self._zstep = self._b.new_Bcosmo(self._source.z, cosmo=kwargs['cosmo'], nsim=kwargs['nsim']) if not kwargs['dL'].lower() == 'none': if type(kwargs['dL']) == list or type( kwargs['dL']) == np.ndarray: dL = kwargs['dL'] else: raise TypeError("dL kwarg must be list or numpy.ndarray") self._zmean = self._zstep[:-1] self._nel = kwargs['n0'] * (1. + self._zmean)**3. dt = self._t.opt_depth(self._zstep[1:],kwargs['EGeV'] / 1.e3) - \ self._t.opt_depth(self._zstep[:-1],kwargs['EGeV'] / 1.e3) # absorption rate in kpc^-1 Gamma = dt.T / dL # init the transfer function with absorption super(MixIGMFCell, self).__init__(kwargs['EGeV'], B, psi, self._nel, dL, alp, Gamma=Gamma, chi=None, Delta=None) self._ee *= (1. + self._zmean ) # transform energies to comoving frame else: dL, self._zstep = trafo.cosmo_cohlength(z, kwargs['L0'] * u.kpc, cosmo=self._cosmo) tra = super(MixIGMFCell, self).readEnviron( kwargs['restore'], alp, filepath=kwargs['restore_path'], ) super(MixIGMFCell, self).__init__(tra.EGeV, tra.B, tra.psin, tra.nel, tra.dL, tra.alp, Gamma=tra.Gamma, chi=tra.chi, Delta=tra.Delta) return
def __init__(self, **kwargs): """ Initialize the Cascade class. kwargs ------ BIGMF: float, intergalactic magnetic field strength in 10^-15 G (default = 1.) cohlnth: float, intergalactic magnetic field coherence length in Mpc (default = 1.) tmax: float, time in years for which AGN has been emitting gamma-rays (default = 10.) EmaxTeV: float, maximum energy of primary gamma-ray emission in TeV (default = 50.) EminTeV: float, minimum energy of primary gamma-ray emission in TeV (default = 0.01) eblModel: string, ebl model string (default = 'franceschini') bulkGamma: float, gamma factor of bulk plasma in jet (default = 1.) intSpec: function pointer to intrinsic AGN spectrum, call signature: intSpec(Energy (TeV), intSpecPar) in 1 / TeV / cm^2 / s (default= power law) intSpecPar: dictionary, intrinsic spectral parameters (default: {'Prefactor': 1e-10, 'Scale': 100 GeV, 'Index': -2.}) zSource: float, source redshift (default = 0.1) """ # --- setting the defaults kwargs.setdefault('BIGMF', 1.) kwargs.setdefault('cohlnth', 1.) kwargs.setdefault('zSource', 0.1) kwargs.setdefault('tmax', 10.) kwargs.setdefault('eblModel', 'franceschini') kwargs.setdefault('bulkGamma', 1.) kwargs.setdefault('EmaxTeV', 15.) kwargs.setdefault('EminTeV', 0.01) kwargs.setdefault('intSpec', lambda e, **par: pl(e, **par)) kwargs.setdefault('intSpecPar', { 'Prefactor': 1e-10, 'Scale': 100., 'Index': -2. }) # ------------------------ self.__dict__.update(kwargs) self.tau = OptDepth.readmodel(model=self.eblModel) # energy (in GeV) of CMB photon upscattered by electron produced in EBL self.E2eps = lambda ETeV: 0.63 * ETeV**2. # pair production with primary gamma-ray of energy E in TeV self.eps2E = lambda epsGeV: 1.26 * np.sqrt(epsGeV) # energy (in TeV) of primary gamma-ray for # upscattered CMB photon of energy eps (GeV) # IC cooling length for primary gamma rays. # See e.g. Meyer et al. (2016), Eq. 3 self.D_IC_Mpc = lambda epsGeV: 0.7 / self.eps2E(epsGeV) return
def __init__(self,**kwargs): """ Initialize the Cascade class. kwargs ------ BIGMF: float, intergalactic magnetic field strength in 10^-15 G (default = 1.) cohlnth: float, intergalactic magnetic field coherence length in Mpc (default = 1.) tmax: float, time in years for which AGN has been emitting gamma-rays (default = 10.) EmaxTeV: float, maximum energy of primary gamma-ray emission in TeV (default = 50.) EminTeV: float, minimum energy of primary gamma-ray emission in TeV (default = 0.01) eblModel: string, ebl model string (default = 'franceschini') bulkGamma: float, gamma factor of bulk plasma in jet (default = 1.) intSpec: function pointer to intrinsic AGN spectrum, call signature: intSpec(Energy (TeV), intSpecPar) in 1 / TeV / cm^2 / s (default= power law) intSpecPar: dictionary, intrinsic spectral parameters (default: {'Prefactor': 1e-10, 'Scale': 100 GeV, 'Index': -2.}) zSource: float, source redshift (default = 0.1) """ # --- setting the defaults kwargs.setdefault('BIGMF',1.) kwargs.setdefault('cohlnth',1.) kwargs.setdefault('zSource',0.1) kwargs.setdefault('tmax',10.) kwargs.setdefault('eblModel','franceschini') kwargs.setdefault('bulkGamma',1.) kwargs.setdefault('EmaxTeV',15.) kwargs.setdefault('EminTeV',0.01) kwargs.setdefault('intSpec',lambda e,**par: pl(e, **par)) kwargs.setdefault('intSpecPar', {'Prefactor': 1e-10, 'Scale': 100. , 'Index': -2.} ) # ------------------------ self.__dict__.update(kwargs) self.tau = OptDepth.readmodel(model = self.eblModel) # energy (in GeV) of CMB photon upscattered by electron produced in EBL self.E2eps = lambda ETeV: 0.63*ETeV**2. # pair production with primary gamma-ray of energy E in TeV self.eps2E = lambda epsGeV: 1.26*np.sqrt(epsGeV) # energy (in TeV) of primary gamma-ray for # upscattered CMB photon of energy eps (GeV) # IC cooling length for primary gamma rays. # See e.g. Meyer et al. (2016), Eq. 3 self.D_IC_Mpc= lambda epsGeV: 0.7 / self.eps2E(epsGeV) return
# out = join(os.getcwd(), "out") AnalysisType = "DominguezNoCutOff" #AnalysisType = "Dominguez3TeVCutOff" eblmodel = "dominguez" work = join(os.getcwd(), "work/"+AnalysisType) out = join(os.getcwd(), "out/"+AnalysisType) datapath = join(os.getcwd(), "out/"+AnalysisType) # datapath = join("/gpfs/LAPP-DATA/cta/ScienceTools", AnalysisType) os.system("mkdir -p "+work) sourcename,ra,dec,z,_,_ = SimulScript.GetInfoFromTable(TableInfo,i) data = join(datapath,sourcename+"_0.05TeV_event00001.fits") ############### Correct for EBL using EBL model energy = np.logspace(-2,2,100) #TeV tau = OD.readmodel(model = eblmodel) TauEBL = tau.opt_depth(z,energy) ############### simutime=100. irfTime=CF.IrfChoice(simutime) irf = "South_z20_"+str(int(float(irfTime)))+"h" caldb = "prod3b" for index in np.arange(Gmin,Gmax,Gstep): phi = powerlaw(energy,norm,index) for alpha in np.arange(alphamin,alphamax,alphastep): # create_fileFunctions(TauEBL, sourcename,phi,alpha,index) EBL_corrected_phi = phi*np.exp(-alpha * TauEBL) Filefunction = join(work,sourcename.replace(" ","").replace("-","m").replace("+","p")+"_alpha_"+str(alpha)+"_index_"+str(index)+".txt") CF.MakeFileFunction(energy*1e6,EBL_corrected_phi,Filefunction)
data = [Flux,DFlux,Index,DIndex,Ec] Spec = PlotLibrary.Spectrum(data,Model="PowerLaw",Emin=1e-4,Emax=Emax,escale = "TeV") #compute the model and the butterfly enerphi,phi = Spec.GetModel() enerbut,but = Spec.GetButterfly() #For comparison, show the butterfly in the Fermi energy range SpecNotExtrapolated = PlotLibrary.Spectrum(data,Model="PowerLaw",Emin=1e-4,Emax=0.064,escale = "TeV") #compute the model and the butterfly enerphi_NotExtrapolated,phi_NotExtrapolated = SpecNotExtrapolated.GetModel() enerbut_NotExtrapolated,but_NotExtrapolated = SpecNotExtrapolated.GetButterfly() #Correct for EBL using Dominguez model tau = OD.readmodel(model = 'dominguez') Tau_dominguez = tau.opt_depth(z,enerphi) EBL_corrected_phi = phi*numpy.exp(-1. * Tau_dominguez) Tau_dominguez = tau.opt_depth(z,enerbut) EBL_corrected_but = but*numpy.exp(-1. * Tau_dominguez) #draw import matplotlib.pyplot as plt plt.plot(enerbut, but, 'b--') plt.plot(enerphi,phi, 'b--',label = "Fermi measurement extrapolated") plt.legend(bbox_to_anchor=(.2, .98, .40, .102), loc=1, ncol=1, borderaxespad=0.) plt.yscale('log') plt.xscale('log')
enerphi, phi = Spec.GetModel() enerbut, but = Spec.GetButterfly() #For comparison, show the butterfly in the Fermi energy range SpecNotExtrapolated = PlotLibrary.Spectrum(data, Model="PowerLaw", Emin=1e-4, Emax=0.064, escale="TeV") #compute the model and the butterfly enerphi_NotExtrapolated, phi_NotExtrapolated = SpecNotExtrapolated.GetModel() enerbut_NotExtrapolated, but_NotExtrapolated = SpecNotExtrapolated.GetButterfly( ) #Correct for EBL using Dominguez model tau = OD.readmodel(model='dominguez') Tau_dominguez = tau.opt_depth(z, enerphi) EBL_corrected_phi = phi * numpy.exp(-1. * Tau_dominguez) Tau_dominguez = tau.opt_depth(z, enerbut) EBL_corrected_but = but * numpy.exp(-1. * Tau_dominguez) #draw import matplotlib.pyplot as plt plt.plot(enerbut, but, 'b--') plt.plot(enerphi, phi, 'b--', label="Fermi measurement extrapolated") plt.legend(bbox_to_anchor=(.2, .98, .40, .102), loc=1, ncol=1, borderaxespad=0.) plt.yscale('log')
enerphi, phi = Spec.GetModel() enerbut, but = Spec.GetButterfly() #For comparison, show the butterfly in the Fermi energy range SpecNotExtrapolated = PlotLibrary.Spectrum(data, Model="PowerLaw", Emin=1e-4, Emax=0.064, escale="TeV") #compute the model and the butterfly enerphi_NotExtrapolated, phi_NotExtrapolated = SpecNotExtrapolated.GetModel() enerbut_NotExtrapolated, but_NotExtrapolated = SpecNotExtrapolated.GetButterfly( ) #Correct for EBL using Dominguez model tau = OD(model='dominguez') Tau_dominguez = tau.opt_depth_array(z, enerphi) EBL_corrected_phi = phi * numpy.exp(-1. * Tau_dominguez[0]) Tau_dominguez = tau.opt_depth_array(z, enerbut) EBL_corrected_but = but * numpy.exp(-1. * Tau_dominguez[0]) #draw import matplotlib.pyplot as plt plt.plot(enerbut, but, 'b--') plt.plot(enerphi, phi, 'b--', label="Fermi measurement extrapolated") plt.legend(bbox_to_anchor=(.2, .98, .40, .102), loc=1, ncol=1, borderaxespad=0.) plt.yscale('log')
# ------------------------------ # # Source redshift z = 0.117 # array with energies in TeV ETeV = numpy.logspace(-1, 1, 50) #compute the optical depth #Supported EBL models: # Name: Publication: # franceschini Franceschini et al. (2008) http://www.astro.unipd.it/background/ # kneiske Kneiske & Dole (2010) # dominguez Dominguez et al. (2011) # inoue Inuoe et al. (2013) http://www.slac.stanford.edu/~yinoue/Download.html # gilmore Gilmore et al. (2012) (fiducial model) tau = OD.readmodel(model='franceschini') Tau_franceschini = tau.opt_depth(z, ETeV) tau = OD.readmodel(model='kneiske') Tau_kneiske = tau.opt_depth(z, ETeV) tau = OD.readmodel(model='dominguez') Tau_dominguez = tau.opt_depth(z, ETeV) #tau = OD(model = 'inoue') #Tau_inuoe = tau.opt_depth_array(z,ETeV) tau = OD.readmodel(model='gilmore') Tau_gilmore = tau.opt_depth(z, ETeV) #Draw part
Emin = Ebound[i]['E_MIN'] * 1e-9 #in MeV firstbin_found = True print "Found minimal energy for the analysis to be ", Emin print "Found maximal energy for the analysis to be ", Emax filefun.write("\nFound minimal energy for the analysis to be " + str(Emin) + "\n") filefun.write("Found maximal energy for the analysis to be " + str(Emax)) Analyse.config["energy"]["emin"] = Emin Analyse.config["energy"]["emax"] = Emax Script.config["energy"]["emin"] = Emin Script.config["energy"]["emax"] = Emax #------------------ Value of the EBL and redshift ETeV = numpy.logspace(-2, 2.5, 200) tau = OD.readmodel(model='franceschini') Tau_values = tau.opt_depth(redshift, ETeV) #------------------ Make the XML model lib, doc = xml.CreateLib() srcname = config["target"]["name"] #SOURCE SPECTRUM if Model == "PL": spec = xml.addPowerLaw1(lib, srcname, "PointSource", eflux=1e6 * numpy.sqrt(Analyse.config["energy"]["emax"] * Analyse.config["energy"]["emin"]), flux_value=1e-14, flux_max=1000.0,
# ------------------------------ # # Source redshift z = 0.117 # array with energies in TeV ETeV = numpy.logspace(-1,1,50) #compute the optical depth #Supported EBL models: # Name: Publication: # franceschini Franceschini et al. (2008) http://www.astro.unipd.it/background/ # kneiske Kneiske & Dole (2010) # dominguez Dominguez et al. (2011) # inoue Inuoe et al. (2013) http://www.slac.stanford.edu/~yinoue/Download.html # gilmore Gilmore et al. (2012) (fiducial model) tau = OD(model = 'franceschini') Tau_franceschini = tau.opt_depth_array(z,ETeV) tau = OD(model = 'kneiske') Tau_kneiske = tau.opt_depth_array(z,ETeV) tau = OD(model = 'dominguez') Tau_dominguez = tau.opt_depth_array(z,ETeV) #tau = OD(model = 'inoue') #Tau_inuoe = tau.opt_depth_array(z,ETeV) tau = OD(model = 'gilmore') Tau_gilmore = tau.opt_depth_array(z,ETeV) #Draw part
# out = join(os.getcwd(), "out") AnalysisType = "DominguezNoCutOff" #AnalysisType = "Dominguez3TeVCutOff" eblmodel = "dominguez" work = join(os.getcwd(), "work/" + AnalysisType) out = join(os.getcwd(), "out/" + AnalysisType) datapath = join(os.getcwd(), "out/" + AnalysisType) # datapath = join("/gpfs/LAPP-DATA/cta/ScienceTools", AnalysisType) os.system("mkdir -p " + work) sourcename, ra, dec, z, _, _ = SimulScript.GetInfoFromTable(TableInfo, i) data = join(datapath, sourcename + "_0.05TeV_event00001.fits") ############### Correct for EBL using EBL model energy = np.logspace(-2, 2, 100) #TeV tau = OD.readmodel(model=eblmodel) TauEBL = tau.opt_depth(z, energy) ############### simutime = 100. irfTime = CF.IrfChoice(simutime) irf = "South_z20_" + str(int(float(irfTime))) + "h" caldb = "prod3b" for index in np.arange(Gmin, Gmax, Gstep): phi = powerlaw(energy, norm, index) for alpha in np.arange(alphamin, alphamax, alphastep): # create_fileFunctions(TauEBL, sourcename,phi,alpha,index) EBL_corrected_phi = phi * np.exp(-alpha * TauEBL) Filefunction = join( work,
def __init__(self, x, y, dy, z, dx=None, x_min=None, x_max=None, llh_fermi_interp=None, casc=None, ebl_model='dominguez', interp_casc=True, on_region_radius=0.2): """ Initialize the class Parameters ---------- x: array-like Energy values in TeV for IACT measurement y: array-like Flux values in TeV for IACT measurement in dN / dE format in units of (TeV s cm^2)^-1 dy: array-like Errors on flux z: float source redshift dx: array-like or None Bin width in TeV llh_fermi_interp: interpolation function Function that receives spectral parameters as input and returns the Fermi-LAT likelhood casc: `~cascmaps.CascMap` Cascade map container ebl_model: str EBL model identifier on_region_radius: float assumed size for ON region in degrees interp_casc: bool if True, use 1D cubic interpolation to calculate cascade contribution to IACT spectrum """ self._x = x self._y = y self._dx = dx self._dy = dy self._x_min = x_min self._x_max = x_max self._llh_fermi_interp = llh_fermi_interp self._casc = casc self._par_names = None self._par_islog = None self._cov_inv = None self._minimize_f = None self._m = None self._res = None self._z = z self._y_pred = None self._tau = OptDepth.readmodel(model=ebl_model) self._atten = np.exp(-self._tau.opt_depth(self._z, self._x)) self._on_region_rad = Angle(on_region_radius, unit="deg") self._on_region = None self._llh_fermi = None self._cr_spec = None self._int_spec = None self._interp_casc = interp_casc
def add_propagation(self, environ, order, **kwargs): """ Add a propagation environment to the module list Parameters ---------- environ: str identifier for environment, see notes for possibilities order: int the order of the environment along the line of sight, starting at zero, where zero is closest to the source and highest value is closest to the observer Notes ----- kwargs are passed to the specific environment. Available environments are the classes given in :py:class:`~gammaALPs.base.environs`, where all the specific options are listed. The identifiers for the environments are: - IGMF: initializes :py:class:`~gammaALPs.base.environs.MixIGMFCell` for mixing in intergalactic magnetic field (IGMF) which is assumed to be of a cell-like structure - ICMCell: initializes :py:class:`~gammaALPs.base.environs.MixICMCell` for mixing in intra-cluster medium which is assumed to be of a cell-like structure - ICMGaussTurb: initializes :py:class:`~gammaALPs.base.environs.MixICMGaussTurb` for mixing in intra-cluster medium which is assumed to follow a Gaussian turbulence spectrum - Jet: initializes :py:class:`~gammaALPs.base.environs.MixJet` for mixing in the AGN jet, where the field is assumed to be coherent - JetHelicalTangled: initializes :py:class:`~gammaALPs.base.environs.MixJetHelicalTangled` for mixing in the AGN jet with two field components (tangled and helical) - GMF: initializes :py:class:`~gammaALPs.base.environs.MixGMF` for mixing in the Galactic magnetic field (GMF) of the Milky Way - File: initializes :py:class:`~gammaALPs.base.environs.MixFromFile` for mixing in a magnetic field given by a data file - Array: initializes :py:class:`~gammaALPs.base.environs.MixFromArray` for mixing in a magnetic field given by a numpy arrays for B,psi,nel,r, and dL - EBL: initializes :py:class:`~ebltable.tau_from_model.OptDepth` for EBL attenuation, i.e. no photon-ALP mixing in the intergalactic medium """ kwargs.setdefault('eblmodel', 'dominguez') kwargs.setdefault('eblnorm', 1.) kwargs.setdefault('seed', self._seed) self._eblnorm = kwargs['eblnorm'] if environ == 'EBL': self._modules.insert(order, OptDepth.readmodel(model=kwargs['eblmodel'])) self._atten = np.exp(-self._eblnorm *\ self._modules[order].opt_depth(self.source.z, self.EGeV / 1e3)) elif environ == 'IGMF': self._modules.insert(order, env.MixIGMFCell(self.alp, self.source, EGeV=self.EGeV, **kwargs)) elif environ == 'ICMCell': self._modules.insert(order, env.MixICMCell(self.alp, EGeV=self.EGeV * (1. + self.source.z), **kwargs)) elif environ == 'ICMGaussTurb': self._modules.insert(order, env.MixICMGaussTurb(self.alp, EGeV=self.EGeV * (1. + self.source.z), **kwargs)) elif environ == 'Jet': self._modules.insert(order, env.MixJet(self.alp, self.source, EGeV=self.EGeV * (1. + self.source.z), **kwargs)) elif environ == 'JetHelicalTangled': self._modules.insert(order, env.MixJetHelicalTangled(self.alp, self.source, EGeV=self.EGeV * (1. + self.source.z), **kwargs)) elif environ == 'GMF': self._modules.insert(order, env.MixGMF(self.alp, self.source, EGeV=self.EGeV, **kwargs)) elif environ == 'File': self._modules.insert(order, env.MixFromFile(self.alp, EGeV=self.EGeV, **kwargs)) elif environ == 'Array': self._modules.insert(order, env.MixFromArray(self.alp, EGeV=self.EGeV, **kwargs)) else: raise ValueError("Unkwon Environment chosen") return
import matplotlib.pyplot as plt # ------------------------------ # # initialize the optical depth class # the model keyword specifies the EBL model to be used. #Supported EBL models: # Name: Publication: # franceschini Franceschini et al. (2008) http://www.astro.unipd.it/background/ # kneiske Kneiske & Dole (2010) # dominguez Dominguez et al. (2011) # inuoe Inuoe et al. (2013) http://www.slac.stanford.edu/~yinoue/Download.html # gilmore Gilmore et al. (2012) (fiducial model) # Note: make sure that you have set the environment variable EBL_FILE_PATH # by e.g. # export EBL_FILE_PATH=/path/to/repro/ebl/ebl_model_files tau = OD(model='franceschini') # Source redshift z = 0.2 # array with energies in TeV ETeV = np.logspace(-1, 1, 50) # calculating the optical depth for a redshift z and TeV energies # this returns a two dimensional array with dimensions # of the redshift array times dimensions of the energy array. # Since z is a scalar here, it will return a 1 x 50 dim array. t = tau.opt_depth_array(z, ETeV) # calculate the energy in TeV for which we reach an optical depth of 1: tauLim = 1. ETeV_tEq1 = 10.**tau.opt_depth_Inverse(z, tauLim) / 1e3