Ejemplo n.º 1
0
def create_xml_from_fileFunctions(sourcename, ra, dec, outfile):
    '''
    Create xml file for given alpha and index
    Parameters
    ---------
    sourcename: studied source
    ra,dec: coordinates of the source
    alpha: EBL normalisation
    index: index of the power law
    '''
    lib, doc = xml.CreateLib()
    spec = xml.addFileFunction(lib,
                               sourcename,
                               type="PointSource",
                               filefun=outfile,
                               flux_free=1,
                               flux_value=1.,
                               flux_scale=1.,
                               flux_max=100000000.0,
                               flux_min=0.0)
    spatial = xml.AddPointLike(doc, ra, dec)
    spec.appendChild(spatial)
    lib.appendChild(spec)
    bkg = xml.addCTAIrfBackground(lib)
    lib.appendChild(bkg)
    open(outfile.replace('txt', 'xml'), 'w').write(doc.toprettyxml('  '))
Ejemplo n.º 2
0
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)):
	    filefun.write(str(ETeV[j]*1e6)+" "+str(max(1e-10,numpy.exp(-Tau_values)[j]))+"\n")
	#------------------ Make the XML model
        spec = xml.PowerLawEBL(lib,srcname,filename,eflux=1e6,flux_value=1.0e-16,index_value=-2.0,flux_free=0, index_free=0)
def GetSourceInformation(source, datfile):
    # table for the data
    xdata = []
    ydata = []
    dydata = []

    #Read Data : either you use the FGL name or another name (should be recognize by the astropy module
    #source = "3FGL J1517.6-2422"
    #Cat = FermiCatalogReader(source,FERMI_CATALOG_DIR,"e2dnde","TeV")

    Cat = FermiCatalogReader.fromName(source, FK5, FERMI_CATALOG_DIR, "e2dnde",
                                      "TeV")

    #print some information
    print "2FGL association ", Cat.Association('3FGL')
    print "3FGL Name ", Cat.Association('2FHL', '3FGL_name')
    print "3FGL Var Index ", Cat.GetVarIndex("3FGL")

    enerbut, but, enerphi, phi, ener3FGL, e2dnde3FGL, dem3FGL, dep3FGL, de2dnde3FGL = Get3FGL(
        Cat, xdata, ydata, dydata)
    enerbut2FHL, but2FHL, enerphi2FHL, phi2FHL, ener2FHL, e2dnde2FHL, dem2FHL, dep2FHL, de2dnde2FHL = Get2FHL(
        Cat, xdata, ydata, dydata)

    if datfile:
        #Read TEV DATA
        TeVData = numpy.genfromtxt(datfile, unpack=True)
        #read data from  https://arxiv.org/abs/1410.5897

        ener_TeV = TeVData[1]
        flux_TeV = TeVData[2] * ener_TeV**2.16
        Dflux_TeV_m = (TeVData[2] - TeVData[3]) * ener_TeV**2.16
        Dflux_TeV_p = (TeVData[4] - TeVData[2]) * ener_TeV**2.16

        for i in xrange(len(ener_TeV)):
            xdata.append(numpy.log10(ener_TeV[i]))
            ydata.append(numpy.log10(flux_TeV[i]))
            dydata.append(numpy.log10((Dflux_TeV_m[i] + Dflux_TeV_p[i]) / 2.))


################################## FIT
    xdata = numpy.array(xdata)
    ydata = numpy.array(ydata)
    dydata = numpy.array(dydata)
    popt, pcov = scipy.optimize.curve_fit(logparabola,
                                          xdata,
                                          ydata,
                                          p0=[1e-12, 1.5, 0.3],
                                          sigma=dydata)

    x = numpy.arange(-6, 2, .1)

    print "Norm at 0.1 TeV : ", popt[0], " +/- ", numpy.sqrt(pcov[0][0])
    print "Alpha : ", popt[1], " +/- ", numpy.sqrt(pcov[1][1])
    print "Beta : ", popt[2], " +/- ", numpy.sqrt(pcov[2][2])

    #change in ctools units
    escale = 1e5  #MeV
    norm = popt[0] * 624152.206 / escale**2

    import ctoolsAnalysis.xml_generator as xml

    lib, doc = xml.CreateLib()

    #SOURCE SPECTRUM
    #norm is at 100 GeV
    spec = xml.addLogparabola(lib, source, "PointSource", escale, 1, norm, 0,
                              1000, 1e-5, 1, popt[1], .5, 5., 1, popt[2])

    # Simulation at the 3FGL position
    ra, dec = Cat.GetPosition("3FGL")
    spatial = xml.AddPointLike(doc, ra, dec)

    spec.appendChild(spatial)
    lib.appendChild(spec)
    bkg = xml.addCTAIrfBackground(lib)
    lib.appendChild(bkg)
    print bkg
    open("out/" + source.replace(" ", "") + '_forSimu3FGLPosition.xml',
         'w').write(doc.toprettyxml('  '))

    ########################################"plot
    '''   
    catalog = FermiCatalogReader(None,FERMI_CATALOG_DIR)
    ra  = catalog.CatalogData['2FGL']['data'].field('RAJ2000')
    dec = catalog.CatalogData['2FGL']['data'].field('DEJ2000')
    ra_2,dec_2 = Cat.GetPosition("2FGL")
    r = calcAngSepDeg(ra,dec,ra_2,dec_2)
    res = r.argmin()        
    catalog.findfromCoordinate('2FGL',ra_2,dec_2)
    name_2FGL = catalog.CatalogData['2FGL']['data'].field('Source_Name')[res]
    #print name_2FGL.replace(" ","")
    read_Data = False
    try :    
        Data_2FGL_Ener = []
        Data_2FGL_dnde_sup = []
        Data_2FGL_dnde_inf = []
        Data_2FGL_dnde_moy = []
        with open(name_2FGL.replace(" ","")+".txt") as f:
         for line in f:
            Data_2FGL_Ener.append(float(line.split("\t")[0])/10e12)
            Data_2FGL_dnde_sup.append(float(line.split("\t")[2]))
            Data_2FGL_dnde_inf.append(float(line.split("\t")[3]))
            Data_2FGL_dnde_moy.append((float(line.split("\t")[2])+float(line.split("\t")[3]))/2)
        read_Data = True
    except IOError as e:
        print "I/O error({0}): {1}".format(e.errno, e.strerror) 
    '''

    import matplotlib.pyplot as plt
    fig = plt.figure()
    plt.loglog()
    plt.plot(enerbut, but, 'b-', label="3FGL")
    plt.plot(enerphi, phi, 'b-')
    plt.plot(enerbut2FHL, but2FHL, 'r-', label="2FHL")
    plt.plot(enerphi2FHL, phi2FHL, 'r-')

    plt.errorbar(ener3FGL,
                 e2dnde3FGL,
                 xerr=[dem3FGL, dep3FGL],
                 yerr=de2dnde3FGL,
                 fmt='o')
    plt.errorbar(ener2FHL,
                 e2dnde2FHL,
                 xerr=[dem2FHL, dep2FHL],
                 yerr=de2dnde2FHL,
                 fmt='o')

    if datfile:
        plt.errorbar(ener_TeV,
                     flux_TeV,
                     yerr=[Dflux_TeV_m, Dflux_TeV_p],
                     fmt='o',
                     label="H.E.S.S.")

    plt.legend(loc=3)

    #plot fit function

    plt.plot(numpy.power(10, x),
             numpy.power(10, logparabola(x, popt[0], popt[1], popt[2])), "b-")

    plt.ylabel('E2dN/dE(erg.cm-2.s-1)')
    plt.xlabel('energy (TeV)')
    plt.title(str(source))
    #plt.show()
    fig.savefig('plots/bad_spectrum/' + str(source) + '.png')
    fichier = open(
        "out/" + source.replace(" ", "") + '_forSimu3FGLPosition.xml', 'r+w')
    fichier2 = open("out/" + 'tmp.xml', 'w')
    with fichier as f:
        for line in f:

            if line.replace(" ", "").replace(
                    "\n", "") == '<sourcename="' + str(source).replace(
                        " ", "") + '"type="PointSource">':
                line = line.replace('type="PointSource">',
                                    'type="PointSource" tscalc="1">')
                print line
            fichier2.write(line)
            #print "ok"
            #line[ite] = line

            #ite = ite +1
        #if line.split("\t")[0]
    os.remove("out/" + source.replace(" ", "") + '_forSimu3FGLPosition.xml')
    shutil.move("out/" + "tmp.xml",
                "out/" + source.replace(" ", "") + '_forSimu3FGLPosition.xml')

    fichier3 = open("out/" + str(source) + '_results.xml', 'r')
    with fichier3 as f:
        for line in f:
            if line.find(str(source)) != -1:

                num = 41 + len(str(source))
                ts = float(line[num:num + 6])
            #break

    return popt[0], popt[1], popt[2], ts