def make_xml(nametag):
    spatial = gammalib.GModelSpatialDiffuseCube(
        gammalib.GFilename(nametag + '_map.fits'))
    spectral = gammalib.GModelSpectralConst(1.)
    model = gammalib.GModelSky(spatial, spectral)
    model.name(nametag)
    # fill to model container and write to disk
    models = gammalib.GModels()
    models.append(model)
    models.save(nametag + '.xml')
Пример #2
0
    def save(self):
        """
        Save the cube and optionally the updated XML model file
        """
        # Save the generated cube if the cube and filename are not empty
        if ((not self._cubegen.mapcube().cube().is_empty()) and
            self['outcube'].is_valid()):
            self._cubegen.mapcube().save(self['outcube'].filename(),
                                         self['clobber'].boolean())
        
        # If requested, save the updated list of models
        if self['outmodel'].is_valid():

            # Generate a list of models that will be output to file
            outmodels = gammalib.GModels(self._models)
            
            # Remove all models used in the generated cube
            for model in self._cubemodels:
                outmodels.remove(model.name())

            # Generate the actual cube model
            spat     = gammalib.GModelSpatialDiffuseCube(self['outcube'].filename())
            spec     = gammalib.GModelSpectralConst()
            newmodel = gammalib.GModelSky(spat, spec)

            # Give the model a default name
            newmodel.name(self.cubemodelname())

            # Now append the model to the list of output models
            outmodels.append(newmodel)

            # Save the model list
            outmodels.save(self['outmodel'].filename())

        # Return
        return
Пример #3
0
    def _generate_initial_model(self, sigma_min=2.0, sigma_max=1000.0):
        """
        Generate initial background model

        Parameters
        ----------
        sigma_min : float, optional
            Minimum sigma
        sigma_max : float, optional
            Maximum sigma

        Returns
        -------
        model : `~gammalib.GModelData()`
            Background model
        """
        # Handle IRF model
        if self['spatial'].string() == 'IRF':
            epivot = gammalib.GEnergy(1.0, 'TeV')
            spectral = gammalib.GModelSpectralPlaw(1.0, 0.0, epivot)
            model = gammalib.GCTAModelIrfBackground(spectral)

        # Handle AEFF model
        elif self['spatial'].string() == 'AEFF':
            epivot = gammalib.GEnergy(1.0, 'TeV')
            spectral = gammalib.GModelSpectralPlaw(1.0e-13, -2.5, epivot)
            model = gammalib.GCTAModelAeffBackground(spectral)

        # Handle other models
        else:

            # Handle LOOKUP model
            if self['spatial'].string() == 'LOOKUP':

                # Set spatial model
                factor1 = gammalib.GCTAModelSpatialLookup(
                    self['slufile'].filename())

            # Handle GAUSS model
            elif self['spatial'].string() == 'GAUSS':

                # Set spatial model
                factor1 = gammalib.GCTAModelRadialGauss(3.0)
                factor1['Sigma'].min(sigma_min)
                factor1['Sigma'].max(sigma_max)

            # Handle GAUSS(E) model
            elif self['spatial'].string() == 'GAUSS(E)':

                # Set spatial model. If a single energy bin is specified then
                # use the GAUSS model. Otherwise allocate a node spectrum for
                # the energy nodes of GAUSS(E).
                if self['snumbins'].integer() == 1:
                    factor1 = gammalib.GCTAModelRadialGauss(3.0)
                    factor1['Sigma'].min(sigma_min)
                    factor1['Sigma'].max(sigma_max)
                else:
                    emin = gammalib.GEnergy(self['smin'].real(), 'TeV')
                    emax = gammalib.GEnergy(self['smax'].real(), 'TeV')
                    energies = gammalib.GEnergies(self['snumbins'].integer(),
                                                  emin, emax)
                    spectrum = gammalib.GModelSpectralConst(3.0)
                    nodes = gammalib.GModelSpectralNodes(spectrum, energies)
                    for i in range(nodes.nodes()):
                        nodes[i * 2 + 1].min(sigma_min)
                        nodes[i * 2 + 1].max(sigma_max)
                    nodes.autoscale()
                    factor1 = gammalib.GCTAModelSpatialGaussSpectrum(nodes)

            # Handle PROFILE model
            elif self['spatial'].string() == 'PROFILE':

                # Set spatial model
                factor1 = gammalib.GCTAModelRadialProfile(2.0, 4.0, 5.0)
                factor1['Width'].min(1.0)
                factor1['Width'].max(10.0)
                factor1['Core'].min(1.0)
                factor1['Core'].max(10.0)
                factor1['Tail'].min(1.0)
                factor1['Tail'].max(10.0)
                factor1['Tail'].free()

            # Handle POLYNOM model
            elif self['spatial'].string() == 'POLYNOM':

                # Set spatial model
                factor1 = gammalib.GCTAModelRadialPolynom([1.0, -0.1, +0.1])
                factor1['Coeff0'].min(0.1)
                factor1['Coeff0'].max(10.0)
                factor1['Coeff0'].fix()
                factor1['Coeff1'].min(-10.0)
                factor1['Coeff1'].max(10.0)
                factor1['Coeff2'].min(-10.0)
                factor1['Coeff2'].max(10.0)

            # Any other strings (should never occur)
            else:
                model = None

            # Optionally add gradient
            if self['gradient'].boolean():
                spatial = gammalib.GCTAModelSpatialMultiplicative()
                factor2 = gammalib.GCTAModelSpatialGradient()
                spatial.append(factor1)
                spatial.append(factor2)
            else:
                spatial = factor1

            # Set spectral model
            epivot = gammalib.GEnergy(1.0, 'TeV')
            spectral = gammalib.GModelSpectralPlaw(3.0e-4, -1.5, epivot)
            spectral['Prefactor'].min(1.0e-8)

            # Set background model
            model = gammalib.GCTAModelBackground(spatial, spectral)

        # Set background name and instrument
        if model is not None:
            model.name('Background')
            model.instruments(self._instrument)

        # Return model
        return model
Пример #4
0
    def _background_spectrum(self, prefactor, index, emin=0.01, emax=100.0):
        """
        Create a background spectrum model dependent on user parameters
        
        Parameters
        ----------
        prefactor : float
            Power law prefactor of spectral model
        index : float
            Power law index of spectral model
        emin : float
            Minimum energy (in case a spectral node function is required)
        emax : float
            Maximum energy (in case a spectral node function is required)
        
        Returns
        -------
        spec : `~gammalib.GModelSpectral()`
            Spectral model for the background shape     
        """
        # Handle constant spectral model
        if index == 0.0 and self._bkgpars <= 1:
            spec = gammalib.GModelSpectralConst()

            # Set parameter range
            spec['Normalization'].min(prefactor / self._bkg_range_factor)
            spec['Normalization'].max(prefactor * self._bkg_range_factor)
            spec['Normalization'].value(prefactor)

            # Freeze or release normalisation parameter
            if self._bkgpars == 0:
                spec['Normalization'].fix()
            else:
                spec['Normalization'].free()

        else:

            # Create power law model
            if self._bkgpars <= 2:

                # Set Power Law model with arbitrary pivot energy
                pivot = gammalib.GEnergy(1.0, 'TeV')
                spec = gammalib.GModelSpectralPlaw(prefactor, index, pivot)

                # Set parameter ranges
                spec[0].min(prefactor / self._bkg_range_factor)
                spec[0].max(prefactor * self._bkg_range_factor)
                spec[1].scale(1)
                spec[1].min(-5.0)
                spec[1].max(5.0)

                # Set number of free parameters
                if self._bkgpars == 0:
                    spec[0].fix()
                    spec[1].fix()
                elif self._bkgpars == 1:
                    spec[0].free()
                    spec[1].fix()
                else:
                    spec[0].free()
                    spec[1].free()

            else:

                # Create reference powerlaw
                pivot = gammalib.GEnergy(1.0, 'TeV')
                plaw = gammalib.GModelSpectralPlaw(prefactor, index, pivot)

                # Create spectral model and energy values
                spec = gammalib.GModelSpectralNodes()

                # Create logarithmic energy nodes
                bounds = gammalib.GEbounds(self._bkgpars,
                                           gammalib.GEnergy(emin, 'TeV'),
                                           gammalib.GEnergy(emax, 'TeV'), True)

                # Loop over bounds and set intensity value
                for i in range(bounds.size()):
                    energy = bounds.elogmean(i)
                    value = plaw.eval(energy)

                    # Append energy, value - tuple to node function
                    spec.append(energy, value)

                # Loop over parameters
                for par in spec:

                    # Fix energy nodes
                    if 'Energy' in par.name():
                        par.fix()

                    # Release intensity nodes
                    elif 'Intensity' in par.name():
                        value = par.value()
                        par.scale(value)
                        par.min(value / self._bkg_range_factor)
                        par.max(value * self._bkg_range_factor)

        # Return spectrum
        return spec
Пример #5
0
    def _background_spectrum(self,
                             run,
                             prefactor,
                             index,
                             emin=0.01,
                             emax=100.0):

        # Handle constant spectral model
        if index == 0.0 and self._bkgpars <= 1:
            spec = gammalib.GModelSpectralConst()
            spec['Normalization'].min(prefactor / self._bkg_range_factor)
            spec['Normalization'].max(prefactor * self._bkg_range_factor)
            spec['Normalization'].value(prefactor)
            if self._bkgpars == 0:
                spec['Normalization'].fix()
            else:
                spec['Normalization'].free()

        else:

            # Create power law model
            if self._bkgpars <= 2:
                e = gammalib.GEnergy(1.0, 'TeV')
                spec = gammalib.GModelSpectralPlaw(prefactor, index, e)

                # Set parameter ranges
                spec[0].min(prefactor / self._bkg_range_factor)
                spec[0].max(prefactor * self._bkg_range_factor)
                spec[1].scale(1)
                spec[1].min(-5.0)
                spec[1].max(5.0)

                # Set number of free parameters
                if self._bkgpars == 0:
                    spec[0].fix()
                    spec[1].fix()
                elif self._bkgpars == 1:
                    spec[0].free()
                    spec[1].fix()
                else:
                    spec[0].free()
                    spec[1].free()

            else:

                # Create reference powerlaw
                plaw = gammalib.GModelSpectralPlaw(
                    prefactor, index, gammalib.GEnergy(1.0, 'TeV'))

                # Create spectral model and energy values
                spec = gammalib.GModelSpectralNodes()
                bounds = gammalib.GEbounds(self._bkgpars,
                                           gammalib.GEnergy(emin, 'TeV'),
                                           gammalib.GEnergy(emax, 'TeV'), True)
                for i in range(bounds.size()):
                    energy = bounds.elogmean(i)
                    value = plaw.eval(energy, gammalib.GTime())
                    spec.append(energy, value)
                for par in spec:

                    if 'Energy' in par.name():
                        par.fix()
                    elif 'Intensity' in par.name():
                        value = par.value()
                        par.scale(value)
                        par.min(value / self._bkg_range_factor)
                        par.max(value * self._bkg_range_factor)

        # Return spectrum
        return spec
            for idx2 in (np.arange(0,int(width/binsize))[::-1]):
                if (idx2+1.0)/(idx1+1.0) < (np.tan((125-ang)*np.pi/180.) - 7/binsize/(idx1+1.0)): #+ 80/idx1+1.0:
                    skymap.data[j,idx1,idx2] *= 0
                else:
                    continue

### Smooth the map
skymap = skymap.smooth(width=0.08 * u.deg, kernel="gauss")

### Save the map
skymap.write('hessj1825_cube.fits', hdu='Primary', overwrite='True')

hdul = fits.open('hessj1825_cube.fits')
hdul[0].header.set('BUNIT', 'photon/cm2/s/MeV/sr', 'Photon flux')
hdul[0].verify('fix')
del hdul[0].header['BANDSHDU']
hdul[1].name='ENERGIES'
hdul[1].header['TTYPE2']='Energy'
hdul[1].verify('fix')
hdul.writeto('hessj1825_map.fits',overwrite=True)

### create gammalib model
spatial = gammalib.GModelSpatialDiffuseCube(gammalib.GFilename('hessj1825_map.fits'))
spectral = gammalib.GModelSpectralConst(1.)
model = gammalib.GModelSky(spatial,spectral)
## fill to model container and write to disk
models = gammalib.GModels()
models.append(model)
models.save('hessj1825.xml')