Exemplo n.º 1
0
def Analysis(folder,
             config,
             configgeneric=None,
             tag="",
             convtyp='-1',
             verbose=1):
    import os
    from enrico import utils
    from enrico.gtfunction import Observation
    from enrico.fitmaker import FitMaker
    import Loggin

    mes = Loggin.Message()
    """ run an analysis"""
    Obs = Observation(folder, config, tag=tag)
    if verbose:
        utils._log('SUMMARY: ' + tag)
        Obs.printSum()

    FitRunner = FitMaker(Obs, config)  ##Class
    if config['Spectrum']['FitsGeneration'] == 'yes':
        FitRunner.FirstSelection(
            configgeneric)  #Generates fits files for the coarse selection
        FitRunner.GenerateFits(
        )  #Generates fits files for the rest of the products
    return FitRunner
Exemplo n.º 2
0
def Analysis(folder, config, tag="", convtyp='-1', verbose = 1):
    """ run an analysis"""
    Obs = Observation(folder, config, convtyp, tag=tag)
    if verbose:
        utils._log('SUMMARY: ' + tag)
        Obs.printSum()
    FitRunner = FitMaker(Obs, config)##Class
    if config['Spectrum']['FitsGeneration'] == 'yes':
        FitRunner.GenerateFits() #Generates fits files
    return FitRunner
Exemplo n.º 3
0
def Analysis(folder, config, tag="", convtyp='-1', verbose=1):
    """ run an analysis"""
    Obs = Observation(folder, config, convtyp, tag=tag)
    if verbose:
        utils._log('SUMMARY: ' + tag)
        Obs.printSum()
    FitRunner = FitMaker(Obs, config)  ##Class
    if config['Spectrum']['FitsGeneration'] == 'yes':
        FitRunner.GenerateFits()  #Generates fits files
    return FitRunner
Exemplo n.º 4
0
def AppLC(infile):
    '''Main function of the apperture photometrie Lightcurve script. Read the config file and run the analysis'''
    ROOT.gROOT.SetBatch(ROOT.kTRUE)  #Batch mode

    enricodir = environ.DIRS.get('ENRICO_DIR')
    fermidir = environ.DIRS.get('FERMI_DIR')
    config = get_config(infile)

    folder = config['out']
    #Create a subfolder name LightCurve
    LCoutfolder = folder + "/" + AppLCPath
    os.system("mkdir -p " + LCoutfolder)

    #Change the ROI to the desired radius in degree, legacy 1 deg.
    try:
        config['space']['rad'] = config['AppLC']['rad']
    except NameError:
        config['space']['rad'] = 1

    Nbins = config['AppLC']['NLCbin']  #Number of bins
    #Get The time bin
    dt = (config['time']['tmax'] - config['time']['tmin']) / Nbins  #sec

    Obs = Observation(LCoutfolder, config, tag="")
    if config['AppLC']["FitsGeneration"] == "yes":
        _log('gtselect', 'Select data from library')  #run gtselect
        Obs.FirstCut()
        Obs.SelectEvents()
        _log('gtmktime',
             'Update the GTI and cut data based on ROI')  #run gtdiffresp
        Obs.MkTime()

        #Binning from data or using a fix bin size
        if config['AppLC']['binsFromData'] == "no":
            _log('gtbin', 'bin the data into a light-curve using fixe time bin'
                 )  #run gtbin
            print "Use a dt of %2.2e seconds" % (dt)
            Obs.GtLCbin(dt=dt)
        else:
            spfile = pyfits.open(Obs.eventfile)
            diff = spfile[1].data.field(9)[1:-1] - spfile[1].data.field(9)[:-2]
            dt = np.min(
                diff
            ) / 2.  ##Compute the delta T as being the min delta t between 2 events divided by 2
            timefile = LCoutfolder + "/Timebin.txt"
            MakeTimebinFile(Obs, timefile)
            _log('gtbindef', 'define de bins')  #run gtbindef
            Obs.GtBinDef(timefile)
            _log('gtbin',
                 'bin the data into a light-curve using bins based on data'
                 )  #run gtbin
            Obs.GtLCbin(dt=0)

        _log('gtexposure', 'compute the exposure')  #run gtexposure
        Obs.GtExposure()

    #Get Some usefull value here. This allow PlotAppLC to be call independently
    Nbins = config['AppLC']['NLCbin']  #Number of bins
    #Plot the results and dump into ascii files
    PlotAppLC(Nbins, LCoutfolder, Obs.lcfile)
Exemplo n.º 5
0
def Analysis(folder, config, configgeneric=None, tag="", convtyp='-1', verbose = 1):

    mes = Loggin.Message()
    """ run an analysis"""
    Obs = Observation(folder, config, tag=tag)
    if verbose:
        utils._log('SUMMARY: ' + tag)
        Obs.printSum()

    FitRunner = FitMaker(Obs, config)##Class
    if config['Spectrum']['FitsGeneration'] == 'yes':
        FitRunner.FirstSelection(configgeneric) #Generates fits files for the coarse selection
        FitRunner.GenerateFits() #Generates fits files for the rest of the products
    return FitRunner
Exemplo n.º 6
0
    def PlotTSmap(self) :
        """ Gather the results of the evaluation of 
        each pixel and fill a fits file"""
        folder = self.config['out']

        # Read the cmap produced before to get the grid for the TS map
        FitRunner = Observation(folder, self.config)
        try :
             header = pyfits.getheader(FitRunner.cmapfile)
        except :
             self.error('Count map not found.')
        data = pyfits.getdata(FitRunner.cmapfile)*0.
        npix_im = min(header['NAXIS1'],header['NAXIS2'])
        npix = min(self.config['TSMap']['npix'],npix_im)
        Xref = header['CRPIX1']
        Yref = header['CRPIX2']
        binsz = header['CDELT1']

        import string # read the results
        for i in xrange(npix):
            for j in xrange(npix):
                try : 
                    lines = open(self._PixelFile(i,j),"r").readlines()
                    Value = float(string.split(lines[0])[2])
                except :
                    self.warning("Cannot find, open or read "+self._PixelFile(i,j))
                    Value = 0.
                data[Xref+ (i-npix/2.)][Yref+ (j-npix/2.)] = Value

        # save in a fits files
        pyfits.writeto(folder+"/"+self.TSfits,data,header)
        self.info("TS Map saved in "+folder+"/"+self.TSfits)
Exemplo n.º 7
0
def Runsrcprob(config):
    config['space']['rad'] = config['srcprob']['rad']
    Obs = Observation(config['out'], config, tag="srcprob")
    _log("Summary")
    Obs.printSum()
    if config['srcprob']['FitsGeneration'] =='yes':
        _log("Select data")
        Obs.FirstCut()
        if config['analysis']['ComputeDiffrsp'] == 'yes':
            _log("Compute diffuse responses")
            Obs.DiffResps()
    _log("Run gtsrcprob")
    Obs.SrcProb()
    probfile=fits.open(Obs.Probfile)
    srclist = open(config['srcprob']['srclist'],"r").readlines()
    for src in srclist:
      proba = probfile[1].data.field(string.split(src)[0])
      energy = probfile[1].data.field("ENERGY")
      ra = probfile[1].data.field("RA")
      dec = probfile[1].data.field("DEC")
      time = probfile[1].data.field("TIME")
      indices = energy.argsort()
      mes = Loggin.Message()
      mes.info( "Results sorted by decreasing energy")
      Print(indices,config,ra,dec,proba,energy,time)
      print 
      mes.info( "Results sorted by decreasing probability")
      indices = proba.argsort()
      Print(indices,config,ra,dec,proba,energy,time)
Exemplo n.º 8
0
    def _GenFit(self):
        try:
            del self.Fit
        except:
            pass

        if self.config['Spectrum']['SummedLike'] == 'yes':
            Obs1 = Observation(self.folder, self.config, tag="FRONT")
            Obs2 = Observation(self.folder, self.config, tag="BACK")
            self.FitRunnerfront = FitMaker(Obs1, self.config)
            self.FitRunnerback = FitMaker(Obs2, self.config)
            self.FitRunnerfront.CreateLikeObject()
            self.FitRunnerback.CreateLikeObject()
            self.Fit = SummedLikelihood.SummedLikelihood()
        else:
            Obs = Observation(self.folder, self.config, tag="")
            self.FitRunner = FitMaker(Obs, self.config)  ##Class
            self.Fit = self.FitRunner.CreateLikeObject()
Exemplo n.º 9
0
def Analysis(folder, config, configgeneric=None, tag="", convtyp='-1', verbose = 1):

    mes = Loggin.Message()
    """ run an analysis"""
    # If there are no xml files, create it and print a warning <--- This should be here?
    #if len(glob.glob(config['file']['xml'].replace('.xml','*.xml')))==0:
    if len(glob.glob(config['file']['xml']))==0: #.replace('.xml','*.xml')))==0:
        mes.warning("Xml not found, creating one for the given config %s" %config['file']['xml'])
        XmlMaker(config)
    
    Obs = Observation(folder, config, tag=tag)
    if verbose:
        utils._log('SUMMARY: ' + tag)
        Obs.printSum()

    FitRunner = FitMaker(Obs, config)##Class
    if config['Spectrum']['FitsGeneration'] == 'yes':
        FitRunner.FirstSelection(configgeneric) #Generates fits files for the coarse selection
        FitRunner.GenerateFits() #Generates fits files for the rest of the products
    return FitRunner
Exemplo n.º 10
0
def FindSrc(infile):
    config = get_config(infile)
    folder = config['out']

    Obs = Observation(folder, config)
    utils._log('SUMMARY: ')
    Obs.printSum()

    FitRunner = FitMaker(Obs, config)

    if config["findsrc"]["FitsGeneration"]== "yes":
        config['analysis']['likelihood'] = 'unbinned'
        FitRunner.GenerateFits()

    FitRunner._log('gtfindsrc', 'Optimize source position')
    os.system("rm "+utils._dump_findsrcout(config))
    Obs.FindSource()
    try:
      update_reg(config)
    except:
      pass
Exemplo n.º 11
0
    def __init__(self, config):
         self.config = config
         self.folder = self.config['out']
         os.system("mkdir -p "+self.folder+"/TestModel")
         convtype = self.config['analysis']['convtype']

         if self.config['Spectrum']['SummedLike'] == 'yes':
             Obs1 = Observation(self.folder, self.config, convtype=0, tag="FRONT")
             Obs2 = Observation(self.folder, self.config, convtype=1, tag="BACK")
             FitRunnerfront = FitMaker(Obs1, self.config)
             FitRunnerback = FitMaker(Obs2, self.config)
             FitRunnerfront.CreateLikeObject()
             FitRunnerback.CreateLikeObject()
             self.Fit = SummedLikelihood.SummedLikelihood()
         else:
             Obs = Observation(self.folder, self.config, convtype, tag="")
             FitRunner = FitMaker(Obs, self.config)##Class
             self.Fit = FitRunner.CreateLikeObject()

         # Store the results in a dictionnary
         self.Results = {}
         self.Results["PowerLaw"] = 0
         self.Results["LogParabola"] = 0
         self.Results["PLSuperExpCutoff"] = 0
Exemplo n.º 12
0
 def __init__(self,config,infile):
     super(TSMap,self).__init__()
     Loggin.Message.__init__(self)
     self.config = config
     self.config['Spectrum']['FitsGeneration'] = 'no'
     self.tsfolder = self.config['out']+"/"+TSMapPath
     self.TSfits = self.config['target']['name']+'_'+self.config['file']['tag']+"_TSMap.fits"
     self.infile = infile
     self.npix = self.config['TSMap']['npix']
     # Read the cmap produced before to get the grid for the TS map
     FitRunner = Observation(self.config['out'], self.config)
     try :
          cmap = pyfits.open(FitRunner.cmapfile)
     except :
          self.error('Count map not found.')
     
     npix_im = min(cmap[0].header['NAXIS1'],cmap[0].header['NAXIS2'])
     self.npix = min(self.npix,npix_im)
     self.RAref = cmap[0].header['CRVAL1']
     self.DECref = cmap[0].header['CRVAL2']
     self.binsz = cmap[0].header['CDELT1']
Exemplo n.º 13
0
    f.tick_labels.set_style('colons')
    #f.tick_labels.set_font(size='small')
    f.axis_labels.set_xtext('Right Ascension (deg)')
    f.axis_labels.set_ytext('Declination (deg)')


try:
    infile = sys.argv[1]
except:
    "Please provide a configuration file"
    sys.exit(1)

print
config = get_config(infile)
obs = Observation(config["out"],
                  config,
                  convtyp=config['analysis']['convtype'])

counts = dict(label='Counts', filename=obs.cmapfile)
model = dict(label='Model', filename=obs.ModelMap)
residuals = dict(label='Residuals',
                 filename=config['out'] + "/" + config['target']['name'] +
                 '_Residual_Model_cmap.fits')
images = [counts, model, residuals][::-1]

# Determine image center and width / height
dpi = 2000
header = fits.getheader(images[0]['filename'])
wcs = WCS(header)
header['NAXIS1'] / dpi
header['NAXIS2'] / dpi
Exemplo n.º 14
0
    f.tick_labels.set_xformat('dd')
    f.tick_labels.set_yformat('dd')
    f.tick_labels.set_style('colons')
    #f.tick_labels.set_font(size='small')
    f.axis_labels.set_xtext('Right Ascension (deg)')
    f.axis_labels.set_ytext('Declination (deg)')

try:
  infile = sys.argv[1]
except:
  "Please provide a configuration file"
  sys.exit(1)

print 
config = get_config(infile)
obs = Observation(config["out"], config)

counts = dict(label='Counts', filename=obs.cmapfile)
model = dict(label='Model', filename=obs.ModelMap)
residuals = dict(label='Residuals', filename=config['out'] + "/" + config['target']['name']+'_Residual_Model_cmap.fits')
images = [counts, model, residuals][::-1]


# Determine image center and width / height
dpi = 2000
header = fits.getheader(images[0]['filename'])
wcs = WCS(header)
header['NAXIS1'] / dpi
header['NAXIS2'] / dpi
lon, lat = header['NAXIS1'] / 2., header['NAXIS2'] / 2.
x_center, y_center = wcs.wcs_pix2world(lon, lat, 0)