Exemple #1
0
def fitsToPNG(fitsfile, pngfile, vmin=None, vmax=None, **kwargs):
    #Display the TS map
    #figure                      = plt.figure()
    tsfig = aplpy.FITSFigure(fitsfile, convention='calabretta')
    tsfig.set_tick_labels_font(size='small')
    tsfig.set_axis_labels_font(size='small')
    if (vmin is not None and vmax is not None):
        tsfig.show_colorscale(cmap='gist_heat',
                              aspect='auto',
                              vmin=float(vmin),
                              vmax=float(vmax))
    else:
        #Get maximum of image
        f = pyfits.open(fitsfile)
        maximum = f[0].data.max()
        f.close()
        tsfig.show_colorscale(cmap='gist_heat',
                              aspect='auto',
                              vmin=0,
                              vmax=float(maximum))
    # 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()
    tsfig.add_colorbar()

    if ('sources' in kwargs.keys()):
        sources = kwargs['sources']
        for src in sources:
            tsfig.add_label(float(src[1]),
                            float(src[2]),
                            "%s" % src[0],
                            relative=False,
                            weight='bold',
                            color='green',
                            size='x-small',
                            verticalalignment='top',
                            horizontalalignment='left')
            tsfig.show_markers([float(src[1])], [float(src[2])],
                               edgecolor='green',
                               marker='x')
        pass
    if ('ra' in kwargs.keys()):
        ra = float(kwargs['ra'])
        dec = float(kwargs['dec'])
        tsfig.show_markers([ra], [dec],
                           edgecolor='cyan',
                           facecolor='cyan',
                           marker='x',
                           s=120,
                           alpha=0.5,
                           linewidth=3)
    pass

    #figure.canvas.draw()
    tsfig.save(pngfile)
    def displayImage(self):
        self.image = aplpy.FITSFigure(self.skyimage,
                                      convention='calabretta',
                                      figure=self.figure,
                                      subplot=[0.1, 0.10, 0.40, 0.7],
                                      label='sky image')

        imageFits = pyfits.open(self.skyimage)
        img = imageFits[0].data

        # Apply grayscale mapping of image
        if (not self.empty):
            skm = self.image.show_colorscale(cmap='gist_heat',
                                             vmin=0.1,
                                             vmax=max(img.flatten()),
                                             stretch='log')
        else:
            skm = self.image.show_colorscale(cmap='gist_heat',
                                             vmin=0,
                                             vmax=0.1)
        imageFits.close()

        # Modify the tick labels for precision and format
        self.image.tick_labels.set_xformat('ddd.dd')
        self.image.tick_labels.set_yformat('ddd.dd')

        # Display a grid and tweak the properties
        try:
            self.image.show_grid()
        except:
            #show_grid throw an exception if the grid was already there
            pass
        pass

        #Try to plot a cross at the source position

        if (self.obj_ra is not None):
            self.image.show_markers([float(self.obj_ra)],
                                    [float(self.obj_dec)],
                                    edgecolor='cyan',
                                    facecolor='cyan',
                                    marker='x',
                                    s=120,
                                    alpha=0.5,
                                    linewidth=2)

        self.figure.canvas.draw()
Exemple #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('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
Exemple #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