Example #1
0
def PlotUL(pars,config,ULFlux,Index):

    #Compute the SED
    E = np.logspace(np.log10(pars.Emin), np.log10(pars.Emax), pars.N)
    SED = MEV_TO_ERG  * E ** 2 * (-Index+1)*ULFlux* np.power(E,-Index)/(np.power(pars.Emax,-Index+1)-np.power(pars.Emin,-Index+1))

    #Actually make the plot
    plt.xlabel(r"E [MeV]")
    plt.ylabel(r"$E^{2}dN/dE [ erg.cm^{-2}.s^{-1} ]$")
    plt.loglog()
    plt.plot(E,SED,"-",color='black')

    # Plot the upper limits. For some reason, matplotlib draws the arrows inverted for uplim and lolim [?]
    # This is a known issue fixed in matplotlib 1.4: https://github.com/matplotlib/matplotlib/pull/2452
    if LooseVersion(matplotlib.__version__) < LooseVersion("1.4.0"):
        plt.errorbar([E[0],E[-1]], [SED[0],SED[-1]],  yerr=[SED[0]*0.8,SED[-1]*0.8],fmt='.',color='black',ls='None',lolims=[1,1])
    else:
        plt.errorbar([E[0],E[-1]], [SED[0],SED[-1]],  yerr=[SED[0]*0.8,SED[-1]*0.8],fmt='.',color='black',ls='None',uplims=[1,1])

    #save the plot
    filebase = utils._SpecFileName(config)
    plt.tight_layout()
    plt.savefig(filebase + '.png', dpi=150, facecolor='w', edgecolor='w',
            orientation='portrait', papertype=None, format=None,
            transparent=False, bbox_inches=None, pad_inches=0.1,
            frameon=None)
Example #2
0
def plot_sed_fromconfig(config,ignore_missing_bins=False):
    utils.mkdir_p(config["out"]+"/Spectrum")
    srcname = config['target']['name']
    Emin = config['energy']['emin']
    Emax = config['energy']['emax']
    filename = utils._SpecFileName(config)
    Param = Params(srcname, Emin=Emin, Emax=Emax, PlotName=filename)
    Result = utils.ReadResult(config)

    # if the TS > ts limit plot the butterfly, if not draw UL
    if Result["TS"]> config['UpperLimit']['TSlimit'] :
        PlotSED(config,Param,ignore_missing_bins)
    else :
        try :
            PlotUL(Param,config,Result['Ulvalue'],config['UpperLimit']['SpectralIndex'])
        except :
            print "Not able to plot an upper limit in a SED diagram. UL computed?"
Example #3
0
def plot_sed_fromconfig(config, ignore_missing_bins=False):
    utils.mkdir_p(config["out"] + "/Spectrum")
    srcname = config['target']['name']
    Emin = config['energy']['emin']
    Emax = config['energy']['emax']
    filename = utils._SpecFileName(config)
    Param = Params(srcname, Emin=Emin, Emax=Emax, PlotName=filename)
    Result = utils.ReadResult(config)

    # if the TS > ts limit plot the butterfly, if not draw UL
    if Result["TS"] > config['UpperLimit']['TSlimit']:
        PlotSED(config, Param, ignore_missing_bins)
    else:
        try:
            PlotUL(Param, config, Result['Ulvalue'],
                   config['UpperLimit']['SpectralIndex'])
        except:
            print "Not able to plot an upper limit in a SED diagram. UL computed?"
Example #4
0
def PlotUL(pars, config, ULFlux, Index):

    ROOT.gROOT.SetBatch(ROOT.kTRUE)
    root_style.RootStyle()

    # Compute the SED
    E = np.logspace(np.log10(pars.Emin), np.log10(pars.Emax), pars.N)
    SED = (
        MEV_TO_ERG
        * E ** 2
        * (-Index + 1)
        * ULFlux
        * np.power(E, -Index)
        / (np.power(pars.Emax, -Index + 1) - np.power(pars.Emin, -Index + 1))
    )

    # Actually make the plot
    c_plot = ROOT.TCanvas(pars.PlotName)
    c_plot.SetLogx()
    c_plot.SetLogy()

    xmin, xmax = E[0] * 0.7, E[-1] * 1.6
    ymin = min(SED[0], SED[-1]) * 0.15
    ymax = max(SED[0], SED[-1]) * 3
    ghSED = ROOT.TH2F("ghSED", "", 10000, xmin, xmax, 100, ymin, ymax)
    ghSED.SetStats(000)
    ghSED.SetTitle(pars.PlotName)
    ghSED.SetXTitle("E [MeV]")
    ghSED.SetYTitle("E^{2}dN/dE [ erg cm^{-2} s^{-1} ] ")
    ghSED.Draw()

    tgr = ROOT.TGraph(pars.N, np.array(E), np.array(SED))
    tgr.Draw("L")

    Ar_1 = ROOT.TArrow(E[0], SED[0] * 0.2, E[0], SED[0], 0.02)
    Ar_2 = ROOT.TArrow(E[-1], SED[-1] * 0.2, E[-1], SED[-1], 0.02)
    Ar_2.Draw("<|")
    Ar_1.Draw("<|")

    # save the canvas
    filebase = utils._SpecFileName(config)
    c_plot.Print(filebase + ".C")
    c_plot.Print(filebase + ".eps")
    c_plot.Print(filebase + ".png")
Example #5
0
def PlotUL(pars, config, ULFlux, Index):

    #Compute the SED
    E = np.logspace(np.log10(pars.Emin), np.log10(pars.Emax), pars.N)
    SED = MEV_TO_ERG * E**2 * (-Index + 1) * ULFlux * np.power(E, -Index) / (
        np.power(pars.Emax, -Index + 1) - np.power(pars.Emin, -Index + 1))

    #Actually make the plot
    plt.xlabel(r"E [MeV]")
    plt.ylabel(r"$E^{2}dN/dE [ erg.cm^{-2}.s^{-1} ]$")
    plt.loglog()
    plt.plot(E, SED, "-", color='black')

    # Plot the upper limits. For some reason, matplotlib draws the arrows inverted for uplim and lolim [?]
    # This is a known issue fixed in matplotlib 1.4: https://github.com/matplotlib/matplotlib/pull/2452
    if LooseVersion(matplotlib.__version__) < LooseVersion("1.4.0"):
        plt.errorbar([E[0], E[-1]], [SED[0], SED[-1]],
                     yerr=[SED[0] * 0.8, SED[-1] * 0.8],
                     fmt='.',
                     color='black',
                     ls='None',
                     lolims=[1, 1])
    else:
        plt.errorbar([E[0], E[-1]], [SED[0], SED[-1]],
                     yerr=[SED[0] * 0.8, SED[-1] * 0.8],
                     fmt='.',
                     color='black',
                     ls='None',
                     uplims=[1, 1])

    #save the plot
    filebase = utils._SpecFileName(config)
    plt.tight_layout()
    plt.savefig(filebase + '.png',
                dpi=150,
                facecolor='w',
                edgecolor='w',
                orientation='portrait',
                papertype=None,
                format=None,
                transparent=False,
                bbox_inches=None,
                pad_inches=0.1,
                frameon=None)
Example #6
0
def PlotUL(pars, config, ULFlux, Index):

    ROOT.gROOT.SetBatch(ROOT.kTRUE)
    root_style.RootStyle()

    #Compute the SED
    E = np.logspace(np.log10(pars.Emin), np.log10(pars.Emax), pars.N)
    SED = MEV_TO_ERG * E**2 * (-Index + 1) * ULFlux * np.power(E, -Index) / (
        np.power(pars.Emax, -Index + 1) - np.power(pars.Emin, -Index + 1))

    #Actually make the plot
    c_plot = ROOT.TCanvas(pars.PlotName)
    c_plot.SetLogx()
    c_plot.SetLogy()

    xmin, xmax = E[0] * 0.7, E[-1] * 1.6
    ymin = min(SED[0], SED[-1]) * 0.15
    ymax = max(SED[0], SED[-1]) * 3
    ghSED = ROOT.TH2F("ghSED", "", 10000, xmin, xmax, 100, ymin, ymax)
    ghSED.SetStats(000)
    ghSED.SetTitle(pars.PlotName)
    ghSED.SetXTitle("E [MeV]")
    ghSED.SetYTitle("E^{2}dN/dE [ erg cm^{-2} s^{-1} ] ")
    ghSED.Draw()

    tgr = ROOT.TGraph(pars.N, np.array(E), np.array(SED))
    tgr.Draw("L")

    Ar_1 = ROOT.TArrow(E[0], SED[0] * 0.2, E[0], SED[0], 0.02)
    Ar_2 = ROOT.TArrow(E[-1], SED[-1] * 0.2, E[-1], SED[-1], 0.02)
    Ar_2.Draw("<|")
    Ar_1.Draw("<|")

    #save the canvas
    filebase = utils._SpecFileName(config)
    c_plot.Print(filebase + '.C')
    c_plot.Print(filebase + '.eps')
    c_plot.Print(filebase + '.png')
Example #7
0
def PlotSED(config,pars):
    """plot a nice SED with a butterfly and points"""
    ROOT.gROOT.SetBatch(ROOT.kTRUE)
    root_style.RootStyle()

    # Read the ascii file where the butterfly is stored
    filebase = utils._SpecFileName(config)

    lines = open(filebase + '.dat', 'r').readlines()
    SED = []
    E = []
    Err = []

    for i in xrange(len(lines) - 1):
        words = lines[i + 1].split()
        if float(words[0])<pars.Emax :
            E.append(float(words[0]))
            SED.append(float(words[1]))
            Err.append(float(words[2]))
    ilen = len(SED)

    #From dN/dE to SED
    Fluxp = np.array(SED)*np.exp(np.array(Err)/np.array(SED))
    Fluxm =  np.array(SED)*np.exp(-np.array(Err)/np.array(SED))
    ErrorFlux = np.zeros(2 * ilen + 1)
    ErrorE = np.zeros(2 * ilen + 1)

    #Compute the butterfly and close it
    for i in xrange(ilen):
        ErrorFlux[i] = Fluxp[i]
        ErrorE[i] = E[i]
    for i in xrange(ilen):
        ErrorFlux[ilen + i] = Fluxm[ilen - i - 1]
        ErrorE[ilen + i] = E[ilen - i - 1]
    ErrorFlux[-1] = Fluxp[0]
    ErrorE[-1] = E[0]

    #Actually make the plot
    c_plot = ROOT.TCanvas(pars.PlotName)
    c_plot.SetLogx()
    c_plot.SetLogy()

    xmin, xmax = E[0] * 0.8, E[-1] * 1.5
    ymin = min(np.array(SED) - np.array(Err)) * 0.2
    ymax = max(np.array(SED) + np.array(Err)) * 3
    ghSED = ROOT.TH2F("ghSED", "", 10000, xmin, xmax, 100, ymin, ymax)
    ghSED.SetStats(000)
    ghSED.SetTitle(pars.PlotName)
    ghSED.SetXTitle("E [MeV]")
    ghSED.SetYTitle("E^{2}dN/dE [ erg cm^{-2} s^{-1} ] ")
    ghSED.Draw()

    tgr = ROOT.TGraph(ilen, np.array(E), np.array(SED))
    tgr.SetLineWidth(2)
    tgr.SetLineColor(pars.LineColor)
    tgr.Draw("L")

    tgerr = ROOT.TGraph(2 * ilen + 1, ErrorE, ErrorFlux)
    tgerr.SetLineColor(pars.LineColor)
    tgerr.Draw("L")

    #Plot points
    NEbin = int(config['Ebin']['NumEnergyBins'])
    if NEbin > 0:
        tgpoint, Arrow = PlotDataPoints(config,pars) #collect data points
        tgpoint.SetLineColor(pars.PointColor)
        tgpoint.SetMarkerColor(pars.PointColor)
        tgpoint.Draw("pz")
        for i in xrange(len(Arrow)):
            Arrow[i].SetLineColor(pars.PointColor)
            Arrow[i].SetFillColor(pars.PointColor)
            Arrow[i].Draw()

    #save the canvas
    c_plot.Print(filebase + '.C')
    c_plot.Print(filebase + '.eps')
    c_plot.Print(filebase + '.png')
Example #8
0
def PlotSED(config, pars, ignore_missing_bins=False):
    """plot a nice SED with a butterfly and points"""

    # Read the ascii file where the butterfly is stored
    filebase = utils._SpecFileName(config)

    lines = open(filebase + '.dat', 'r').readlines()
    SED = []
    E = []
    Err = []

    for i in xrange(len(lines) - 1):
        words = lines[i + 1].split()
        if float(words[0]) < pars.Emax:
            E.append(float(words[0]))
            SED.append(float(words[1]))
            Err.append(float(words[2]))
    ilen = len(SED)

    #From dN/dE to SED
    Fluxp = np.array(SED) * np.exp(np.array(Err) / np.array(SED))
    Fluxm = np.array(SED) * np.exp(-np.array(Err) / np.array(SED))
    ErrorFlux = np.zeros(2 * ilen + 1)
    ErrorE = np.zeros(2 * ilen + 1)

    #Compute the butterfly and close it
    for i in xrange(ilen):
        ErrorFlux[i] = Fluxp[i]
        ErrorE[i] = E[i]
    for i in xrange(ilen):
        ErrorFlux[ilen + i] = Fluxm[ilen - i - 1]
        ErrorE[ilen + i] = E[ilen - i - 1]
    ErrorFlux[-1] = Fluxp[0]
    ErrorE[-1] = E[0]

    #Actually make the plot
    plt.figure()
    plt.title(pars.PlotName.split("/")[-1].replace('_', '\_'))
    name = pars.PlotName.split("/")[-1]
    plt.loglog()

    plt.xlabel(r"Energy (MeV)")
    plt.ylabel(r"$\mathrm{E^2\ dN/dE}\ \mathrm{(erg\ cm^{-2} s^{-1})}$")
    plt.plot(E, SED, "-r", label='LAT model')
    plt.plot(ErrorE, ErrorFlux, "-r")

    #Plot points
    NEbin = int(config['Ebin']['NumEnergyBins'])
    if NEbin > 0:
        Epoint, Fluxpoint, EpointErrm, EpointErrp, FluxpointErrm, FluxpointErrp, uplim = GetDataPoints(
            config, pars, ignore_missing_bins)  #collect data points
        plot_errorbar_withuls(Epoint, EpointErrm, EpointErrp, Fluxpoint,
                              FluxpointErrm, FluxpointErrp, uplim)

    #print uplim
    #print FluxpointErrm
    #print FluxpointErrp

    #Set meaningful axes limits
    xlim = plt.xlim()
    ylim = plt.ylim()
    xlim = (max([20, xlim[0]]), min([2e6, xlim[1]]))
    ylim = (max([1e-13, ylim[0]]), min([1e-8, ylim[1]]))
    plt.xlim(xlim)
    plt.ylim(ylim)
    # turn them into log10 scale
    #xticks = plt.xticks()[0]
    #xticklabels = np.array(np.log10(xticks),dtype=int)
    #plt.xticks(xticks,xticklabels)
    #plt.xlabel('$\mathrm{\log_{10}\mathbf{(Energy)} \\ \\ [MeV]}$')

    plt.legend(fontsize='small',ncol=1,\
               loc=3,numpoints=1)#,framealpha=0.75)

    #Upper horizontal secondary axis with frequency
    #Plt2 = plt.twiny()
    #Plt2.set_xscale('log')
    #Plt2.set_xlim(2.417990504024163e+20 *np.array(xlim))
    #Plt2.set_xticklabels(np.array(np.log10(Plt2.get_xticks()),dtype=int))
    #Plt2.set_xlabel('$\mathrm{\log_{10}\mathbf{(Frequency)} \\ \\ [Hz]}$')

    #save the canvas
    #plt.grid()
    plt.tight_layout()
    plt.savefig("%s.png" % filebase,
                dpi=150,
                facecolor='w',
                edgecolor='w',
                orientation='portrait',
                papertype=None,
                format=None,
                transparent=False,
                bbox_inch=None,
                pad_inches=0.1,
                frameon=None)
Example #9
0
def PlotSED(config,pars,ignore_missing_bins=False):
    """plot a nice SED with a butterfly and points"""

    # Read the ascii file where the butterfly is stored
    filebase = utils._SpecFileName(config)

    lines = open(filebase + '.dat', 'r').readlines()
    SED = []
    E = []
    Err = []

    for i in xrange(len(lines) - 1):
        words = lines[i + 1].split()
        if float(words[0])<pars.Emax :
            E.append(float(words[0]))
            SED.append(float(words[1]))
            Err.append(float(words[2]))
    ilen = len(SED)

    #From dN/dE to SED
    Fluxp = np.array(SED)*np.exp(np.array(Err)/np.array(SED))
    Fluxm =  np.array(SED)*np.exp(-np.array(Err)/np.array(SED))
    ErrorFlux = np.zeros(2 * ilen + 1)
    ErrorE = np.zeros(2 * ilen + 1)

    #Compute the butterfly and close it
    for i in xrange(ilen):
        ErrorFlux[i] = Fluxp[i]
        ErrorE[i] = E[i]
    for i in xrange(ilen):
        ErrorFlux[ilen + i] = Fluxm[ilen - i - 1]
        ErrorE[ilen + i] = E[ilen - i - 1]
    ErrorFlux[-1] = Fluxp[0]
    ErrorE[-1] = E[0]

    #Actually make the plot
    plt.figure()
    plt.title(pars.PlotName.split("/")[-1].replace('_','\_'))
    name = pars.PlotName.split("/")[-1]
    plt.loglog()

    plt.xlabel(r"Energy (MeV)")
    plt.ylabel(r"$\mathrm{E^2\ dN/dE}\ \mathrm{(erg\ cm^{-2} s^{-1})}$")
    plt.plot(E,SED,"-r",label='LAT model')
    plt.plot(ErrorE,ErrorFlux,"-r")

    #Plot points
    NEbin = int(config['Ebin']['NumEnergyBins'])
    if NEbin > 0:
        Epoint, Fluxpoint, EpointErrm, EpointErrp, FluxpointErrm, FluxpointErrp, uplim = GetDataPoints(config,pars,ignore_missing_bins) #collect data points
        plot_errorbar_withuls(Epoint,EpointErrm,EpointErrp,Fluxpoint,FluxpointErrm,FluxpointErrp,uplim)

    #print uplim
    #print FluxpointErrm
    #print FluxpointErrp

    #Set meaningful axes limits
    xlim = plt.xlim()
    ylim = plt.ylim()
    xlim = (max([20,xlim[0]]),min([2e6,xlim[1]]))
    ylim = (max([1e-13,ylim[0]]),min([1e-8,ylim[1]]))
    plt.xlim(xlim)
    plt.ylim(ylim)
    # turn them into log10 scale
    #xticks = plt.xticks()[0]
    #xticklabels = np.array(np.log10(xticks),dtype=int)
    #plt.xticks(xticks,xticklabels)
    #plt.xlabel('$\mathrm{\log_{10}\mathbf{(Energy)} \\ \\ [MeV]}$')

    plt.legend(fontsize='small',ncol=1,\
               loc=3,numpoints=1)#,framealpha=0.75)


    #Upper horizontal secondary axis with frequency
    #Plt2 = plt.twiny()
    #Plt2.set_xscale('log')
    #Plt2.set_xlim(2.417990504024163e+20 *np.array(xlim))
    #Plt2.set_xticklabels(np.array(np.log10(Plt2.get_xticks()),dtype=int))
    #Plt2.set_xlabel('$\mathrm{\log_{10}\mathbf{(Frequency)} \\ \\ [Hz]}$')

    #save the canvas
    #plt.grid()
    plt.tight_layout()
    plt.savefig("%s.png" %filebase, dpi=150, facecolor='w', edgecolor='w',
            orientation='portrait', papertype=None, format=None,
            transparent=False, bbox_inch=None, pad_inches=0.1,
            frameon=None)