Example #1
0
    def create_from_fits(fitsfile):

        cat = Catalog()
        hdulist = pyfits.open(fitsfile)
        table = hdulist[1]

        cols = {}
        for icol, col in enumerate(table.columns.names):

            col_data = hdulist[1].data[col]
            if type(col_data[0]) == np.float32:
                cols[col] = np.array(col_data, dtype=float)
            elif type(col_data[0]) == str:
                cols[col] = np.array(col_data, dtype=str)
            elif type(col_data[0]) == np.int16:
                cols[col] = np.array(col_data, dtype=int)

        nsrc = len(hdulist[1].data)

        cat._src_radec = np.zeros(shape=(nsrc, 3))

        for i in range(nsrc):

            src = {}
            for icol, col in enumerate(cols):
                if not col in cols: continue
                src[col] = cols[col][i]

            src['Source_Name'] = src['Source_Name'].strip()
            cat.load_source(CatalogSource(src))

        return cat
Example #2
0
    def create_from_fits(fitsfile):

        cat = Catalog()
        hdulist = pyfits.open(fitsfile)
        table = hdulist[1]

        cols = {}
        for icol, col in enumerate(table.columns.names):

            col_data = hdulist[1].data[col]
            if type(col_data[0]) == np.float32: 
                cols[col] = np.array(col_data,dtype=float)
            elif type(col_data[0]) == str: 
                cols[col] = np.array(col_data,dtype=str)
            elif type(col_data[0]) == np.int16: 
                cols[col] = np.array(col_data,dtype=int)

        nsrc = len(hdulist[1].data)

        cat._src_radec = np.zeros(shape=(nsrc,3))

        for i in range(nsrc):

            src = {}
            for icol, col in enumerate(cols):
                if not col in cols: continue
                src[col] = cols[col][i]

            src['Source_Name'] = src['Source_Name'].strip()                
            cat.load_source(CatalogSource(src))

        return cat
Example #3
0
    def load_file(self, file):
        """Load PSF data from gtpsf file."""

        hdulist = pyfits.open(file)
        self._dtheta = np.array(hdulist[2].data.field(0))
        self._energy = np.array(hdulist[1].data.field(0))
        self._exps = np.array(hdulist[1].data.field(1))
        self._psf = np.array(hdulist[1].data.field(2))
Example #4
0
    def load_file(self,file):
        """Load PSF data from gtpsf file."""

        hdulist = pyfits.open(file)
        self._dtheta = np.array(hdulist[2].data.field(0))
        self._energy = np.array(hdulist[1].data.field(0))
        self._exps = np.array(hdulist[1].data.field(1))
        self._psf = np.array(hdulist[1].data.field(2))
Example #5
0
    def __init__(self,fits_file):
        
        self._hdulist = pyfits.open(fits_file)        
        hdulist = self._hdulist
        
        self.setup_axes(hdulist[1].data)
        self._aeff = np.array(hdulist[1].data[0][4])

        nx = self._cth_axis.nbins
        ny = self._energy_axis.nbins

        self._aeff.resize((nx,ny))
        self._aeff_hist = Histogram2D(self._cth_axis,self._energy_axis,
                                      counts=self._aeff,var=0)
Example #6
0
    def load_ltfile(self,ltfile):

        print 'Loading ', ltfile
        
        hdulist = pyfits.open(ltfile)
                
        if self._ltmap is None:
            self._ltmap = hdulist[1].data.field(0)
            self._tstart = hdulist[0].header['TSTART']
            self._tstop = hdulist[0].header['TSTOP']
        else:
            self._ltmap += hdulist[1].data.field(0)
            self._tstart = min(self._tstart,hdulist[0].header['TSTART'])
            self._tstop = max(self._tstop,hdulist[0].header['TSTOP'])

        cth_edges = np.array(hdulist[3].data.field(0))
        cth_edges = np.concatenate(([1],cth_edges))
        cth_edges = cth_edges[::-1]
        self._cth_axis = Axis(cth_edges)

        self._domega = (self._cth_axis.edges[1:]-
                        self._cth_axis.edges[:-1])*2*np.pi
Example #7
0
    def __init__(self,fits_file):
        
        self._hdulist = pyfits.open(fits_file)
        hdulist = self._hdulist
#        hdulist.info()
       
        self._elo = np.log10(np.array(hdulist[1].data[0][0]))
        self._ehi = np.log10(np.array(hdulist[1].data[0][1]))
        self._cthlo = np.array(hdulist[1].data[0][2])
        self._cthhi = np.array(hdulist[1].data[0][3])

        edges = np.concatenate((self._elo,np.array(self._ehi[-1],ndmin=1)))
        self._energy_axis = Axis(edges)
        edges = np.concatenate((self._cthlo,np.array(self._cthhi[-1],ndmin=1)))
        self._cth_axis = Axis(edges)
        
        
        self._center = [0.5*(self._cthlo + self._cthhi),
                        0.5*(self._elo + self._ehi)]
        
        self._bin_width = [self._cthhi-self._cthlo,
                           self._ehi-self._elo]
Example #8
0
usage = "usage: %(prog)s [options] [ft1file]"
description = "Produce a binned counts map."
parser = argparse.ArgumentParser(usage=usage,description=description)

parser.add_argument('files', nargs='+')
parser.add_argument('--prefix', default = '')
parser.add_argument('--rsmooth', default = 3.0, type=float)

args = parser.parse_args()

bexpmap_file = args.files[0]
ccube_file = args.files[1]

bexpcube = SkyCube.createFromFITS(bexpmap_file)

hdulist = pyfits.open(bexpmap_file)
ccube_hp = HealpixSkyCube.createFromFITS(ccube_file)

# Convert CAR projection to HP map
bexpcube_hp = HealpixSkyCube.create(ccube_hp.axes()[0],ccube_hp.nside)
c = bexpcube_hp.center()

print 'Interpolating'
exp = bexpcube.interpolate(c[1],c[2],c[0]).reshape(bexpcube_hp.counts.shape)

print 'Copying'
bexpcube_hp._counts = exp

flux_hp = ccube_hp/bexpcube_hp

print 'Plotting'
Example #9
0
    def __init__(self,fits_file,interpolate_density=True):

        self._interpolate_density = interpolate_density
        self._hdulist = pyfits.open(fits_file)
        hdulist = self._hdulist
#        hdulist.info()

        if re.search('front',fits_file.lower()) is not None: self._ct = 'front'
        elif re.search('back',fits_file.lower()) is not None: self._ct = 'back'
        else: self._ct = 'none'

        self.load_scaling_params(hdulist)
        
        self.setup_axes(hdulist[1].data)
        nx = self._cth_axis.nbins
        ny = self._energy_axis.nbins
        shape = (nx,ny)
        
        ncore = np.array(hdulist[1].data[0][4]).reshape(shape)
        ntail = np.array(hdulist[1].data[0][5]).reshape(shape)
        score = np.array(hdulist[1].data[0][6]).reshape(shape)
        stail = np.array(hdulist[1].data[0][7]).reshape(shape)
        gcore = np.array(hdulist[1].data[0][8]).reshape(shape)
        gtail = np.array(hdulist[1].data[0][9]).reshape(shape)        
        fcore = 1./(1.+ntail*np.power(stail/score,2))
        
        self._ncore_hist = Histogram2D(self._cth_axis,self._energy_axis,
                                       counts=ncore,var=0)
        self._ntail_hist = Histogram2D(self._cth_axis,self._energy_axis,
                                       counts=ntail,var=0)
        self._score_hist = Histogram2D(self._cth_axis,self._energy_axis,
                                       counts=score,var=0)
        self._stail_hist = Histogram2D(self._cth_axis,self._energy_axis,
                                       counts=stail,var=0)
        self._gcore_hist = Histogram2D(self._cth_axis,self._energy_axis,
                                       counts=gcore,var=0)
        self._gtail_hist = Histogram2D(self._cth_axis,self._energy_axis,
                                       counts=gtail,var=0)
        self._fcore_hist = Histogram2D(self._cth_axis,self._energy_axis,
                                       counts=fcore,var=0)

        try:
            
            fisheye_axes = IRFComponent.load_table_axes(hdulist['FISHEYE_CORRECTION'].data)[::-1]
            fisheye_shape = (fisheye_axes[0].nbins,fisheye_axes[1].nbins)
        
            fisheye_mean   = np.array(hdulist['FISHEYE_CORRECTION'].
                                      data[0][4]).reshape(fisheye_shape)
            fisheye_median = np.array(hdulist['FISHEYE_CORRECTION'].
                                      data[0][5]).reshape(fisheye_shape)
            fisheye_peak   = np.array(hdulist['FISHEYE_CORRECTION'].
                                      data[0][6]).reshape(fisheye_shape)
        except:
            fisheye_axes = (self._cth_axis,self._energy_axis)
            fisheye_mean   = np.zeros(shape)
            fisheye_median   = np.zeros(shape)
            fisheye_peak   = np.zeros(shape)

        self._mean_hist = Histogram2D(*fisheye_axes,counts=fisheye_mean,var=0)
        self._median_hist = Histogram2D(*fisheye_axes,counts=fisheye_median,
                                         var=0)
        self._peak_hist = Histogram2D(*fisheye_axes,counts=fisheye_peak,var=0)

        psf_scale = np.degrees(self.psf_scale(self._mean_hist.axis(1).center))
        
        self._mean_hist *= psf_scale
        self._median_hist *= psf_scale
        self._peak_hist *= psf_scale
        
        self._theta_axis = Axis(np.linspace(-3.0,np.log10(90.0),101))
        self._psf_hist = HistogramND([self._cth_axis,
                                      self._energy_axis,
                                      self._theta_axis])
                                     
        th = self._theta_axis.center

        for i in range(nx):
            for j in range(ny):
                x = self._cth_axis.center[i]
                y = self._energy_axis.center[j]                
                z = self.eval(10**th,y,x)
                self._psf_hist._counts[i,j] = self.eval(10**th,y,x)


        return
        plt.figure()

        egy0 = self._energy_axis.center[10]
        cth0 = self._cth_axis.center[5]

        y0 = self.eval2(10**th,egy0,cth0)
        y1 = self.eval(10**th,egy0,cth0)

        self._psf_hist.slice([0,1],[5,10]).plot(hist_style='line')
        plt.plot(th,y0)
        plt.plot(th,y1)
        plt.gca().set_yscale('log')

        plt.figure()
        self._psf_hist.interpolateSlice([0,1],[cth0,egy0]).plot(hist_style='line')
        self._psf_hist.slice([0,1],[5,10]).plot(hist_style='line')
        plt.gca().set_yscale('log')

        plt.figure()
        sh = self._psf_hist.interpolateSlice([0,1],[cth0+0.01,egy0+0.03])
        y0 = self.eval2(10**th,egy0+0.03,cth0+0.01)
        y1 = self.eval(10**th,egy0+0.03,cth0+0.01)
        y2 = sh.counts()
        y3 = self._psf_hist.interpolate(np.vstack(((cth0+0.01)*np.ones(100),
                                                   (egy0+0.03)*np.ones(100),
                                                   th)))

        sh.plot(hist_style='line')
        plt.plot(th,y0)
        plt.plot(th,y1)
        plt.plot(th,y3)
        plt.gca().set_yscale('log')

        plt.figure()
        plt.plot(th,y0/y2)
        plt.plot(th,y0/y3)
        plt.plot(th,y0/y1)
#        plt.plot(th,y2/y1)

        plt.figure()
        self._psf_hist.slice([0],[5]).plot(logz=True)

        plt.show()

        return
Example #10
0
    def load_photons(self, ft1file):

        hdulist = pyfits.open(ft1file)
        evhdu = hdulist['EVENTS']

        if self.config['max_events'] is not None:
            table = evhdu.data[0:self.config['max_events']]
        else:
            table = evhdu.data

        msk = table.field('ZENITH_ANGLE') < self.config['zmax']

        if not self.config['event_class_id'] is None:
            event_class = bitarray_to_int(table.field('EVENT_CLASS'), True)
            msk &= (event_class &
                    ((0x1) << int(self.config['event_class_id'])) > 0)

        if not self.config['event_type_id'] is None:
            event_type = bitarray_to_int(table.field('EVENT_TYPE'), True)
            msk &= (event_type &
                    ((0x1) << int(self.config['event_type_id'])) > 0)

        table = table[msk]

        if self.config['erange'] is not None:

            erange = [float(t) for t in self.config['erange'].split('/')]

            msk = ((np.log10(table.field('ENERGY')) > erange[0]) &
                   (np.log10(table.field('ENERGY')) < erange[1]))
            table = table[msk]

        if self.config['conversion_type'] is not None:

            if self.config['conversion_type'] == 'front':
                msk = table.field('CONVERSION_TYPE') == 0
            else:
                msk = table.field('CONVERSION_TYPE') == 1

            table = table[msk]

        if self.config['phase_selection'] is not None:
            msk = table.field('PULSE_PHASE') < 0
            phases = self.config['phase_selection'].split(',')
            for p in phases:
                (plo, phi) = p.split('/')
                msk |= ((table.field('PULSE_PHASE') > float(plo)) &
                        (table.field('PULSE_PHASE') < float(phi)))

            table = table[msk]

        nevent = len(table)
        print 'Loading ', ft1file, ' nevent: ', nevent

        pd = self._photon_data

        for isrc, (src_ra,
                   src_dec) in enumerate(zip(self.src_ra_deg,
                                             self.src_dec_deg)):

            vsrc = Vector3D.createLatLon(np.radians(src_dec),
                                         np.radians(src_ra))

            msk = ((table.field('DEC') > (src_dec - self.config['max_dist'])) &
                   (table.field('DEC') < (src_dec + self.config['max_dist'])))
            table_src = table[msk]

            vra = np.array(table_src.field('RA'), dtype=float)
            vdec = np.array(table_src.field('DEC'), dtype=float)

            vptz_ra = np.array(table_src.field('PtRaz'), dtype=float)
            vptz_dec = np.array(table_src.field('PtDecz'), dtype=float)

            dth = separation_angle(self.src_radec[isrc][0],
                                   self.src_radec[isrc][1], np.radians(vra),
                                   np.radians(vdec))

            print 'Applying distance max'
            msk = dth < np.radians(self.config['max_dist'])
            table_src = table_src[msk]

            vra = vra[msk]
            vdec = vdec[msk]
            vptz_ra = vptz_ra[msk]
            vptz_dec = vptz_dec[msk]

            veq = Vector3D.createLatLon(np.radians(vdec), np.radians(vra))

            eptz = Vector3D.createLatLon(np.radians(vptz_dec),
                                         np.radians(vptz_ra))

            # True incidenge angle from source
            src_theta = vsrc.separation(eptz)

            print 'Getting projected direction'
            vp = veq.project2d(vsrc)
            vx = np.degrees(vp.theta() * np.sin(vp.phi()))
            vy = -np.degrees(vp.theta() * np.cos(vp.phi()))
            vptz = eptz.project2d(vsrc)

            vp2 = copy.deepcopy(vp)
            vp2.rotatez(-vptz.phi())

            print 'Getting projected direction2'
            vx2 = np.degrees(vp2.theta() * np.sin(vp2.phi()))
            vy2 = -np.degrees(vp2.theta() * np.cos(vp2.phi()))

            #            import matplotlib.pyplot as plt

            #            print vp.theta()[:10]
            #            print vp2.theta()[:10]

            #            print np.sqrt(vx**2+vy**2)[:10]
            #            print np.sqrt(vx2**2+vy2**2)[:10]

            #            plt.figure()
            #            plt.plot(vx2,vy2,marker='o',linestyle='None')

            #            plt.gca().set_xlim(-80,80)
            #            plt.gca().set_ylim(-80,80)

            #            plt.figure()
            #            plt.plot(vx,vy,marker='o',linestyle='None')

            #            plt.show()

            #            vx2 = np.degrees(vp.theta()*np.sin(vp.phi()))
            #            vy2 = -np.degrees(vp.theta()*np.cos(vp.phi()))

            src_index = np.zeros(len(table_src), dtype=int)
            src_index[:] = isrc

            src_phase = np.zeros(len(table_src))
            if 'PULSE_PHASE' in evhdu.columns.names:
                src_phase = table_src.field('PULSE_PHASE')

            psf_core = np.zeros(len(table_src))
            if 'CTBCORE' in evhdu.columns.names:
                psf_core = list(table_src.field('CTBCORE'))

            event_type = np.zeros(len(table_src), dtype='int')
            if 'EVENT_TYPE' in evhdu.columns.names:
                event_type = bitarray_to_int(table_src.field('EVENT_TYPE'),
                                             True)

            event_class = bitarray_to_int(table_src.field('EVENT_CLASS'), True)

            pd.append('psfcore', psf_core)
            pd.append('time', table_src.field('TIME'))
            pd.append('ra', table_src.field('RA'))
            pd.append('dec', table_src.field('DEC'))
            pd.append('delta_ra', vx)
            pd.append('delta_dec', vy)
            pd.append('delta_phi', vx2)
            pd.append('delta_theta', vy2)
            pd.append('energy', np.log10(table_src.field('ENERGY')))
            pd.append('dtheta', dth[msk])
            pd.append('event_class', event_class)
            pd.append('event_type', event_type)
            pd.append('conversion_type',
                      table_src.field('CONVERSION_TYPE').astype('int'))
            pd.append('src_index', src_index)
            pd.append('phase', src_phase)

            pd.append('cth', np.cos(src_theta))
            #            pd.append('cth',np.cos(np.radians(table_src.field('THETA'))))
            #            costheta2 = np.cos(src_theta)
            #            costheta = np.cos(np.radians(table_src.field('THETA')))

            if self._phist is not None:
                import skymaps
                cthv = []
                for k in range(len(table_src)):
                    sd = skymaps.SkyDir(src_ra, src_dec)
                    pi = self._phist(table_src.field('TIME')[k])
                    cth = np.cos(pi.zAxis().difference(sd))

                    print k, pd['energy'][k], cth, np.cos(
                        theta3[k]), costheta[k]

                    cthv.append(cth)

                pd.append('cth', cthv)

        print 'Finished'
        #        print 'Loaded ', len(self.dtheta), ' events'

        hdulist.close()
Example #11
0
usage = "usage: %(prog)s [options] [FT1 file ...]"
description = """Plot the contents of a FITS image file."""

parser = argparse.ArgumentParser(usage=usage, description=description)

parser.add_argument('files', nargs='+')

parser.add_argument('--hdu',
                    default=0,
                    type=int,
                    help='Set the HDU number to plot.')

args = parser.parse_args()

hdulist = pyfits.open(args.files[0])

im = FITSImage.createFromFITS(args.files[0], args.hdu)
if isinstance(im, SkyCube):

    # Integrate over 3rd (energy) dimension
    im = im.marginalize(2)

plt.figure()

im.plot(cmap='ds9_b')

plt.figure()

# Smooth by 0.2 deg
im.smooth(0.2).plot(cmap='ds9_b')
Example #12
0
    def __init__(self,fits_file):
        
        self._hdulist = pyfits.open(fits_file)
        hdulist = self._hdulist
#        hdulist.info()

        if re.search('front',fits_file.lower()) is not None: self._ct = 'front'
        elif re.search('back',fits_file.lower()) is not None: self._ct = 'back'
        else: self._ct = 'none'

        self.load_scaling_params(hdulist)

        self.setup_axes(hdulist[1].data)
        
        self._elo = np.log10(np.array(hdulist[1].data[0][0]))
        self._ehi = np.log10(np.array(hdulist[1].data[0][1]))
        self._cthlo = np.array(hdulist[1].data[0][2])
        self._cthhi = np.array(hdulist[1].data[0][3])

        nx = self._cth_axis.nbins
        ny = self._energy_axis.nbins
        shape = (nx,ny)
        
        self._param_hists = {
            'f' : Histogram2D(self._cth_axis,self._energy_axis,
                              counts=np.array(hdulist[1].data[0][4]).reshape(shape),var=0),
            's1' : Histogram2D(self._cth_axis,self._energy_axis,
                              counts=np.array(hdulist[1].data[0][5]).reshape(shape),var=0),
            'k1' : Histogram2D(self._cth_axis,self._energy_axis,
                              counts=np.array(hdulist[1].data[0][6]).reshape(shape),var=0),
            'bias' : Histogram2D(self._cth_axis,self._energy_axis,
                              counts=np.array(hdulist[1].data[0][7]).reshape(shape),var=0),
            'bias2' : Histogram2D(self._cth_axis,self._energy_axis,
                              counts=np.array(hdulist[1].data[0][8]).reshape(shape),var=0),
            's2' : Histogram2D(self._cth_axis,self._energy_axis,
                              counts=np.array(hdulist[1].data[0][9]).reshape(shape),var=0),
            'k2' : Histogram2D(self._cth_axis,self._energy_axis,
                              counts=np.array(hdulist[1].data[0][10]).reshape(shape),var=0),
            'pindex1' : Histogram2D(self._cth_axis,self._energy_axis,
                              counts=np.array(hdulist[1].data[0][11]).reshape(shape),var=0),
            'pindex2' : Histogram2D(self._cth_axis,self._energy_axis,
                              counts=np.array(hdulist[1].data[0][12]).reshape(shape),var=0)
            }
            
        
        
        edges = np.concatenate((self._elo,np.array(self._ehi[-1],ndmin=1)))
        self._energy_axis = Axis(edges)
        edges = np.concatenate((self._cthlo,np.array(self._cthhi[-1],ndmin=1)))
        self._cth_axis = Axis(edges)
        
        
        self._center = [0.5*(self._cthlo + self._cthhi),
                        0.5*(self._elo + self._ehi)]
        
        self._bin_width = [self._cthhi-self._cthlo,
                           self._ehi-self._elo]


        self._deltae_axis = Axis(np.linspace(-1.0,1.0,1001))
        self._edisp_hist = HistogramND([self._cth_axis,
                                        self._energy_axis,
                                        self._deltae_axis])
                                     
        deltae = self._deltae_axis.center

        for i in range(nx):
            for j in range(ny):
                x = self._cth_axis.center[i]
                y = self._energy_axis.center[j]                
#                z = self.eval(y+deltae,y,x)
                self._edisp_hist._counts[i,j] = np.log10(self.eval(y+deltae,y,x))
Example #13
0
usage = "usage: %(prog)s [options] [ft1file]"
description = "Produce a binned counts map."
parser = argparse.ArgumentParser(usage=usage, description=description)

parser.add_argument('files', nargs='+')
parser.add_argument('--prefix', default='')
parser.add_argument('--rsmooth', default=3.0, type=float)

args = parser.parse_args()

bexpmap_file = args.files[0]
ccube_file = args.files[1]

bexpcube = SkyCube.createFromFITS(bexpmap_file)

hdulist = pyfits.open(bexpmap_file)
ccube_hp = HealpixSkyCube.createFromFITS(ccube_file)

# Convert CAR projection to HP map
bexpcube_hp = HealpixSkyCube.create(ccube_hp.axes()[0], ccube_hp.nside)
c = bexpcube_hp.center()

print 'Interpolating'
exp = bexpcube.interpolate(c[1], c[2], c[0]).reshape(bexpcube_hp.counts.shape)

print 'Copying'
bexpcube_hp._counts = exp

flux_hp = ccube_hp / bexpcube_hp

print 'Plotting'
Example #14
0
from gammatools.core.fits_util import FITSImage, SkyCube, SkyImage
from gammatools.fermi.catalog import Catalog

usage = "usage: %(prog)s [options] [FT1 file ...]"
description = """Plot the contents of a FITS image file."""

parser = argparse.ArgumentParser(usage=usage,description=description)

parser.add_argument('files', nargs='+')

parser.add_argument('--hdu', default = 0, type=int,
                    help = 'Set the HDU number to plot.')
 
args = parser.parse_args()

hdulist = pyfits.open(args.files[0])

im = FITSImage.createFromFITS(args.files[0],args.hdu)
if isinstance(im,SkyCube):

    # Integrate over 3rd (energy) dimension
    im = im.marginalize(2)


plt.figure()

im.plot(cmap='ds9_b')

plt.figure()

# Smooth by 0.2 deg
Example #15
-1
    def load_photons(self,ft1file):

        hdulist = pyfits.open(ft1file)
        evhdu = hdulist['EVENTS']
        
        if self.config['max_events'] is not None:
            table = evhdu.data[0:self.config['max_events']]
        else:
            table = evhdu.data

        msk = table.field('ZENITH_ANGLE')<self.config['zmax']

        if not self.config['event_class_id'] is None:
            event_class = bitarray_to_int(table.field('EVENT_CLASS'),True)
            msk &= (event_class&((0x1)<<int(self.config['event_class_id']))>0)

        if not self.config['event_type_id'] is None:
            event_type = bitarray_to_int(table.field('EVENT_TYPE'),True)
            msk &= (event_type&((0x1)<<int(self.config['event_type_id']))>0)
            
        table = table[msk]
        
        if self.config['erange'] is not None:

            erange = [float(t) for t in self.config['erange'].split('/')]
            
            msk = ((np.log10(table.field('ENERGY')) > erange[0]) &
                   (np.log10(table.field('ENERGY')) < erange[1]))
            table = table[msk]
                            
        if self.config['conversion_type'] is not None:

            if self.config['conversion_type'] == 'front':
                msk = table.field('CONVERSION_TYPE') == 0
            else:
                msk = table.field('CONVERSION_TYPE') == 1

            table = table[msk]
                
        if self.config['phase_selection'] is not None:
            msk = table.field('PULSE_PHASE')<0
            phases = self.config['phase_selection'].split(',')
            for p in phases:
                (plo,phi) = p.split('/')
                msk |= ((table.field('PULSE_PHASE')>float(plo)) & 
                        (table.field('PULSE_PHASE')<float(phi)))

            table = table[msk]
            

            
        nevent = len(table)        
        print 'Loading ', ft1file, ' nevent: ', nevent

        pd = self._photon_data
        
        for isrc, (src_ra,src_dec) in enumerate(zip(self.src_ra_deg,self.src_dec_deg)):

            vsrc = Vector3D.createLatLon(np.radians(src_dec),
                                         np.radians(src_ra))

            if self.src_names[isrc] != 'ridge':                

                msk = ((table.field('DEC')>(src_dec-self.config['max_dist'])) & 
                       (table.field('DEC')<(src_dec+self.config['max_dist'])))
                table_src = table[msk]

                vra = np.array(table_src.field('RA'),dtype=float)
                vdec = np.array(table_src.field('DEC'),dtype=float)
            
                vptz_ra = np.array(table_src.field('PtRaz'),dtype=float)
                vptz_dec = np.array(table_src.field('PtDecz'),dtype=float)
            


                dth = separation_angle(self.src_radec[isrc][0],
                                       self.src_radec[isrc][1],
                                       np.radians(vra),
                                       np.radians(vdec))

                msk = dth < np.radians(self.config['max_dist'])
                table_src = table_src[msk]

                vra = vra[msk]
                vdec = vdec[msk]
                vptz_ra = vptz_ra[msk]
                vptz_dec = vptz_dec[msk]
            
                veq = Vector3D.createLatLon(np.radians(vdec),
                                            np.radians(vra))

                eptz = Vector3D.createLatLon(np.radians(vptz_dec),
                                             np.radians(vptz_ra))

                # True incidenge angle from source
                src_theta = vsrc.separation(eptz)
                vp = veq.project2d(vsrc)
                vx = np.degrees(vp.theta()*np.sin(vp.phi()))
                vy = -np.degrees(vp.theta()*np.cos(vp.phi()))            
                vptz = eptz.project2d(vsrc)

                vp2 = copy.deepcopy(vp)
                vp2.rotatez(-vptz.phi())
                vx2 = np.degrees(vp2.theta()*np.sin(vp2.phi()))
                vy2 = -np.degrees(vp2.theta()*np.cos(vp2.phi()))  

                costheta = np.cos(src_theta)
                dth = dth[msk]
            else:
                table_src = table
                costheta = np.cos(np.radians(table_src.field('THETA')))
                vx = np.zeros(len(costheta))
                vy = np.zeros(len(costheta))
                vx2 = np.zeros(len(costheta))
                vy2 = np.zeros(len(costheta))
                dth = np.zeros(len(costheta))
                        
            src_index = np.zeros(len(table_src),dtype=int)
            src_index[:] = isrc

            src_phase = np.zeros(len(table_src))
            if 'PULSE_PHASE' in evhdu.columns.names:
                src_phase = table_src.field('PULSE_PHASE')

            psf_core = np.zeros(len(table_src))
            if 'CTBCORE' in evhdu.columns.names:
                psf_core = list(table_src.field('CTBCORE'))

            event_type = np.zeros(len(table_src),dtype='int')
            if 'EVENT_TYPE' in evhdu.columns.names:
                event_type = bitarray_to_int(table_src.field('EVENT_TYPE'),True)
            
            event_class = bitarray_to_int(table_src.field('EVENT_CLASS'),True)

            pd.append('psfcore',psf_core)
            pd.append('time',table_src.field('TIME'))
            pd.append('ra',table_src.field('RA'))
            pd.append('dec',table_src.field('DEC'))
            pd.append('glon',table_src.field('L'))
            pd.append('glat',table_src.field('B'))
            pd.append('delta_ra',vx)
            pd.append('delta_dec',vy)
            pd.append('delta_phi',vx2)
            pd.append('delta_theta',vy2)            
            pd.append('energy',np.log10(table_src.field('ENERGY')))
            pd.append('dtheta',dth)
            pd.append('event_class',event_class)
            pd.append('event_type',event_type)
            pd.append('conversion_type',
                      table_src.field('CONVERSION_TYPE').astype('int'))
            pd.append('src_index',src_index) 
            pd.append('phase',src_phase)

            pd.append('cth',costheta)
#            pd.append('cth',np.cos(np.radians(table_src.field('THETA'))))
#            costheta2 = np.cos(src_theta)
#            costheta = np.cos(np.radians(table_src.field('THETA')))

            if self._phist is not None:
                import skymaps
                cthv = []            
                for k in range(len(table_src)):
                    sd = skymaps.SkyDir(src_ra,src_dec)
                    pi = self._phist(table_src.field('TIME')[k])            
                    cth = np.cos(pi.zAxis().difference(sd))

                    print k, pd['energy'][k], cth, np.cos(theta3[k]), costheta[k]
                    
                    cthv.append(cth)

                pd.append('cth',cthv)

        print 'Finished'
#        print 'Loaded ', len(self.dtheta), ' events'
                    
        hdulist.close()