Esempio n. 1
0
def getInteractiveFigureFromCSPEC(cspecfile,**kwargs):
  trigTime                    = dataHandling.getTriggerTime(cspecfile)
  f                           = pyfits.open(cspecfile)  
  if('DETNAM' in f['SPECTRUM'].header.keys()):
    detector                  = transformGBMdetname(f['SPECTRUM'].header['DETNAM'])
  elif('LLECUT' in f['SPECTRUM'].header.keys()):
    detector                  = "LAT"
  elif('TELESCOP' in f['SPECTRUM'].keys()):
    detector                  = f['SPECTRUM'].header['TELESCOP']
  else:    
    detector                  = 'Unknown'
  pass
  s                           = f['SPECTRUM']
  
  d                           = s.data[(s.data.field('QUALITY')==0)]
  #Avoid overflow and underflow channels
  counts                      = d.field('COUNTS')[:,3:126]
  met                         = d.field('TIME')-trigTime
  exposure                    = d.field('EXPOSURE')
  N                           = len(met)
  LC                          = np.zeros(N)
  
  for i in range(N): 
    LC[i]=counts[i].sum()
  
  mask                        = (exposure > 0)
  LC[mask]                   /= exposure[mask]
  kwargs['xlabel']            = "Time since trigger"
  kwargs['ylabel']            = "Counts/s"
  kwargs['xoffset']           = trigTime
  kwargs['title']             = detector
  interactiveFigure           = InteractiveFigure(met,LC,**kwargs)
  f.close()
  
  return interactiveFigure
Esempio n. 2
0
def getInteractiveFigureFromCSPEC(cspecfile, **kwargs):
    trigTime = dataHandling.getTriggerTime(cspecfile)
    f = pyfits.open(cspecfile)
    if ('DETNAM' in f['SPECTRUM'].header.keys()):
        detector = transformGBMdetname(f['SPECTRUM'].header['DETNAM'])
    elif ('LLECUT' in f['SPECTRUM'].header.keys()):
        detector = "LAT"
    elif ('TELESCOP' in f['SPECTRUM'].keys()):
        detector = f['SPECTRUM'].header['TELESCOP']
    else:
        detector = 'Unknown'
    pass
    s = f['SPECTRUM']

    d = s.data[(s.data.field('QUALITY') == 0)]
    #Avoid overflow and underflow channels
    counts = d.field('COUNTS')[:, 3:126]
    met = d.field('TIME') - trigTime
    exposure = d.field('EXPOSURE')
    N = len(met)
    LC = np.zeros(N)

    for i in range(N):
        LC[i] = counts[i].sum()

    mask = (exposure > 0)
    LC[mask] /= exposure[mask]
    kwargs['xlabel'] = "Time since trigger"
    kwargs['ylabel'] = "Counts/s"
    kwargs['xoffset'] = trigTime
    kwargs['title'] = detector
    interactiveFigure = InteractiveFigure(met, LC, **kwargs)
    f.close()

    return interactiveFigure
Esempio n. 3
0
def run(**kwargs):
    if (len(kwargs.keys()) == 0):
        #Nothing specified, the user needs just help!
        thisCommand.getHelp()
        return
    pass

    #Get parameters values
    thisCommand.setParValuesFromDictionary(kwargs)
    try:
        intervals = thisCommand.getParValue('intervals')
        cspecfile = thisCommand.getParValue('cspecfile')
        intervalType = thisCommand.getParValue('intervaltype')
        outfile = thisCommand.getParValue('outfile')
        clobber = _yesOrNoToBool(thisCommand.getParValue('clobber'))
        verbose = _yesOrNoToBool(thisCommand.getParValue('verbose'))
        figure = thisCommand.getParValue('figure')
    except KeyError as err:
        print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %
              (err.args[0]))

        #Print help
        print thisCommand.getHelp()
        return
    pass

    message = Message(verbose)

    #Load LLE data

    trigTime = dataHandling.getTriggerTime(cspecfile)

    if (intervals[0].lower() == 'i'):
        message(" *  Get time intervals interactively...")

        if (intervalType == "background"):
            interactiveFigure = interactivePlots.getInteractiveFigureFromCSPEC(
                cspecfile,
                selectSource=False,
                selectBackground=True,
                figure=figure)
            #interactiveFigure.printHelp()
            interactiveFigure.activate()
            interactiveFigure.wait()
            #Here the user has selected its intervals
            figure.clear()
            figure.canvas.draw()
            timeIntervals = interactiveFigure.backgroundBounds
        elif (intervalType == "source"):
            interactiveFigure = interactivePlots.getInteractiveFigureFromCSPEC(
                cspecfile,
                selectSource=True,
                selectBackground=False,
                figure=figure)
            #interactiveFigure.printHelp()
            interactiveFigure.activate()
            interactiveFigure.wait()
            #Here the user has selected its intervals
            figure.clear()
            figure.canvas.draw()
            timeIntervals = interactiveFigure.sourceBounds
        pass

        message("\n    done.")
    else:
        intervals = intervals.replace(" ", "")
        userBounds = intervals.split(",")
        timeBounds = []
        for i, tt in enumerate(userBounds):
            m = re.search(
                '([-,+]?[0-9]+(\.[0-9]+)?)-([-,+]?[0-9]+(\.[0-9]+)?)', tt)
            if (m != None):
                if (m.group(1) != None and m.group(3) != None):
                    timeBounds.append(m.group(1))
                    timeBounds.append(m.group(3))
                else:
                    raise ValueError(
                        "Could not understand time intervals syntax!")
            else:
                raise ValueError("Could not understand time intervals syntax!")
        pass

        timeIntervals = map(
            lambda x: float(x) + int(float(x) < 231292801.000) * trigTime,
            timeBounds)
    pass

    if (len(timeIntervals) < 2 or float(len(timeIntervals)) % 2 != 0):
        raise commandDefiner.UserError(
            "No intervals selected, or not-even number of boundaries.")

    #Check that time intervals do not overlaps
    tstarts = timeIntervals[::2]
    tstops = timeIntervals[1::2]
    intervals = []

    for t1, t2 in zip(tstarts, tstops):
        intervals.append(dataHandling.TimeInterval(t1, t2))
    pass
    for interval1 in intervals:
        for interval2 in intervals:
            if (interval1 == interval2): continue
            if (interval1.overlapsWith(interval2)):
                raise commandDefiner.UserError(
                    "Intervals MUST be non-overlapping!")
            pass
        pass
    pass

    #Sort
    timeIntervals.sort()

    message(" *  Define ASCII file with time intervals...")
    for i, t1, t2 in zip(range(len(timeIntervals[::2])), timeIntervals[::2],
                         timeIntervals[1::2]):
        message("    Interval %s: %s - %s (%s - %s)" %
                (i + 1, t1, t2, t1 - trigTime, t2 - trigTime))
    interactivePlots.writeAsciiFile(timeIntervals, "__asciiTimeBins.txt")
    message("\n    done.")

    message(" *  Define FITS file with time intervals...")

    gtbindef = GtApp('gtbindef')
    gtbindef['bintype'] = 'T'
    gtbindef['binfile'] = "__asciiTimeBins.txt"
    gtbindef['outfile'] = outfile
    gtbindef['clobber'] = 'yes'
    gtbindef.run()

    message("\n    done.")

    os.remove("__asciiTimeBins.txt")

    message("\n%s done!" % (thisCommand.name))

    return 'outfile', outfile
Esempio n. 4
0
def run(**kwargs):  
  if(len(kwargs.keys())==0):
    #Nothing specified, the user needs just help!
    thisCommand.getHelp()
    return
  pass
    
  #Get parameters values
  thisCommand.setParValuesFromDictionary(kwargs)
  try:
    eventfile                   = thisCommand.getParValue('eventfile')
    rspfile                     = thisCommand.getParValue('rspfile')
    ft2file                     = thisCommand.getParValue('ft2file')
    srcintervals                = thisCommand.getParValue('srcintervals')
    outfile                     = thisCommand.getParValue('srcspectra')
    weightedrsp                 = thisCommand.getParValue('weightedrsp')
    clobber                     = _yesOrNoToBool(thisCommand.getParValue('clobber'))
    verbose                     = _yesOrNoToBool(thisCommand.getParValue('verbose'))
  except KeyError as err:
    print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0]))
    
    #Print help
    thisCommand.getHelp()
    return
  pass
  
  #I import this here to save time if the user makes error in the command line
  from GtBurst import dataHandling
  
  message                     = Message(verbose)
  
  #Load LLE data
  message(" *  Get energy binning from the response matrix...")
  
  lleData                     = dataHandling.LLEData(eventfile,rspfile,ft2file)
  
  message("\n    done.")
  
  #Make PHA2 with gtbin
  
  #This will use the same energy binning as in the EBOUNDS extension of the rspfile
  message("\n *  Run gtbindef and gtbin and bin in energy and time...\n")
  
  lleData.binByEnergyAndTime(srcintervals,outfile)
  message("\n    done.")
  
  #Copy some keywords from the LLE file to the PHA file
  message("\n *  Updating keywords in the headers of the PHA file...")
  
  if(lleData.isTTE):
    dataHandling.fixHeaders(eventfile,outfile)
  else:
    dataHandling.fixHeaders(eventfile,outfile,"SPECTRUM")
  message("\n    done.")
  
  message("\n *  Computing the response matrix for each interval by weighting the input matrices...")
  from GtBurst import RSPweight
  triggerTime                 = dataHandling.getTriggerTime(eventfile)
  RSPweight.RSPweight(eventfile=eventfile,timeBinsFile=srcintervals,
                      rsp2file=rspfile,outfile=os.path.abspath(weightedrsp),triggerTime=triggerTime)
  message("\n *  done.")
  
  message("\n%s done!" %(thisCommand.name))
  
  return 'srcspectra', outfile, 'weightedrsp', weightedrsp
Esempio n. 5
0
def run(**kwargs):

    if (len(kwargs.keys()) == 0):
        #Nothing specified, the user needs just help!
        thisCommand.getHelp()
        return
    pass

    #Get parameters values
    thisCommand.setParValuesFromDictionary(kwargs)
    try:
        cspecfile = thisCommand.getParValue('cspecfile')
        rspfile = thisCommand.getParValue('rspfile')
        bkgintervalsFile = thisCommand.getParValue('bkgintervals')
        srcintervalsFile = thisCommand.getParValue('srcintervals')
        outfile = thisCommand.getParValue('bkgspectra')
        clobber = _yesOrNoToBool(thisCommand.getParValue('clobber'))
        verbose = _yesOrNoToBool(thisCommand.getParValue('verbose'))
    except KeyError as err:
        print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %
              (err.args[0]))

        #Print help
        thisCommand.getHelp()
        return
    pass

    #I import this here to save time if the user makes error in the command line
    from GtBurst import dataHandling

    message = Message(verbose)

    #Load LLE data

    trigTime = dataHandling.getTriggerTime(cspecfile)

    message(" *  Reading background and source time intervals...")

    bkgIntervalsObj = dataHandling.TimeIntervalFitsFile(
        bkgintervalsFile, trigTime)
    bkgIntervals = bkgIntervalsObj.getIntervals()
    srcIntervalsObj = dataHandling.TimeIntervalFitsFile(
        srcintervalsFile, trigTime)
    srcIntervals = srcIntervalsObj.getIntervals()

    message("\n    Using bkg. time intervals:")
    if (verbose):
        print(bkgIntervalsObj)

    message("\n    Using src. time intervals:")
    if (verbose):
        print(srcIntervalsObj)

    message("\n    done.")

    message(" *  Fit background with polynomials...")

    cspecBackground = dataHandling.CspecBackground(cspecfile, rspfile)
    backPha = cspecBackground.getBackgroudSpectrum(bkgIntervals, srcIntervals)
    message("\n    done.")

    #This will use the same energy binning as in the EBOUNDS extension of the rspfile
    message("\n *  Saving the background spectra in a PHA2 file...\n")

    backPha.write(outfile, format="PHA2", clobber=clobber)

    message("\n    done.")

    #Copy some keywords from the LLE file to the CSPEC file
    message("\n *  Updating keywords in the headers of the PHA2 file...")

    dataHandling.fixHeaders(cspecfile, outfile, "SPECTRUM")
    message("\n    done.")

    message("\n%s done!" % (thisCommand.name))

    return 'bkgspectra', outfile, cspecBackground
Esempio n. 6
0
def run(**kwargs):
    if (len(kwargs.keys()) == 0):
        #Nothing specified, the user needs just help!
        thisCommand.getHelp()
        return
    pass

    #Get parameters values
    thisCommand.setParValuesFromDictionary(kwargs)
    try:
        ra = thisCommand.getParValue('ra')
        dec = thisCommand.getParValue('dec')
        particlemodel = thisCommand.getParValue('particle_model')
        galacticmodel = thisCommand.getParValue('galactic_model')
        sourcemodel = thisCommand.getParValue('source_model')
        filteredeventfile = thisCommand.getParValue('filteredeventfile')
        xmlmodel = thisCommand.getParValue('xmlmodel')
        triggername = thisCommand.getParValue('triggername')
        ft2file = thisCommand.getParValue('ft2file')
        fglmode = thisCommand.getParValue('fgl_mode')
        clobber = _yesOrNoToBool(thisCommand.getParValue('clobber'))
        verbose = _yesOrNoToBool(thisCommand.getParValue('verbose'))
    except KeyError as err:
        print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %
              (err.args[0]))

        #Print help
        print thisCommand.getHelp()
        return
    pass

    #Get the IRF from the event file
    try:
        f = pyfits.open(filteredeventfile)
    except:
        raise GtBurstException(
            31, "Could not open filtered event file %s" % (filteredeventfile))

    tstart = float(f[0].header['_TMIN'])
    tstop = float(f[0].header['_TMAX'])
    irf = str(f[0].header['_IRF'])
    ra = float(f[0].header['_ROI_RA'])
    dec = float(f[0].header['_ROI_DEC'])
    roi = float(f[0].header['_ROI_RAD'])

    #Lookup table for the models
    models = {}
    if (particlemodel == 'isotr with pow spectrum'):
        models[
            'isotr with pow spectrum'] = LikelihoodComponent.IsotropicPowerlaw(
            )
    elif (particlemodel == 'isotr template'):
        models['isotr template'] = LikelihoodComponent.IsotropicTemplate(irf)
    pass

    if (galacticmodel == 'template'):
        models['template'] = LikelihoodComponent.GalaxyAndExtragalacticDiffuse(
            irf, ra, dec, 2.5 * roi)
    elif (galacticmodel == 'template (fixed norm.)'):
        models[
            'template (fixed norm.)'] = LikelihoodComponent.GalaxyAndExtragalacticDiffuse(
                irf, ra, dec, 2.5 * roi)
        models['template (fixed norm.)'].fixNormalization()
    pass

    deltat = numpy.sum(f['GTI'].data.field('STOP') -
                       f['GTI'].data.field('START'))
    f.close()
    triggertime = dataHandling.getTriggerTime(filteredeventfile)

    if (irf.lower().find('source') >= 0 and particlemodel != 'isotr template'):
        raise GtBurstException(
            6,
            "Do not use '%s' as model for the particle background in SOURCE class. Use '%s' instead."
            % (particlemodel, 'isotropic template'))

    modelsToUse = [
        LikelihoodComponent.PointSource(ra, dec, triggername, sourcemodel)
    ]
    if (particlemodel != 'none'):
        if (particlemodel == 'bkge'):
            if (ft2file is None or ft2file == ''):
                raise ValueError(
                    "If you want to use the BKGE, you have to provide an FT2 file!"
                )

            modelsToUse.append(
                LikelihoodComponent.BKGETemplate(filteredeventfile, ft2file,
                                                 tstart, tstop, triggername,
                                                 triggertime))
        else:
            modelsToUse.append(models[particlemodel])
    if (galacticmodel != 'none'):
        modelsToUse.append(models[galacticmodel])

    xml = LikelihoodComponent.LikelihoodModel()
    xml.addSources(*modelsToUse)
    xml.writeXML(xmlmodel)

    if (fglmode == 'complete'):

        #Use a very large delta T so that
        #all FGL sources are included in the
        #xml model
        deltat = 1e12

    xml.add2FGLsources(ra, dec, float(roi) + 8.0, xmlmodel, deltat)

    dataHandling._writeParamIntoXML(xmlmodel,
                                    IRF=irf,
                                    OBJECT=triggername,
                                    RA=ra,
                                    DEC=dec)

    return 'xmlmodel', xmlmodel
Esempio n. 7
0
def run(**kwargs):
  if(len(kwargs.keys())==0):
    #Nothing specified, the user needs just help!
    thisCommand.getHelp()
    return
  pass
  
  #Get parameters values
  thisCommand.setParValuesFromDictionary(kwargs)
  try:
    intervals                   = thisCommand.getParValue('intervals')
    cspecfile                   = thisCommand.getParValue('cspecfile')
    intervalType                = thisCommand.getParValue('intervaltype')
    outfile                     = thisCommand.getParValue('outfile')
    clobber                     = _yesOrNoToBool(thisCommand.getParValue('clobber'))
    verbose                     = _yesOrNoToBool(thisCommand.getParValue('verbose'))
    figure                      = thisCommand.getParValue('figure')
  except KeyError as err:
    print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0]))
    
    #Print help
    print thisCommand.getHelp()
    return
  pass
  
  message                     = Message(verbose)
  
  #Load LLE data

  trigTime                    = dataHandling.getTriggerTime(cspecfile)
  
  if(intervals[0].lower()=='i'):
    message(" *  Get time intervals interactively...")
        
    if(intervalType=="background"):
      interactiveFigure           = interactivePlots.getInteractiveFigureFromCSPEC(cspecfile,selectSource=False,
                                                                                   selectBackground=True,
                                                                                   figure=figure)
      #interactiveFigure.printHelp()
      interactiveFigure.activate()
      interactiveFigure.wait()
      #Here the user has selected its intervals
      figure.clear()
      figure.canvas.draw()
      timeIntervals               = interactiveFigure.backgroundBounds
    elif(intervalType=="source"):
      interactiveFigure           = interactivePlots.getInteractiveFigureFromCSPEC(cspecfile,selectSource=True,
                                                                                   selectBackground=False,
                                                                                   figure=figure)
      #interactiveFigure.printHelp()
      interactiveFigure.activate()
      interactiveFigure.wait()
      #Here the user has selected its intervals
      figure.clear()
      figure.canvas.draw()
      timeIntervals               = interactiveFigure.sourceBounds
    pass
        
    message("\n    done.")
  else:
    intervals                     = intervals.replace(" ","")
    userBounds                    = intervals.split(",") 
    timeBounds                    = []
    for i,tt in enumerate(userBounds):
      m                           = re.search('([-,+]?[0-9]+(\.[0-9]+)?)-([-,+]?[0-9]+(\.[0-9]+)?)', tt)
      if(m is not None):
        if(m.group(1) is not None and m.group(3) is not None):
          timeBounds.append(m.group(1))
          timeBounds.append(m.group(3))
        else:
          raise ValueError("Could not understand time intervals syntax!")
      else:
        raise ValueError("Could not understand time intervals syntax!")
    pass

    timeIntervals                 = map(lambda x:float(x)+int(float(x) < 231292801.000)*trigTime,timeBounds)
  pass
  
  if(len(timeIntervals) < 2 or float(len(timeIntervals))%2 !=0):
    raise commandDefiner.UserError("No intervals selected, or not-even number of boundaries.")
  
  #Check that time intervals do not overlaps
  tstarts                     = timeIntervals[::2]
  tstops                      = timeIntervals[1::2]
  intervals                   = []
  
  for t1,t2 in zip(tstarts,tstops):
    intervals.append(dataHandling.TimeInterval(t1,t2))
  pass
  for interval1 in intervals:
    for interval2 in intervals:
      if(interval1==interval2): continue
      if(interval1.overlapsWith(interval2)):
        raise commandDefiner.UserError("Intervals MUST be non-overlapping!")
      pass
    pass
  pass
  
  #Sort
  timeIntervals.sort()
      
  message(" *  Define ASCII file with time intervals...")
  for i,t1,t2 in zip(range(len(timeIntervals[::2])),timeIntervals[::2],timeIntervals[1::2]):
    message("    Interval %s: %s - %s (%s - %s)" %(i+1,t1,t2,t1-trigTime,t2-trigTime))
  interactivePlots.writeAsciiFile(timeIntervals,"__asciiTimeBins.txt")
  message("\n    done.")
  
  message(" *  Define FITS file with time intervals...")
  
  gtbindef=GtApp('gtbindef')
  gtbindef['bintype']='T'
  gtbindef['binfile']="__asciiTimeBins.txt"
  gtbindef['outfile']=outfile
  gtbindef['clobber']='yes'
  gtbindef.run()
  
  message("\n    done.")
  
  os.remove("__asciiTimeBins.txt")
  
  message("\n%s done!" %(thisCommand.name))
  
  return 'outfile', outfile
Esempio n. 8
0
    def __init__(self, ft1file, skyimage, figure, obj_ra=None, obj_dec=None):
        self.skyimage = skyimage
        ft1 = pyfits.open(ft1file)
        self.events = ft1['EVENTS'].data
        self.empty = False
        if (len(self.events) == 0):
            print("No events in FT1 file %s" % (ft1file))
            self.empty = True
            #raise RuntimeError("No events in FT1 file %s" %(ft1file))
        pass

        self.obj_ra = obj_ra
        self.obj_dec = obj_dec

        #Read in the different classes of events
        self.trigtime = dataHandling.getTriggerTime(ft1file)
        time = self.events.field("TIME")
        energy = self.events.field("ENERGY")
        if (not self.empty):
            self.tmin = min(time) - self.trigtime
            self.tmax = max(time) - self.trigtime
            self.energyMin = min(energy)
            self.energyMax = max(energy)
        else:
            self.tmin = float(ft1['EVENTS'].header['TSTART'])
            self.tmax = float(ft1['EVENTS'].header['TSTOP'])
            self.energyMin = 100
            self.energyMax = 1e7
        pass

        #Get the reprocessing
        self.reprocVer = str(ft1[0].header['PROC_VER'])
        self.generateColorMap()

        #Print a summary
        irfs = numpy.array(
            map(lambda x: IRFS.fromEvclassToIRF(self.reprocVer, x),
                self.events.field("EVENT_CLASS")))
        print("")
        for irf in IRFS.PROCS[self.reprocVer]:
            try:
                n = irfs[irfs == irf].shape[0]
            except:
                n = 0
            pass
            print("%-50s %s" % ("Class %s only:" % irf, n))

        self.pickerID = None
        self.oldxmin = -1e9
        self.oldxmax = 1e9
        self.oldymin = -1e9
        self.oldymax = 1e9
        self.user_ra = None
        self.user_dec = None
        self.evtext = None

        self.figure = figure
        self.figure.clear()
        self.displayImage()
        self.initEventDisplay()
        self.displayEvents()
        self.figure.canvas.draw()
        self.connectEvents()
        ft1.close()
Esempio n. 9
0
def run(**kwargs):
  
  if(len(kwargs.keys())==0):
    #Nothing specified, the user needs just help!
    thisCommand.getHelp()
    return
  pass
  
  #Get parameters values
  thisCommand.setParValuesFromDictionary(kwargs)
  try:
    cspecfile                   = thisCommand.getParValue('cspecfile')
    rspfile                     = thisCommand.getParValue('rspfile')
    bkgintervalsFile            = thisCommand.getParValue('bkgintervals')
    srcintervalsFile            = thisCommand.getParValue('srcintervals')
    outfile                     = thisCommand.getParValue('bkgspectra')
    clobber                     = _yesOrNoToBool(thisCommand.getParValue('clobber'))
    verbose                     = _yesOrNoToBool(thisCommand.getParValue('verbose'))
  except KeyError as err:
    print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0]))
    
    #Print help
    thisCommand.getHelp()
    return
  pass
  
  #I import this here to save time if the user makes error in the command line
  from GtBurst import dataHandling
  
  message                       = Message(verbose)
  
  #Load LLE data
  
  trigTime                      = dataHandling.getTriggerTime(cspecfile)
  
  message(" *  Reading background and source time intervals...")
  
  bkgIntervalsObj               = dataHandling.TimeIntervalFitsFile(bkgintervalsFile,trigTime)
  bkgIntervals                  = bkgIntervalsObj.getIntervals()
  srcIntervalsObj               = dataHandling.TimeIntervalFitsFile(srcintervalsFile,trigTime)
  srcIntervals                  = srcIntervalsObj.getIntervals()
  
  message("\n    Using bkg. time intervals:")
  if(verbose):
    print(bkgIntervalsObj)
  
  message("\n    Using src. time intervals:")
  if(verbose):
    print(srcIntervalsObj)
  
  message("\n    done.")
  
  message(" *  Fit background with polynomials...")
  
  cspecBackground               = dataHandling.CspecBackground(cspecfile,rspfile)
  backPha                       = cspecBackground.getBackgroudSpectrum(bkgIntervals,srcIntervals)
  message("\n    done.")
    
  #This will use the same energy binning as in the EBOUNDS extension of the rspfile
  message("\n *  Saving the background spectra in a PHA2 file...\n")
  
  backPha.write(outfile,format="PHA2",clobber=clobber)
  
  message("\n    done.")
    
  #Copy some keywords from the LLE file to the CSPEC file
  message("\n *  Updating keywords in the headers of the PHA2 file...")
  
  dataHandling.fixHeaders(cspecfile,outfile,"SPECTRUM")
  message("\n    done.")
  
  message("\n%s done!" %(thisCommand.name))
  
  return 'bkgspectra', outfile, cspecBackground
Esempio n. 10
0
def run(**kwargs):
  if(len(kwargs.keys())==0):
    #Nothing specified, the user needs just help!
    thisCommand.getHelp()
    return
  pass
  
  #Get parameters values
  thisCommand.setParValuesFromDictionary(kwargs)
  try:
    ra                          = thisCommand.getParValue('ra')
    dec                         = thisCommand.getParValue('dec')
    particlemodel               = thisCommand.getParValue('particle_model')
    galacticmodel               = thisCommand.getParValue('galactic_model')
    sourcemodel                 = thisCommand.getParValue('source_model')
    filteredeventfile           = thisCommand.getParValue('filteredeventfile')
    xmlmodel                    = thisCommand.getParValue('xmlmodel')
    triggername                 = thisCommand.getParValue('triggername')
    ft2file                     = thisCommand.getParValue('ft2file')
    fglmode                     = thisCommand.getParValue('fgl_mode')
    clobber                     = _yesOrNoToBool(thisCommand.getParValue('clobber'))
    verbose                     = _yesOrNoToBool(thisCommand.getParValue('verbose'))
  except KeyError as err:
    print("\n\nERROR: Parameter %s not found or incorrect! \n\n" %(err.args[0]))
    
    #Print help
    print thisCommand.getHelp()
    return
  pass
  
  #Get the IRF from the event file
  try:
    f                             = pyfits.open(filteredeventfile)
  except:
    raise GtBurstException(31,"Could not open filtered event file %s" %(filteredeventfile))
  
  tstart                        = float(f[0].header['_TMIN'])
  tstop                         = float(f[0].header['_TMAX'])
  irf                           = str(f[0].header['_IRF'])
  ra                            = float(f[0].header['_ROI_RA'])
  dec                           = float(f[0].header['_ROI_DEC'])
  roi                           = float(f[0].header['_ROI_RAD'])
  
  #Lookup table for the models
  models = {}
  if(particlemodel=='isotr with pow spectrum'):
    models['isotr with pow spectrum'] = LikelihoodComponent.IsotropicPowerlaw()
  elif(particlemodel=='isotr template'):
    models['isotr template']          = LikelihoodComponent.IsotropicTemplate(irf)
  pass
  
  if(galacticmodel=='template'):
    models['template']                = LikelihoodComponent.GalaxyAndExtragalacticDiffuse(irf,ra,dec,2.5*roi)
  elif(galacticmodel=='template (fixed norm.)'):
    models['template (fixed norm.)']  = LikelihoodComponent.GalaxyAndExtragalacticDiffuse(irf,ra,dec,2.5*roi)
    models['template (fixed norm.)'].fixNormalization()
  pass
  
  deltat                        = numpy.sum(f['GTI'].data.field('STOP')-f['GTI'].data.field('START'))
  f.close()
  triggertime                   = dataHandling.getTriggerTime(filteredeventfile)
  
  if(irf.lower().find('source')>=0 and particlemodel!='isotr template'):
    raise GtBurstException(6,"Do not use '%s' as model for the particle background in SOURCE class. Use '%s' instead." 
                     %(particlemodel,'isotropic template'))
  
  modelsToUse                   = [LikelihoodComponent.PointSource(ra,dec,triggername,sourcemodel)]
  if(particlemodel!='none'):
    if(particlemodel=='bkge'):
      if(ft2file is None or ft2file==''):
        raise ValueError("If you want to use the BKGE, you have to provide an FT2 file!")
      
      modelsToUse.append(LikelihoodComponent.BKGETemplate(filteredeventfile,
                                                          ft2file,tstart,tstop,triggername,triggertime))
    else:
      modelsToUse.append(models[particlemodel])
  if(galacticmodel!='none'):
    modelsToUse.append(models[galacticmodel])
  
  xml                          = LikelihoodComponent.LikelihoodModel()
  xml.addSources(*modelsToUse)
  xml.writeXML(xmlmodel)
  
  if(fglmode=='complete'):
    
    #Use a very large delta T so that 
    #all FGL sources are included in the
    #xml model
    deltat                     = 1e12
  
  xml.add2FGLsources(ra,dec,float(roi)+8.0,xmlmodel,deltat)
    
  
  dataHandling._writeParamIntoXML(xmlmodel,IRF=irf,OBJECT=triggername,RA=ra,DEC=dec)
    
  return 'xmlmodel', xmlmodel
Esempio n. 11
0
  def __init__(self,ft1file,skyimage,figure,obj_ra=None,obj_dec=None):
    self.skyimage             = skyimage
    ft1                       = pyfits.open(ft1file)
    self.events               = ft1['EVENTS'].data
    self.empty                = False
    if(len(self.events)==0):
      print("No events in FT1 file %s" %(ft1file))
      self.empty              = True
      #raise RuntimeError("No events in FT1 file %s" %(ft1file))
    pass
    
    self.obj_ra               = obj_ra
    self.obj_dec              = obj_dec
    
    #Read in the different classes of events
    self.trigtime             = dataHandling.getTriggerTime(ft1file)
    time                      = self.events.field("TIME")
    energy                    = self.events.field("ENERGY")
    if(not self.empty):
      self.tmin                 = min(time)-self.trigtime
      self.tmax                 = max(time)-self.trigtime
      self.energyMin            = min(energy)
      self.energyMax            = max(energy)
    else:
      self.tmin               = float(ft1['EVENTS'].header['TSTART'])
      self.tmax               = float(ft1['EVENTS'].header['TSTOP'])
      self.energyMin          = 100
      self.energyMax          = 1e7
    pass
    
    #Get the reprocessing
    self.reprocVer            = str(ft1[0].header['PROC_VER'])
    self.generateColorMap()
    
    #Print a summary
    irfs                      = numpy.array(map(lambda x:IRFS.fromEvclassToIRF(self.reprocVer,x),self.events.field("EVENT_CLASS")))
    print("")
    for irf in IRFS.PROCS[self.reprocVer]:
      try:
        n                     = irfs[irfs==irf].shape[0]
      except:
        n                     = 0
      pass
      print("%-50s %s" %("Class %s only:" % irf,n))

    
    self.pickerID             = None
    self.oldxmin              = -1e9
    self.oldxmax              = 1e9
    self.oldymin              = -1e9
    self.oldymax              = 1e9
    self.user_ra              = None
    self.user_dec             = None
    self.evtext               = None
    
    self.figure               = figure
    self.figure.clear()
    self.displayImage()
    self.initEventDisplay()
    self.displayEvents()
    self.figure.canvas.draw()
    self.connectEvents()
    ft1.close()