Example #1
0
    def _addNewSource(self, ra, dec):
        """Add new source to the model

        Parameters:
        - self - This DS9Connector object
        - ra - The RA of the center of the ds9 region to be added as a source
        - dec - The Dec of the cetner of the ds9 region to be added as a source

        Return value:
        - none

        Description:
            This method adds a default Source object (PowerLaw spectrum) at
        the RA and Dec passed to it.  The source name is constructed from the
        RA and Dec and proceeded with the 'ME_' designation to show it was
        added via ds9 and the model editor.
            Access to the SourceLibraryDocumentEditor object is controlled
        via a thread lock to prevent race conditions.  As this method causes
        modifications in the GUI, it must be run on the main thread.
        """
        #        print "Entering _addNewSource"
        # create a name
        name = "ME_" + str(ra) + "_" + str(dec)
        # make a default PL source
        source = Source(name=name)
        # set the RA/dec
        raParam = Parameter(name="RA",
                            value=ra,
                            scale=1.0,
                            min=0.0,
                            max=360.0,
                            free=False)
        decParam = Parameter(name="DEC",
                             value=dec,
                             scale=1.0,
                             min=-90.0,
                             max=90.0,
                             free=False)
        spatialModel = SpatialModel(type="SkyDirFunction",
                                    parameters=[raParam, decParam])
        source.setSpatialModel(spatialModel)

        #        print "Locking editor"
        # add source to model list
        with self.docLock:
            sourceLibraryDocument = self.sourceLibraryDocumentEditor.get()
            sourceLibraryDocument.addSource(source)
            self.sourceLibraryDocumentEditor.set(sourceLibraryDocument)
            self.sourceLibraryDocumentEditor.commit()
#        print "Unlocked editor"
#get Source index of new source and set as selected source
        self.sourceLibraryDocumentEditor.selectSource(name)
    def _add3FGLSources(self):
        """Extract sources from the 3FGL catalog file

        Parameters:
        - self - This CatalogSourceExtractor object

        Return value:
        - none - Sets the self.sources variable to a list of source objects

        Usage:
           self._add3FGLSources()

        Description:
            This function loops over all of the sources in the 3FGL catalog file and extracts all those
        that lie within 5 degrees of the ROI.  It creates Source objects for each on assigning it the
        appropriate spectral and spatial models based on the data provided in the catalog.  Each model
        is added to the object's local list of sources.

        """
        file = self.catFile.fitsFilePtr
        #        file=pyfits.open(self.catParams['catalogFile']) #open source list file and access necessary fields, requires LAT source catalog definitions and names
        data = file[1].data
        extendedinfo = file[5].data
        extName = extendedinfo.field('Source_Name')
        extFile = extendedinfo.field('Spatial_Filename')
        name = data.field('Source_Name')
        ExtName = data.field('Extended_Source_Name')
        ra = data.field('RAJ2000')
        dec = data.field('DEJ2000')
        flux = data.field('Flux_Density')
        pivot = data.field('Pivot_Energy')
        index = data.field('Spectral_Index')
        cutoff = data.field('Cutoff')
        spectype = data.field('SpectrumType')
        beta = data.field('beta')
        sigma = data.field('Signif_Avg')
        ptSrcNum = 0
        extSrcNum = 0

        for n, f, i, r, d, p, c, t, b, S, EN in zip(name, flux, index, ra, dec,
                                                    pivot, cutoff, spectype,
                                                    beta, sigma, ExtName):
            dist = angsep(self.ra, self.dec, r,
                          d)  # get distance from object to ROI center
            if (r == self.ra and d
                    == self.dec):  # just to avoid any small number errors
                dist = 0.0
            if (dist <= self.radius + 5.0):  # object is in target area
                sourceName = ''
                for N in n.split(' '):  # remove spaces from name
                    sourceName += N
                if EN != '' and not self.catParams[
                        'forcePointSource']:  # We're making an extended source model
                    extSrcNum += 1
                    Name = (
                        EN if not EN[0].isdigit() else "_" + EN
                    )  # add an underscore to prevent string/number issues if name starts with a digit
                    Type = "DiffuseSource"
                else:  # we're building a point source model
                    ptSrcNum += 1
                    Name = (
                        sourceName if not sourceName[0].isdigit() else "_" +
                        sourceName
                    )  # add an underscore to prevent string/number issues if name starts with a digit
                    Type = "PointSource"
                source = Source(name=Name, type=Type)
                if EN != 'Vela X' and EN != 'MSH 15-52':
                    if t == 'PowerLaw':
                        self._PLspec(source, f, i, p, dist, S)
                    elif t == 'PowerLaw2':  #no value for flux from 100 MeV to 100 GeV in fits file0
                        if i != 1.:  #so calculate it by integrating PowerLaw spectral model
                            F = f * p**i / (-i + 1) * (1.e5**(-i + 1) -
                                                       1.e2**(-1 + 1))
                        else:
                            F = f * p * log(1.e3)
                        self._PL2spec(source, F, i, dist, S)
                    elif t == 'LogParabola':
                        self._LPspec(source, f, i, p, b, dist, S)
                    else:
                        self._COspec(source, f, i, p, c, dist, S)
                else:
                    if EN == 'Vela X':
                        self._VXspec(source, i, dist)
                    else:
                        self._MSHspec(source, i, dist)
                if EN != '' and not self.catParams['forcePointSource']:
                    eFile = None
                    for exN, exf in zip(extName, extFile):
                        if exN == EN:
                            if len(self.catParams['extTempDir']) > 0:
                                if self.catParams['extTempDir'][-1] == '/':
                                    eFile = self.catParams['extTempDir'] + exf
                                else:
                                    eFile = self.catParams[
                                        'extTempDir'] + '/' + exf
                            else:
                                eFile = exf
                            break
                    if eFile == None:
                        showError(
                            "The model template file for" + n +
                            " does to seem to exist in the specified directory.  Please update model file parameter by hand."
                        )
                        spatialModel = SpatialModel(
                            type="SpatialMap",
                            file=self.catParams['extTempDir'])
                    else:
                        spatialModel = SpatialModel(type="SpatialMap",
                                                    file=eFile)
                else:
                    ra = Parameter(name="RA",
                                   value=r,
                                   scale=1.0,
                                   min=0.0,
                                   max=360.0,
                                   free=False)
                    dec = Parameter(name="DEC",
                                    value=d,
                                    scale=1.0,
                                    min=-90.0,
                                    max=90.0,
                                    free=False)
                    spatialModel = SpatialModel(type="SkyDirFunction",
                                                parameters=[ra, dec])
                source.setSpatialModel(spatialModel)

                if (None == self.sources):
                    self.sources = []
                self.sources.append(source)

        # Set Galactic Diffuse model
        gdSpatial = SpatialModel(type="MapCubeFunction",
                                 file=self.catParams['galDiffFile'])
        gdSource = Source(
            name=self.catParams['gdModelName'],
            type='DiffuseSource',
            spatialModel=gdSpatial)  #default spectrum is PowerLaw
        # but we need to fix the index
        spec = gdSource.getSpectrum()
        index = spec.getParameterByName("Index")
        index.setFree(False)
        spec.setParameterByName("Index", index)
        gdSource.setSpectrum(spec)
        self.sources.append(gdSource)

        # Set isotropic diffuse source
        if (
                None == self.catParams['isoTempFile']
        ):  #null means no file so assume user wants an isotropic power law component
            isoSpectrum = Specturm()  # create a default PowerLaw Spectrum
            Name = '<source name="%s" type="DiffuseSource">\n' % ISOn
        else:  #if a file is given assume it is an isotropic template
            isoSpectrum = Spectrum(type="FileFunction",
                                   file=self.catParams['isoTempFile'])
        #both of the above options use the same spatial model
        isoSpatial = SpatialModel(type="ConstantValue")
        isoSource = Source(name=self.catParams['isTempName'],
                           type="DiffuseSource",
                           spectrum=isoSpectrum,
                           spatialModel=isoSpatial)
        self.sources.append(isoSource)
    def _add1FGLSources(self):
        """Extract sources from the 1FGL catalog file

        Parameters:
        - self - This CatalogSourceExtractor object

        Return value:
        - none - Sets the self.sources variable to a list of source objects

        Usage:
           self._add1FGLSources()

        Description:
           This function loops over all of the sources in the 1FGL catalog file and extracts all those
        that lie within 5 degrees of the ROI.  It creates PowerLaw source objects for each.  Each model
        is added to the object's local list of sources.  The Galactic Diffuse source is added but with
        a fixed index of 0.  The user should modify this by hand if desired.
        """
        #        file=pyfits.open(self.catParams['catalogFile'])
        file = self.catFile.fitsFilePtr
        data = file[1].data
        try:
            name = data.field('Source_Name')
        except:
            name = data.field('NickName')
        ra = data.field('RA')
        dec = data.field('DEC')
        flux = data.field('Flux_Density')
        pivot = data.field('Pivot_Energy')
        index = data.field('Spectral_Index')
        sigma = data.field('Signif_Avg')
        for n, f, i, r, d, p, s in zip(name, flux, index, ra, dec, pivot,
                                       sigma):
            dist = angsep(self.ra, self.dec, r,
                          d)  # get distance from object to ROI center
            if (r == self.ra and d
                    == self.dec):  # just to avoid any small number errors
                dist = 0.0
            if (dist <= self.radius + 5.0):  # object is in target area
                fscale = int(floor(log10(f)))
                sourceName = ''
                for N in n.split(' '):
                    sourceName += N
                Name = (
                    sourceName if not sourceName[0].isdigit() else "_" +
                    sourceName
                )  # add an underscore to prevent string/number issues if name starts with a digit
                source = Source(name=Name, type="PointSource")
                self._PLspec(source, f, i, p, dist, s)
                ra = Parameter(name="RA",
                               value=r,
                               scale=1.0,
                               min=0.0,
                               max=360.0,
                               free=False)
                dec = Parameter(name="DEC",
                                value=d,
                                scale=1.0,
                                min=-90.0,
                                max=90.0,
                                free=False)
                spatialModel = SpatialModel(type="SkyDirFunction",
                                            parameters=[ra, dec])
                source.setSpatialModel(spatialModel)
                if (None == self.sources):
                    self.sources = []
                self.sources.append(source)
        # Set Galactic Diffuse model
        gdSpatial = SpatialModel(type="MapCubeFunction",
                                 file=self.catParams['galDiffFile'])
        gdSource = Source(
            name=self.catParams['gdModelName'],
            type='DiffuseSource',
            spatialModel=gdSpatial)  #default spectrum is PowerLaw
        # but we need to fix the index
        spec = gdSource.getSpectrum()
        index = spec.getParameterByName("Index")
        index.setFree(False)
        # and also set it to zero (why?  echoing Tyrel's script.  This probably won't be used much at all give the existence of 2FGL and soon 3FGL)
        index.setMax("1.0")
        index.setValue("0.0")
        spec.setParameterByName("Index", index)
        gdSource.setSpectrum(spec)
        self.sources.append(gdSource)

        # Set isotropic diffuse source
        if (
                None == self.catParams['isoTempFile']
        ):  #null means no file so assume user wants an isotropic power law component
            isoSpectrum = Specturm()  # create a default PowerLaw Spectrum
            Name = '<source name="%s" type="DiffuseSource">\n' % ISOn
        else:  #if a file is given assume it is an isotropic template
            isoSpectrum = Spectrum(type="FileFunction",
                                   file=self.catParams['isoTempFile'])
        #both of the above options use the same spatial model
        isoSpatial = SpatialModel(type="ConstantValue")
        isoSource = Source(name=self.catParams['isTempName'],
                           type="DiffuseSource",
                           spectrum=isoSpectrum,
                           spatialModel=isoSpatial)
        self.sources.append(isoSource)