def FitOnePixel(self,ra,dec,i,j) : """Run a evaluation of the pixel (i,j) corresponding to position (ra,dec)""" outXml = utils._dump_xml(self.config) folder = self.config['out'] _,Fit = GenAnalysisObjects(self.config,xmlfile=outXml) #get the Fit object src = GetSrc(Fit,ra,dec) # get the Source object at postion ra dec if self.config['TSMap']['RemoveTarget'] : # remove the target is asked Fit.deleteSource(self.config['target']['name']) if self.config['TSMap']['Re-Fit']: # reoptimze before is asked Fit.fit(0,optimizer=self.config['fitting']['optimizer']) for par in xrange(Fit.logLike.getNumParams()): # freeze all the source parameters Fit[par].setFree(0) Fit.addSource(src)# add a spurious source # dump the *new* xml file Fit.writeXml(self.tsfolder+"/model_"+str(ra)+"_"+str(dec)+".xml") # a new Fit object with the new xml file is needed. # just changing the position of the spurious source does not work _,TSFit = GenAnalysisObjects(self.config,xmlfile=self.tsfolder+"/model_"+str(ra)+"_"+str(dec)+".xml") #get the Fit object TSFit.fit(0,optimizer=self.config['fitting']['optimizer']) # save the result fsave = open(self._PixelFile(i,j),'w') fsave.write(str(ra)+"\t"+str(dec)+"\t"+ str(TSFit.Ts("Spurious"))+"\t"+ str(TSFit.logLike.value())) fsave.close()
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
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
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
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