Example #1
0
def ChangeModel(comp, E1, E2, name, Pref, Gamma):
    """Change the spectral model of a source called name
    to allow a fit between E1 and E2
    If the spectral model is PowerLaw, the prefactor is updated
    if not the model is change to PowerLaw.
    The index is frozen in all cases"""
    
    # if approximated Gamma is outside of bounds set it to limit
    Gamma_min=-5
    Gamma_max=0.5
    Gamma = min(max(Gamma_min,Gamma),Gamma_max)
    
    Eav = utils.GetE0(E1, E2)

    spectrum = comp.logLike.getSource(name).getSrcFuncs()['Spectrum']
    spectrum.getParam('Prefactor').setBounds(1e-5,1e5)
    spectrum.getParam('Prefactor').setScale(utils.fluxScale(Pref))
    spectrum.getParam('Prefactor').setValue(utils.fluxNorm(Pref))
    spectrum.getParam('Index').setBounds(Gamma_min,Gamma_max)
    spectrum.getParam('Index').setValue(Gamma)
    spectrum.getParam('Index').setFree(False)
    spectrum.getParam('Scale').setValue(Eav)
    spectrum.getParam('Scale').setBounds(20,3e6)

    return comp
Example #2
0
def ChangeModel(comp, E1, E2, name, Pref, Gamma):
    """Change the spectral model of a source called name
    to allow a fit between E1 and E2
    If the spectral model is PowerLaw, the prefactor is updated
    if not the model is change to PowerLaw.
    The index is frozen in all cases"""

    # if approximated Gamma is outside of bounds set it to limit
    Gamma_min = -5
    Gamma_max = 0.5
    Gamma = min(max(Gamma_min, Gamma), Gamma_max)

    Eav = utils.GetE0(E1, E2)

    spectrum = comp.logLike.getSource(name).getSrcFuncs()['Spectrum']
    spectrum.getParam('Prefactor').setBounds(1e-5, 1e5)
    spectrum.getParam('Prefactor').setScale(utils.fluxScale(Pref))
    spectrum.getParam('Prefactor').setValue(utils.fluxNorm(Pref))
    spectrum.getParam('Index').setBounds(Gamma_min, Gamma_max)
    spectrum.getParam('Index').setValue(Gamma)
    spectrum.getParam('Index').setFree(0)
    spectrum.getParam('Scale').setValue(Eav)
    spectrum.getParam('Scale').setBounds(20, 3e6)

    return comp
Example #3
0
def ChangeModel(Fit, E1, E2, name, Pref, Gamma):
    """Change the spectral model of a source called name
    to allow a fit between E1 and E2
    If the spectral model is PowerLaw, the prefactor is updated
    if not the model is change to PowerLaw.
    The index is frozen in all cases"""

    Eav = utils.GetE0(E1, E2)

    # Set Parameters
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam(
        'Prefactor').setBounds(1e-5, 1e5)
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam(
        'Prefactor').setScale(utils.fluxScale(Pref))
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam(
        'Prefactor').setValue(utils.fluxNorm(Pref))

    Gamma_min = -5
    Gamma_max = 0
    # if approximated Gamma is outside of bounds set it to limit
    if Gamma < Gamma_min:
        Gamma = Gamma_min
    elif Gamma > Gamma_max:
        Gamma = Gamma_max

    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam(
        'Index').setBounds(Gamma_min, Gamma_max)
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam(
        'Index').setValue(Gamma)
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam(
        'Index').setFree(0)

    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam(
        'Scale').setValue(Eav)
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam(
        'Scale').setBounds(20, 3e6)

    return Fit
Example #4
0
    def VariabilityIndex(self):
        """Compute the variability index as in the 2FLG catalogue. (see Nolan et al, 2012)"""
        LcOutPath = self.LCfolder + self.config['target']['name']

        utils._log('Computing Variability index ')

        self.config['Spectrum']['FitsGeneration'] = 'no'

        try :
            ResultDicDC = utils.ReadResult(self.generalconfig)
        except :
            self.warning("No results file found; please run enrico_sed first.")
            return
        
        LogL1 = []
        LogL0 = []
        Time = []
        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 the config file ",i)
                continue

#            LogL1.append(ResultDic.get("log_like"))
            #Update the time and time error array
            Time.append((ResultDic.get("tmax")+ResultDic.get("tmin"))/2.)

            ##############################################################
            #   Compute the loglike value using the DC flux or prefactor
            ##############################################################
            # Create one obs instance
            CurConfig['Spectrum']['FitsGeneration'] = 'no'
            _,Fit = GenAnalysisObjects(CurConfig,verbose=0)#be quiet
            Fit.ftol = float(self.config['fitting']['ftol'])

            #Spectral index management!
            parameters = dict()
            parameters['Index']  = -2.
            parameters['alpha']  = +2.
            parameters['Index1'] = -2.
            parameters['beta']   = 0
            parameters['Index2'] = 2.
            parameters['Cutoff'] = 30000. # set the cutoff to be high

            for key in parameters.keys():
                try:
                    utils.FreezeParams(Fit, self.srcname, key, parameters[key])
                except:
                    continue

            LogL1.append(-Fit.fit(0,optimizer=CurConfig['fitting']['optimizer']))

            for key in ["norm","Prefactor","Integral"]:
                try:
                    utils.FreezeParams(Fit,self.srcname,key, utils.fluxNorm(ResultsDicDC[key]))
                except:
                    continue
            
            LogL0.append(-Fit.fit(0,optimizer=CurConfig['fitting']['optimizer']))

            del Fit #Clean memory


        plt.figure()
        plt.xlabel("Time")
        plt.ylabel("Log(Like) Variability")
        plt.errorbar(Time,LogL0,fmt='o',color='black',ls='None')

        plt.savefig(LcOutPath+"_VarIndex.png", dpi=150, facecolor='w', edgecolor='w',
                orientation='portrait', papertype=None, format=None,
                transparent=False, bbox_inches=None, pad_inches=0.1,
                frameon=None)

        self.info("Variability index calculation") 
        print "\t TSvar = ",2*(sum(LogL1)-sum(LogL0))
        print "\t NDF = ",len(LogL0)-1
        print "\t Chi2 prob = ",1 - chi2.cdf(2*(sum(LogL1)-sum(LogL0)),len(LogL0)-1)
        print 
Example #5
0
    def VariabilityIndex(self):
        """Compute the variability index as in the 2FGL catalogue. (see Nolan et al, 2012)"""
        LcOutPath = self.LCfolder + self.config['target']['name']

        utils._log('Computing Variability index ')

        self.config['Spectrum']['FitsGeneration'] = 'no'

        try :
            ResultDicDC = utils.ReadResult(self.generalconfig)
        except :
            self.warning("No results file found; please run enrico_sed first.")
            return

        LogL1 = []
        LogL0 = []
        Time = []
        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 the config file ",i)
                continue

#            LogL1.append(ResultDic.get("log_like"))
            #Update the time and time error array
            Time.append((ResultDic.get("tmax")+ResultDic.get("tmin"))/2.)

            ##############################################################
            #   Compute the loglike value using the DC flux or prefactor
            ##############################################################
            # Create one obs instance
            CurConfig['Spectrum']['FitsGeneration'] = 'no'
            _,Fit = GenAnalysisObjects(CurConfig,verbose=0)#be quiet
            Fit.ftol = float(self.config['fitting']['ftol'])

            #Spectral index management!
            parameters = dict()
            parameters['Index']  = -2.
            parameters['alpha']  = +2.
            parameters['Index1'] = -2.
            parameters['beta']   = 0
            parameters['Index2'] = 2.
            parameters['Cutoff'] = 30000. # set the cutoff to be high

            for key in parameters.keys():
                try:
                    utils.FreezeParams(Fit, self.srcname, key, parameters[key])
                except:
                    continue

            LogL1.append(-Fit.fit(0,optimizer=CurConfig['fitting']['optimizer']))

            for key in ["norm","Prefactor","Integral"]:
                try:
                    utils.FreezeParams(Fit,self.srcname,key, utils.fluxNorm(ResultsDicDC[key]))
                except:
                    continue

            LogL0.append(-Fit.fit(0,optimizer=CurConfig['fitting']['optimizer']))

            del Fit #Clean memory


        plt.figure()
        plt.xlabel("Time")
        plt.ylabel("Log(Like) Variability")
        plt.errorbar(Time,LogL0,fmt='o',color='black',ls='None')
        plt.xlim(xmin=max(plt.xlim()[0],1.02*min(Time)-0.02*max(Time)),
                 xmax=min(plt.xlim()[1],1.02*max(Time)-0.02*min(Time)))

        # Move the offset to the axis label
        ax = plt.gca()
        ax.get_yaxis().get_major_formatter().set_useOffset(False)
        offset_factor = int(np.mean(np.log10(np.abs(ax.get_ylim()))))
        if (offset_factor != 0):
            ax.set_yticklabels([float(round(k,5)) \
              for k in ax.get_yticks()*10**(-offset_factor)])
            ax.yaxis.set_label_text(ax.yaxis.get_label_text() +\
               r" [${\times 10^{%d}}$]" %offset_factor)

        # Secondary axis with MJD
        mjdaxis = ax.twiny()
        mjdaxis.set_xlim([utils.met_to_MJD(k) for k in ax.get_xlim()])
        mjdaxis.set_xlabel(r"Time (MJD)")
        mjdaxis.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter(useOffset=False))
        plt.setp( mjdaxis.xaxis.get_majorticklabels(), rotation=15 )
        plt.tight_layout()

        plt.savefig(LcOutPath+"_VarIndex.png", dpi=150, facecolor='w', edgecolor='w',
                orientation='portrait', papertype=None, format=None,
                transparent=False, bbox_inches=None, pad_inches=0.1,
                frameon=None)

        self.info("Variability index calculation")
        print "\t TSvar = ",2*(sum(LogL1)-sum(LogL0))
        print "\t NDF = ",len(LogL0)-1
        print "\t Chi2 prob = ",1 - chi2.cdf(2*(sum(LogL1)-sum(LogL0)),len(LogL0)-1)
        print
Example #6
0
    def VariabilityIndex(self):
        """Compute the variability index as in the 2FLG catalogue. (see Nolan et al, 2012)"""
        LcOutPath = self.LCfolder + self.config['target']['name']

        utils._log('Computing Variability index ')

        self.config['Spectrum']['FitsGeneration'] = 'no'
#        ValueDC = self.GetDCValue()
        ResultDicDC = utils.ReadResult(self.config)
        LogL1 = []
        LogL0 = []
        Time = []
        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 :
                print "WARNING : fail reading the config file : ",CurConfig
                print "Job Number : ",i
                print "Please have a look at this job log file"
                continue

#            LogL1.append(ResultDic.get("log_like"))
            #Update the time and time error array
            Time.append((ResultDic.get("tmax")+ResultDic.get("tmin"))/2.)

            ##############################################################
            #   Compute the loglike value using the DC flux or prefactor
            ##############################################################
            # Create one obs instance
            CurConfig['Spectrum']['FitsGeneration'] = 'no'
            _,Fit = GenAnalysisObjects(CurConfig,verbose=0)#be quiet
            Fit.ftol = float(self.config['fitting']['ftol'])

            #Spectral index management!
            utils.FreezeParams(Fit, self.srcname, 'Index', -2)
            LogL1.append(-Fit.fit(0,optimizer=CurConfig['fitting']['optimizer']))

            Model_type = Fit.model.srcs[self.srcname].spectrum().genericName()
            if (Model_type == 'PowerLaw') :
                utils.FreezeParams(Fit, self.srcname, 'Prefactor', utils.fluxNorm(ResultDicDC['Prefactor']))
            if (Model_type == 'PowerLaw2') :
                utils.FreezeParams(Fit, self.srcname, 'Integral', utils.fluxNorm(ResultDicDC['Integral']))
            LogL0.append(-Fit.fit(0,optimizer=CurConfig['fitting']['optimizer']))

            del Fit #Clean memory

        Can = _GetCanvas()
        TgrDC = ROOT.TGraph(len(Time),np.array(Time),np.array(LogL0))
        TgrDC.Draw("ALP*")
        TgrDC = ROOT.TGraph(len(Time),np.array(Time),np.array(LogL0))
        TgrDC.SetMarkerColor(2)
        TgrDC.Draw("PL*")
        #Save the canvas in the LightCurve subfolder
        Can.Print(LcOutPath+'_VarIndex.eps')
        Can.Print(LcOutPath+'_VarIndex.C')
        print 
        print "\t TSvar = ",2*(sum(LogL1)-sum(LogL0))
        print "\t NDF = ",len(LogL0)-1
        print "\t Chi2 prob = ",ROOT.TMath.Prob(2*(sum(LogL1)-sum(LogL0)),len(LogL0)-1)
        print 
Example #7
0
def ChangeModel(Fit, E1, E2, name, Pref, Gamma):
    """Change the spectral model of a source called name
    to allow a fit between E1 and E2
    If the spectral model is PowerLaw, the prefactor is updated
    if not the model is change to PowerLaw.
    The index is frozen in all cases"""

    Eav = utils.GetE0(E1, E2)

    # Set Parameters
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam('Prefactor').setBounds(1e-5,1e5)
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam('Prefactor').setScale(utils.fluxScale(Pref))
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam('Prefactor').setValue(utils.fluxNorm(Pref))

    Gamma_min=-5
    Gamma_max=0
    # if approximated Gamma is outside of bounds set it to limit
    if Gamma < Gamma_min:
        Gamma = Gamma_min
    elif Gamma > Gamma_max:
        Gamma = Gamma_max

    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam('Index').setBounds(Gamma_min,Gamma_max)
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam('Index').setValue(Gamma)
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam('Index').setFree(0)

    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam('Scale').setValue(Eav)
    Fit.logLike.getSource(name).getSrcFuncs()['Spectrum'].getParam('Scale').setBounds(20,3e6)

    return Fit
Example #8
0
    def VariabilityIndex(self):
        """Compute the variability index as in the 2FLG catalogue. (see Nolan et al, 2012)"""
        LcOutPath = self.LCfolder + self.config["target"]["name"]

        utils._log("Computing Variability index ")

        self.config["Spectrum"]["FitsGeneration"] = "no"
        #        ValueDC = self.GetDCValue()
        ResultDicDC = utils.ReadResult(self.config)
        LogL1 = []
        LogL0 = []
        Time = []
        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 the config file ", i)
                #                print "WARNING : fail reading the config file : ",CurConfig
                #                print "Job Number : ",i
                #                print "Please have a look at this job log file"
                continue

            #            LogL1.append(ResultDic.get("log_like"))
            # Update the time and time error array
            Time.append((ResultDic.get("tmax") + ResultDic.get("tmin")) / 2.0)

            ##############################################################
            #   Compute the loglike value using the DC flux or prefactor
            ##############################################################
            # Create one obs instance
            CurConfig["Spectrum"]["FitsGeneration"] = "no"
            _, Fit = GenAnalysisObjects(CurConfig, verbose=0)  # be quiet
            Fit.ftol = float(self.config["fitting"]["ftol"])

            # Spectral index management!
            self.info("Spectral index frozen to a value of 2")
            utils.FreezeParams(Fit, self.srcname, "Index", -2)
            LogL1.append(-Fit.fit(0, optimizer=CurConfig["fitting"]["optimizer"]))

            Model_type = Fit.model.srcs[self.srcname].spectrum().genericName()
            if Model_type == "PowerLaw":
                utils.FreezeParams(Fit, self.srcname, "Prefactor", utils.fluxNorm(ResultDicDC["Prefactor"]))
            if Model_type == "PowerLaw2":
                utils.FreezeParams(Fit, self.srcname, "Integral", utils.fluxNorm(ResultDicDC["Integral"]))
            LogL0.append(-Fit.fit(0, optimizer=CurConfig["fitting"]["optimizer"]))

            del Fit  # Clean memory

        Can = _GetCanvas()
        TgrDC = ROOT.TGraph(len(Time), np.array(Time), np.array(LogL0))
        TgrDC.Draw("ALP*")
        TgrDC = ROOT.TGraph(len(Time), np.array(Time), np.array(LogL0))
        TgrDC.SetMarkerColor(2)
        TgrDC.Draw("PL*")
        # Save the canvas in the LightCurve subfolder
        Can.Print(LcOutPath + "_VarIndex.eps")
        Can.Print(LcOutPath + "_VarIndex.C")
        self.info("Variability index calculation")
        print "\t TSvar = ", 2 * (sum(LogL1) - sum(LogL0))
        print "\t NDF = ", len(LogL0) - 1
        print "\t Chi2 prob = ", ROOT.TMath.Prob(2 * (sum(LogL1) - sum(LogL0)), len(LogL0) - 1)
        print
Example #9
0
    def VariabilityIndex(self):
        """Compute the variability index as in the 2FGL catalogue. (see Nolan et al, 2012)"""
        LcOutPath = self.LCfolder + self.config['target']['name']

        utils._log('Computing Variability index ')

        self.config['Spectrum']['FitsGeneration'] = 'no'

        try :
            ResultDicDC = utils.ReadResult(self.generalconfig)
        except :
            self.warning("No results file found; please run enrico_sed first.")
            return

        LogL1 = []
        LogL0 = []
        Time = []
        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 the config file ",i)
                continue

#            LogL1.append(ResultDic.get("log_like"))
            #Update the time and time error array
            Time.append((ResultDic.get("tmax")+ResultDic.get("tmin"))/2.)

            ##############################################################
            #   Compute the loglike value using the DC flux or prefactor
            ##############################################################
            # Create one obs instance
            CurConfig['Spectrum']['FitsGeneration'] = 'no'
            _,Fit = GenAnalysisObjects(CurConfig,verbose=0)#be quiet
            Fit.ftol = float(self.config['fitting']['ftol'])

            #Spectral index management!
            parameters = dict()
            parameters['Index']  = -2.
            parameters['alpha']  = +2.
            parameters['Index1'] = -2.
            parameters['beta']   = 0
            parameters['Index2'] = 2.
            parameters['Cutoff'] = 100000. # set the cutoff to be high

            for key in parameters.keys():
                try:
                    utils.FreezeParams(Fit, self.srcname, key, parameters[key])
                except:
                    continue

            LogL1.append(-Fit.fit(0,optimizer=CurConfig['fitting']['optimizer']))

            for key in ["norm","Prefactor","Integral"]:
                try:
                    utils.FreezeParams(Fit,self.srcname,key, utils.fluxNorm(ResultsDicDC[key]))
                except:
                    continue

            LogL0.append(-Fit.fit(0,optimizer=CurConfig['fitting']['optimizer']))

            del Fit #Clean memory


        plt.figure()
        plt.xlabel("Time")
        plt.ylabel("Log(Like) Variability")
        plt.errorbar(Time,LogL0,fmt='o',color='black',ls='None')
        plt.xlim(xmin=max(plt.xlim()[0],1.02*min(Time)-0.02*max(Time)),
                 xmax=min(plt.xlim()[1],1.02*max(Time)-0.02*min(Time)))

        # Move the offset to the axis label
        ax = plt.gca()
        ax.get_yaxis().get_major_formatter().set_useOffset(False)
        offset_factor = int(np.mean(np.log10(np.abs(ax.get_ylim()))))
        if (offset_factor != 0):
            ax.set_yticklabels([float(round(k,5)) \
              for k in ax.get_yticks()*10**(-offset_factor)])
            ax.yaxis.set_label_text(ax.yaxis.get_label_text() +\
               r" [${\times 10^{%d}}$]" %offset_factor)

        # Secondary axis with MJD
        mjdaxis = ax.twiny()
        mjdaxis.set_xlim([utils.met_to_MJD(k) for k in ax.get_xlim()])
        mjdaxis.set_xlabel(r"Time (MJD)")
        mjdaxis.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter(useOffset=False))
        plt.setp( mjdaxis.xaxis.get_majorticklabels(), rotation=15 )
        plt.tight_layout()

        plt.savefig(LcOutPath+"_VarIndex.png", dpi=150, facecolor='w', edgecolor='w',
                orientation='portrait', papertype=None, format=None,
                transparent=False, bbox_inches=None, pad_inches=0.1,
                frameon=None)

        self.info("Variability index calculation")
        print "\t TSvar = ",2*(sum(LogL1)-sum(LogL0))
        print "\t NDF = ",len(LogL0)-1
        print "\t Chi2 prob = ",1 - chi2.cdf(2*(sum(LogL1)-sum(LogL0)),len(LogL0)-1)
        print
Example #10
0
    def VariabilityIndex(self):
        """Compute the variability index as in the 2FLG catalogue. (see Nolan et al, 2012)"""
        LcOutPath = self.LCfolder + self.config['target']['name']

        utils._log('Computing Variability index ')

        self.config['Spectrum']['FitsGeneration'] = 'no'
        #        ValueDC = self.GetDCValue()
        ResultDicDC = utils.ReadResult(self.config)
        LogL1 = []
        LogL0 = []
        Time = []
        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 the config file ", i)
                #                print "WARNING : fail reading the config file : ",CurConfig
                #                print "Job Number : ",i
                #                print "Please have a look at this job log file"
                continue


#            LogL1.append(ResultDic.get("log_like"))
#Update the time and time error array
            Time.append((ResultDic.get("tmax") + ResultDic.get("tmin")) / 2.)

            ##############################################################
            #   Compute the loglike value using the DC flux or prefactor
            ##############################################################
            # Create one obs instance
            CurConfig['Spectrum']['FitsGeneration'] = 'no'
            _, Fit = GenAnalysisObjects(CurConfig, verbose=0)  #be quiet
            Fit.ftol = float(self.config['fitting']['ftol'])

            #Spectral index management!
            self.info("Spectral index frozen to a value of 2")
            utils.FreezeParams(Fit, self.srcname, 'Index', -2)
            LogL1.append(
                -Fit.fit(0, optimizer=CurConfig['fitting']['optimizer']))

            Model_type = Fit.model.srcs[self.srcname].spectrum().genericName()
            if (Model_type == 'PowerLaw'):
                utils.FreezeParams(Fit, self.srcname, 'Prefactor',
                                   utils.fluxNorm(ResultDicDC['Prefactor']))
            if (Model_type == 'PowerLaw2'):
                utils.FreezeParams(Fit, self.srcname, 'Integral',
                                   utils.fluxNorm(ResultDicDC['Integral']))
            LogL0.append(
                -Fit.fit(0, optimizer=CurConfig['fitting']['optimizer']))

            del Fit  #Clean memory

        Can = _GetCanvas()
        TgrDC = ROOT.TGraph(len(Time), np.array(Time), np.array(LogL0))
        TgrDC.Draw("ALP*")
        TgrDC = ROOT.TGraph(len(Time), np.array(Time), np.array(LogL0))
        TgrDC.SetMarkerColor(2)
        TgrDC.Draw("PL*")
        #Save the canvas in the LightCurve subfolder
        Can.Print(LcOutPath + '_VarIndex.eps')
        Can.Print(LcOutPath + '_VarIndex.C')
        self.info("Variability index calculation")
        print "\t TSvar = ", 2 * (sum(LogL1) - sum(LogL0))
        print "\t NDF = ", len(LogL0) - 1
        print "\t Chi2 prob = ", ROOT.TMath.Prob(2 * (sum(LogL1) - sum(LogL0)),
                                                 len(LogL0) - 1)
        print
Example #11
0
    def VariabilityIndex(self):
        """Compute the variability index as in the 2FLG catalogue. (see Nolan et al, 2012)"""
        LcOutPath = self.LCfolder + self.config['target']['name']

        utils._log('Computing Variability index ')

        self.config['Spectrum']['FitsGeneration'] = 'no'

        try:
            ResultDicDC = utils.ReadResult(self.generalconfig)
        except:
            self.warning("No results file found; please run enrico_sed first.")
            return

        LogL1 = []
        LogL0 = []
        Time = []
        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 the config file ", i)
                #                print "WARNING : fail reading the config file : ",CurConfig
                #                print "Job Number : ",i
                #                print "Please have a look at this job log file"
                continue


#            LogL1.append(ResultDic.get("log_like"))
#Update the time and time error array
            Time.append((ResultDic.get("tmax") + ResultDic.get("tmin")) / 2.)

            ##############################################################
            #   Compute the loglike value using the DC flux or prefactor
            ##############################################################
            # Create one obs instance
            CurConfig['Spectrum']['FitsGeneration'] = 'no'
            _, Fit = GenAnalysisObjects(CurConfig, verbose=0)  #be quiet
            Fit.ftol = float(self.config['fitting']['ftol'])

            #Spectral index management!
            parameters = dict()
            parameters['Index'] = -2.
            parameters['alpha'] = +2.
            parameters['Index1'] = -2.
            parameters['beta'] = 0
            parameters['Index2'] = 2.
            parameters['Cutoff'] = 30000.  # set the cutoff to be high

            for key in parameters.keys():
                try:
                    utils.FreezeParams(Fit, self.srcname, key, parameters[key])
                except:
                    continue

            LogL1.append(
                -Fit.fit(0, optimizer=CurConfig['fitting']['optimizer']))

            for key in ["norm", "Prefactor", "Integral"]:
                try:
                    utils.FreezeParams(Fit, self.srcname, key,
                                       utils.fluxNorm(ResultsDicDC[key]))
                except:
                    continue

            LogL0.append(
                -Fit.fit(0, optimizer=CurConfig['fitting']['optimizer']))

            del Fit  #Clean memory

        Can = _GetCanvas()
        TgrDC = ROOT.TGraph(len(Time), np.array(Time), np.array(LogL0))
        TgrDC.Draw("ALP*")
        TgrDC = ROOT.TGraph(len(Time), np.array(Time), np.array(LogL0))
        TgrDC.SetMarkerColor(2)
        TgrDC.Draw("PL*")
        #Save the canvas in the LightCurve subfolder
        Can.Print(LcOutPath + '_VarIndex.eps')
        Can.Print(LcOutPath + '_VarIndex.C')
        self.info("Variability index calculation")
        print "\t TSvar = ", 2 * (sum(LogL1) - sum(LogL0))
        print "\t NDF = ", len(LogL0) - 1
        print "\t Chi2 prob = ", ROOT.TMath.Prob(2 * (sum(LogL1) - sum(LogL0)),
                                                 len(LogL0) - 1)
        print