コード例 #1
0
    def _updateGtlikeModel(self):
        """
        #Slow! But no other options at the moment
        self.like.writeXml(self.xmlModel)
        self.like.logLike.reReadXml(self.xmlModel)
        """

        energies = self.lmc.energiesKeV

        if self._source_name is None:
            for id, srcName in enumerate(
                    self.likelihoodModel.point_sources.keys()):

                values = self.likelihoodModel.get_point_source_fluxes(
                    id, energies, tag=self._tag)

                # on the second iteration, self.like doesn't have the second srcName defined so that needs to be carried from flags
                gtlikeSrcModel = self.like[srcName]

                my_function = gtlikeSrcModel.getSrcFuncs()["Spectrum"]
                my_file_function = pyLike.FileFunction_cast(my_function)

                my_file_function.setParam("Normalization", 1)

                # Cap the values to avoid numerical errors

                capped_values = numpy.minimum(
                    numpy.maximum(values * 1000, 1e-25), 1e5)

                my_file_function.setSpectrum(energies / 1000.0, capped_values)
                gtlikeSrcModel.setSpectrum(my_file_function)

                # TODO: extended sources
        else:
            srcName = self._source_name
            id = self.likelihoodModel.point_sources.keys().index(srcName)

            values = self.likelihoodModel.get_point_source_fluxes(
                id, energies, tag=self._tag)

            # on the second iteration, self.like doesn't have the second srcName defined so that needs to be carried from flags
            gtlikeSrcModel = self.like[srcName]

            my_function = gtlikeSrcModel.getSrcFuncs()["Spectrum"]
            my_file_function = pyLike.FileFunction_cast(my_function)

            my_file_function.setParam("Normalization", 1)

            # Cap the values to avoid numerical errors

            capped_values = numpy.minimum(numpy.maximum(values * 1000, 1e-25),
                                          1e5)

            my_file_function.setSpectrum(energies / 1000.0, capped_values)
            gtlikeSrcModel.setSpectrum(my_file_function)

        self.like.syncSrcParams()
コード例 #2
0
    def _updateGtlikeModel(self):
        """
        #Slow! But no other options at the moment
        self.like.writeXml(self.xmlModel)
        self.like.logLike.reReadXml(self.xmlModel)
        """

        energies = self.lmc.energiesKeV

        for id, srcName in enumerate(
                self.likelihoodModel.point_sources.keys()):

            values = self.likelihoodModel.get_point_source_fluxes(
                id, energies, tag=self._tag)

            gtlikeSrcModel = self.like[srcName]

            my_function = gtlikeSrcModel.getSrcFuncs()["Spectrum"]
            my_file_function = pyLike.FileFunction_cast(my_function)

            my_file_function.setParam("Normalization", 1)

            # Cap the values to avoid numerical errors

            capped_values = numpy.minimum(numpy.maximum(values * 1000, 1e-25),
                                          1e5)

            my_file_function.setSpectrum(energies / 1000.0, capped_values)
            gtlikeSrcModel.setSpectrum(my_file_function)

            # TODO: extended sources

        self.like.syncSrcParams()
コード例 #3
0
ファイル: save.py プロジェクト: mahmoud-lsw/PhD-python
def gtlike_spectrum_to_dict(spectrum, errors=False):
    """ Convert a pyLikelihood object to a python 
        dictionary which can be easily saved to a file. """
    parameters=ParameterVector()
    spectrum.getParams(parameters)
    d = dict(name = spectrum.genericName(), method='gtlike')
    for p in parameters: 
        d[p.getName()]= p.getTrueValue()
        if errors: 
            d['%s_err' % p.getName()]= p.error()*p.getScale() if p.isFree() else np.nan
        if d['name'] == 'FileFunction': 
            ff=pyLikelihood.FileFunction_cast(spectrum)
            d['file']=ff.filename()
    return d
コード例 #4
0
def gtlike_spectrum_to_dict(spectrum):
    """ Convert a pyLikelihood object to a python dictionary which can
        be easily saved to a file."""
    parameters = pyLike.ParameterVector()
    spectrum.getParams(parameters)
    d = dict(spectrum_type=spectrum.genericName())
    for p in parameters:

        pname = p.getName()
        pval = p.getTrueValue()
        perr = abs(p.error() * p.getScale()) if p.isFree() else np.nan
        d[pname] = np.array([pval, perr])

        if d['spectrum_type'] == 'FileFunction':
            ff = pyLike.FileFunction_cast(spectrum)
            d['file'] = ff.filename()
    return d
コード例 #5
0
ファイル: test_model.py プロジェクト: laofei177/pyLikelihood
                parnames = pyLike.StringVector()
                self.func.getFreeParamNames(parnames)
                print "Parameter : ", i, parnames[i]
                print "%.3e  " * len(num_derivs) % tuple(num_derivs)
                print "%.3e  " * len(derivs) % tuple(derivs) + "\n"
        return tuple(params)

    def __getattr__(self, attrname):
        return getattr(self.func, attrname)


if __name__ == '__main__':
    funcs = ('AbsEdge', 'BrokenPowerLaw', 'BrokenPowerLawExpCutoff',
             'BrokenPowerLaw2', 'ConstantValue', 'ExpCutoff', 'Gaussian',
             'LogParabola', 'PowerLaw', 'PowerLaw2', 'FileFunction')

    for func in funcs:
        tester = DerivTester(func)
        print "\n" + func
        verbose = 0
        if (func == 'PowerLaw2'):
            tester.func.parameter('Index').setValue(-1)
        if (func == 'FileFunction'):
            tester.func = pyLike.FileFunction_cast(tester.func)
            tester.func.readFunction('foo.dat')
#            verbose = 1
        tester(100, verbose)
        tester(200, verbose)
        tester(1001, verbose)
        tester(2000, verbose)
コード例 #6
0
ファイル: models.py プロジェクト: mahmoud-lsw/PhD-python
def build_pointlike_model(spectrum):
    """ Convert a gtlike model object to a pointlike
        model object.
        
            >>> spectrum = _funcFactory.create('PowerLaw')

            >>> param=spectrum.getParam('Prefactor')
            >>> param.setScale(10)
            >>> param.setTrueValue(1e-9)
            >>> param.setBounds(1e-11,1e-9)
            >>> param.setError(3e-11)
            >>> param.setFree(True)

            >>> param=spectrum.getParam('Index')
            >>> param.setScale(2)
            >>> param.setBounds(-10,5)
            >>> param.setTrueValue(-3)
            >>> param.setError(0.125)
            >>> param.setFree(False)

        Check spectral values:

            >>> model = build_pointlike_model(spectrum)
            >>> energies = np.logspace(1, 6, 10000)
            >>> from uw.darkmatter.spectral import DMFitFunction
            >>> np.allclose(DMFitFunction.call_pylike_spectrum(spectrum, energies),
            ...     model(energies), rtol=1e-20, atol=1e-20) 
            True

        Check prefactor:

            >>> model.get_scale('norm')
            10.0
            >>> np.allclose(model.get_limits('norm'),[1e-10, 1e-08])
            True
            >>> np.allclose(model.getp('norm'),1e-9)
            True
            >>> np.allclose(model.error('norm'),1e-10)
            True
            >>> model.get_free('norm')
            True

        Check index params:

            >>> model.get_scale('index')
            -2.0
            >>> model.get_limits('index')
            [-10.0, 20.0]
            >>> model.getp('index')
            3.0
            >>> np.allclose(model.error('index'),0.25)
            True
            >>> model.get_free('index')
            False

        Example creating a FileFunction object:
        
        First, create file out of old model:

            >>> from tempfile import NamedTemporaryFile
            >>> temp = NamedTemporaryFile()
            >>> filename = temp.name
            >>> model.save_profile(filename, emin=1, emax=1e6)
        
        Now, make FileFunction:

            >>> spectrum = pyLikelihood.FileFunction()
            >>> spectrum.readFunction(filename)

        Set param values:

            >>> param=spectrum.getParam('Normalization')
            >>> param.setScale(2)
            >>> param.setTrueValue(4)
            >>> param.setBounds(.1,10)

            >>> model = build_pointlike_model(spectrum)

        Test spectral points:

            >>> np.allclose(DMFitFunction.call_pylike_spectrum(spectrum, energies),
            ...     model(energies), rtol=1e-20, atol=1e-20) 
            True

        Test param values:

            >>> model.get_scale('Normalization')
            2.0
            >>> model.getp('Normalization')
            4.0
            >>> model.get_limits('Normalization')
            [0.2, 20.0]


    """
    gtlike_name = spectrum.genericName()

    if gtlike_name == 'FileFunction':
        ff = pyLikelihood.FileFunction_cast(spectrum)
        filename = ff.filename()
        model = FileFunction(file=filename)
    else:
        model = XML_to_Model.modict[gtlike_name]()

    param_names = pyLikelihood.StringVector()
    spectrum.getParamNames(param_names)
    for gtlike_name in param_names:
        pointlike_name = model.get_pointlike_name(gtlike_name)

        param = spectrum.getParam(gtlike_name)

        if pointlike_name in model.default_extra_params.keys():
            # no mapping for extra params
            model.setp(pointlike_name, param.getTrueValue())
        else:
            model.setp_gtlike(pointlike_name, param.getTrueValue())

            if pointlike_name in model.param_names:
                model.set_mapper(pointlike_name, LinearMapper)

                if param.getBounds()[0] < -3.4e+38 and param.getBounds(
                )[1] > 3.4e+38:
                    # No effective bound on parameters
                    pass
                else:
                    model.set_limits_gtlike(
                        pointlike_name,
                        lower=param.getBounds()[0] * param.getScale(),
                        upper=param.getBounds()[1] * param.getScale(),
                        scale=param.getScale())
                    model.set_error(pointlike_name,
                                    abs(param.error() * param.getScale()))
                    model.set_free(pointlike_name, param.isFree())
    return model