Exemplo n.º 1
0
def analyse(obsname, bkgname, srcmodel, spec, pars, alphas=[1.0]):
    """
    Analyse observations

    Parameters
    ----------
    obsname : str
        Observation definition XML file
    bkgname : str
        Background model definition XML file
    srcmodels : list of str
        List of source models
    spec : str
        Spectral model
    pars : dict
        Dictionary of analysis parameters
    alphas : list of float, optional
        List of template map scaling factors
    """
    # Handle map
    if srcmodel == 'map':

        # Loop over alphas
        for alpha in alphas:

            # Load observations
            _obsname = set_observation(obsname,
                                       srcmodel,
                                       bkgname,
                                       pars,
                                       alpha=alpha)
            obs = gammalib.GObservations(_obsname)

            # Set analysis
            analysis = set_analysis(srcmodel, bkgname, spec, pars, alpha=alpha)

            # Fit model
            fit(obs, srcmodel, spec, bkgname, analysis, pars, alpha=alpha)

            # Determine Npred
            npred(obs, analysis, pars)

    # Handle other models
    else:

        # Load observations
        _obsname = set_observation(obsname, srcmodel, bkgname, pars, alpha=1.0)
        obs = gammalib.GObservations(_obsname)

        # Set analysis
        analysis = set_analysis(srcmodel, bkgname, spec, pars, alpha=1.0)

        # Fit model
        fit(obs, srcmodel, spec, bkgname, analysis, pars, alpha=1.0)

        # Determine Npred
        npred(obs, analysis, pars)

    # Return
    return
Exemplo n.º 2
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
Exemplo n.º 3
0
def plot_phases(filename, plotfile, nphases=40):
    """
    Plot phases

    Parameters
    ----------
    filename : str
        Name of lightcurve FITS file
    plotfile : str
        Plot file name
    """
    # Read observation container. If an exception occurs then try loading the
    # file as an event list and build an observation container.
    try:
        obs = gammalib.GObservations(filename)
    except:
        obs = gammalib.GObservations()
        obs.append(gammalib.GCTAObservation(filename))

    # Initialise phases
    phases = []

    # Loop over all observations
    for run in obs:

        # Get events
        events = run.events()

        # Loop over all events
        for event in events:

            # Get phase
            phase = event.phase()

            # Collect phase
            phases.append(phase)
            phases.append(phase + 1.0)

    # Plot phase
    plt.figure()
    plt.hist(phases, bins=nphases, range=(0.0, 2.0), facecolor='r')
    plt.xlabel('Phase')
    plt.ylabel('Events')

    # Show figure
    if len(plotfile) > 0:
        plt.savefig(plotfile)
    else:
        plt.show()

    # Return
    return
Exemplo n.º 4
0
 def selection_run(self,
                   input_obs_list,
                   output_obs_list,
                   tmin=0,
                   tmax=None,
                   energy=[None, None],
                   prefix='selected_',
                   log_file='ctselect.log',
                   force=False,
                   save=False):
     if tmin < 0 or tmax < 1 or tmin >= tmax:
         raise Exception("ctselect needs better tmin/tmax")
     select = ctools.ctselect()
     if isinstance(input_obs_list, gammalib.GObservations):
         select.obs(input_obs_list)
     elif os.path.isfile(input_obs_list):
         # observations list from file
         select["inobs"] = input_obs_list
     else:
         raise Exception('Cannot understand input obs list for csphagen')
     select["rad"] = "INDEF"
     select["ra"] = "INDEF"
     select["dec"] = "INDEF"
     select["tmin"] = tmin
     select["tmax"] = tmax
     select["emin"] = energy[0] if energy[0] else "INDEF"
     select["emax"] = energy[1] if energy[1] else "INDEF"
     select["prefix"] = prefix
     select["outobs"] = output_obs_list
     select["logfile"] = log_file
     if force or not os.path.isfile(output_obs_list):
         select.logFileOpen()
         select.run()
     elif os.path.isfile(output_obs_list):
         basename, ext = os.path.splitext(output_obs_list)
         if ext == '.xml':
             select = ctools.ctselect(
                 gammalib.GObservations(output_obs_list))
         else:  # .fits
             container = gammalib.GObservations()
             gcta_obs = gammalib.GCTAObservation(output_obs_list)
             container.append(gcta_obs)
             select.obs(container)
     else:
         raise Exception("Cannot proceed with ctselect")
     saved = False
     if (save and force) or (save and not os.path.isfile(output_obs_list)):
         select.save()  # why it doesn't save anytime?
         saved = True
         logger.info("Files {} created.".format(output_obs_list))
     return select
Exemplo n.º 5
0
def get_onoff_info(on_off_obs_file):
    obs = gammalib.GObservations(on_off_obs_file)
    onoff_obs = obs[0]  # GCTAOnOffObservation
    # Pulse Height Analyzer class.
    # This class implements a Pulse Height Analyzer (PHA) spectrum that is used
    # as data container for an XSPEC analysis. A PHA spectrum is a vector that
    # provides the number of measured counts as function of the channel number.
    pha_on = onoff_obs.on_spec()
    pha_off = onoff_obs.off_spec()
    spectrum_bins = pha_on.size()
    if spectrum_bins != 1:
        print(
            "spectrum bins are more then expected. Need to change something in code to manage them"
        )
    on_count = pha_on.counts()
    off_count = pha_off.counts()
    alpha_val = pha_on.backscal(spectrum_bins -
                                1)  # index 0 = spectrum_bins -1
    li_ma_val = li_ma(on_count, off_count, alpha_val)
    return {
        "N_on": on_count,
        "N_off": off_count,
        "N_s": (on_count - alpha_val * off_count),
        "alpha": alpha_val,
        "li_ma": li_ma_val,
    }
Exemplo n.º 6
0
    def __init__(self, *argv):
        """
        Constructor.

        Parameters
        ----------
        argv : list of str
            List of IRAF command line parameter strings of the form
            ``parameter=3``.
        """
        # Set name and version
        self._name    = 'csobsdef'
        self._version = '1.1.0'

        # Initialise class members
        self._obs    = gammalib.GObservations()
        self._pntdef = gammalib.GCsv()
        self._tmin   = 0.0

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

        # Return
        return
Exemplo n.º 7
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
Exemplo n.º 8
0
    def __init__(self, *argv):
        """
        Constructor.
        """
        # Set name
        self._name = "cstsdist"
        self._version = "1.1.0"

        # Initialise some members
        self._obs = gammalib.GObservations()
        self._pattern = "single"
        self._srcname = ""
        self._enumbins = 0
        self._npix = 0
        self._binsz = 0.0
        self._outfile = gammalib.GFilename("ts.dat")
        self._ntrials = 10
        self._edisp = False
        self._debug = False
        self._log_clients = False

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

        # Return
        return
Exemplo n.º 9
0
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
Exemplo n.º 10
0
def generate_background_lookup():
    """
    Generate background lookup from empty field observations
    """
    # Set filenames
    obsname = '$HESSDATA/obs/obs_off.xml'
    filename = 'off_lookup.fits'

    # Continue only if lookup table does not yet exist
    if not os.path.isfile(filename):

        # Initialise lookup table
        emin = gammalib.GEnergy(0.2, 'TeV')
        emax = gammalib.GEnergy(50.0, 'TeV')
        ebds = gammalib.GEbounds(10, emin, emax)
        lookup = gammalib.GCTAModelSpatialLookup(2.0, 0.2, ebds)

        # Load empty field observations
        obs = gammalib.GObservations(obsname)

        # Fill lookup table
        lookup.fill(obs)

        # Save lookup table
        lookup.save(filename, True)

    # Return
    return
Exemplo n.º 11
0
    def _generate_runwise_bkg(self):
        """
        Generate background models
        """
        # Loop over observations
        for run in self.obs():

            # Write header
            self._log_header2(gammalib.TERSE, self._get_obs_header(run))

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

            # Generate background model for
            model = self._generate_bkg(obs)

            # Set model attributes
            model.name(('Background_%s' % run.id()))
            model.ids(run.id())

            # Write model
            self._log_string(gammalib.NORMAL, str(model))

            # Append background model
            self._models.append(model)

        # Return
        return
Exemplo n.º 12
0
    def _check_obsdef_file(self, filename):
        """
        Check observation definition file
        """
        # Load observation definition file
        obs = gammalib.GObservations(filename)

        # Check number of observations
        self.test_value(
            obs.size(), 3,
            'Check for 3 observations in observation definition file')

        # Loop over all observations
        for o in obs:
            self.test_value(o.instrument(), 'CTA',
                            'Check for "CTA" instrument')
            self.test_value(o.ontime(), 1800.0, 1.0e-6,
                            'Check for ontime of 1800 sec')
            self.test_value(o.deadc(), 0.95, 1.0e-6,
                            'Check for deadtime correction of 0.95')
            self.test_value(o.events().ebounds().emin().TeV(), 0.1, 1.0e-6,
                            'Check for minimum energy of 0.1 TeV')
            self.test_value(o.events().ebounds().emax().TeV(), 100.0, 1.0e-6,
                            'Check for maximum energy of 100 TeV')
            self.test_value(o.roi().radius(), 5.0, 1.0e-6,
                            'Check for ROI radois of 5 deg')

        # Return
        return
Exemplo n.º 13
0
    def _get_parameters(self):
        """
        Get parameters from parfile
        """
        # Initialise observation container if it is currently empty
        if self.obs().size() == 0:

            # If an observation definition file was provided then load it,
            # otherwise build a single observation with response information
            if self['inobs'].is_valid():
                self.obs(gammalib.GObservations(self['inobs'].filename()))
            else:
                cta = gammalib.GCTAObservation()
                caldb = gammalib.GCaldb('cta', self['caldb'].string())
                rsp = gammalib.GCTAResponseIrf(self['irf'].string(), caldb)
                cta.response(rsp)
                self.obs().append(cta)

        # Query input parameters
        self['emin'].real()
        self['emax'].real()
        self['aeffthres'].real()
        self['bkgthres'].real()

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

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

        # Return
        return
def generate_background_lookup(obslist=None, suffix=''):
    """
    Generate background lookup from empty field observations

    Parameters
    ----------
    obslist : list of int, optional
        Indices of observations to use
    suffix : str, optional
        Background lookup file suffix
    """
    # Set filenames
    obsname = '$HESSDATA/obs/obs_off.xml'
    filename = 'bkg_lookup%s.fits' % suffix

    # Continue only if lookup table does not yet exist
    if not os.path.isfile(filename):

        # Initialise lookup table
        emin = gammalib.GEnergy(0.2, 'TeV')
        emax = gammalib.GEnergy(50.0, 'TeV')
        ebds = gammalib.GEbounds(10, emin, emax)
        lookup = gammalib.GCTAModelSpatialLookup(2.0, 0.2, ebds)

        # Load empty field observations
        obs = gammalib.GObservations(obsname)

        # If an observation list was specified then exclude observations
        # in list
        if obslist != None:
            newobs = gammalib.GObservations()
            for i, run in enumerate(obs):
                if i not in obslist:
                    newobs.append(run)
                else:
                    print('Exclude %s' % (run.id()))
            obs = newobs
            print('%d observations in lookup table' % (len(obs)))

        # Fill lookup table
        lookup.fill(obs)

        # Save lookup table
        lookup.save(filename, True)

    # Return
    return
Exemplo n.º 15
0
def analyse(obsname, bkgname, srcmodel, spec, pars, select=None,
            fitname='pks_results', npredname='pks_npred'):
    """
    Analyse observations

    Parameters
    ----------
    obsname : str
        Observation definition XML file
    bkgname : str
        Background model definition XML file
    srcmodel : str
        Source model
    spec : str
        Spectral model
    pars : dict
        Dictionary of analysis parameters
    select : list of int, optional
        Indices for observation selection
    fitname : str, optional
        Fit result prefix
    npredname : str, optional
        Npred result prefix
    """
    # Load observations
    _obsname = set_observation(obsname, srcmodel, bkgname, pars)
    obs = gammalib.GObservations(_obsname)

    # Optionally select observations
    if select != None:
        obs_select = gammalib.GObservations()
        for i in select:
            obs_select.append(obs[i])
        obs = obs_select

    # Set analysis
    analysis = set_analysis(srcmodel, bkgname, spec, pars, select=select)

    # Fit model
    fit(obs, srcmodel, spec, bkgname, analysis, pars, fitname=fitname)

    # Determine Npred
    npred(obs, analysis, pars, fitname=fitname, npredname=npredname)

    # Return
    return
Exemplo n.º 16
0
    def _set_obs(self, lpnt=0.0, bpnt=0.0, emin=0.1, emax=100.0):
        """
        Set an observation container.

        Kwargs:
            lpnt: Galactic longitude of pointing [deg] (default: 0.0)
            bpnt: Galactic latitude of pointing [deg] (default: 0.0)
            emin: Minimum energy [TeV] (default: 0.1)
            emax: Maximum energy [TeV] (default: 100.0)

        Returns:
            Observation container.
        """
        # If an observation was provided on input then load it from XML
        # file
        filename = self["inobs"].filename()
        if filename != "NONE" and filename != "":
            obs = self._get_observations()

        # ... otherwise allocate a single observation
        else:

            # Read relevant user parameters
            caldb = self["caldb"].string()
            irf = self["irf"].string()
            deadc = self["deadc"].real()
            duration = self["duration"].real()
            rad = self["rad"].real()

            # Allocate observation container
            obs = gammalib.GObservations()

            # Set single pointing
            pntdir = gammalib.GSkyDir()
            pntdir.lb_deg(lpnt, bpnt)

            # Create CTA observation
            run = obsutils.set_obs(pntdir,
                                   caldb=caldb,
                                   irf=irf,
                                   duration=duration,
                                   deadc=deadc,
                                   emin=emin,
                                   emax=emax,
                                   rad=rad)

            # Append observation to container
            obs.append(run)

            # Set source position
            offset = self["offset"].real()
            pntdir.lb_deg(lpnt, bpnt + offset)
            self._ra = pntdir.ra_deg()
            self._dec = pntdir.dec_deg()

        # Return observation container
        return obs
Exemplo n.º 17
0
    def _masked_cube(self,
                     cube,
                     ra,
                     dec,
                     rad,
                     emin='INDEF',
                     emax='INDEF',
                     regfile='NONE'):
        """
        Mask an event cube and returns the masked cube

        Parameters
        ----------
        cube : `~gammalib.GCTAEventCube`
            Event cube
        ra : float (str 'INDEF' for no selection on direction)
            Right Ascension (deg)
        dec : float (str 'INDEF' for no selection on direction)
            Declination (deg)
        rad : float (str 'INDEF' for no selection on direction)
            Radius (deg)
        emin : float (str 'INDEF' for no selection on energy)
            Minimum energy (TeV)
        emax : float (str 'INDEF' for no selection on energy)
            Maximum energy (TeV)

        Returns
        -------
        cube : `~gammalib.GCTAEventCube`
            Event cube
        """
        # Turn cube into observation container to feed to ctcubemask
        obs = gammalib.GCTAObservation()
        obs.events(cube)
        obs_cont = gammalib.GObservations()
        obs_cont.append(obs)

        # Use ctcubemask to mask event cube pixels
        cubemask = ctools.ctcubemask(obs_cont)
        cubemask['ra'] = ra
        cubemask['dec'] = dec
        cubemask['rad'] = rad
        cubemask['emin'] = emin
        cubemask['emax'] = emax
        cubemask['regfile'] = regfile
        cubemask.run()

        # Extract copy of cube from observation container (copy is needed to
        # avoid memory leaks in SWIG)
        cube = cubemask.obs()[0].events().copy()

        # Return cube
        return cube
Exemplo n.º 18
0
    def _check_outobs(self, filenameroot, nout):
        """
        Check the output XML file containing ON/OFF observations
        """
        # Load observation container
        obs = gammalib.GObservations(filenameroot)

        # Check container size
        self.test_value(obs.size(), nout,
                        'Check for ' + str(nout) + ' observations in XML file')

        # Return
        return
Exemplo n.º 19
0
    def _check_observation_file(self, filename, number):
        """
        Check observation definition file
        """
        # Open observations
        obs = gammalib.GObservations(filename)

        # Check number of models
        self.test_value(
            obs.size(), number,
            'Check for ' + str(number) + ' observations in XML file')

        # Return
        return
Exemplo n.º 20
0
    def __init__(self, *argv):
        """
        Constructor
        """
        # Initialise application by calling the base class constructor
        self._init_cscript(self.__class__.__name__, ctools.__version__, argv)

        # Initialise some members
        self._obs = gammalib.GObservations()
        self._ebounds = gammalib.GEbounds()
        self._datapath = os.getenv('VHEFITS', '')
        self._prodname = ''
        self._xml = gammalib.GXml()
        self._models = gammalib.GModels()
        self._runlist = []
        self._runlistfile = gammalib.GFilename()
        self._bkgpars = 0
        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 empty observation definition XML file
        self._xml.append(
            gammalib.GXmlElement('observation_list '
                                 'title="observation list"'))

        # Append an observation list to XML instance
        self._xml.append(
            gammalib.GXmlElement('observation_list title="observation list"'))
        self._xml_obslist = self._xml.element('observation_list', 0)

        # Return
        return
Exemplo n.º 21
0
    def obs(self):
        """
        Returns GObservations object
        """
        # Initialise observations
        obs = gammalib.GObservations()

        # Read observations if XML is filled
        if self._xml.size():
            obs.read(self._xml)

        # Assign models
        obs.models(self._models)

        # Return observations
        return obs
Exemplo n.º 22
0
    def open_observation(self, obsfilename):

        print('Open observation')

        obs = gammalib.GObservations()

        self.obsconf = ObservationConfiguration(obsfilename,
                                                self.runconf.timesys,
                                                self.runconf.timeunit,
                                                self.runconf.skyframeref,
                                                self.runconf.skyframeunitref)
        print(self.obsconf.caldb)

        pntdir = gammalib.GSkyDir()

        in_pnttype = self.obsconf.point_frame
        print(in_pnttype)
        if in_pnttype == 'fk5':
            pntdir.radec_deg(self.obsconf.point_ra, self.obsconf.point_dec)

        #if in_pnttype == 'equatorial' :
        #pntdir.radec_deg(self.obs_ra, self.obs_dec)

        #if in_pnttype == 'galactic' :
        #	pntdir.radec_deg(self.in_l, self.in_b)

        #pntdir.radec_deg(self.obsconf.obs_point_ra, self.obsconf.obs_point_dec)

        tstart = self.obsconf.tstart - self.runconf.timeref
        print(tstart)
        if self.runconf.timeref_timesys == 'mjd':
            tstart = tstart * 86400.

        print("TSTART " + str(tstart))

        obs1 = obsutils.set_obs(pntdir, tstart, self.obsconf.duration, 1.0, \
         self.obsconf.emin, self.obsconf.emax, self.obsconf.roi_fov, \
         self.obsconf.irf, self.obsconf.caldb, self.obsconf.id)

        print(obs1)

        obs.append(obs1)

        #print(obs1)
        return obs
Exemplo n.º 23
0
    def _check_obsdef(self, filename, obs_expected):
        """
        Check observation definition XML file
        """
        # Load observation definition XML file
        obs = gammalib.GObservations(filename)

        # Check number of observations
        self.test_value(
            obs.size(), obs_expected,
            'Check for ' + str(obs_expected) + ' observations in XML file')

        # If there are observations in the XML file then check their content
        if obs_expected > 0:

            # Get response
            rsp = obs[0].response()

            # Test response
            self.test_value(obs[0].eventfile().file(), 'events_0.fits.gz',
                            'Check event file name')
            self.test_value(obs[0].eventfile().extname(), 'EVENTS',
                            'Check event extension name')
            self.test_value(rsp.aeff().filename().file(), 'irf_file.fits.gz',
                            'Check effective area file name')
            self.test_value(rsp.aeff().filename().extname(), 'EFFECTIVE AREA',
                            'Check effective area extension name')
            self.test_value(rsp.psf().filename().file(), 'irf_file.fits.gz',
                            'Check point spread function file name')
            self.test_value(rsp.psf().filename().extname(),
                            'POINT SPREAD FUNCTION',
                            'Check point spread function extension name')
            self.test_value(rsp.edisp().filename().file(), 'irf_file.fits.gz',
                            'Check energy dispersion file name')
            self.test_value(rsp.edisp().filename().extname(),
                            'ENERGY DISPERSION',
                            'Check energy dispersion extension name')
            self.test_value(rsp.background().filename().file(),
                            'irf_file.fits.gz', 'Check background file name')
            self.test_value(rsp.background().filename().extname(),
                            'BACKGROUND', 'Check background extension name')

        # Return
        return
Exemplo n.º 24
0
def create_lightcurve_gti(obsname, gtiname):
    """
    Generate lightcurve for GTIs

    Parameters
    ----------
    obsname : str
        Observation definition XML file
    gtiname : str
        GTI output filename
    """
    # Load observations
    obs = gammalib.GObservations(obsname)

    # Initialize GTIs
    gti = gammalib.GGti()

    # Loop over observations
    for run in obs:

        # Get start time and ontime of GTIs
        tstart = run.gti().tstart().copy()
        ontime = run.gti().ontime()

        # Set time bins
        tbin = ontime / 14.0

        # Loop over time bins
        for i in range(14):

            # Compute stop time
            tstop = tstart + tbin

            # Append GTI
            gti.append(tstart, tstop)

            # Update start time
            tstart = tstop.copy()

    # Save GTIs
    gti.save(gtiname, True)

    # Return
    return
Exemplo n.º 25
0
    def _setup_sim(self, two=False):
        """
        Setup method for sim() function test
        """
        # Set-up observation container
        pnt = gammalib.GSkyDir()
        pnt.radec_deg(83.6331, 22.0145)
        obs = gammalib.GObservations()
        run = obsutils.set_obs(pnt, duration=20.0, emin=1.0, emax=10.0)
        run.id('0')
        obs.append(run)
        if two:
            run.id('1')
            obs.append(run)

        # Append model
        obs.models(gammalib.GModels(self._model))

        # Return
        return obs
Exemplo n.º 26
0
def run_multi_ctobssim(RA, DEC, TSTART, DURATION, DEADC, EMIN, EMAX, RAD, IRF,
                       CALDB, outfile, nobs):
    """TODO: document what it does"""

    observations = gammalib.GObservations()

    # Automatically generate a number of nobs
    for i in xrange(nobs):
        obs = set(RA, DEC, TSTART, DURATION, DEADC, EMIN, EMAX, RAD, IRF,
                  CALDB)
        obs.id(str(i))
        observations.append(obs)

    observations.models('$CTOOLS/share/models/crab.xml')

    ctobssim = ctools.ctobssim(observations)
    ctobssim.logFileOpen()
    ctobssim['outfile'].filename(outfile)

    ctobssim.execute()
Exemplo n.º 27
0
    def __init__(self, *argv):
        """
        Constructor

        Parameters
        ----------
        argv : list of str
            List of IRAF command line parameter strings of the form
            ``parameter=3``.
        """
        # Initialise application by calling the base class constructor
        self._init_cscript(self.__class__.__name__, ctools.__version__, argv)

        # Initialise class members
        self._obs = gammalib.GObservations()
        self._pntdef = gammalib.GCsv()
        self._tmin = 0.0

        # Return
        return
Exemplo n.º 28
0
 def simulation_run(self,
                    model_file,
                    events_file,
                    ra=None,
                    dec=None,
                    time=[0, 1800],
                    energy=[None, None],
                    log_file='ctobssim.log',
                    force=False,
                    save=False):
     sim = ctools.ctobssim()
     sim["inmodel"] = model_file
     sim["outevents"] = events_file
     sim["seed"] = self.seed
     sim["ra"] = ra if ra else self.ra
     sim["dec"] = dec if dec else self.dec
     sim["rad"] = self.rad
     sim["tmin"] = float(time[0])
     sim["tmax"] = float(time[1])
     sim["emin"] = energy[0] if energy[0] else self.energy_min
     sim["emax"] = energy[1] if energy[1] else self.energy_max
     sim["caldb"] = self.caldb
     sim["irf"] = self.irf
     sim["logfile"] = log_file
     sim["nthreads"] = self.nthreads
     if force or not os.path.isfile(events_file):
         sim.logFileOpen()
         sim.run()
     else:
         container = gammalib.GObservations()
         gcta_obs = gammalib.GCTAObservation(events_file)
         container.append(gcta_obs)
         sim.obs(container)
         sim.obs().models(gammalib.GModels(model_file))
     saved = False
     if (save and force) or (save and not os.path.isfile(events_file)):
         sim.save()
         saved = True
         logger.info("Events file '{}' saved. time [{}-{}]".format(
             sim["outevents"].value(), time[0], time[1]))
     return sim
Exemplo n.º 29
0
def plot_obs_zeniths(ax, obsname, color, srcname, y0=-0.015):
    """
    Plot observation results

    Parameters
    ----------
    ax : pyplot
        Subplot
    obsname : str
        Observation definition XML file
    color : str
        Color string
    srcname : str
        Source name
    y0 : float, optional
        Vertical axis location of lower edge of bar
    """
    # Get zenith angle range
    zenith_min = 90.0
    zenith_max =  0.0
    obs        = gammalib.GObservations(obsname)
    for run in obs:
        zenith = run.pointing().zenith()
        if zenith < zenith_min:
            zenith_min = zenith
        if zenith > zenith_max:
            zenith_max = zenith

    # Plot filled rectangle
    x0     = zenith_min
    width  = zenith_max - zenith_min
    height = 0.006
    ax.add_patch(Rectangle((x0,y0), width, height, alpha=1,
                           facecolor=color))
    ax.text(x0+0.5*width,y0+0.5*height, srcname, fontsize=7,
            horizontalalignment='center',
            verticalalignment='center')

    # Return
    return
Exemplo n.º 30
0
    def _test_python(self):
        """
        Test csobs2caldb from Python
        """
        # Set-up csobs2caldb using "inobs" parameter
        irf = cscripts.csobs2caldb()
        irf['inobs'] = self._inobs
        irf['caldb'] = 'cta'
        irf['irf'] = 'Py1'
        irf['rootdir'] = 'caldb'
        irf['logfile'] = 'csobs2caldb_py1.log'
        irf['chatter'] = 2

        # Run csobs2caldb script and save IRF
        irf.logFileOpen()  # Make sure we get a log file
        irf.run()
        irf.save()

        # Check response
        self._check_response('cta', 'Py1')

        # Load observation container
        obs = gammalib.GObservations(self._inobs)

        # Set-up csobs2caldb using observation container
        irf = cscripts.csobs2caldb(obs)
        irf['caldb'] = 'cta'
        irf['irf'] = 'Py2'
        irf['rootdir'] = 'caldb'
        irf['logfile'] = 'csobs2caldb_py2.log'
        irf['chatter'] = 3

        # Execute csobs2caldb script
        irf.execute()

        # Check response
        self._check_response('cta', 'Py2')

        # Return
        return