Пример #1
0
def cluster(model_tot,
            file_map,
            file_spec,
            ClusterName='Cluster',
            tscalc=True):
    """
    Build a ctools model for the cluster.
        
    Parameters
    ----------
    - model_tot: a gammalib.GModels object
    - file_map (str): the full name of the fits map
    - file_spec (str): the full name of the text file spectrum
    - ClusterName (str): the name of the source
    - tscalc (bool): request TS computation or not

    Outputs
    --------
    - the model is updated to include the cluster
    """

    spatial = gammalib.GModelSpatialDiffuseMap(file_map)
    spectral = gammalib.GModelSpectralFunc(file_spec, 1.0)
    timing = gammalib.GModelTemporalConst(1)

    model = gammalib.GModelSky(spatial, spectral, timing)
    model.name(ClusterName)
    model.tscalc(tscalc)

    model_tot.append(model)
Пример #2
0
]
#masses = [0.300,0.400,0.600,0.700,0.800,0.900,2,3,4,5,6,7,8,9,10]

#jfactorname = "DM/jfactor/jfactorLMC.fits"

jfactorname = "DM/jfactor/annihil_LMC2D_FOVdiameter10.0deg_alphaint0.10deg_nside1024NFW-JFACTOR-Jsmooth-image.fits"

for mass in masses:
    #Standarized name for the produced model so the other programs can use it easily:
    #_______________________________________________________________________________
    if mass < 1:
        masstr = str(int(mass * 1000)) + 'GeV'
    else:
        masstr = str(mass) + 'TeV'
    specname = 'flux' + particle + masstr + '.txt'
    modelname = 'dm_LMC_' + particle + masstr
    suf = '_jfactorNFW'
    #_______________________________________________________________________________

    for model in models:
        modelcontainer = gammalib.GModels()
        model.spectral().filename(
            PATH_SPEC + specname
        )  #Put the spectrum for the specific mass in the model file
        spectral = model.spectral()
        spatial = gammalib.GModelSpatialDiffuseMap(DATA_PATH + jfactorname)
        model = gammalib.GModelSky(spatial, spectral)
        modelcontainer.append(model)
    modelcontainer.save(PATH_MODELS + modelname + suf +
                        '.xml')  #Save the model
Пример #3
0
beta = 0.1  # smoothness parameter
flux = 11.05e-12  # ph cm-2 s-1
flux_ethresh = gammalib.GEnergy(200., 'GeV')

# output files
out_fits = 'ic443_map.fits'
out_xml = 'ic443.xml'

###############################################################

# normalize template
normalize_template(in_fits, in_hdu, out_fits)

# create gammalib model
# spatial model
spatial = gammalib.GModelSpatialDiffuseMap(out_fits)
# spectral model
spectral = gammalib.GModelSpectralSmoothBrokenPlaw(1., index1, eref, index2,
                                                   ebreak, beta)
# change prefactor to get correct flux
norm = spectral.flux(flux_ethresh, gammalib.GEnergy(100, 'TeV'))
spectral['Prefactor'].value(flux / norm)

# create source model
source = gammalib.GModelSky(spatial, spectral)

# create model container and append source
models = gammalib.GModels()
models.append(source)

# write to disk
Пример #4
0
def set_source_model(srcmodel,
                     spec='plaw',
                     alpha=1.0,
                     mapname='../map_RXJ1713.fits'):
    """
    Set source model

    Parameters
    ----------
    srcmodel : str
        Source model name
    spec : str, optional
        Spectral model
    alpha : float, optional
        Map scaling factor
    mapname : str, optional
        Sky map name

    Returns
    -------
    source : `~gammalib.GModelSky()`
        Source model
    """
    # Set spectral component
    if spec == 'plaw':
        spectral = gammalib.GModelSpectralPlaw(1.0e-17, -2.0,
                                               gammalib.GEnergy(1.0, 'TeV'))
        spectral['Prefactor'].min(1.0e-25)
    elif spec == 'eplaw':
        spectral = gammalib.GModelSpectralExpPlaw(
            1.0e-17, -2.0, gammalib.GEnergy(1.0, 'TeV'),
            gammalib.GEnergy(10.0, 'TeV'))
        spectral['CutoffEnergy'].min(1.0e6)
        spectral['CutoffEnergy'].max(1.0e8)
        spectral['Prefactor'].min(1.0e-25)
    elif spec == 'inveplaw':
        spectral = gammalib.GModelSpectralExpInvPlaw(
            1.0e-17, -2.0, gammalib.GEnergy(1.0, 'TeV'),
            gammalib.GEnergy(10.0, 'TeV'))
        spectral['Prefactor'].min(1.0e-25)
    elif spec == 'logparabola':
        spectral = gammalib.GModelSpectralLogParabola(
            1.0e-17, -2.0, gammalib.GEnergy(1.0, 'TeV'), -0.3)
        spectral['Prefactor'].min(1.0e-25)
    elif spec == 'abdalla2018':
        spectral = gammalib.GModelSpectralExpPlaw(
            2.3e-17, -2.06, gammalib.GEnergy(1.0, 'TeV'),
            gammalib.GEnergy(12.9, 'TeV'))
        spectral['Prefactor'].fix()
        spectral['Index'].fix()
        spectral['CutoffEnergy'].fix()
    elif spec == 'abdalla2018Ec':
        spectral = gammalib.GModelSpectralExpPlaw(
            2.3e-17, -2.06, gammalib.GEnergy(1.0, 'TeV'),
            gammalib.GEnergy(12.9, 'TeV'))
        spectral['CutoffEnergy'].fix()
        spectral['Prefactor'].min(1.0e-25)
    elif spec == 'aharonian2007':
        spectral = gammalib.GModelSpectralLogParabola(
            2.06e-17, -2.02, gammalib.GEnergy(1.0, 'TeV'), -0.29)
        spectral['Prefactor'].fix()
        spectral['Index'].fix()
        spectral['Curvature'].fix()

    # Set spatial component
    if 'map' in srcmodel:
        filename = '%s' % mapname
        map = gammalib.GSkyMap(filename)
        map = scale_map(map, alpha)
        filename = 'map_RXJ1713_%.2f.fits' % alpha
        map.save(filename, True)
        spatial = gammalib.GModelSpatialDiffuseMap(filename)
    elif 'disk' in srcmodel:
        dir = gammalib.GSkyDir()
        dir.radec_deg(258.3, -39.7)
        spatial = gammalib.GModelSpatialRadialDisk(dir, 0.5)
        spatial['RA'].free()
        spatial['DEC'].free()
    elif 'gauss' in srcmodel:
        dir = gammalib.GSkyDir()
        dir.radec_deg(258.3, -39.7)
        spatial = gammalib.GModelSpatialRadialGauss(dir, 0.5)
        spatial['RA'].free()
        spatial['DEC'].free()
    elif 'shell' in srcmodel:
        dir = gammalib.GSkyDir()
        dir.radec_deg(258.3, -39.7)
        spatial = gammalib.GModelSpatialRadialShell(dir, 0.4, 0.2)
        spatial['RA'].free()
        spatial['DEC'].free()

    # Set source model
    source = gammalib.GModelSky(spatial, spectral)
    source.name('RX J1713.7-3946')
    source.tscalc(True)

    # Return source model
    return source
                replaced += 1
            else:
                added += 1
        # add templates
        models_template = gammalib.GModels(
            '../known-sources/templates/{}.xml'.format(name))
        for model in models_template:
            # if model contains spatial map take care of it
            if model.spatial().type() == 'DiffuseMap':
                # find model map name and path
                filename = model.spatial().filename().file()
                filepath = model.spatial().filename().path()
                # copy file to output directory
                shutil.copy(filepath + filename, './')
                # replace file with the one in output directory
                model.spatial(gammalib.GModelSpatialDiffuseMap(filename))
            # if model contains spatial map take care of it
            if model.spectral().type() == 'FileFunction':
                # find spectrum file name and path
                filename = model.spectral().filename().file()
                filepath = model.spectral().filename().path()
                # copy file to output directory
                shutil.copy(filepath + filename, './')
                # replace file with the one in output directory
                model.spectral(
                    gammalib.GModelSpectralFunc(
                        gammalib.GFilename(filename),
                        model.spectral()['Normalization'].value()))
            # append model to container
            models.append(model)
Пример #6
0
def build_model_grid(cpipe,
                     subdir,
                     rad,
                     prof_ini,
                     spatial_value,
                     spatial_idx,
                     profile_reso,
                     includeIC=False,
                     rm_tmp=False):
    """
    Build a grid of models for the cluster and background, using
    as n_CRp(r) propto n_CRp_ref^scaling.
    
    Parameters
    ----------

    Outputs files
    -------------
    - 

    """

    # Save the cluster model before modification
    cluster_tmp = copy.deepcopy(cpipe.cluster)

    #----- Loop changing profile
    spatial_npt = len(spatial_value)

    for imod in range(spatial_npt):
        print('--- Building model template ' + str(1 + imod) + '/' +
              str(spatial_npt))

        #---------- Indexing
        spatial_i = spatial_value[imod]
        exti = 'TMP_' + str(imod)
        print('    spatial = ', str(spatial_i), ', ext = ', exti)

        #---------- Compute the model spectrum, map, and xml model file
        # Re-scaling
        cluster_tmp.density_crp_model = {
            'name': 'User',
            'radius': rad,
            'profile': prof_ini.value**spatial_i
        }

        # Cluster model
        make_cluster_template.make_map(cluster_tmp,
                                       subdir + '/Model_Map_' + exti + '.fits',
                                       Egmin=cpipe.obs_setup.get_emin(),
                                       Egmax=cpipe.obs_setup.get_emax(),
                                       includeIC=includeIC)
        make_cluster_template.make_spectrum(
            cluster_tmp,
            subdir + '/Model_Spectrum_' + exti + '.txt',
            energy=np.logspace(-1, 5, 1000) * u.GeV,
            includeIC=includeIC)

        # xml model
        model_tot = gammalib.GModels(cpipe.output_dir +
                                     '/Ana_Model_Input_Stack.xml')
        clencounter = 0
        for i in range(len(model_tot)):
            if model_tot[i].name() == cluster_tmp.name:
                spefn = subdir + '/Model_Spectrum_' + exti + '.txt'
                model_tot[i].spectral().filename(spefn)
                spafn = subdir + '/Model_Map_' + exti + '.fits'
                model_tot[i].spatial(gammalib.GModelSpatialDiffuseMap(spafn))
                clencounter += 1
        if clencounter != 1:
            raise ValueError('No cluster encountered in the input stack model')
        model_tot.save(subdir + '/Model_Input_' + exti + '.xml')

        #---------- Likelihood fit
        like = ctools.ctlike()
        like['inobs'] = cpipe.output_dir + '/Ana_Countscube.fits'
        like['inmodel'] = subdir + '/Model_Input_' + exti + '.xml'
        like['expcube'] = cpipe.output_dir + '/Ana_Expcube.fits'
        like['psfcube'] = cpipe.output_dir + '/Ana_Psfcube.fits'
        like['bkgcube'] = cpipe.output_dir + '/Ana_Bkgcube.fits'
        like['edispcube'] = cpipe.output_dir + '/Ana_Edispcube.fits'
        like['edisp'] = cpipe.spec_edisp
        like['outmodel'] = subdir + '/Model_Output_' + exti + '.xml'
        like['outcovmat'] = 'NONE'
        like['statistic'] = cpipe.method_stat
        like['refit'] = False
        like['like_accuracy'] = 0.005
        like['max_iter'] = 50
        like['fix_spat_for_ts'] = False
        like['logfile'] = subdir + '/Model_Output_log_' + exti + '.txt'
        like.logFileOpen()
        like.execute()
        like.logFileClose()

        #---------- Compute the 3D residual cube
        cpipe._rm_source_xml(subdir + '/Model_Output_' + exti + '.xml',
                             subdir + '/Model_Output_Cluster_' + exti + '.xml',
                             cluster_tmp.name)

        modcube = cubemaking.model_cube(
            cpipe.output_dir,
            cpipe.map_reso,
            cpipe.map_coord,
            cpipe.map_fov,
            cpipe.spec_emin,
            cpipe.spec_emax,
            cpipe.spec_enumbins,
            cpipe.spec_ebinalg,
            edisp=cpipe.spec_edisp,
            stack=cpipe.method_stack,
            silent=True,
            logfile=subdir + '/Model_Cube_log_' + exti + '.txt',
            inmodel_usr=subdir + '/Model_Output_' + exti + '.xml',
            outmap_usr=subdir + '/Model_Cube_' + exti + '.fits')

        modcube_Cl = cubemaking.model_cube(
            cpipe.output_dir,
            cpipe.map_reso,
            cpipe.map_coord,
            cpipe.map_fov,
            cpipe.spec_emin,
            cpipe.spec_emax,
            cpipe.spec_enumbins,
            cpipe.spec_ebinalg,
            edisp=cpipe.spec_edisp,
            stack=cpipe.method_stack,
            silent=True,
            logfile=subdir + '/Model_Cube_Cluster_log_' + exti + '.txt',
            inmodel_usr=subdir + '/Model_Output_Cluster_' + exti + '.xml',
            outmap_usr=subdir + '/Model_Cube_Cluster_' + exti + '.fits')

    #----- Build the data
    hdul = fits.open(cpipe.output_dir + '/Ana_Countscube.fits')
    header = hdul[0].header
    header.remove('NAXIS3')
    header['NAXIS'] = 2
    cntmap = np.sum(hdul[0].data, axis=0)
    hdul.close()
    r_dat, p_dat, err_dat = radial_profile_cts(
        cntmap, [
            cpipe.cluster.coord.icrs.ra.to_value('deg'),
            cpipe.cluster.coord.icrs.dec.to_value('deg')
        ],
        stddev=np.sqrt(cntmap),
        header=header,
        binsize=profile_reso.to_value('deg'),
        stat='POISSON',
        counts2brightness=True)
    tabdat = Table()
    tabdat['radius'] = r_dat
    tabdat['radius_min'] = r_dat - profile_reso.to_value('deg') / 2.0
    tabdat['radius_max'] = r_dat + profile_reso.to_value('deg') / 2.0
    tabdat['profile'] = p_dat

    dat_hdu = fits.BinTableHDU(tabdat)

    #----- Build the grid
    modgrid_bk = np.zeros((spatial_npt, len(p_dat)))
    modgrid_cl = np.zeros((spatial_npt, len(p_dat)))

    for imod in range(spatial_npt):
        exti = 'TMP_' + str(imod)

        # Extract the profile
        hdul = fits.open(subdir + '/Model_Cube_' + exti + '.fits')
        cntmap = np.sum(hdul[0].data, axis=0)
        hdul.close()

        hdul_cl = fits.open(subdir + '/Model_Cube_Cluster_' + exti + '.fits')
        cntmap_cl = np.sum(hdul_cl[0].data, axis=0)
        hdul_cl.close()

        map_cl = cntmap - cntmap_cl
        map_bk = cntmap_cl

        r_cl, p_cl, err_cl = radial_profile_cts(
            map_cl, [
                cpipe.cluster.coord.icrs.ra.to_value('deg'),
                cpipe.cluster.coord.icrs.dec.to_value('deg')
            ],
            stddev=np.sqrt(map_cl),
            header=header,
            binsize=profile_reso.to_value('deg'),
            stat='POISSON',
            counts2brightness=True)
        r_bk, p_bk, err_bk = radial_profile_cts(
            map_bk, [
                cpipe.cluster.coord.icrs.ra.to_value('deg'),
                cpipe.cluster.coord.icrs.dec.to_value('deg')
            ],
            stddev=np.sqrt(map_bk),
            header=header,
            binsize=profile_reso.to_value('deg'),
            stat='POISSON',
            counts2brightness=True)
        modgrid_bk[imod, :] = p_bk
        modgrid_cl[imod, :] = p_cl

    grid_cl_hdu = fits.ImageHDU(modgrid_cl)
    grid_bk_hdu = fits.ImageHDU(modgrid_bk)

    #----- Make the index table
    scal = Table()
    scal['index'] = spatial_idx
    scal['value'] = spatial_value
    scal_hdu = fits.BinTableHDU(scal)

    #----- Make and save HDUlist
    hdul = fits.HDUList()
    hdul.append(scal_hdu)
    hdul.append(dat_hdu)
    hdul.append(grid_cl_hdu)
    hdul.append(grid_bk_hdu)
    hdul.writeto(subdir + '/Grid_Sampling.fits', overwrite=True)

    #----- Save the properties of the last computation run
    np.save(subdir + '/Grid_Parameters.npy', [cpipe.cluster, spatial_value],
            allow_pickle=True)

    #----- remove TMP files
    if rm_tmp:
        for imod in range(spatial_npt):
            exti = 'TMP_' + str(imod)
            os.remove(subdir + '/Model_Map_' + exti + '.fits')
            os.remove(subdir + '/Model_Spectrum_' + exti + '.txt')
            os.remove(subdir + '/Model_Cube_' + exti + '.fits')
            os.remove(subdir + '/Model_Cube_log_' + exti + '.txt')
            os.remove(subdir + '/Model_Cube_Cluster_' + exti + '.fits')
            os.remove(subdir + '/Model_Cube_Cluster_log_' + exti + '.txt')
            os.remove(subdir + '/Model_Input_' + exti + '.xml')
            os.remove(subdir + '/Model_Output_' + exti + '.xml')
            os.remove(subdir + '/Model_Output_log_' + exti + '.txt')
            os.remove(subdir + '/Model_Output_Cluster_' + exti + '.xml')
    # divide pixel value by distance (1/r profile as in Aharonian+ 2019)
    hdu.data /= r

    # clip tempate
    # calculate median flux at max rad
    low_flux = np.median(
        hdu.data[np.abs(r * out_res - rad_max[s]) < 4 * out_res])
    # clip at this flux level
    hdu.data[hdu.data < low_flux] = 0.

    # normalize map
    hdu.data /= np.sum(hdu.data)

    # create fits map file
    hdu.verify('fix')
    mapname = name + '_map.fits'
    hdu.writeto(mapname, overwrite=True)

    # create gammalib spatial model component based on map
    spatial = gammalib.GModelSpatialDiffuseMap(mapname)

    # create model and save as xml
    model = gammalib.GModelSky(spatial, spectral_models[s])
    model.name(name)
    models = gammalib.GModels()
    models.append(model)
    models.save(name + '.xml')

    # move output files to template directory
    os.system('mv {}* {}'.format(name, outdir))
Пример #8
0
    def _gen_model_anna(self, i) :
        """
        in-fly Creation of GModel

        Return
        ------
        GModel for a dark matter annihilation
        """

        #   Create xml element for the spectral type

        #   These are the min and max values that can take
        #   the prefactor parameter
        #   Note: I am not sure why I need to rise so much
        #   the maxval to specify the valid range od the
        #   parameter
        #   I hope this issue change when implementing the
        #   GModelSpectralDMMmodel class
        minval  = 1.0e-20
        maxval  = 1.0e+20

        #   Model type
        modtype  = self['modtype'].string()

        #   recover filename created with _gen_dmfile_anna
        srcname = self['srcname'].string()

        #   Create spectral container using GModelSpectralTable
        #   and setup the mass, channel and normalization of the model
        ch_number = self._get_channel_key()
        dmmass    = self._masses[i]
        jfactor   = math.pow(10., self['logastfactor'].real())
        sigmav    = math.pow(10., self['logsigmav'].real())
        fluxnorm  = sigmav * jfactor / 8. / gammalib.pi / dmmass / dmmass
        fluxnorm *= 1.e-3
        ffile     = self['dmspecfits'].filename()

        dmspec    = gammalib.GModelSpectralTable()
        dmspec.load(ffile)
        dmspec['Mass'].value(dmmass)
        dmspec['Channel'].value(ch_number)
        dmspec['Channel'].scale(1)
        dmspec['Normalization'].value(fluxnorm)
        dmspec['Normalization'].range(minval, maxval)

        #   Mass and Channel parameters should be fixed
        #   But, just to be sure
        dmspec['Mass'].fix()
        dmspec['Channel'].fix()
        dmspec['Normalization'].free()

        #   Creating Spatial container
        if self[ 'modtype' ].string() == 'PointSource' :

            ra     = self['ra'].real()
            dec    = self['dec'].real()
            dmspat = gammalib.GModelSpatialPointSource(ra, dec)

        elif self[ 'modtype' ].string() == 'DiffuseSource' :

            mfile  = self['map_fits'].filename()
            dmspat = gammalib.GModelSpatialDiffuseMap(mfile)

        #   Then generate GModel from spatial and spectral part
        #   This must avoid to create a lot of XML Templates
        #   to specify DM models :P
        dmmodel = gammalib.GModelSky(dmspat, dmspec)
        dmmodel.name(srcname)
        dmmodel.tscalc(True)

        #   Return
        return dmmodel