예제 #1
0
    def __init__(self,
                 name,
                 diffuse_sources,
                 file,
                 emin,
                 emax,
                 skydir,
                 scaling_factor=1):
        """ Approximates a linear combination of
            diffuse sources as a single isotropic
            spectrum. 
            
            Note, probably does not work for extended
            sources. """

        self.name = name
        self.scaling_factor = scaling_factor

        for ds in diffuse_sources:
            if len(ds.dmodel) != 1:
                raise Exception("dmodels must have length 1")

        self.file = open(file, 'w')
        self.file.write(
            self._make_file(diffuse_sources, skydir, emin, emax,
                            self.scaling_factor))
        self.file.close()

        self.smodel = FileFunction(file=file)
        self.dmodel = [IsotropicConstant()]
예제 #2
0
def pointlike_dict_to_spectrum(d):
    if d['name'] == 'FileFunction':
        model = FileFunction(file=d['file'])
    elif d['name'] == 'DMFitFunction':
        model = DMFitFunction()
    else:
        model = uw.like.Models.__dict__[d['name']]()
    for k,v in d.items(): 
        if k not in ['name','method','file','covariance_matrix']:
            if len(k) > 10 and k[-10:] in ['_upper_err','_lower_err']:
                pass
            elif len(k) > 4 and k[-4:] == '_err': 
                model.set_error(k[:-4],v)
            else:
                model[k]=v
    return model
예제 #3
0
    def test_ff(self):
        """ Simulate from a filefunction object and test that the best
        fit flux
            is consistent with the simulated flux. """
        name = 'ff'

        model = PowerLaw(index=2)
        model.set_flux(1e-6)
        simdir = path.expand('$SIMDIR/%s' % name)
        if not os.path.exists(simdir):
            os.makedirs(simdir)

        filename = abspath(join(simdir, 'file_function.txt'))
        model.save_profile(filename, 10, 1e6)
        ff = FileFunction(file=filename)

        center = SkyDir(0, 0)
        ps = PointSource(name='source', skydir=center, model=ff)
        point_sources = [ps]
        diffuse_sources = None
        roi = PointlikeTest.get_roi(name,
                                    center,
                                    point_sources,
                                    diffuse_sources,
                                    emin=1e2,
                                    emax=1e5,
                                    binsperdec=4)

        if PointlikeTest.VERBOSE:
            roi.print_summary()
            print roi

        roi.fit(use_gradient=PointlikeTest.USE_GRADIENT)

        if PointlikeTest.VERBOSE:
            roi.print_summary()
            print roi

        fit, error = ff.i_flux(1e2, 1e5, error=True)
        true = model.i_flux(1e2, 1e5, error=False)
        self.assertPull(fit, true, error, 'flux')
예제 #4
0
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
예제 #5
0
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
예제 #6
0
def get_diffuse_source(spatialModel='ConstantValue',
                              spatialModelFile=None,
                              spectralModel='PowerLaw',
                              spectralModelFile=None,
                              name=None,
                              diffdir = None):

    """ Return a DiffuseSource instance suitable for
         instantiating a child of ROIDiffuseModel.

         NB -- don't support front/back distinction atm.

         The list of supported models is currently very short, but covers
         the usual cases for modeling diffuse backgrounds.  Additional
         use cases can be developed on an ad hoc basis.
         
         Arguments:
         
         spatialModel -- an XML-style keyword.  Valid options are
                               1) ConstantValue (isotropic)
                               2) MapCubeFunction (from a FITS file)
                               
         spatialModelFile -- if a mapcube is specified, its location
         
         spectralModel -- This can be either an XML-style keyword or an
                                instance of Model.
                                If an XML-style keyword, valid options are
                                1) FileFunction
                                2) PowerLaw
                                3) Constant
                               
         spectralModelFile -- if a tabular function is specified,
                                     its location

         name -- a name for the ol' model

         
         diffdir -- if the XML files specify paths relative to some
                        directory, set this variable appropriately
    """

    if (diffdir is not None):
        if spatialModelFile is not None:
            spatialModelFile = os.path.join(diffdir,spatialModelFile)
        if spectralModelFile is not None:
            spectralModelFile = os.path.join(diffdir,spectralModelFile)

    # check input sanity
    if not isinstance(spectralModel,Model):
        if (spectralModelFile is not None):
            if not os.path.exists(path.expand(spectralModelFile)):
                raise Exception('Could not find the ASCII file specified for FileFunction')
        elif not (spectralModel == 'PowerLaw' or spectralModel == 'Constant'):
            raise NotImplementedError,'Must provide one of the understood spectral models.'
        else:
            pass

    if spatialModel=='MapCubeFunction':
        if (spatialModelFile is None) or (not os.path.exists(path.expand(spatialModelFile))):
            raise Exception('Could not find the FITS file specified for MapCubeFunction (file = %s).' % spatialModelFile)
    elif spatialModel != 'ConstantValue':
        raise NotImplementedError,'Must provide one of the understood spatial models.'
    else:
        pass                  

    ston = Singleton2()
    dmodel = None; smodel = None


    # deal with isotropic models
    if spatialModel=='ConstantValue':
        if isinstance(spectralModel,Model):
            smodel=spectralModel
            dmodel=IsotropicConstant()
        elif spectralModelFile is not None:
            smodel = FileFunction(normalization=1, file=spectralModelFile)
            dmodel = IsotropicConstant()
        elif spectralModel == 'PowerLaw':
            # use Sreekumar-like defaults
            smodel = PowerLaw(index=2.1)
            smodel.set_flux(1.5e-5, emin=100, emax=N.inf)

            dmodel = IsotropicConstant()
        else:
            raise Exception("Unable to parse input.")

    # deal with mapcubes
    else:
        if spectralModel == 'FileFunction':
            dmodel1 = IsotropicSpectrum(spectralModelFile)
            dmodel2 = ston.add(DiffuseFunction,spatialModelFile,spatialModelFile)
            dmodel  = CompositeSkySpectrum(dmodel1,dmodel2)
            dmodel.saveme1 = dmodel1; dmodel.saveme2 = dmodel2
            smodel  = Constant()
        else:
            dmodel = ston.add(DiffuseFunction,path.expand(spatialModelFile),path.expand(spatialModelFile))
            dmodel.filename=spatialModelFile
            if spectralModel == 'PowerLaw':
                smodel = ScalingPowerLaw()
            elif spectralModel == 'Constant':
                smodel = Constant()
            else:
                smodel = spectralModel

    if (dmodel is None) or (smodel is None):
         raise Exception('Was unable to parse input.')

    return DiffuseSource(dmodel,smodel,name)