Пример #1
0
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
Пример #2
0
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
Пример #3
0
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('eventfile')
        rspfile = thisCommand.getParValue('rspfile')
        ft2file = thisCommand.getParValue('ft2file')
        ra = thisCommand.getParValue('ra')
        dec = thisCommand.getParValue('dec')
        rad = thisCommand.getParValue('rad')
        irf = thisCommand.getParValue('irf')
        zmax = thisCommand.getParValue('zmax')
        tstart = thisCommand.getParValue('tstart')
        tstop = thisCommand.getParValue('tstop')
        emin = thisCommand.getParValue('emin')
        emax = thisCommand.getParValue('emax')
        skybinsize = thisCommand.getParValue('skybinsize')
        outfile = thisCommand.getParValue('skymap')
        strategy = thisCommand.getParValue('strategy')
        thetamax = float(thisCommand.getParValue('thetamax'))
        allowEmpty = _yesOrNoToBool(thisCommand.getParValue('allowEmpty'))
        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
    global lastDisplay

    LATdata = dataHandling.LATData(eventfile, rspfile, ft2file)

    if (strategy.lower() == "time"):
        #gtmktime cut
        filteredFile, nEvents = LATdata.performStandardCut(ra,
                                                           dec,
                                                           rad,
                                                           irf,
                                                           tstart,
                                                           tstop,
                                                           emin,
                                                           emax,
                                                           zmax,
                                                           thetamax,
                                                           True,
                                                           strategy='time')
    elif (strategy.lower() == "events"):
        #no gtmktime cut, Zenith cut applied directly to the events
        filteredFile, nEvents = LATdata.performStandardCut(ra,
                                                           dec,
                                                           rad,
                                                           irf,
                                                           tstart,
                                                           tstop,
                                                           emin,
                                                           emax,
                                                           zmax,
                                                           thetamax,
                                                           True,
                                                           strategy='events')
    pass

    LATdata.doSkyMap(outfile, skybinsize)

    #Now open the output file and get exposure and total number of events
    skymap = pyfits.open(outfile)
    totalNumberOfEvents = numpy.sum(skymap[0].data)
    totalTime = numpy.sum(skymap['GTI'].data.field('STOP') -
                          skymap['GTI'].data.field('START'))
    skymap.close()
    print("\nTotal number of events in the counts map: %s" %
          (totalNumberOfEvents))
    print("Total time in Good Time Intervals:        %s" % (totalTime))
    if ((totalTime == 0) and allowEmpty == False):
        raise GtBurstException(
            2, "Your filter resulted in zero exposure. \n\n" +
            " Loose your cuts, or enlarge the time interval. You might want to "
            +
            " check also the navigation plots (in the Tools menu) to make sure "
            +
            " that the ROI is within the LAT FOV in the desired time interval."
        )

    displ = None

    if (figure != None):
        if (lastDisplay != None):
            lastDisplay.unbind()
        pass
        from GtBurst.InteractiveFt1Display import InteractiveFt1Display
        lastDisplay = InteractiveFt1Display(filteredFile, outfile, figure, ra,
                                            dec)
    pass

    return 'skymap', outfile, 'filteredeventfile', filteredFile, 'irf', irf, 'eventDisplay', lastDisplay
Пример #4
0
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