コード例 #1
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')
コード例 #2
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')
コード例 #3
0
ファイル: lightcurve.py プロジェクト: prokoph/enrico
    def _PlotLC(self, folded=False):
        root_style.RootStyle()  #Nice plot style

        self.info("Reading files produced by enrico")
        LcOutPath = self.LCfolder + self.config['target']['name']

        #Result are stored into list. This allow to get rid of the bin which failled
        Time = []
        TimeErr = []
        Flux = []
        FluxErr = []
        Index = []
        IndexErr = []
        Cutoff = []
        CutoffErr = []
        FluxForNpred = []
        FluxErrForNpred = []
        Npred = []
        Npred_detected_indices = []
        TS = []

        # Find name used for index parameter
        if (self.config['target']['spectrum'] == 'PowerLaw'
                or self.config['target']['spectrum'] == 'PowerLaw2'):
            IndexName = 'Index'
            CutoffName = None
        elif (self.config['target']['spectrum'] == 'PLExpCutoff'
              or self.config['target']['spectrum'] == 'PLSuperExpCutoff'):
            IndexName = 'Index1'
            CutoffName = 'Cutoff'
            CutoffErrName = 'dCutoff'
        IndexErrName = 'd' + IndexName

        Nfail = 0
        for i in xrange(self.Nbin):
            CurConfig = get_config(self.configfile[i])
            #Read the result. If it fails, it means that the bins has not bin computed. A warning message is printed
            try:
                ResultDic = utils.ReadResult(CurConfig)
            except:
                self._errorReading("Fail reading config file", i)
                Nfail += 1
                continue

            #Update the time and time error array
            Time.append((ResultDic.get("tmax") + ResultDic.get("tmin")) / 2.)
            TimeErr.append(
                (ResultDic.get("tmax") - ResultDic.get("tmin")) / 2.)
            #Check is an ul have been computed. The error is set to zero for the TGraph.
            if ResultDic.has_key('Ulvalue'):
                Flux.append(ResultDic.get("Ulvalue"))
                FluxErr.append(0)
                Index.append(ResultDic.get(IndexName))
                IndexErr.append(0)
            else:
                Flux.append(ResultDic.get("Flux"))
                FluxErr.append(ResultDic.get("dFlux"))
                Index.append(ResultDic.get(IndexName))
                IndexErr.append(ResultDic.get(IndexErrName))
                if CutoffName is not None:
                    Cutoff.append(ResultDic.get(CutoffName))
                    CutoffErr.append(ResultDic.get(CutoffErrName))
            FluxErrForNpred.append(ResultDic.get("dFlux"))
            FluxForNpred.append(ResultDic.get("Flux"))
            #Get the Npred and TS values
            Npred.append(ResultDic.get("Npred"))
            TS.append(ResultDic.get("TS"))
            if (CurConfig['LightCurve']['TSLightCurve'] < float(
                    ResultDic.get("TS"))):
                Npred_detected_indices.append(i - Nfail)

        #change the list into np array
        TS = np.array(TS)
        Npred = np.array(Npred)
        Npred_detected = Npred[Npred_detected_indices]
        Time = np.array(Time)
        TimeErr = np.array(TimeErr)
        Flux = np.array(Flux)
        FluxErr = np.array(FluxErr)
        Index = np.array(Index)
        IndexErr = np.array(IndexErr)
        Cutoff = np.array(Cutoff)
        CutoffErr = np.array(CutoffErr)
        FluxForNpred = np.array(FluxForNpred)
        FluxErrForNpred = np.array(FluxErrForNpred)

        #Plots the diagnostic plots is asked
        # Plots are : Npred vs flux
        #             TS vs Time
        if self.config['LightCurve']['DiagnosticPlots'] == 'yes':
            fittedFunc = self.CheckNpred(
                Npred, FluxForNpred, FluxErrForNpred,
                Npred_detected_indices)  #check the errors calculation
            gTHNpred, TgrNpred = plotting.PlotNpred(Npred, FluxForNpred,
                                                    FluxErrForNpred)
            CanvNpred = _GetCanvas()
            gTHNpred.Draw()
            TgrNpred.Draw('zP')

            _, TgrNpred_detected = plotting.PlotNpred(
                Npred_detected, Flux[Npred_detected_indices],
                FluxErrForNpred[Npred_detected_indices])
            TgrNpred_detected.SetLineColor(2)
            TgrNpred_detected.SetMarkerColor(2)
            TgrNpred_detected.Draw('zP')
            fittedFunc.Draw("SAME")

            CanvNpred.Print(LcOutPath + "_Npred.png")
            CanvNpred.Print(LcOutPath + "_Npred.eps")
            CanvNpred.Print(LcOutPath + "_Npred.C")

            gTHTS, TgrTS = plotting.PlotTS(Time, TimeErr, TS)
            CanvTS = _GetCanvas()
            gTHTS.Draw()
            TgrTS.Draw('zP')
            CanvTS.Print(LcOutPath + '_TS.png')
            CanvTS.Print(LcOutPath + '_TS.eps')
            CanvTS.Print(LcOutPath + '_TS.C')

#    Plot the LC itself. This function return a TH2F for a nice plot
#    a TGraph and a list of TArrow for the ULs
        if folded:
            phase = np.linspace(0, 1, self.Nbin + 1)
            Time = (phase[1:] + phase[:-1]) / 2.
            TimeErr = (phase[1:] - phase[:-1]) / 2.
            gTHLC, TgrLC, ArrowLC = plotting.PlotFoldedLC(
                Time, TimeErr, Flux, FluxErr)
            gTHIndex, TgrIndex, ArrowIndex = plotting.PlotFoldedLC(
                Time, TimeErr, Index, IndexErr)
            if CutoffName is not None:
                gTHCutoff, TgrCutoff, ArrowCutoff = plotting.PlotFoldedLC(
                    Time, TimeErr, Cutoff, CutoffErr)
        else:
            gTHLC, TgrLC, ArrowLC = plotting.PlotLC(Time, TimeErr, Flux,
                                                    FluxErr)
            gTHIndex, TgrIndex, ArrowIndex = plotting.PlotLC(
                Time, TimeErr, Index, IndexErr)
            if CutoffName is not None:
                gTHCutoff, TgrCutoff, ArrowCutoff = plotting.PlotFoldedLC(
                    Time, TimeErr, Cutoff, CutoffErr)

        ### plot and save the flux LC
        CanvLC = ROOT.TCanvas()
        gTHLC.Draw()
        TgrLC.Draw('zP')

        #plot the ul as arrow
        for i in xrange(len(ArrowLC)):
            ArrowLC[i].Draw()

        # compute Fvar and probability of being cst

        self.info("Flux vs Time: infos")
        self.FitWithCst(TgrLC)
        self.Fvar(Flux, FluxErr)

        #Save the canvas in the LightCurve subfolder
        CanvLC.Print(LcOutPath + '_LC.png')
        CanvLC.Print(LcOutPath + '_LC.eps')
        CanvLC.Print(LcOutPath + '_LC.C')

        ### plot and save the Index LC
        CanvIndex = ROOT.TCanvas()
        gTHIndex.Draw()
        TgrIndex.Draw('zP')

        #plot the ul as arrow
        for i in xrange(len(ArrowIndex)):
            ArrowIndex[i].Draw()

        #Save the canvas in the LightCurve subfolder
        if self.config["LightCurve"]["SpectralIndex"] == 0:
            self.info("Index vs Time")
            self.FitWithCst(TgrIndex)
            CanvIndex.Print(LcOutPath + '_Index.png')
            CanvIndex.Print(LcOutPath + '_Index.eps')
            CanvIndex.Print(LcOutPath + '_Index.C')

        if len(Cutoff) > 0:
            ### plot and save the Cutoff LC
            CanvCutoff = ROOT.TCanvas()
            gTHCutoff.Draw()
            TgrCutoff.Draw('zP')

            #plot the ul as arrow
            for i in xrange(len(ArrowCutoff)):
                ArrowCutoff[i].Draw()

            print "Cutoff vs Time: infos"
            self.FitWithCst(TgrCutoff)
            CanvCutoff.Print(LcOutPath + '_Cutoff.png')
            CanvCutoff.Print(LcOutPath + '_Cutoff.eps')
            CanvCutoff.Print(LcOutPath + '_Cutoff.C')

        #Dump into ascii
        lcfilename = LcOutPath + "_results.dat"
        self.info("Write to Ascii file : " + lcfilename)
        WriteToAscii(Time, TimeErr, Flux, FluxErr, Index, IndexErr, Cutoff,
                     CutoffErr, TS, Npred, lcfilename)

        if self.config["LightCurve"]['ComputeVarIndex'] == 'yes':
            self.VariabilityIndex()
コード例 #4
0
    def _PlotLC(self, folded=False):
        root_style.RootStyle()  #Nice plot style

        print "Reading files produced by enrico"
        LcOutPath = self.LCfolder + self.config['target']['name']

        #Result are stored into list. This allow to get rid of the bin which failled
        Time = []
        TimeErr = []
        Flux = []
        FluxErr = []
        FluxForNpred = []
        FluxErrForNpred = []
        Npred = []
        Npred_detected_indices = []
        TS = []

        for i in xrange(self.Nbin):
            CurConfig = get_config(self.configfile[i])
            #Read the result. If it fails, it means that the bins has not bin computed. A warning message is printed
            try:
                ResultDic = utils.ReadResult(CurConfig)
            except:
                self._errorReading("fail reading config file", i)
                continue

            #Update the time and time error array
            Time.append((ResultDic.get("tmax") + ResultDic.get("tmin")) / 2.)
            TimeErr.append(
                (ResultDic.get("tmax") - ResultDic.get("tmin")) / 2.)
            #Check is an ul have been computed. The error is set to zero for the TGraph.
            if ResultDic.has_key('Ulvalue'):
                Flux.append(ResultDic.get("Ulvalue"))
                FluxErr.append(0)
            else:
                Flux.append(ResultDic.get("Flux"))
                FluxErr.append(ResultDic.get("dFlux"))
            FluxErrForNpred.append(ResultDic.get("dFlux"))
            FluxForNpred.append(ResultDic.get("Flux"))
            #Get the Npred and TS values
            Npred.append(ResultDic.get("Npred"))
            TS.append(ResultDic.get("TS"))
            if (CurConfig['LightCurve']['TSLightCurve'] < float(
                    ResultDic.get("TS"))):
                Npred_detected_indices.append(i)

        #change the list into np array
        TS = np.array(TS)
        Npred = np.array(Npred)
        Npred_detected = Npred[Npred_detected_indices]
        Time = np.array(Time)
        TimeErr = np.array(TimeErr)
        Flux = np.array(Flux)
        FluxErr = np.array(FluxErr)
        FluxForNpred = np.array(FluxForNpred)
        FluxErrForNpred = np.array(FluxErrForNpred)

        fittedFunc = self.CheckNpred(
            Npred, FluxForNpred, FluxErrForNpred,
            Npred_detected_indices)  #check the errors calculation

        #Plots the diagnostic plots is asked
        # Plots are : Npred vs flux
        #             TS vs Time
        if self.config['LightCurve']['DiagnosticPlots'] == 'yes':
            gTHNpred, TgrNpred = plotting.PlotNpred(Npred, FluxForNpred,
                                                    FluxErrForNpred)
            CanvNpred = _GetCanvas()
            gTHNpred.Draw()
            TgrNpred.Draw('zP')

            _, TgrNpred_detected = plotting.PlotNpred(
                Npred_detected, Flux[Npred_detected_indices],
                FluxErrForNpred[Npred_detected_indices])
            TgrNpred_detected.SetLineColor(2)
            TgrNpred_detected.SetMarkerColor(2)
            TgrNpred_detected.Draw('zP')
            fittedFunc.Draw("SAME")

            CanvNpred.Print(LcOutPath + "_Npred.eps")
            CanvNpred.Print(LcOutPath + "_Npred.C")

            gTHTS, TgrTS = plotting.PlotTS(Time, TimeErr, TS)
            CanvTS = _GetCanvas()
            gTHTS.Draw()
            TgrTS.Draw('zP')
            CanvTS.Print(LcOutPath + '_TS.eps')
            CanvTS.Print(LcOutPath + '_TS.C')

#    Plot the LC itself. This function return a TH2F for a nice plot
#    a TGraph and a list of TArrow for the ULs
        if folded:
            phase = np.linspace(0, 1, self.Nbin + 1)
            Time = (phase[1:] + phase[:-1]) / 2.
            TimeErr = (phase[1:] - phase[:-1]) / 2.
            gTHLC, TgrLC, ArrowLC = plotting.PlotFoldedLC(
                Time, TimeErr, Flux, FluxErr)
        else:
            gTHLC, TgrLC, ArrowLC = plotting.PlotLC(Time, TimeErr, Flux,
                                                    FluxErr)
        CanvLC = ROOT.TCanvas()
        gTHLC.Draw()
        TgrLC.Draw('zP')

        #plot the ul as arrow
        for i in xrange(len(ArrowLC)):
            ArrowLC[i].Draw()

        # compute Fvar and probability of being cst
        self.FitWithCst(TgrLC)
        self.Fvar(Flux, FluxErr)

        #Save the canvas in the LightCurve subfolder
        CanvLC.Print(LcOutPath + '_LC.eps')
        CanvLC.Print(LcOutPath + '_LC.C')

        #Dump into ascii
        lcfilename = LcOutPath + "_results.dat"
        print "Write to Ascii file : ", lcfilename
        WriteToAscii(Time, TimeErr, Flux, FluxErr, TS, Npred, lcfilename)

        if self.config["LightCurve"]['ComputeVarIndex'] == 'yes':
            self.VariabilityIndex()