Example #1
0
    def set_model(self, likelihoodModel, source_name=None):
        """
        Set the model to be used in the joint minimization.
        Must be a LikelihoodModel instance.

        This method can also set or override a previously set source name.
        """

        # with suppress_stdout():

        if self._source_name is not None:
            if (source_name
                    is not None) and (source_name != self._source_name):
                log.warning('Changing target source from %s to %s' %
                            (self._source_name, source_name))
                self._source_name = source_name

            assert self._source_name in likelihoodModel.point_sources, (
                'Source %s is not a source in the likelihood model! ' %
                self._source_name)

        self.lmc = LikelihoodModelConverter(likelihoodModel,
                                            self.irf,
                                            source_name=self._source_name)
        self.lmc.setFileSpectrumEnergies(self.emin, self.emax, self.Nenergies)

        xmlFile = str("%s.xml" % get_random_unique_name())

        temp_files = self.lmc.writeXml(xmlFile, self.ra, self.dec, self.rad)

        if self.kind == "BINNED":
            self.like = BinnedAnalysis.BinnedAnalysis(self.obs,
                                                      xmlFile,
                                                      optimizer="DRMNFB")

        else:
            #import pdb;pdb.set_trace()
            self.like = UnbinnedAnalysis.UnbinnedAnalysis(self.obs,
                                                          xmlFile,
                                                          optimizer="DRMNFB")

        self.likelihoodModel = likelihoodModel

        # Here we need also to compute the logLike value, so that the model
        # in the XML file will be chanded if needed
        dumb = self.get_log_like()

        # Since now the Galactic template is in RAM, we can remove the temporary file
        os.remove(self.lmc._unique_filename)
        os.remove(xmlFile)

        # Delete temporary spectral files
        for temp_file in temp_files:

            os.remove(temp_file)

        # Build the list of the nuisance parameters
        new_nuisance_parameters = self._setNuisanceParameters()

        self.update_nuisance_parameters(new_nuisance_parameters)
Example #2
0
    def _makeFileSpectrum(self, ip):

        name = self.likelihoodModel.get_point_source_name(ip)

        values = self.likelihoodModel.get_point_source_fluxes(
            ip, self.energiesKeV)

        tempName = "__%s_%s.txt" % (name, get_random_unique_name())

        with open(tempName, "w+") as f:
            for e, v in zip(self.energiesKeV, values):
                # Gtlike needs energies in MeV and fluxes in ph/MeV/cm2)

                f.write("%s %s\n" % (e / 1000.0, v * 1000.0))

        # p                         = fileFunction.parameter("Normalization")
        # p.setBounds(1-float(effAreaAllowedSize),1+effAreaAllowedSize)

        # Now generate the XML source wrapper
        # This is convoluted, but that's the ST way of doing things...
        # The final product is a class with a writeXml method

        src = "\n".join((
            ('<source name= "%s" ' % name) + 'type="PointSource">',
            '   <spectrum type="PowerLaw2"/>',
            "   <!-- point source units are cm^-2 s^-1 MeV^-1 -->",
            '   <spatialModel type="SkyDirFunction"/>',
            "</source>\n",
        ))
        src = FuncFactory.minidom.parseString(src).getElementsByTagName(
            "source")[0]
        src = FuncFactory.Source(src)

        src.spectrum = FuncFactory.FileFunction()
        src.spectrum.file = tempName
        src.spectrum.parameters["Normalization"].value = 1.0
        src.spectrum.parameters["Normalization"].max = 1.1
        src.spectrum.parameters["Normalization"].min = 0.9
        src.spectrum.parameters["Normalization"].free = False
        src.spectrum.setAttributes()
        src.deleteChildElements("spectrum")
        src.node.appendChild(src.spectrum.node)

        src.spatialModel = FuncFactory.SkyDirFunction()
        src.deleteChildElements("spatialModel")
        src.node.appendChild(src.spatialModel.node)

        ra, dec = self.likelihoodModel.get_point_source_position(ip)

        src.spatialModel.RA.value = ra
        src.spatialModel.DEC.value = dec
        src.spatialModel.setAttributes()
        src.setAttributes()

        return MyPointSource(src, name, tempName)
Example #3
0
    def writeXml(self, xmlfile, ra, dec, roi):

        # Loop through all the sources in the likelihood model and generate a FileSpectrum
        # for all of them. This is necessary to allow the FermiLATLike class
        # to update the spectrum in pyLikelihood without having to write and read a .xml file
        # on the disk

        allSourcesForPyLike = []
        temp_files = []

        nPtsrc = self.likelihoodModel.get_number_of_point_sources()

        for ip in range(nPtsrc):

            this_src = self._makeFileSpectrum(ip)

            allSourcesForPyLike.append(this_src)
            temp_files.append(this_src.temp_file)

        # Now the same for extended sources

        nExtSrc = self.likelihoodModel.get_number_of_extended_sources()

        if nExtSrc > 0:
            raise NotImplemented("Cannot support extended sources yet!")

        iso = LikelihoodComponent.IsotropicTemplate(self.irfs)

        iso.source.spectrum.Normalization.max = 1.5
        iso.source.spectrum.Normalization.min = 0.5
        iso.source.spectrum.setAttributes()

        allSourcesForPyLike.append(iso)

        # Get a temporary filename which is guaranteed to be unique
        self._unique_filename = get_random_unique_name()

        gal = LikelihoodComponent.GalaxyAndExtragalacticDiffuse(
            self.irfs, ra, dec, 2.5 * roi, cutout_name=self._unique_filename)
        gal.source.spectrum.Value.max = 1.5
        gal.source.spectrum.Value.min = 0.5
        gal.source.spectrum.setAttributes()

        allSourcesForPyLike.append(gal)

        # Now generate the xml file with also the Galactic and Isotropic diffuse
        # templates
        xml = LikelihoodComponent.LikelihoodModel()
        xml.addSources(*allSourcesForPyLike)
        xml.writeXML(xmlfile)

        return temp_files
Example #4
0
    def writeXml(self, xmlfile, ra, dec, roi):

        # Loop through all the sources in the likelihood model and generate a FileSpectrum
        # for all of them. This is necessary to allow the FermiLATLike class
        # to update the spectrum in pyLikelihood without having to write and read a .xml file
        # on the disk

        allSourcesForPyLike = []
        temp_files = []

        nPtsrc = self.likelihoodModel.get_number_of_point_sources()

        for ip in range(nPtsrc):

            this_src = self._makeFileSpectrum(ip)

            allSourcesForPyLike.append(this_src)
            temp_files.append(this_src.temp_file)

        # Now the same for extended sources

        nExtSrc = self.likelihoodModel.get_number_of_extended_sources()

        if (nExtSrc > 0):
            raise NotImplemented("Cannot support extended sources yet!")

        iso = LikelihoodComponent.IsotropicTemplate(self.irfs)

        iso.source.spectrum.Normalization.max = 1.5
        iso.source.spectrum.Normalization.min = 0.5
        iso.source.spectrum.setAttributes()

        allSourcesForPyLike.append(iso)

        # Get a temporary filename which is guaranteed to be unique
        self._unique_filename = get_random_unique_name()

        gal = LikelihoodComponent.GalaxyAndExtragalacticDiffuse(
            self.irfs, ra, dec, 2.5 * roi, cutout_name=self._unique_filename)
        gal.source.spectrum.Value.max = 1.5
        gal.source.spectrum.Value.min = 0.5
        gal.source.spectrum.setAttributes()

        allSourcesForPyLike.append(gal)

        # Now generate the xml file with also the Galactic and Isotropic diffuse
        # templates
        xml = LikelihoodComponent.LikelihoodModel()
        xml.addSources(*allSourcesForPyLike)
        xml.writeXML(xmlfile)

        return temp_files
Example #5
0
    def _makeFileSpectrum(self, ip):

        name = self.likelihoodModel.get_point_source_name(ip)

        values = self.likelihoodModel.get_point_source_fluxes(ip,
                                                              self.energiesKeV)

        tempName = "__%s_%s.txt" % (name, get_random_unique_name())

        with open(tempName, "w+") as f:
            for e, v in zip(self.energiesKeV, values):
                # Gtlike needs energies in MeV and fluxes in ph/MeV/cm2)

                f.write("%s %s\n" % (e / 1000.0, v * 1000.0))

        # p                         = fileFunction.parameter("Normalization")
        # p.setBounds(1-float(effAreaAllowedSize),1+effAreaAllowedSize)

        # Now generate the XML source wrapper
        # This is convoluted, but that's the ST way of doing things...
        # The final product is a class with a writeXml method

        src = '\n'.join((('<source name= "%s" ' % name) + 'type="PointSource">',
                         '   <spectrum type="PowerLaw2"/>',
                         '   <!-- point source units are cm^-2 s^-1 MeV^-1 -->',
                         '   <spatialModel type="SkyDirFunction"/>',
                         '</source>\n'))
        src = FuncFactory.minidom.parseString(src).getElementsByTagName('source')[0]
        src = FuncFactory.Source(src)

        src.spectrum = FuncFactory.FileFunction()
        src.spectrum.file = tempName
        src.spectrum.parameters['Normalization'].value = 1.0
        src.spectrum.parameters['Normalization'].max = 1.1
        src.spectrum.parameters['Normalization'].min = 0.9
        src.spectrum.parameters['Normalization'].free = False
        src.spectrum.setAttributes()
        src.deleteChildElements('spectrum')
        src.node.appendChild(src.spectrum.node)

        src.spatialModel = FuncFactory.SkyDirFunction()
        src.deleteChildElements('spatialModel')
        src.node.appendChild(src.spatialModel.node)

        ra, dec = self.likelihoodModel.get_point_source_position(ip)

        src.spatialModel.RA.value = ra
        src.spatialModel.DEC.value = dec
        src.spatialModel.setAttributes()
        src.setAttributes()

        return MyPointSource(src, name, tempName)
Example #6
0
    def set_model(self, likelihoodModel):
        """
        Set the model to be used in the joint minimization.
        Must be a LikelihoodModel instance.
        """

        with suppress_stdout():

            self.lmc = LikelihoodModelConverter(likelihoodModel, self.irf)

            self.lmc.setFileSpectrumEnergies(self.emin, self.emax,
                                             self.Nenergies)

            xmlFile = str("%s.xml" % get_random_unique_name())

            temp_files = self.lmc.writeXml(xmlFile, self.ra, self.dec,
                                           self.rad)

        if self.kind == "BINNED":
            self.like = BinnedAnalysis.BinnedAnalysis(self.obs,
                                                      xmlFile,
                                                      optimizer="DRMNFB")

        else:

            self.like = UnbinnedAnalysis.UnbinnedAnalysis(self.obs,
                                                          xmlFile,
                                                          optimizer="DRMNFB")

        self.likelihoodModel = likelihoodModel

        # Here we need also to compute the logLike value, so that the model
        # in the XML file will be chanded if needed
        dumb = self.get_log_like()

        # Since now the Galactic template is in RAM, we can remove the temporary file
        os.remove(self.lmc._unique_filename)
        os.remove(xmlFile)

        # Delete temporary spectral files
        for temp_file in temp_files:

            os.remove(temp_file)

        # Build the list of the nuisance parameters
        new_nuisance_parameters = self._setNuisanceParameters()

        self.update_nuisance_parameters(new_nuisance_parameters)
Example #7
0
    def set_model(self, likelihoodModel):
        '''
        Set the model to be used in the joint minimization.
        Must be a LikelihoodModel instance.
        '''

        with suppress_stdout():

            self.lmc = LikelihoodModelConverter(likelihoodModel,
                                                self.irf)

            self.lmc.setFileSpectrumEnergies(self.emin, self.emax, self.Nenergies)

            xmlFile = '%s.xml' % get_random_unique_name()

            temp_files = self.lmc.writeXml(xmlFile, self.ra, self.dec, self.rad)

        if (self.kind == "BINNED"):
            self.like = BinnedAnalysis.BinnedAnalysis(self.obs,
                                                      xmlFile,
                                                      optimizer='DRMNFB')

        else:

            self.like = UnbinnedAnalysis.UnbinnedAnalysis(self.obs,
                                                          xmlFile,
                                                          optimizer='DRMNFB')

        self.likelihoodModel = likelihoodModel

        # Here we need also to compute the logLike value, so that the model
        # in the XML file will be chanded if needed
        dumb = self.get_log_like()

        # Since now the Galactic template is in RAM, we can remove the temporary file
        os.remove(self.lmc._unique_filename)
        os.remove(xmlFile)

        # Delete temporary spectral files
        for temp_file in temp_files:

            os.remove(temp_file)

        # Build the list of the nuisance parameters
        new_nuisance_parameters = self._setNuisanceParameters()

        self.update_nuisance_parameters(new_nuisance_parameters)