def run(**kwargs): if(len(kwargs.keys())==0): #Nothing specified, the user needs just help! thisCommand.getHelp() return pass #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: xmlmodel = thisCommand.getParValue('likexmlresults') tkwindow = thisCommand.getParValue('tkwindow') except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0])) #Print help print thisCommand.getHelp() return pass from GtBurst import dataHandling irf = dataHandling._getParamFromXML(xmlmodel,'IRF') ra = dataHandling._getParamFromXML(xmlmodel,'RA') dec = dataHandling._getParamFromXML(xmlmodel,'DEC') name = dataHandling._getParamFromXML(xmlmodel,'OBJECT') xml = xmlModelGUI.xmlModelGUI(xmlmodel,tkwindow) if(irf!=None): dataHandling._writeParamIntoXML(xmlmodel,IRF=irf,OBJECT=name,RA=ra,DEC=dec) pass return 'likexmlresults', xmlmodel
def run(**kwargs): if(len(kwargs.keys())==0): #Nothing specified, the user needs just help! thisCommand.getHelp() return pass #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: xmlmodel = thisCommand.getParValue('likexmlresults') tkwindow = thisCommand.getParValue('tkwindow') except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0])) #Print help print thisCommand.getHelp() return pass from GtBurst import dataHandling irf = dataHandling._getParamFromXML(xmlmodel,'IRF') ra = dataHandling._getParamFromXML(xmlmodel,'RA') dec = dataHandling._getParamFromXML(xmlmodel,'DEC') name = dataHandling._getParamFromXML(xmlmodel,'OBJECT') xml = xmlModelGUI.xmlModelGUI(xmlmodel,tkwindow) if(irf is not None): dataHandling._writeParamIntoXML(xmlmodel,IRF=irf,OBJECT=name,RA=ra,DEC=dec) pass return 'likexmlresults', xmlmodel
def run(**kwargs): if(len(kwargs.keys())==0): #Nothing specified, the user needs just help! thisCommand.getHelp() return pass #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: eventfile = thisCommand.getParValue('filteredeventfile') rspfile = thisCommand.getParValue('rspfile') ft2file = thisCommand.getParValue('ft2file') xmlmodel = thisCommand.getParValue('xmlmodel') tsltcube = thisCommand.getParValue('tsltcube') tsexpomap = thisCommand.getParValue('tsexpomap') tsmap = thisCommand.getParValue('tsmap') step = float(thisCommand.getParValue('step')) side = thisCommand.getParValue('side') if(side=='auto'): side = None # showmodelimage = thisCommand.getParValue('showmodelimage') # optimize = thisCommand.getParValue('optimizeposition') # tsmin = float(thisCommand.getParValue('tsmin')) # skymap = thisCommand.getParValue('skymap') clobber = _yesOrNoToBool(thisCommand.getParValue('clobber')) verbose = _yesOrNoToBool(thisCommand.getParValue('verbose')) figure = thisCommand.getParValue('figure') except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0])) #Print help print thisCommand.getHelp() return pass from GtBurst import dataHandling from GtBurst.angularDistance import getAngularDistance origra = float(dataHandling._getParamFromXML(xmlmodel,'RA')) origdec = float(dataHandling._getParamFromXML(xmlmodel,'DEC')) sourceName = dataHandling._getParamFromXML(xmlmodel,'OBJECT') #Verify that TS map, if provided, is compatible with the position in the XML if(tsexpomap is not None and tsexpomap!=''): if(os.path.exists(tsexpomap)): header = pyfits.getheader(tsexpomap) ra,dec = (float(header.get('CRVAL1')),float(header.get('CRVAL2'))) angdist = getAngularDistance(origra,origdec,ra,dec) if(angdist > 0.1): print("Provided exposure map has a different center. Will compute it again.") tsexpomap = None else: print("Provided exposure map does not exist. Will compute it again.") tsexpomap = None LATdata = dataHandling.LATData(eventfile,rspfile,ft2file) tsmap = LATdata.makeTSmap(xmlmodel,sourceName,step,side,tsmap,tsltcube,tsexpomap) tsltcube = LATdata.livetimeCube tsexpomap = LATdata.exposureMap ra,dec,tsmax = dataHandling.findMaximumTSmap(tsmap,tsexpomap) print("\nCoordinates of the maximum of the TS map in the allowed region (TS = %.1f):" %(tsmax)) print("(R.A., Dec.) = (%6.3f, %6.3f)\n" %(ra,dec)) print("Distance from ROI center = %6.3f\n\n" %(getAngularDistance(origra,origdec,ra,dec))) if(figure is not None): from GtBurst import aplpy #Display the TS map figure.clear() tsfig = aplpy.FITSFigure(tsmap,convention='calabretta',figure=figure) tsfig.set_tick_labels_font(size='small') tsfig.set_axis_labels_font(size='small') tsfig.show_colorscale(cmap='gist_heat',aspect='auto') tsfig.show_markers([ra], [dec], edgecolor='green', facecolor='none', marker='o', s=10, alpha=0.5) # Modify the tick labels for precision and format tsfig.tick_labels.set_xformat('ddd.dd') tsfig.tick_labels.set_yformat('ddd.dd') # Display a grid and tweak the properties tsfig.show_grid() figure.canvas.draw() pass return 'tsmap', tsmap, 'tsmap_ra', ra, 'tsmap_dec', dec, 'tsmap_maxTS', tsmax, 'tsltcube', tsltcube, 'tsexpomap', tsexpomap
def run(**kwargs): if (len(kwargs.keys()) == 0): #Nothing specified, the user needs just help! thisCommand.getHelp() return pass #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: eventfile = thisCommand.getParValue('filteredeventfile') rspfile = thisCommand.getParValue('rspfile') ft2file = thisCommand.getParValue('ft2file') xmlmodel = thisCommand.getParValue('xmlmodel') tsltcube = thisCommand.getParValue('tsltcube') tsexpomap = thisCommand.getParValue('tsexpomap') tsmap = thisCommand.getParValue('tsmap') step = float(thisCommand.getParValue('step')) side = thisCommand.getParValue('side') if (side == 'auto'): side = None # showmodelimage = thisCommand.getParValue('showmodelimage') # optimize = thisCommand.getParValue('optimizeposition') # tsmin = float(thisCommand.getParValue('tsmin')) # skymap = thisCommand.getParValue('skymap') clobber = _yesOrNoToBool(thisCommand.getParValue('clobber')) verbose = _yesOrNoToBool(thisCommand.getParValue('verbose')) figure = thisCommand.getParValue('figure') except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" % (err.args[0])) #Print help print thisCommand.getHelp() return pass from GtBurst import dataHandling from GtBurst.angularDistance import getAngularDistance origra = float(dataHandling._getParamFromXML(xmlmodel, 'RA')) origdec = float(dataHandling._getParamFromXML(xmlmodel, 'DEC')) sourceName = dataHandling._getParamFromXML(xmlmodel, 'OBJECT') #Verify that TS map, if provided, is compatible with the position in the XML if (tsexpomap is not None and tsexpomap != ''): if (os.path.exists(tsexpomap)): header = pyfits.getheader(tsexpomap) ra, dec = (float(header.get('CRVAL1')), float(header.get('CRVAL2'))) angdist = getAngularDistance(origra, origdec, ra, dec) if (angdist > 0.1): print( "Provided exposure map has a different center. Will compute it again." ) tsexpomap = None else: print( "Provided exposure map does not exist. Will compute it again.") tsexpomap = None LATdata = dataHandling.LATData(eventfile, rspfile, ft2file) tsmap = LATdata.makeTSmap(xmlmodel, sourceName, step, side, tsmap, tsltcube, tsexpomap) tsltcube = LATdata.livetimeCube tsexpomap = LATdata.exposureMap ra, dec, tsmax = dataHandling.findMaximumTSmap(tsmap, tsexpomap) print( "\nCoordinates of the maximum of the TS map in the allowed region (TS = %.1f):" % (tsmax)) print("(R.A., Dec.) = (%6.3f, %6.3f)\n" % (ra, dec)) print("Distance from ROI center = %6.3f\n\n" % (getAngularDistance(origra, origdec, ra, dec))) if (figure is not None): from GtBurst import aplpy #Display the TS map figure.clear() tsfig = aplpy.FITSFigure(tsmap, convention='calabretta', figure=figure) tsfig.set_tick_labels_font(size='small') tsfig.set_axis_labels_font(size='small') tsfig.show_colorscale(cmap='gist_heat', aspect='auto') tsfig.show_markers([ra], [dec], edgecolor='green', facecolor='none', marker='o', s=10, alpha=0.5) # Modify the tick labels for precision and format tsfig.tick_labels.set_xformat('ddd.dd') tsfig.tick_labels.set_yformat('ddd.dd') # Display a grid and tweak the properties tsfig.show_grid() figure.canvas.draw() pass return 'tsmap', tsmap, 'tsmap_ra', ra, 'tsmap_dec', dec, 'tsmap_maxTS', tsmax, 'tsltcube', tsltcube, 'tsexpomap', tsexpomap
def run(**kwargs): if(len(kwargs.keys())==0): #Nothing specified, the user needs just help! thisCommand.getHelp() return pass #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: eventfile = thisCommand.getParValue('filteredeventfile') rspfile = thisCommand.getParValue('rspfile') ft2file = thisCommand.getParValue('ft2file') tsmin = float(thisCommand.getParValue('tsmin')) fixphindex = thisCommand.getParValue('fixphindex') expomap = thisCommand.getParValue('expomap') ltcube = thisCommand.getParValue('ltcube') xmlmodel = thisCommand.getParValue('xmlmodel') sedtxt = thisCommand.getParValue('sedtxt') energybins = thisCommand.getParValue('energybins') clobber = _yesOrNoToBool(thisCommand.getParValue('clobber')) verbose = _yesOrNoToBool(thisCommand.getParValue('verbose')) figure = thisCommand.getParValue('figure') except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0])) #Print help print thisCommand.getHelp() return pass from GtBurst import dataHandling from GtBurst.angularDistance import getAngularDistance LATdata = dataHandling.LATData(eventfile,rspfile,ft2file) try: outfilelike, sources = LATdata.doUnbinnedLikelihoodAnalysis(xmlmodel,tsmin=20,expomap=expomap,ltcube=ltcube) except GtBurstException as gt: raise gt except: raise #Now produce a pha1 file (just to compute the total exposure) pha1file = LATdata.binByEnergy(2) totalExposure = pyfits.getheader(pha1file,'SPECTRUM').get("EXPOSURE") print("\nTotal exposure: %s s" %(totalExposure)) #Transfer information on the source from the input to the output XML irf = dataHandling._getParamFromXML(xmlmodel,'IRF') ra = dataHandling._getParamFromXML(xmlmodel,'RA') dec = dataHandling._getParamFromXML(xmlmodel,'DEC') sourceName = dataHandling._getParamFromXML(xmlmodel,'OBJECT') if(irf is None): print("\n\nWARNING: could not read IRF from XML file. Be sure you know what you are doing...") else: dataHandling._writeParamIntoXML(outfilelike,IRF=irf,OBJECT=sourceName,RA=ra,DEC=dec) pass #Make a copy of the output XML file and freeze all parameters except the source tree = ET.parse(outfilelike) root = tree.getroot() phIndex = -2.0 for source in root.findall('source'): if(source.get('name')!=sourceName): #Freeze all parameters for spectrum in source.findall('spectrum'): for param in spectrum.findall('parameter'): param.set('free',"%s" % 0) pass pass else: if(fixphindex.lower()!='no' and fixphindex!=False): #Fix photon index for spectrum in source.findall('spectrum'): for param in spectrum.findall('parameter'): if(param.get('name')=='Index'): if(fixphindex.lower()!='prefit'): try: value = float(fixphindex) except: raise ValueError("The value for the photon index (%s) is not a float. Value not recognized." % fixphindex) print("\n\nFixing photon index to the provided value (%s) \n\n" %(value)) param.set('value',"%s" % value) else: print("\n\nFixing photon index to the best fit value on the whole energy range\n\n") param.set('free',"%s" % 0) phIndex = float(param.get('value')) pass pass pass pass f = open("__temporary_XML.xml",'w+') tree.write(f) f.write('''<!-- OBJECT=%s --> <!-- DEC=%s --> <!-- RA=%s --> <!-- IRF=%s -->\n''' %(sourceName,ra,dec,irf)) f.close() #Now for each energy band, make a likelihood and compute the flux f = pyfits.open(eventfile) #Take the list in inverse order so I will rebin at low energies, instead that at high energies energies = numpy.array(sorted(f['EVENTS'].data.ENERGY)[::-1]) totalInputCounts = len(energies) f.close() if(energybins is not None): energyBoundaries = map(lambda x:float(x),energybins.split(',')) else: energyBoundaries = LikelihoodComponent.optimizeBins(LATdata.like1,energies,sourceName,minTs=tsmin,minEvt=3) print("\nEnergy boundaries:") for i,ee1,ee2 in zip(range(len(energyBoundaries)-1),energyBoundaries[:-1],energyBoundaries[1:]): print("%02i: %10s - %10s" %(i+1,ee1,ee2)) pass print("\n") print("\nNumber of energy bins: %s\n" %(len(energyBoundaries)-1)) fluxes = numpy.zeros(len(energyBoundaries)-1) fluxes_errors = numpy.zeros(len(energyBoundaries)-1) phfluxes = numpy.zeros(len(energyBoundaries)-1) phfluxes_errors = numpy.zeros(len(energyBoundaries)-1) TSs = numpy.zeros(len(energyBoundaries)-1) phIndexes = numpy.zeros(len(energyBoundaries)-1) totalCounts = 0 for i,e1,e2 in zip(range(len(fluxes)),energyBoundaries[:-1],energyBoundaries[1:]): thisLATdata = dataHandling.LATData(eventfile,rspfile,ft2file,root="SED_%s-%s" %(e1,e2)) #Further cut in the energy range for this Band #Remove the version _vv from the name of the irf cleanedIrf = "_".join(LATdata.irf.split("_")[:-1]) outf,thisCounts = thisLATdata.performStandardCut(LATdata.ra,LATdata.dec,LATdata.rad,cleanedIrf, LATdata.tmin,LATdata.tmax,e1,e2,180,gtmktime=False,roicut=False) totalCounts += thisCounts #Perform the likelihood analysis outfilelike, sources = thisLATdata.doUnbinnedLikelihoodAnalysis("__temporary_XML.xml", tsmin=tsmin, dogtdiffrsp=False, expomap=expomap, ltcube=ltcube) source = filter(lambda x:x.name==sourceName,sources)[0] if(source.flux.find("<")>=0): #This is an upper limit source.flux = float(source.flux.split("<")[1].strip()) source.fluxError = -1 source.photonFlux = float(source.photonFlux.split("<")[1].strip()) source.photonFluxError = -1 pass fluxes[i] = source.flux fluxes_errors[i] = source.fluxError phfluxes[i] = source.photonFlux phfluxes_errors[i] = source.photonFluxError TSs[i] = float(source.TS) phIndexes[i] = float(source.photonIndex) pass if(totalCounts!=totalInputCounts): raise RuntimeError("We have losted somewhere %s counts!" %(totalInputCounts-totalCounts)) pass #Now compute the SED points MeV2Erg = 1.60217657e-6 ee1 = numpy.array(energyBoundaries[:-1]) ee2 = numpy.array(energyBoundaries[1:]) ee = (ee1+ee2)/2.0 de = (ee2-ee1) #Use the photon index of the total fit to compute the mean energy pow = numpy.power meanEnergies = numpy.array(map(lambda x:computeMeanEnergy(x[0],x[1],x[2]),zip(phIndexes,ee1,ee2))) nuFnu = phfluxes / de * pow(meanEnergies,2.0) * MeV2Erg nuFnuError = phfluxes_errors / de * pow(meanEnergies,2.0) * MeV2Erg #Print the results of the SED fw = open(sedtxt,'w+') fw.write("#Energy_min Energy_Max Flux Flux_error PhotonFlux PhotonFluxError TS nuFnu_energy nuFnu_energy_negerr nuFnu_energy_poserr nuFnu_value nuFnu_value_error\n") fw.write("#MeV MeV erg/cm2/s erg/cm2/s ph/cm2/s ph/cm2/s - MeV MeV MeV erg/cm2/s erg/cm2/s\n") fw.write("#Total exposure: %s s\n" %(totalExposure)) for e1,e2,f,fe,ph,phe,ts,ne,nee1,nee2,nuF,nuFe in zip(energyBoundaries[:-1],energyBoundaries[1:],fluxes,fluxes_errors,phfluxes,phfluxes_errors,TSs,meanEnergies,meanEnergies-ee1,ee2-meanEnergies,nuFnu,nuFnuError): fw.write("%s %s %s %s %s %s %s %s %s %s %s %s\n" %(e1,e2,f,fe,ph,phe,ts,ne,nee1,nee2,nuF,nuFe)) print("%10s - %10s MeV -> %g +/- %g erg/cm2/s, %g +/- %g ph/cm2/s, TS = %s" %(e1,e2,f,fe,ph,phe,ts)) pass fw.close() if(figure is not None): #Display the SED if(os.environ.get('DISPLAY') is None): os.environ.set('DISPLAY','/dev/null') import matplotlib matplotlib.use('Agg') pass import matplotlib.pyplot as plt try: figure.clear() except: print("Creating new figure...") try: figure = plt.figure() except: plt.switch_backend('Agg') figure = plt.figure() pass sub = figure.add_subplot(111) sub.errorbar(meanEnergies,nuFnu,xerr=[meanEnergies-ee1,ee2-meanEnergies],yerr=nuFnuError,fmt='.') sub.set_xlabel("Energy (MeV)") sub.set_ylabel("Flux (erg/cm2/s)") sub.loglog() sub.set_xlim(0.9*min(ee1),1.1*max(ee2)) figure.canvas.draw() figure.savefig("%s.png" % ".".join(sedtxt.split(".")[0:-1])) pass return 'sedtxt', sedtxt
def run(**kwargs): if (len(kwargs.keys()) == 0): #Nothing specified, the user needs just help! thisCommand.getHelp() return pass #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: eventfile = thisCommand.getParValue('filteredeventfile') rspfile = thisCommand.getParValue('rspfile') ft2file = thisCommand.getParValue('ft2file') expomap = thisCommand.getParValue('expomap') ltcube = thisCommand.getParValue('ltcube') xmlmodel = thisCommand.getParValue('xmlmodel') showmodelimage = thisCommand.getParValue('showmodelimage') optimize = thisCommand.getParValue('optimizeposition') spectralfiles = thisCommand.getParValue('spectralfiles') tsmin = float(thisCommand.getParValue('tsmin')) skymap = thisCommand.getParValue('skymap') liketype = thisCommand.getParValue('liketype') clobber = _yesOrNoToBool(thisCommand.getParValue('clobber')) verbose = _yesOrNoToBool(thisCommand.getParValue('verbose')) figure = thisCommand.getParValue('figure') except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" % (err.args[0])) #Print help print thisCommand.getHelp() return pass from GtBurst import dataHandling from GtBurst.angularDistance import getAngularDistance LATdata = dataHandling.LATData(eventfile, rspfile, ft2file) try: if (liketype == 'unbinned'): outfilelike, sources = LATdata.doUnbinnedLikelihoodAnalysis( xmlmodel, tsmin, expomap=expomap, ltcube=ltcube) else: #Generation of spectral files and optimization of the position is #not supported yet for binned analysis if (spectralfiles == 'yes'): print( "\nWARNING: you specified spectralfiles=yes, but the generation of spectral files is not supported for binned analysis\n" ) spectralfiles = 'no' if (optimize == 'yes'): print( "\nWARNING: you specified optimize=yes, but position optimization is not supported for binned analysis\n" ) optimize = 'no' outfilelike, sources = LATdata.doBinnedLikelihoodAnalysis( xmlmodel, tsmin, expomap=expomap, ltcube=ltcube) except GtBurstException as gt: raise gt except: raise #Transfer information on the source from the input to the output XML irf = dataHandling._getParamFromXML(xmlmodel, 'IRF') ra = dataHandling._getParamFromXML(xmlmodel, 'RA') dec = dataHandling._getParamFromXML(xmlmodel, 'DEC') name = dataHandling._getParamFromXML(xmlmodel, 'OBJECT') try: grb = filter(lambda x: x.name.lower().find(name.lower()) >= 0, sources)[0] grb_TS = grb.TS except: #A model without GRB print("\nWarning: no GRB in the model!") grb_TS = -1 pass if (irf == None): print( "\n\nWARNING: could not read IRF from XML file. Be sure you know what you are doing..." ) else: dataHandling._writeParamIntoXML(outfilelike, IRF=irf, OBJECT=name, RA=ra, DEC=dec) pass if (spectralfiles == 'yes'): phafile, rspfile, bakfile = LATdata.doSpectralFiles(outfilelike) pass localizationMessage = '' bestra = '' bestdec = '' poserr = '' distance = '' if (optimize == 'yes'): sourceName = name #If the TS for the source is above tsmin, optimize its position #grb = filter(lambda x:x.name.lower().find(sourceName.lower())>=0,sources)[0] if (math.ceil(grb_TS) >= tsmin): try: bestra, bestdec, poserr = LATdata.optimizeSourcePosition( outfilelike, sourceName) except: raise GtBurstException( 207, "gtfindsrc execution failed. Were the source detected in the likelihood step?" ) else: localizationMessage += "\nNew localization from gtfindsrc:\n\n" localizationMessage += "(R.A., Dec) = (%6.3f, %6.3f)\n" % ( bestra, bestdec) localizationMessage += "68 %s containment radius = %6.3f\n" % ( '%', poserr) localizationMessage += "90 %s containment radius = %6.3f\n" % ( '%', 1.41 * poserr) distance = getAngularDistance(float(ra), float(dec), float(bestra), float(bestdec)) localizationMessage += "Distance from initial position = %6.3f\n\n" % ( distance) localizationMessage += "NOTE: this new localization WILL NOT be used by default. If you judge" localizationMessage += " it is a better localization than the one you started with, update the" localizationMessage += " coordinates yourself and re-run the likelihood\n" pass pass if (figure != None and skymap != None and showmodelimage == 'yes'): #Now produce the binned exposure map (needed in order to display the fitted model as an image) modelmapfile = LATdata.makeModelSkyMap(outfilelike) #Display point sources in the image, and report in the table #all 2FGL sources with TS > 9 + always the GRB, independently of its TS detectedSources = [] grbFlux = 1e-13 for src in sources: weight = 'bold' if (src.type == 'PointSource'): if (src.TS > 4): detectedSources.append(src) if (src.name.find('2FGL') < 0): #GRB grbFlux = src.flux pass pass pass #Display the counts map from GtBurst import aplpy import matplotlib.pyplot as plt figure.clear() orig = aplpy.FITSFigure(skymap, convention='calabretta', figure=figure, subplot=[0.1, 0.1, 0.45, 0.7]) vmax = max(pyfits.open(skymap)[0].data.flatten()) nEvents = numpy.sum(pyfits.open(skymap)[0].data) telapsed = pyfits.open(eventfile)[0].header['TSTOP'] - pyfits.open( eventfile)[0].header['TSTART'] orig.set_tick_labels_font(size='small') orig.set_axis_labels_font(size='small') orig.show_colorscale(cmap='gist_heat', vmin=0.1, vmax=max(vmax, 0.11), stretch='log', aspect='auto') # Modify the tick labels for precision and format orig.tick_labels.set_xformat('ddd.dd') orig.tick_labels.set_yformat('ddd.dd') # Display a grid and tweak the properties orig.show_grid() #Renormalize the modelmapfile to the flux of the grb f = pyfits.open(modelmapfile, 'update') f[0].data = f[0].data / numpy.max(f[0].data) * nEvents / telapsed print(numpy.max(f[0].data)) f.close() img = aplpy.FITSFigure(modelmapfile, convention='calabretta', figure=figure, subplot=[0.55, 0.1, 0.4, 0.7]) img.set_tick_labels_font(size='small') img.set_axis_labels_font(size='small') #vmax = max(pyfits.open(modelmapfile)[0].data.flatten()) img.show_colorscale(cmap='gist_heat', aspect='auto', stretch='log') for src in detectedSources: img.add_label(float(src.ra), float(src.dec), "%s\n(ts = %i)" % (src.name, int(math.ceil(src.TS))), relative=False, weight=weight, color='green', size='small') pass # Modify the tick labels for precision and format img.tick_labels.set_xformat('ddd.dd') img.tick_labels.set_yformat('ddd.dd') # Display a grid and tweak the properties img.show_grid() #ax = figure.add_axes([0.1,0.72,0.85,0.25],frame_on=False) #ax.xaxis.set_visible(False) #ax.yaxis.set_visible(False) #col_labels =['Source Name','TS','Energy flux','Photon index'] #table_vals = map(lambda x:[x.name,"%i" %(int(math.ceil(x.TS))), # "%s +/- %s" % (x.flux,x.fluxError), # "%s +/- %s" % (x.photonIndex,x.photonIndexError)],detectedSources) # #if(len(table_vals)>0): # the_table = ax.table(cellText=table_vals, # colLabels=col_labels, # loc='upper center') figure.canvas.draw() figure.savefig("likelihood_results.png") pass if (figure != None): #Assume we have an X server running #Now display the results likemsg = "Log(likelihood) = %s" % (LATdata.logL) displayResults( figure.canvas._tkcanvas, LATdata.resultsStrings + "\n" + likemsg + "\n" + localizationMessage) print(localizationMessage) return 'likexmlresults', outfilelike, 'TS', grb_TS, 'bestra', bestra, 'bestdec', bestdec, 'poserr', poserr, 'distance', distance, 'sources', sources
def run(**kwargs): if(len(kwargs.keys())==0): #Nothing specified, the user needs just help! thisCommand.getHelp() return #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: ft2file = thisCommand.getParValue('ft2file') infile = thisCommand.getParValue('xmlsimmodel') simeventfile = thisCommand.getParValue('simeventfile') srclist = thisCommand.getParValue('srclist') tstart = thisCommand.getParValue('tstart') tstop = thisCommand.getParValue('tstop') triggertime = thisCommand.getParValue('triggertime') irf = thisCommand.getParValue('irf') seed = thisCommand.getParValue('seed') figure = thisCommand.getParValue('figure') outdir = thisCommand.getParValue('outdir') clobber = _yesOrNoToBool(thisCommand.getParValue('clobber')) verbose = _yesOrNoToBool(thisCommand.getParValue('verbose')) except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0])) print thisCommand.getHelp() return from GtBurst import dataHandling irf_ = dataHandling._getParamFromXML(infile,'IRF') ra = dataHandling._getParamFromXML(infile,'RA') dec = dataHandling._getParamFromXML(infile,'DEC') name = dataHandling._getParamFromXML(infile,'OBJECT') if(irf_ is None and irf=='None'): raise RuntimeError("Could not read IRF from XML file, and you did not specify it with the 'irf' command line parameter") if(irf==''): irf = irf_ pass simtime = float(tstop)-float(tstart) LATSimulation = dataHandling.Simulation(ft2file,irf,triggertime) outfile, idsfile = LATSimulation.doSimulation(infile=infile, srclist=srclist, evroot ='__temp', simtime=float(simtime), tstart =float(tstart), seed =int(seed)) os.rename(outfile,simeventfile) ############################ #This happens only if the input XML has been generated by the tool in GtBurst if(irf_ is not None and ra is not None and dec is not None and name is not None): try: #If the simeventfile follows the convention gll_ft1_tr_[triggerName]_v[version].fit #then produce a ft2 file which follows that too rootname = simeventfile.split("_")[3] version = simeventfile.split("_")[4] newft2 = 'gll_ft2_tr_%s_%s.fit' %(rootname,version) except: #Just add a 'sim' before the extension rootname = "%ssim" % name atoms = os.path.basename(ft2file).split('.') newft2 = "%ssim.%s" %(atoms[0],atoms[1]) pass shutil.copyfile(ft2file,newft2) ft1,rsp,ft2,cspec = dataHandling._makeDatasetsOutOfLATdata(simeventfile,newft2,rootname, tstart,tstop,ra,dec,triggertime,'.') if(figure is not None): tempfile = '__temp__skymap_sim.fit' gtdocountsmap.gtdocountsmap(eventfile=ft1,rspfile=rsp,ft2file=ft2,ra=ra,dec=dec,rad=40, irf='transient',zmax=180,tstart=tstart,tstop=tstop,emin=10, emax=1e9,skybinsize=0.2,skymap=tempfile,figure=figure) os.remove(tempfile) pass pass #Now move them in the output directory if(outdir!='.'): destdir = os.path.abspath(os.path.expanduser(outdir)) try: os.makedirs(destdir) except os.error: print("Note: directory %s already exists" %(outdir)) for orig,dest in zip([ft1,ft2,rsp,cspec],map(lambda x:os.path.join(destdir,x),[ft1,ft2,rsp,cspec])): if(os.path.exists(dest)): if(clobber==True): os.remove(dest) else: raise RuntimeError("File %s already exists and clobber=no" %(dest)) pass pass shutil.move(orig,dest) pass pass return 'simeventfile', simeventfile
def run(**kwargs): if(len(kwargs.keys())==0): #Nothing specified, the user needs just help! thisCommand.getHelp() return pass #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: eventfile = thisCommand.getParValue('filteredeventfile') rspfile = thisCommand.getParValue('rspfile') ft2file = thisCommand.getParValue('ft2file') expomap = thisCommand.getParValue('expomap') ltcube = thisCommand.getParValue('ltcube') xmlmodel = thisCommand.getParValue('xmlmodel') showmodelimage = thisCommand.getParValue('showmodelimage') optimize = thisCommand.getParValue('optimizeposition') spectralfiles = thisCommand.getParValue('spectralfiles') tsmin = float(thisCommand.getParValue('tsmin')) skymap = thisCommand.getParValue('skymap') liketype = thisCommand.getParValue('liketype') clobber = _yesOrNoToBool(thisCommand.getParValue('clobber')) verbose = _yesOrNoToBool(thisCommand.getParValue('verbose')) flemin = thisCommand.getParValue('flemin') flemax = thisCommand.getParValue('flemax') clul = float(thisCommand.getParValue('clul')) figure = thisCommand.getParValue('figure') except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0])) #Print help print thisCommand.getHelp() return pass assert clul < 1.0, "The confidence level for the upper limit (clul) must be < 1" from GtBurst import dataHandling from GtBurst.angularDistance import getAngularDistance LATdata = dataHandling.LATData(eventfile,rspfile,ft2file) try: if(liketype=='unbinned'): outfilelike, sources = LATdata.doUnbinnedLikelihoodAnalysis(xmlmodel,tsmin,expomap=expomap,ltcube=ltcube,emin=flemin,emax=flemax, clul=clul) else: #Generation of spectral files and optimization of the position is #not supported yet for binned analysis if(spectralfiles=='yes'): print("\nWARNING: you specified spectralfiles=yes, but the generation of spectral files is not supported for binned analysis\n") spectralfiles = 'no' if(optimize=='yes'): print("\nWARNING: you specified optimize=yes, but position optimization is not supported for binned analysis\n") optimize = 'no' outfilelike, sources = LATdata.doBinnedLikelihoodAnalysis(xmlmodel,tsmin,expomap=expomap,ltcube=ltcube,emin=flemin,emax=flemax, clul=clul) except GtBurstException as gt: raise gt except: raise #Transfer information on the source from the input to the output XML irf = dataHandling._getParamFromXML(xmlmodel,'IRF') ra = dataHandling._getParamFromXML(xmlmodel,'RA') dec = dataHandling._getParamFromXML(xmlmodel,'DEC') name = dataHandling._getParamFromXML(xmlmodel,'OBJECT') try: grb = filter(lambda x:x.name.lower().find(name.lower())>=0,sources)[0] grb_TS = grb.TS except: #A model without GRB print("\nWarning: no GRB in the model!") grb_TS = -1 pass if(irf is None): print("\n\nWARNING: could not read IRF from XML file. Be sure you know what you are doing...") else: dataHandling._writeParamIntoXML(outfilelike,IRF=irf,OBJECT=name,RA=ra,DEC=dec) pass if(spectralfiles=='yes'): phafile,rspfile,bakfile = LATdata.doSpectralFiles(outfilelike) pass localizationMessage = '' bestra = '' bestdec = '' poserr = '' distance = '' if(optimize=='yes'): sourceName = name #If the TS for the source is above tsmin, optimize its position #grb = filter(lambda x:x.name.lower().find(sourceName.lower())>=0,sources)[0] if(math.ceil(grb_TS) >= tsmin): try: bestra,bestdec,poserr = LATdata.optimizeSourcePosition(outfilelike,sourceName) except: raise GtBurstException(207,"gtfindsrc execution failed. Were the source detected in the likelihood step?") else: localizationMessage += "\nNew localization from gtfindsrc:\n\n" localizationMessage += "(R.A., Dec) = (%6.3f, %6.3f)\n" %(bestra,bestdec) localizationMessage += "68 %s containment radius = %6.3f\n" %('%',poserr) localizationMessage += "90 %s containment radius = %6.3f\n" %('%',1.41*poserr) distance = getAngularDistance(float(ra),float(dec),float(bestra),float(bestdec)) localizationMessage += "Distance from initial position = %6.3f\n\n" %(distance) localizationMessage += "NOTE: this new localization WILL NOT be used by default. If you judge" localizationMessage += " it is a better localization than the one you started with, update the" localizationMessage += " coordinates yourself and re-run the likelihood\n" pass pass if(figure is not None and skymap is not None and showmodelimage=='yes'): #Now produce the binned exposure map (needed in order to display the fitted model as an image) modelmapfile = LATdata.makeModelSkyMap(outfilelike) #Display point sources in the image, and report in the table #all 3FGL sources with TS > 9 + always the GRB, independently of its TS detectedSources = [] grbFlux = 1e-13 for src in sources: weight = 'bold' if(src.type=='PointSource'): if(src.TS > 4): detectedSources.append(src) if(src.name.find('3FGL')<0): #GRB grbFlux = src.flux pass pass pass #Display the counts map from GtBurst import aplpy import matplotlib.pyplot as plt figure.clear() orig = aplpy.FITSFigure(skymap,convention='calabretta', figure=figure,subplot=[0.1,0.1,0.45,0.7]) vmax = max(pyfits.open(skymap)[0].data.flatten()) nEvents = numpy.sum(pyfits.open(skymap)[0].data) telapsed = pyfits.open(eventfile)[0].header['TSTOP']-pyfits.open(eventfile)[0].header['TSTART'] orig.set_tick_labels_font(size='small') orig.set_axis_labels_font(size='small') orig.show_colorscale(cmap='gist_heat',vmin=0.1,vmax=max(vmax,0.11),stretch='log',aspect='auto') # Modify the tick labels for precision and format orig.tick_labels.set_xformat('ddd.dd') orig.tick_labels.set_yformat('ddd.dd') # Display a grid and tweak the properties orig.show_grid() #Renormalize the modelmapfile to the flux of the grb f = pyfits.open(modelmapfile,'update') f[0].data = f[0].data/numpy.max(f[0].data)*nEvents/telapsed print(numpy.max(f[0].data)) f.close() img = aplpy.FITSFigure(modelmapfile,convention='calabretta', figure=figure,subplot=[0.55,0.1,0.4,0.7]) img.set_tick_labels_font(size='small') img.set_axis_labels_font(size='small') #vmax = max(pyfits.open(modelmapfile)[0].data.flatten()) img.show_colorscale(cmap='gist_heat',aspect='auto',stretch='log') for src in detectedSources: img.add_label(float(src.ra),float(src.dec), "%s\n(ts = %i)" %(src.name,int(math.ceil(src.TS))), relative=False,weight=weight, color='green', size='small') pass # Modify the tick labels for precision and format img.tick_labels.set_xformat('ddd.dd') img.tick_labels.set_yformat('ddd.dd') # Display a grid and tweak the properties img.show_grid() #ax = figure.add_axes([0.1,0.72,0.85,0.25],frame_on=False) #ax.xaxis.set_visible(False) #ax.yaxis.set_visible(False) #col_labels =['Source Name','TS','Energy flux','Photon index'] #table_vals = map(lambda x:[x.name,"%i" %(int(math.ceil(x.TS))), # "%s +/- %s" % (x.flux,x.fluxError), # "%s +/- %s" % (x.photonIndex,x.photonIndexError)],detectedSources) # #if(len(table_vals)>0): # the_table = ax.table(cellText=table_vals, # colLabels=col_labels, # loc='upper center') figure.canvas.draw() figure.savefig("likelihood_results.png") pass if(figure is not None): #Assume we have an X server running #Now display the results likemsg = "Log(likelihood) = %s" %(LATdata.logL) displayResults(figure.canvas._tkcanvas, LATdata.resultsStrings + "\n" + likemsg + "\n" + localizationMessage) print(localizationMessage) return 'likexmlresults', outfilelike, 'TS', grb_TS, 'bestra', bestra, 'bestdec', bestdec, 'poserr', poserr, 'distance', distance,'sources', sources
def run(**kwargs): if (len(kwargs.keys()) == 0): #Nothing specified, the user needs just help! thisCommand.getHelp() return #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: ft2file = thisCommand.getParValue('ft2file') infile = thisCommand.getParValue('xmlsimmodel') simeventfile = thisCommand.getParValue('simeventfile') srclist = thisCommand.getParValue('srclist') tstart = thisCommand.getParValue('tstart') tstop = thisCommand.getParValue('tstop') triggertime = thisCommand.getParValue('triggertime') irf = thisCommand.getParValue('irf') seed = thisCommand.getParValue('seed') figure = thisCommand.getParValue('figure') outdir = thisCommand.getParValue('outdir') clobber = _yesOrNoToBool(thisCommand.getParValue('clobber')) verbose = _yesOrNoToBool(thisCommand.getParValue('verbose')) except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" % (err.args[0])) print thisCommand.getHelp() return from GtBurst import dataHandling irf_ = dataHandling._getParamFromXML(infile, 'IRF') ra = dataHandling._getParamFromXML(infile, 'RA') dec = dataHandling._getParamFromXML(infile, 'DEC') name = dataHandling._getParamFromXML(infile, 'OBJECT') if (irf_ is None and irf == 'None'): raise RuntimeError( "Could not read IRF from XML file, and you did not specify it with the 'irf' command line parameter" ) if (irf == ''): irf = irf_ pass simtime = float(tstop) - float(tstart) LATSimulation = dataHandling.Simulation(ft2file, irf, triggertime) outfile, idsfile = LATSimulation.doSimulation(infile=infile, srclist=srclist, evroot='__temp', simtime=float(simtime), tstart=float(tstart), seed=int(seed)) os.rename(outfile, simeventfile) ############################ #This happens only if the input XML has been generated by the tool in GtBurst if (irf_ is not None and ra is not None and dec is not None and name is not None): try: #If the simeventfile follows the convention gll_ft1_tr_[triggerName]_v[version].fit #then produce a ft2 file which follows that too rootname = simeventfile.split("_")[3] version = simeventfile.split("_")[4] newft2 = 'gll_ft2_tr_%s_%s.fit' % (rootname, version) except: #Just add a 'sim' before the extension rootname = "%ssim" % name atoms = os.path.basename(ft2file).split('.') newft2 = "%ssim.%s" % (atoms[0], atoms[1]) pass shutil.copyfile(ft2file, newft2) ft1, rsp, ft2, cspec = dataHandling._makeDatasetsOutOfLATdata( simeventfile, newft2, rootname, tstart, tstop, ra, dec, triggertime, '.') if (figure is not None): tempfile = '__temp__skymap_sim.fit' gtdocountsmap.gtdocountsmap(eventfile=ft1, rspfile=rsp, ft2file=ft2, ra=ra, dec=dec, rad=40, irf='transient', zmax=180, tstart=tstart, tstop=tstop, emin=10, emax=1e9, skybinsize=0.2, skymap=tempfile, figure=figure) os.remove(tempfile) pass pass #Now move them in the output directory if (outdir != '.'): destdir = os.path.abspath(os.path.expanduser(outdir)) try: os.makedirs(destdir) except os.error: print("Note: directory %s already exists" % (outdir)) for orig, dest in zip([ft1, ft2, rsp, cspec], map(lambda x: os.path.join(destdir, x), [ft1, ft2, rsp, cspec])): if (os.path.exists(dest)): if (clobber == True): os.remove(dest) else: raise RuntimeError( "File %s already exists and clobber=no" % (dest)) pass pass shutil.move(orig, dest) pass pass return 'simeventfile', simeventfile
def run(**kwargs): if (not available): raise RuntimeError( "The command gtconvertxmlmodel.py is not currently usable with public Science Tools" ) if (len(kwargs.keys()) == 0): #Nothing specified, the user needs just help! thisCommand.getHelp() return pass #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: xmlmodel = thisCommand.getParValue('likexmlresults') Emin = float(thisCommand.getParValue('emin')) Emax = float(thisCommand.getParValue('emax')) xmlsimmodel = thisCommand.getParValue('xmlsimmodel') clobber = _yesOrNoToBool(thisCommand.getParValue('clobber')) verbose = _yesOrNoToBool(thisCommand.getParValue('verbose')) except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" % (err.args[0])) #Print help print thisCommand.getHelp() return from GtBurst import dataHandling irf = dataHandling._getParamFromXML(xmlmodel, 'IRF') ra = dataHandling._getParamFromXML(xmlmodel, 'RA') dec = dataHandling._getParamFromXML(xmlmodel, 'DEC') name = dataHandling._getParamFromXML(xmlmodel, 'OBJECT') if (irf == None): print( "\n\nWARNING: could not read IRF from XML file. Be sure you know what you are doing..." ) sourceList = xmlmodel.replace('.xml', '.txt') #Quick fix: MCModelBuilder cannot integrate a isotropic model if it has not a normalization of 1 #We will edit the XML model, put temporarily the normalization of the IsotropicTemplate to 1, #convert the XML, then multiply the output normalization by the factor contained at the beginning tmpxml = "__temp__xmlmodel.xml" shutil.copy(xmlmodel, tmpxml) originalNorm = dataHandling.getIsotropicTemplateNormalization(xmlmodel) if (originalNorm != None or originalNorm != 1): dataHandling.setIsotropicTemplateNormalization(tmpxml, 1) else: #Either the template is not in the XML file (possibly because the user used Transient class), #or it is already 1, nothing to do originalNorm = 1 pass ps, ds = parse_sources(tmpxml) sources = ps sources.extend(ds) mc = uw.like.roi_monte_carlo.MCModelBuilder(sources, savedir='.', emin=Emin, emax=Emax) mc.build(xmlsimmodel) dataHandling.multiplyIsotropicTemplateFluxSim(xmlsimmodel, originalNorm) os.remove(tmpxml) txt = '' for x in sources: txt += x.name.replace('2FGL ', '_2FGL_').replace('-', 'm').replace( '.', '') + '\n' file(sourceList, 'w').writelines(txt) lines = file(xmlsimmodel, 'r').readlines() newlines = '' pwd = os.environ['PWD'] for l in lines: newlines += l.replace('$($SIMDIR)', pwd) pass file(xmlsimmodel, 'w').writelines(newlines) if (irf != None): dataHandling._writeParamIntoXML(xmlsimmodel, IRF=irf, OBJECT=name, RA=ra, DEC=dec) pass return 'xmlsimmodel', xmlsimmodel, 'srclist', sourceList
targs['fgl_mode'] = args.fgl_mode targs['ft2file'] = dataset['ft2file'] targs['source_model'] = 'powerlaw2' printCommand("gtbuildxmlmodel",targs) _,xmlmodel = gtbuildxmlmodel.run(**targs) # Now if the user has specified a specific photon index for upper limits, # change the photon index in the XML file # Save parameters in comments (ET will strip them out) pars_in_comments = {} for key in ['OBJECT','RA','DEC','IRF']: pars_in_comments[key] = dataHandling._getParamFromXML(xmlmodel,key) # Now change the photon index in the XML file tree = ET.parse(xmlmodel) root = tree.getroot() index = root.findall("./source[@name='%s']/spectrum/parameter[@name='Index']" % 'GRB')[0] if args.ulphindex==-1.0: args.ulphindex += 0.01 index.set('value', str(args.ulphindex)) tree.write(xmlmodel)
def run(**kwargs): if(not available): raise RuntimeError("The command gtconvertxmlmodel.py is not currently usable with public Science Tools") if(len(kwargs.keys())==0): #Nothing specified, the user needs just help! thisCommand.getHelp() return pass #Get parameters values thisCommand.setParValuesFromDictionary(kwargs) try: xmlmodel = thisCommand.getParValue('likexmlresults') Emin = float(thisCommand.getParValue('emin')) Emax = float(thisCommand.getParValue('emax')) xmlsimmodel = thisCommand.getParValue('xmlsimmodel') clobber = _yesOrNoToBool(thisCommand.getParValue('clobber')) verbose = _yesOrNoToBool(thisCommand.getParValue('verbose')) except KeyError as err: print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0])) #Print help print thisCommand.getHelp() return from GtBurst import dataHandling irf = dataHandling._getParamFromXML(xmlmodel,'IRF') ra = dataHandling._getParamFromXML(xmlmodel,'RA') dec = dataHandling._getParamFromXML(xmlmodel,'DEC') name = dataHandling._getParamFromXML(xmlmodel,'OBJECT') if(irf is None): print("\n\nWARNING: could not read IRF from XML file. Be sure you know what you are doing...") sourceList = xmlmodel.replace('.xml','.txt') #Quick fix: MCModelBuilder cannot integrate a isotropic model if it has not a normalization of 1 #We will edit the XML model, put temporarily the normalization of the IsotropicTemplate to 1, #convert the XML, then multiply the output normalization by the factor contained at the beginning tmpxml = "__temp__xmlmodel.xml" shutil.copy(xmlmodel,tmpxml) originalNorm = dataHandling.getIsotropicTemplateNormalization(xmlmodel) if(originalNorm is not None or originalNorm!=1): dataHandling.setIsotropicTemplateNormalization(tmpxml,1) else: #Either the template is not in the XML file (possibly because the user used Transient class), #or it is already 1, nothing to do originalNorm = 1 pass ps,ds = parse_sources(tmpxml) sources = ps sources.extend(ds) mc = uw.like.roi_monte_carlo.MCModelBuilder(sources,savedir='.',emin=Emin,emax=Emax) mc.build(xmlsimmodel) dataHandling.multiplyIsotropicTemplateFluxSim(xmlsimmodel,originalNorm) os.remove(tmpxml) txt='' for x in sources: txt += x.name.replace('2FGL ','_2FGL_').replace('-','m').replace('.','')+'\n' file(sourceList,'w').writelines(txt) lines = file(xmlsimmodel,'r').readlines() newlines ='' pwd = os.environ['PWD'] for l in lines: newlines += l.replace('$($SIMDIR)',pwd) pass file(xmlsimmodel,'w').writelines(newlines) if(irf is not None): dataHandling._writeParamIntoXML(xmlsimmodel,IRF=irf,OBJECT=name,RA=ra,DEC=dec) pass return 'xmlsimmodel', xmlsimmodel, 'srclist', sourceList