Ignore:
Timestamp:
09/24/14 12:45:47 (10 years ago)
Author:
dneise
Message:
added convenience class AuxFile
File:
1 edited

Legend:

Unmodified
Added
Removed
  • fact/tools/pyscripts/new_pyfact/pyfact.py

    r17842 r17972  
    88import numpy as np
    99import ROOT
    10 
     10import pylab
     11
     12from scipy.signal import firwin, iirdesign, lfilter
    1113
    1214########## BUILDING OF THE SHARED OBJECT FILES ###############################
     
    3941    To just build the shared object libs call:
    4042    python pyfact.py build
    41    
     43
    4244    To build (if necessary) and open an example file
    4345    python -i pyfact.py /path/to/data_file.zfits /path/to/calib_file.drs.fits.gz
    44    
     46
    4547    Any of the 3 file 'types': fits.gz    zfits    fits
    4648    should be supported.
    47    
     49
    4850    To clean all of automatically built files, do something like:
    4951    rm *.so *.d AutoDict_* extern_Mars_mcore/*.so extern_Mars_mcore/*.d
     
    6870class Fits( object ):
    6971    """ General FITS file access
    70    
    71     Wrapper for factfits class from Mars/mcore/factfits.h 
     72
     73    Wrapper for factfits class from Mars/mcore/factfits.h
    7274    (factfits might not be suited to read any FITS file out there, but certainly
    7375    all FACT FITS files can be read using this class)
     
    8284        self._make_header()
    8385        self._setup_columns()
    84    
     86
    8587    def _make_header(self):
    8688        """
     
    9799                raise IOError("Error: entry type unknown.\n Is %s, but should be one of: [I,F,T,B]" % (entry.type) )
    98100            self.header_comments[key] = entry.comment
    99    
     101
    100102    def _setup_columns(self):
    101103        """
     
    113115
    114116    def next(self, row=None):
    115         """ 
     117        """
    116118        """
    117119        if row is None:
     
    124126        return self
    125127
    126    
    127    
     128class AuxFile( Fits ):
     129    """ easy(?) access to FACT aux files
     130    """
     131    __module__ = 'pyfact'
     132    def __init__(self, path, verbose=False):
     133        self._verbose = verbose
     134        super(AuxFile, self).__init__(path)
     135
     136    def _setup_columns(self):
     137        col_type_to_np_type_map = { 'L' : 'b1',  'A' : 'a1', 'B' : 'i1',
     138            'I' : 'i2', 'J' : 'i4', 'K' : 'i8', 'E' : 'f4', 'D' : 'f8'}
     139        self._cols = {}
     140        self.cols = {}
     141        N = self.header['NAXIS2']
     142        for key,col in self.f.GetColumns():
     143            self._cols[key] = np.zeros(col.num, col_type_to_np_type_map[col.type])
     144            self.cols[key] = np.zeros((N, col.num), col_type_to_np_type_map[col.type])
     145            if col.num != 0:
     146                self.f.SetPtrAddress(key, self._cols[key])
     147
     148
     149        for i,row in enumerate(self):
     150            if self._verbose:
     151                try:
     152                    step = int(self._verbose)
     153                except:
     154                    step = 10
     155                if i % step == 0:
     156                    print "reading line", i
     157
     158            for key in self._cols:
     159                self.cols[key][i,:] = self._cols[key]
     160
     161
     162
     163
    128164class RawData( Fits ):
    129165    """ Special raw data FITS file access (with DRS4 calibration)
    130        
     166
    131167        During iteration the C++ method DrsCalibration::Apply is being called.
    132168    """
     
    144180        self.drs_calibration = ROOT.DrsCalibration()
    145181        self.drs_calibration.ReadFitsImp( calib_path )
    146        
     182
    147183        self.drs_calibrate = ROOT.DrsCalibrate()
    148184        self.list_of_previous_start_cells = []
     
    153189
    154190    def next(self, row=None):
    155         """ 
     191        """
    156192        """
    157193        super(RawData, self).next(row)
    158        
    159         self.drs_calibration.Apply( self.cols['CalibData'], 
    160                                     self.cols['Data'], 
    161                                     self.cols['StartCellData'], 
     194
     195        self.drs_calibration.Apply( self.cols['CalibData'],
     196                                    self.cols['Data'],
     197                                    self.cols['StartCellData'],
    162198                                    self.header['NROI'])
    163        
     199
    164200        for previous_start_cells in self.list_of_previous_start_cells:
    165201            self.drs_calibrate.CorrectStep(
    166                                 self.cols['CalibData'], 
    167                                 self.header['NPIX'], 
    168                                 self.header['NROI'], 
    169                                 previous_start_cells, 
    170                                 self.cols['StartCellData'], 
     202                                self.cols['CalibData'],
     203                                self.header['NPIX'],
     204                                self.header['NROI'],
     205                                previous_start_cells,
     206                                self.cols['StartCellData'],
    171207                                self.header['NROI']+10)
    172208            self.drs_calibrate.CorrectStep(
    173                                 self.cols['CalibData'], 
    174                                 self.header['NPIX'], 
    175                                 self.header['NROI'], 
    176                                 previous_start_cells, 
    177                                 self.cols['StartCellData'], 
     209                                self.cols['CalibData'],
     210                                self.header['NPIX'],
     211                                self.header['NROI'],
     212                                previous_start_cells,
     213                                self.cols['StartCellData'],
    178214                                3)
    179215        self.list_of_previous_start_cells.append(self.cols['StartCellData'])
     
    192228    print "Example for calibrated raw-file"
    193229    f = RawData(sys.argv[1], sys.argv[2])
    194    
     230
    195231    print "number of events:", f.header['NAXIS2']
    196232    print "date of observation:", f.header['DATE']
    197233    print "The files has these cols:", f.cols.keys()
    198    
     234
    199235    for counter,row in enumerate(f):
    200236        print "Event Id:", row.cols['EventNum']
     
    212248    f.next(3)
    213249    print "Event Id:", f.cols['EventNum']
    214    
     250
    215251    import matplotlib.pyplot as plt
    216252    plt.ion()
     253    """
    217254    for i in range(f.header['NPIX']):
    218255        plt.cla()
     
    223260        if 'q' in answer.lower():
    224261            break
    225 
     262    """
     263
     264
     265
     266    from scipy import signal
     267    from scipy.signal import freqs, iirfilter
     268    #b, a = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1')
     269    #b, a = signal.iirfilter(17, [50, 200], rs=60, btype='band',
     270    #                                analog=True, ftype='cheby2')
     271    #w, h = signal.freqs(b, a, 1000)
     272    #w, h = freqs(b, a, worN=np.logspace(-1, 2, 1000))
     273
     274    b, a = iirfilter(N=4, # the order of the filter
     275            Wn = [0.15, 0.25], # critical frequencies
     276            rp = 1,       # maximum ripple in passband
     277            rs = 60,      # minimum attenuation in stopband
     278            btype='bandstop', # {'bandpass', 'lowpass', 'highpass', 'bandstop'}
     279            #analog=True,
     280            ftype='cheby1')
     281    #w, h = freqs(b, a, worN=np.logspace(-1, 5, 1000))
     282    w, h = freqs(b, a)
     283    plt.figure()
     284    plt.semilogx(w, 20 * np.log10(abs(h)))
     285    plt.xlabel('Frequency')
     286    plt.ylabel('Amplitude response [dB]')
     287    plt.grid()
     288    plt.show()
     289
     290
     291
     292
     293
     294    fig1, (ax11,ax12) = plt.subplots(nrows=2)
     295    fig2, (ax21,ax22) = plt.subplots(nrows=2)
     296
     297    flt = firwin(13, [0.15,0.25])
     298    t = np.arange(f.cols['CalibData2D'].shape[1])/2.*1e-9
     299    fig3, (ax31, ax32) = plt.subplots(nrows=2)
     300    ax31.plot(flt)
     301    #w, h = freqs(flt, [1.0])
     302    w, h = freqs(flt, [1.0], worN=np.logspace(-1, 5, 1000))
     303    ax32.semilogx(w, 20 * np.log10(abs(h)))
     304    ax32.set_xlabel('Frequency')
     305    ax32.set_ylabel('Amplitude response [dB]')
     306    ax32.grid()
     307
     308
     309
     310    for i in range(f.header['NPIX']):
     311        data = f.cols['CalibData2D'][i]
     312        fil_data = lfilter(flt, [1.0], data)
     313
     314        ax11.cla()
     315        ax12.cla()
     316        ax11.set_title("Event %d"%(f.cols['EventNum']))
     317        ax11.plot(t, data, '.:', label='pixel %d'%i)
     318        ax11.legend()
     319        ax11.set_ylim(-20,40)
     320        ax12.plot(t[:fil_data.size], fil_data, '.:', label='pixel %d'%i)
     321        ax12.legend()
     322        ax12.set_ylim(-20,40)
     323
     324        """
     325        Pxx, freqs, t, plot = pylab.specgram( f.cols['CalibData2D'][i],
     326                NFFT=32, Fs=2000000000,
     327                detrend=pylab.detrend_none,
     328                window=pylab.window_hanning,
     329                noverlap=16)
     330        """
     331        ax21.cla()
     332        ax22.cla()
     333        dat, freqs, bins, im = ax21.specgram(data,
     334                NFFT=64, Fs=2000000000,
     335                detrend=pylab.detrend_none,
     336                window=pylab.window_hanning,
     337                noverlap=60,
     338                interpolation='nearest')
     339        ax21.axis('tight')
     340        ax21.set_ylabel("frequency [Hz]")
     341        ax21.set_xlabel("time [s]")
     342
     343        dat2, freqs2, bins2, im2 = ax22.specgram(data,
     344                NFFT=64, Fs=2000000000,
     345                detrend=pylab.detrend_none,
     346                window=pylab.window_hanning,
     347                noverlap=60,
     348                interpolation='nearest')
     349        ax22.axis('tight')
     350        ax22.set_ylabel("frequency [Hz]")
     351        ax22.set_xlabel("time [s]")
     352
     353        plt.show()
     354
     355        answer = raw_input('anykey for next pixel; "q" to quit. :')
     356        if 'q' in answer.lower():
     357            break
Note: See TracChangeset for help on using the changeset viewer.