コード例 #1
0
def npred(obs, analysis, pars):
    """
    Determine Npred of source

    Parameters
    ----------
    obs : `~gammalib.GObservations()`
        Observation container
    analysis : str
        Analyse name
    pars : dict
        Dictionary of analysis parameters
    """
    # Set file names
    inmodel = 'rx_results_%s.xml' % analysis
    outmodel = 'rx_npred_%s.xml' % analysis
    logfile = 'rx_npred_%s.log' % analysis

    # Continue only if result file does not exist
    if not os.path.isfile(outmodel) and os.path.isfile(inmodel):

        # Set models
        models = gammalib.GModels(inmodel)
        model = models['RX J1713.7-3946']
        for par in model:
            par.fix()
        model.tscalc(False)  # Otherwise leads to an error
        npred_models = gammalib.GModels()
        npred_models.append(model)

        # Attach models
        obs.models(npred_models)

        # If statistic is wstat then switch to cstat (since wstat does not
        # correctly compute Npred)
        for o in obs:
            if o.statistic() == 'wstat':
                o.statistic('cstat')

        # Perform maximum likelihood fitting
        like = ctools.ctlike(obs)
        like['edisp'] = pars['edisp']
        like['outmodel'] = outmodel
        like['logfile'] = logfile
        like['debug'] = True
        like.logFileOpen()
        like.execute()

    # Return
    return
コード例 #2
0
ファイル: csmodelmerge.py プロジェクト: xxxhycl2010/ctools
    def run(self):
        """
        Run the script
        """
        # Switch screen logging on in debug mode
        if self._logDebug():
            self._log.cout(True)

        # Get parameters
        self._get_parameters()

        # Write header
        if self._logTerse():
            self._log('\n')
            self._log.header1('Merge models')

        # Initialise model container
        self._models = gammalib.GModels()

        # Loop over model files
        for f in self._files:

            # Construct container from XML file
            models = gammalib.GModels(f)

            # Log number of models to add
            if self._logTerse():
                nmodels = models.size()
                if nmodels == 0:
                    self._log(gammalib.parformat('Add no model from file'))
                elif nmodels == 1:
                    self._log(gammalib.parformat('Add 1 model from file'))
                else:
                    self._log(
                        gammalib.parformat('Add %d models from file' %
                                           nmodels))
                self._log(f)
                self._log('\n')

            # Extend model container by adding all models in the model file
            self._models.extend(models)

        # Log total number of models
        if self._logTerse():
            self._log(gammalib.parformat('Models after merging'))
            self._log(self._models.size())
            self._log('\n')

        # Return
        return
コード例 #3
0
def npred(obs, analysis, pars, fitname='pks_results', npredname='pks_npred'):
    """
    Determine Npred of source

    Parameters
    ----------
    obs : `~gammalib.GObservations()`
        Observation container
    analysis : str
        Analyse name
    pars : dict
        Dictionary of analysis parameters
    fitname : str, optional
        Fit result prefix
    npredname : str, optional
        Npred result prefix
    """
    # Set file names
    inmodel  = '%s_%s.xml' % (fitname,  analysis)
    outmodel = '%s_%s.xml' % (npredname, analysis)
    logfile  = '%s_%s.log' % (npredname, analysis)

    # Continue only if result file does not exist
    if not os.path.isfile(outmodel) and os.path.isfile(inmodel):

        # Set models
        models = gammalib.GModels(inmodel)
        model  = models['PKS 2155-304']
        for par in model:
            par.fix()
        model.tscalc(False) # Otherwise leads to an error
        npred_models = gammalib.GModels()
        npred_models.append(model)

        # Attach models
        obs.models(npred_models)

        # Perform maximum likelihood fitting
        like = ctools.ctlike(obs)
        like['edisp']    = pars['edisp']
        like['outmodel'] = outmodel
        like['logfile']  = logfile
        like['debug']    = True
        like.logFileOpen()
        like.execute()

    # Return
    return
コード例 #4
0
    def _gen_cubemodel(self):
        """
        Generates a binned model from the model file using ctmapcube
        """
        # Get a list of sources we DONT want to put into the cube
        sources = self['soilist'].string().split(',')

        # Load the model into a model container
        if (self._models.size() == 0):
            self._models = gammalib.GModels(self['inmodel'].filename())

        # Store a copy of the models
        self._cubemodels = self._models.copy()

        # Loop through models and pull out all models not in the list
        for model in self._models:

            # If model is not a sky model then continue
            if model.classname() != 'GModelSky':
                self._cubemodels.remove(model.name())

            # ... otherwise, if model is in list of sources the remove it
            # from the container
            elif model.name() in sources:
                self._cubemodels.remove(model.name())

        # Log the number of models to be put into the cube
        self._log_value(self['chatter'].integer(), 'Numner of cube models',
                        self._cubemodels.size())

        # Return
        return
コード例 #5
0
def simulate_ctobssim(obs, xmlname, seed=0):
    """
    Simulate events using ctobssim.
    """
    # Create containers
    observations = gammalib.GObservations()
    observations.append(obs)

    # Append models
    models = gammalib.GModels(xmlname)
    observations.models(models)
    print(models[0])

    # Allocate ctobssim application and set parameters
    sim = ctools.ctobssim(observations)
    sim['seed'].integer(seed)

    # Run simulator
    sim.run()

    # Retrieve events
    events = sim.obs()[0].events().copy()

    # Print event statistics
    npred = obs.npred(models)
    print(str(len(events)) + " events simulated.")
    print(str(npred) + " events expected from Npred.")

    # Delete the simulation
    del sim

    # Return events
    return events
コード例 #6
0
def simulate(obs, xmlname):
    """
    Simulate events.
    """
    # Allocate random number generator
    ran = gammalib.GRan()

    # Load models and extract first model
    models = gammalib.GModels(xmlname)
    model = models[0]
    print(model)

    # Simulate events
    events = model.mc(obs, ran)

    # Print event statistics
    npred = obs.npred(models)
    print(str(len(events)) + " events simulated.")
    print(str(npred) + " events expected from Npred.")

    # Check distance
    pntdir = obs.pointing().dir()
    for event in events:
        distance = gammalib.GCTAInstDir(event.dir()).dir().dist_deg(pntdir)
        if (distance > 5.0):
            print("Too far: "+str(distance))

    # Return events
    return events
コード例 #7
0
    def _check_result_files(self, fitsfile, xmlfile, nmodels):
        """
        Check ctfindvar result

        Parameters
        ----------
        fitsfile : str
            FITS file name
        xmlfile : str
            Model definition XML file name
        nmodels : int
            Expected number of models
        """
        # Read variability FITS file
        if fitsfile is not 'NONE':
            fits = gammalib.GFits(fitsfile)
            self.test_value(fits.size(), 3, 'Check for 3 extensions in output file')

        # Read model definition XML file
        models = gammalib.GModels(xmlfile)
        self.test_value(models.size(), nmodels,
             'Check for %d models in model definition XML file' % nmodels)

        # Return
        return
コード例 #8
0
def get_binpop_models(datadir, flux_thresh, outdir, bmax):

    models = gammalib.GModels()

    # get file names
    files = []
    # r=root, d=directories, f = files
    for r, d, f in os.walk(datadir):
        for file in f:
            if '.txt' in file:
                files.append(os.path.join(r, file))

    # load models
    for file in files:
        model, lat = bin2gammalib(file, flux_thresh, outdir)
        if model.size() > 0 and np.abs(lat) < bmax:
            models.append(model)
        else:
            pass

    # dictionary with parameters
    lons, lats, radii, fluxes, names = dist_from_gammalib(models)

    d = {
        'name': np.array(names),
        'GLON': np.array(lons),
        'radius': np.array(radii),
        'GLAT': np.array(lats),
        'flux': np.array(fluxes)
    }

    return models, d
コード例 #9
0
ファイル: csmodelinfo.py プロジェクト: xxxhycl2010/ctools
    def __init__(self, *argv):
        """
        Constructor.
        """
        # Set name
        self._name = "csmodelinfo"
        self._version = "1.1.0"

        # Initialise class members
        self._models = gammalib.GModels()
        self._ds9file = gammalib.GFilename("NONE")
        self._pnt_type = ""
        self._pnt_mark_size = 12
        self._show_labels = True
        self._width = 2
        self._fontfamily = "helvetica"
        self._fontsize = 12
        self._fontweight = "normal"
        self._fontslant = "roman"
        self._show_ext_type = True
        self._free_color = "green"
        self._fixed_color = "magenta"

        # Initialise application by calling the appropriate class
        # constructor.
        self._init_cscript(argv)

        # Return
        return
コード例 #10
0
ファイル: csmodelinfo.py プロジェクト: xxxhycl2010/ctools
    def _get_parameters(self):
        """
        Get parameters from parfile and setup the observation.
        """
        # Get models
        self._models = gammalib.GModels(self["inmodel"].filename())

        # Get hidden parameters for region file
        self._pnt_type = self["pnt_type"].string()
        self._pnt_mark_size = self["pnt_mark_size"].integer()
        self._show_labels = self["show_labels"].boolean()
        self._width = self["width"].integer()
        self._fontfamily = self["fontfamily"].string()
        self._fontsize = self["fontsize"].integer()
        self._fontweight = self["fontweight"].string()
        self._fontslant = self["fontslant"].string()
        self._show_ext_type = self["show_ext_type"].boolean()
        self._free_color = self["free_color"].string()
        self._fixed_color = self["fixed_color"].string()

        # Read ahead DS9 filename
        if self._read_ahead():
            self._ds9file = self["ds9file"].filename()

        # Write input parameters into logger
        if self._logTerse():
            self._log_parameters()
            self._log("\n")

        # Return
        return
コード例 #11
0
    def _check_fit_result(self, filename):
        """
        Check result file
        """
        # Load fit results
        models = gammalib.GModels(filename)

        # Set reference values
        prefactor = 3.63152145731529e-16
        index = 2.39100016863397
        pre_background = 1.30910556742873
        index_background = 0.252909973473968

        # Check fit result values
        self.test_value(models['Crab'][2].value(), prefactor,
                        1.0e-4 * prefactor, 'Check Crab prefactor')
        self.test_value(models['Crab'][3].value(), -index, 1.0e-4 * index,
                        'Check Crab index')
        self.test_value(models['Background'][0].value(), pre_background,
                        1.0e-4 * pre_background,
                        'Check background model prefactor')
        self.test_value(models['Background'][1].value(), -index_background,
                        1.0e-4 * index_background,
                        'Check background model index')

        # Return
        return
コード例 #12
0
def show_model():
    """
    Show model spectrum
    """
    # Set usage string
    usage = 'show_model.py [-n name] [-p plotfile] file'

    # Set default options
    options = [{'option': '-n', 'value': ''}, {'option': '-p', 'value': ''}]

    # Get arguments and options from command line arguments
    args, options = cscripts.ioutils.get_args_options(options, usage)

    # Extract script parameters from options
    name = options[0]['value']
    plotfile = options[1]['value']
    if len(name) == 0:
        name = 0

    # Read models XML file
    models = gammalib.GModels(args[0])

    # Extract relevant model
    model = models[name]

    # Plot spectrum
    plot_spectrum(model, plotfile)

    # Return
    return
コード例 #13
0
def main():
    mev2erg = 1.6021765e-6  # MeV => erg

    input_model = sys.argv[1]
    models = gammalib.GModels(input_model)
    print(models)
    first_model = models[0]
    m_spect = first_model.spectral()
    print("TS:", first_model.ts())

    emin = gammalib.GEnergy(25, 'GeV')
    emax = gammalib.GEnergy(150, 'TeV')
    r = m_spect.flux(emin, emax)
    er = m_spect.eflux(emin, emax)
    print('gl Flux: {:.4e} ph/cm²/s'.format(r))
    print('fl EFlux: {:.4e} erg/cm²/s'.format(er))
    for par in ['Prefactor', 'PivotEnergy', 'Index']:
        print(par, m_spect[par].value(), m_spect[par].error())

    # pref = m_spect['Prefactor'].value()
    # print('pref', pref)

    print('my flux: {0:.4e} ph/cm²/s'.format(
        flux_eval_following_ctools([25 * 1e3, 150 * 1e6])))
    my_eflux = eflux_eval_following_ctools(
        [25 * 1e3, 150 * 1e6])  #, m_spect['Prefactor'].value())
    print('my eflux: {0:.4e} MeV/cm²/s => {1:.4e} erg/cm²/s'.format(
        my_eflux, my_eflux * mev2erg))
コード例 #14
0
    def _get_parameters(self):
        """
        Get parameters from parfile and setup the observation
        """
        # Get models
        self._models = gammalib.GModels(self['inmodel'].filename())

        # Query hidden parameters for region file
        self['pnt_type'].string()
        self['pnt_mark_size'].integer()
        self['show_labels'].boolean()
        self['width'].integer()
        self['fontfamily'].string()
        self['fontsize'].integer()
        self['fontweight'].string()
        self['fontslant'].string()
        self['show_ext_type'].boolean()
        self['free_color'].string()
        self['fixed_color'].string()

        # Query ahead DS9 filename
        if self._read_ahead():
            self['outds9file'].query()

        #  Write input parameters into logger
        self._log_parameters(gammalib.TERSE)

        # Return
        return
コード例 #15
0
ファイル: test_cterror.py プロジェクト: xxxhycl2010/ctools
    def _check_result_file(self, filename):
        """
        Check result file
        """
        # Open result file
        result = gammalib.GModels(filename)

        # Check results
        self.test_value(result['Crab']['Prefactor'].value(), 1.58907e-16,
                        1.0e-3, 'Check fitted Crab Prefactor')
        self.test_value(result['Crab']['Prefactor'].error(), 0.0529105e-16,
                        1.0e-3, 'Check Crab Prefactor error')
        self.test_value(result['Crab']['Index'].value(), -2.43549, 1.0e-3,
                        'Check fitted Crab Index')
        self.test_value(result['Crab']['Index'].error(), 0.027804, 1.0e-3,
                        'Check Crab Index error')
        self.test_value(result['Background']['Prefactor'].value(), 61.6919e-6,
                        1.0e-3, 'Check fitted background Prefactor')
        self.test_value(result['Background']['Prefactor'].error(), 1.49438e-6,
                        1.0e-3, 'Check background Prefactor error')
        self.test_value(result['Background']['Index'].value(), -2.20535,
                        1.0e-3, 'Check fitted background Index')
        self.test_value(result['Background']['Index'].error(), 0.0113269,
                        1.0e-3, 'Check background Index error')
        self.test_value(result['Background']['Sigma'].value(), 3.04252, 1.0e-3,
                        'Check fitted background Sigma')
        self.test_value(result['Background']['Sigma'].error(), 0.0307008,
                        1.0e-3, 'Check background Sigma error')

        # Return
        return
コード例 #16
0
    def _append_inmodels(self):
        """
        Append input models
        """
        # If there are models provided by "inmodels" then append them now to
        # the model container
        if self['inmodel'].is_valid():

            # Get filename
            filename = self['inmodel'].filename().url()

            # Log header and input model file
            self._log_header1(gammalib.TERSE, 'Append input models')
            self._log_value(gammalib.NORMAL, 'Input model file', filename)

            # Load input models
            models = gammalib.GModels(filename)

            # Loop over input models and append them to the model container
            for model in models:
                self._models.append(model)
                self._log_value(gammalib.NORMAL, 'Append model',
                                '"' + model.name() + '"')

        # Return
        return
コード例 #17
0
 def ctlike_run(self,
                input_obs_list,
                input_models=None,
                output_models='ml_result.xml',
                log_file='ctlike.log',
                force=False,
                save=False):
     like = ctools.ctlike()
     if isinstance(input_obs_list, gammalib.GObservations):
         like.obs(input_obs_list)
         if input_models is not None:
             like.obs().models(input_models)
     elif os.path.isfile(input_obs_list) and os.path.isfile(input_models):
         # observations list from file
         like["inobs"] = input_obs_list
         like["inmodel"] = input_models
     else:
         raise Exception('Cannot understand input obs list for ctlike')
     like["outmodel"] = output_models
     like["logfile"] = log_file
     like["nthreads"] = self.nthreads
     if force or not os.path.isfile(output_models):
         like.logFileOpen()
         like.run()
     elif os.path.isfile(output_models):
         ml_models = gammalib.GModels(output_models)
         like.obs().models(ml_models)
     else:
         raise Exception("Cannot proceed with ctlike")
     saved = False
     if (save and force) or (save and not os.path.isfile(output_models)):
         like.save()
         saved = True
         logger.info("File {} created.".format(output_models))
     return like
コード例 #18
0
def lightcurve(cpipe):
    """
    Function running the lightcurve plots
    
    Parameters
    ----------
    - cpipe (ClusterPipe object): a cluster pipe object 
    associated to the analysis

    Outputs
    --------
    - plots
    """

    #========== Flux for each source
    models = gammalib.GModels(cpipe.output_dir + '/Ana_Model_Output.xml')

    for isource in range(len(models)):
        if models[isource].type() not in [
                'CTACubeBackground', 'CTAIrfBackground'
        ]:

            srcname = models[isource].name()
            specfile = cpipe.output_dir + '/Ana_Lightcurve_' + srcname + '.fits'
            outfile = cpipe.output_dir + '/Ana_Lightcurve_' + srcname + '.pdf'

            file_exist = os.path.isfile(specfile)
            if file_exist:
                plotting.show_lightcurve(specfile, outfile)
            else:
                if not cpipe.silent:
                    print(specfile + ' does not exist, no Lightcurve_' +
                          srcname + ' plot')
コード例 #19
0
    def _check_result_files(self, filename, nebounds=5, nmodels=2):
        """
        Check result file

        Parameters
        ----------
        filename : str
            Test file name without extension
        nebounds : int, optional
            Number of energy boundaries
        """
        # Open background cube
        cube = gammalib.GCTACubeBackground(filename + '.fits')

        # Open model definition file
        models = gammalib.GModels(filename + '.xml')

        # Check cube
        self._check_cube(cube, nebounds=nebounds)

        # Check models
        self._check_models(models, nmodels=nmodels)

        # Return
        return
コード例 #20
0
ファイル: csmodelselect.py プロジェクト: misabelber/ctools
    def _get_parameters(self):
        """
        Get parameters from parfile and setup the observation
        """
        # Query input parameters
        self['inobs'].filename()
        self['inmodel'].filename()

        # Query hidden parameters
        self['roilimit'].real()
        self['roimargin'].real()
        self['ethres'].real()
        self['fluxlimit'].real()
        self['tslimit'].real()
        self['fit_pos'].boolean()
        self['fit_shape'].boolean()

        # Query ahead output model filename
        if self._read_ahead():
            self['outmodel'].filename()

        # If there are no observations in container then get them from the
        # parameter file
        if self.obs().size() == 0:
            self.obs(self._get_observations(False))

        # Get models
        self._models = gammalib.GModels(self['inmodel'].filename())

        #  Write input parameters into logger
        self._log_parameters(gammalib.TERSE)

        # Return
        return
コード例 #21
0
ファイル: make_survey.py プロジェクト: xxxhycl2010/ctools
def survey_single():
    """
    Creates a single observation survey for test purposes.
    """
    # Allocate observation container
    obs = gammalib.GObservations()

    # Set single pointing at galactic centre
    pntdir = gammalib.GSkyDir()
    pntdir.lb_deg(0.0, 0.0)
    run = obsutils.set_obs(pntdir)
    obs.append(run)

    # Define single point source with Crab flux at galactic centre
    center = gammalib.GSkyDir()
    center.lb_deg(0.0, 0.0)
    point_spatial  = gammalib.GModelSpatialPointSource(center)
    point_spectrum = crab_spec()
    point          = gammalib.GModelSky(point_spatial, point_spectrum)
    point.name('GC source')

    # Create model container
    models = gammalib.GModels()
    models.append(point)
    obs.models(models)

    # Return observation container
    return obs
コード例 #22
0
def show_events(events, xmlname, duration, emin, emax, ebins=30):
    """
    Show events using matplotlib.
    """
    # Create figure
    plt.figure(1)
    plt.title("MC simulated event spectrum (" + str(emin) + '-' + str(emax) + " TeV)")

    # Setup energy range covered by data
    ebds = gammalib.GEbounds(ebins, gammalib.GEnergy(emin, "TeV"),
                                    gammalib.GEnergy(emax, "TeV"))

    # Create energy axis
    energy = []
    for i in range(ebds.size()):
        energy.append(ebds.elogmean(i).TeV())

    # Fill histogram
    counts = [0.0 for i in range(ebds.size())]
    for event in events:
        index = ebds.index(event.energy())
        counts[index] = counts[index] + 1.0

    # Create error bars
    error = [math.sqrt(c) for c in counts]

    # Get model values
    sum    = 0.0
    models = gammalib.GModels(xmlname)
    m      = models[0]
    model  = []
    t = gammalib.GTime()
    for i in range(ebds.size()):
        eval   = ebds.elogmean(i)
        ewidth = ebds.emax(i) - ebds.emin(i)
        f      = m.npred(eval, t, obs) * ewidth.MeV() * duration
        sum   += f
        model.append(f)
    print(str(sum) + " events expected from spectrum (integration).")

    # Plot data
    plt.loglog(energy, counts, 'ro')
    plt.errorbar(energy, counts, error, fmt=None, ecolor='r')

    # Plot model
    plt.plot(energy, model, 'b-')

    # Set axes
    plt.xlabel("Energy (TeV)")
    plt.ylabel("Number of events")

    # Notify
    print("PLEASE CLOSE WINDOW TO CONTINUE ...")

    # Show plot
    plt.show()

    # Return
    return
コード例 #23
0
    def __init__(self, *argv):
        """
        Constructor.
        """
        # Set name and version
        self._name = 'csiactobs'
        self._version = '1.1.0'

        # Initialise some members
        self._ebounds = gammalib.GEbounds()
        self._datapath = os.getenv('VHEFITS', '')
        self._inmodels = gammalib.GModels()
        self._prodname = ''
        self._xml = gammalib.GXml()
        self._models = gammalib.GModels()
        self._runlist = []
        self._runlistfile = gammalib.GFilename()
        self._bkgpars = 0
        self._outmodel = gammalib.GFilename()
        self._outobs = gammalib.GFilename()
        self._master_indx = ''
        self._use_bkg_scale = False
        self._ev_hiera = ['']
        self._aeff_hiera = ['']
        self._psf_hiera = ['']
        self._bkg_hiera = ['']
        self._edisp_hiera = ['']
        self._bkg_mod_hiera = ['']
        self._bkg_gauss_norm = 1.0
        self._bkg_gauss_index = 0.0
        self._bkg_gauss_sigma = 1.0
        self._bkg_aeff_index = 0.0
        self._bkg_aeff_norm = 1.0
        self._bkg_range_factor = 1.0
        self._hdu_index = ''
        self._obs_index = ''
        self._subdir = ''
        self._debug = False

        # Initialise application by calling the appropriate class
        # constructor.
        self._init_cscript(argv)

        # Return
        return
コード例 #24
0
def spectrum(cpipe):
    """
    Function running the spectrum plots
    
    Parameters
    ----------
    - cpipe (ClusterPipe object): a cluster pipe object 
    associated to the analysis

    Outputs
    --------
    - plots
    """

    #========== Flux for each source
    models = gammalib.GModels(cpipe.output_dir + '/Ana_Model_Output.xml')

    for isource in range(len(models)):
        if models[isource].type() != 'CTACubeBackground':
            srcname = models[isource].name()
            specfile = cpipe.output_dir + '/Ana_Spectrum_' + srcname + '.fits'
            outfile = cpipe.output_dir + '/Ana_Spectrum_' + srcname + '.pdf'
            butfile = cpipe.output_dir + '/Ana_Spectrum_Buterfly_' + srcname + '.txt'
            butexist = os.path.isfile(butfile)
            if butexist:
                butfile_spec = butfile
            else:
                butfile_spec = None
            if srcname == cpipe.cluster.name:
                expfile = cpipe.output_dir + '/Sim_Model_Spectrum.txt'
            else:
                expfile = None

            file_exist = os.path.isfile(specfile)
            if file_exist:
                plotting.show_spectrum(specfile,
                                       outfile,
                                       butfile=butfile_spec,
                                       expected_file=expfile)
            else:
                if not cpipe.silent:
                    print(specfile + ' does not exist, no Spectrum_' +
                          srcname + ' plot')

    #========== Residual counts in ROI
    file_exist = os.path.isfile(cpipe.output_dir +
                                '/Ana_Spectrum_Residual.fits')
    if file_exist:
        plotting.show_spectrum_residual(
            cpipe.output_dir + '/Ana_Spectrum_Residual.fits',
            cpipe.output_dir + '/Ana_Spectrum_Residual.pdf')
    else:
        if not cpipe.silent:
            print(
                cpipe.output_dir +
                '/Ana_Spectrum_Residual.fits does not exist, no Spectrum_Residual plot'
            )
コード例 #25
0
def inspect_likelihood_model(model):
    ml = gl.GModels(model)
    # print(ml)
    ts = ml[0].ts()
    sign = math.sqrt(ts)
    print('''likelihood:
        TS: {}
       √TS: {}'''.format(ts, sign))
    return sign
コード例 #26
0
    def _set_replace_src_spectrum_by_nodes(self):
        """
        Replace source spectrum by node function
        """
        # Initialise model container
        models = gammalib.GModels()

        # Loop over model containers
        for model in self.obs().models():

            # If we deal with source model then replace the spectral model
            # by a node function
            if model.name() == self['srcname'].string():

                # Setup energies at log mean energies of bins
                energies = gammalib.GEnergies()
                for i in range(self._ebounds.size()):
                    energies.append(self._ebounds.elogmean(i))

                # Setup spectral node function
                spectrum = gammalib.GModelSpectralNodes(
                    model.spectral(), energies)
                spectrum.autoscale()

                # Make sure that all nodes are positive. Autoscale all
                # parameters so that their nominal value is unity.
                for i in range(spectrum.nodes()):
                    par = spectrum[i * 2 + 1]
                    par.autoscale()
                    value = par.value()
                    minimum = 1.0e-20 * value
                    if minimum <= 0.0:
                        minimum = 1.0e-20
                        if minimum < value:
                            value = minimum
                    par.value(value)
                    par.min(minimum)

                # Set spectral component of source model
                model.spectral(spectrum)

                # Make sure that TS computation is disabled (makes computation
                # faster)
                model.tscalc(False)

                # Append model
                models.append(model)

            # ... otherwise just append model
            else:
                models.append(model)

        # Put new model in observation containers
        self.obs().models(models)

        # Return
        return
コード例 #27
0
    def _make_model(self, prefix='Model', includeIC=True, obsID=None):
        """
        This function is used to construct the model.
        
        Parameters
        ----------
        - prefix (str): text to add as a prefix of the file names
        - includeIC (bool): include inverse Compton in the model
        
        """

        #----- Make cluster template files
        if (not self.silent) and (self.cluster.map_reso > 0.01 * u.deg):
            print(
                'WARNING: the FITS map resolution (self.cluster.map_reso) is larger'
            )
            print(
                '         than 0.01 deg, while the PSF at 100 TeV is ~0.02 deg.    '
            )
            print('')

        make_cluster_template.make_map(self.cluster,
                                       self.output_dir + '/' + prefix +
                                       '_Map.fits',
                                       Egmin=self.obs_setup.get_emin(),
                                       Egmax=self.obs_setup.get_emax(),
                                       includeIC=includeIC)

        make_cluster_template.make_spectrum(
            self.cluster,
            self.output_dir + '/' + prefix + '_Spectrum.txt',
            energy=np.logspace(-1, 5, 1000) * u.GeV,
            includeIC=includeIC)

        #----- Create the model
        model_tot = gammalib.GModels()

        if self.cluster.X_cr_E[
                'X'] > 0:  # No need to include the cluster if it is 0
            build_ctools_model.cluster(
                model_tot,
                self.output_dir + '/' + prefix + '_Map.fits',
                self.output_dir + '/' + prefix + '_Spectrum.txt',
                ClusterName=self.cluster.name,
                tscalc=True)

        build_ctools_model.compact_sources(model_tot,
                                           self.compact_source,
                                           tscalc=True)

        if obsID is None:
            background = self.obs_setup.bkg
        else:
            background = self.obs_setup.select_obs(obsID).bkg
        build_ctools_model.background(model_tot, background)

        model_tot.save(self.output_dir + '/' + prefix + '_Unstack.xml')
コード例 #28
0
def generate_resmap(emin=0.3, emax=50.0, ebins=40, edisp=True):
    """
    Generate residual map

    Parameters
    ----------
    emin : float, optional
        Minimum energy (TeV)
    emax : float, optional
        Maximum energy (TeV)
    ebins : int, optional
        Number of energy bins
    edisp : bool, optional
        Enable energy dispersion?
    """
    # Set filenames
    inobs = 'obs_rx_selected.xml'
    inmodel = 'rx_results_map0.48_eplaw_lookup_grad_hess_edisp.xml'
    outmodel = 'rx_background_map0.48_eplaw_lookup_grad_hess_edisp.xml'
    outmap = 'rx_resmap.fits'
    logfile = 'rx_resmap.log'

    # Continue only if inmodel exists
    if os.path.isfile(inobs) and os.path.isfile(inmodel):

        # Create model definition XML file without source
        models = gammalib.GModels(inmodel)
        models.remove('RX J1713.7-3946')
        models.save(outmodel)

        # Setup task parameters
        resmap = cscripts.csresmap()
        resmap['inobs'] = inobs
        resmap['inmodel'] = outmodel
        resmap['edisp'] = edisp
        resmap['algorithm'] = 'SUB'
        resmap['ebinalg'] = 'LOG'
        resmap['emin'] = emin
        resmap['emax'] = emax
        resmap['enumbins'] = ebins
        resmap['coordsys'] = 'CEL'
        resmap['proj'] = 'CAR'
        resmap['xref'] = 258.1125
        resmap['yref'] = -39.6867
        resmap['nxpix'] = 300
        resmap['nypix'] = 300
        resmap['binsz'] = 0.02
        resmap['outmap'] = outmap
        resmap['logfile'] = logfile
        resmap.logFileOpen()

        # Generate residual map
        resmap.execute()

    # Return
    return
コード例 #29
0
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')
コード例 #30
0
def get_obs_results(obsname, resname):
    """
    Get observation results

    Parameters
    ----------
    obsname : str
        Observation definition XML file
    resname : str
        Model result XML file
    """
    # Initialise results
    results = []

    # Load observations and models
    inobs  = gammalib.GObservations(obsname)
    models = gammalib.GModels(resname)

    # Loop over runs in observations
    for run in inobs:

        # Build observation container with single run
        obs = gammalib.GObservations()
        obs.append(run)

        # Get background model
        has_model = False
        for model in models:
            if model.classname() == 'GCTAModelBackground' and model.is_valid('HESS', run.id()):
                has_model = True
                break

        # Fall through if we have no model
        if not has_model:
            continue

        # Set results
        result = {'id': run.id(),
                  'ontime': run.ontime(), 'livetime': run.livetime(),
                  'deadc': run.deadc(),
                  'ra': run.pointing().dir().ra_deg(),
                  'dec': run.pointing().dir().dec_deg(),
                  'zenith': run.pointing().zenith(),
                  'azimuth': run.pointing().azimuth(),
                  'detx': model.spatial()[1].value(),
                  'e_detx': model.spatial()[1].error(),
                  'dety': model.spatial()[2].value(),
                  'e_dety': model.spatial()[2].error()}

        # Append results
        results.append(result)

    # Return
    return results