source: fact/tools/pyscripts/pyfact/pyfact_rename.py@ 12898

Last change on this file since 12898 was 12896, checked in by lusterma, 13 years ago
corrections to pyfact coding style
  • Property svn:executable set to *
File size: 11.7 KB
Line 
1#!/usr/bin/python
2#
3# Werner Lustermann
4# ETH Zurich
5#
6from ctypes import *
7import numpy as np
8from scipy import signal
9
10# get the ROOT stuff + my shared libs
11from ROOT import gSystem
12# fitslib.so is made from fits.h and is used to access the data
13gSystem.Load('~/py/fitslib.so')
14from ROOT import *
15
16
17class RawData( object ):
18 """ raw data access and calibration
19
20 - open raw data file and drs calibration file
21 - performs amplitude calibration
22 - performs baseline substraction if wanted
23 - provides all data in an array:
24 row = number of pixel
25 col = length of region of interest
26
27 """
28
29 def __init__(self, data_file_name,
30 calib_file_name, baseline_file_name=''):
31 """ initialize object
32
33 open data file and calibration data file
34 get basic information about the data in data_file_name
35 allocate buffers for data access
36
37 data_file_name : fits or fits.gz file of the data including the path
38 calib_file_name : fits or fits.gz file containing DRS calibration data
39 baseline_file_name : npy file containing the baseline values
40
41 """
42
43 self.data_file_name = data_file_name
44 self.calib_file_name = calib_file_name
45 self.baseline_file_name = baseline_file_name
46
47 # baseline correction: True / False
48 if len(baseline_file_name) == 0:
49 self.correct_baseline = False
50 else:
51 self.correct_baseline = True
52
53 # access data file
54 try:
55 data_file = fits(self.data_file_name)
56 except IOError:
57 print 'problem accessing data file: ', data_file_name
58 raise # stop ! no data
59 #: data file (fits object)
60 self.data_file = data_file
61
62 # get basic information about the data file
63 #: region of interest (number of DRS slices read)
64 self.nroi = data_file.GetUInt('NROI')
65 #: number of pixels (should be 1440)
66 self.npix = data_file.GetUInt('NPIX')
67 #: number of events in the data run
68 self.nevents = data_file.GetNumRows()
69
70 # allocate the data memories
71 self.event_id = c_ulong()
72 self.trigger_type = c_ushort()
73 #: 1D array with raw data
74 self.data = np.zeros( self.npix * self.nroi, np.int16 )
75 #: slice where drs readout started
76 self.start_cells = np.zeros( self.npix, np.int16 )
77
78 # set the pointers to the data++
79 data_file.SetPtrAddress('Event ID', self.event_id)
80 data_file.SetPtrAddress('TriggerType', self.trigger_type)
81 data_file.SetPtrAddress('StartCellData', self.start_cells)
82 data_file.SetPtrAddress('Data', self.data)
83
84 # open the calibration file
85 try:
86 calib_file = fits(self.calib_file_name)
87 except IOError:
88 print 'problem accessing calibration file: ', calib_file_name
89 raise
90 #: drs calibration file
91 self.calib_file = calib_file
92
93 baseline_mean = calib_file.GetN('BaselineMean')
94 gain_mean = calib_file.GetN('GainMean')
95 trigger_offset_mean = calib_file.GetN('TriggerOffsetMean')
96
97 self.blm = np.zeros(baseline_mean, np.float32)
98 self.gm = np.zeros(gain_mean, np.float32)
99 self.tom = np.zeros(trigger_offset_mean, np.float32)
100
101 self.Nblm = baseline_mean / self.npix
102 self.Ngm = gain_mean / self.npix
103 self.Ntom = trigger_offset_mean / self.npix
104
105 calib_file.SetPtrAddress('BaselineMean', self.blm)
106 calib_file.SetPtrAddress('GainMean', self.gm)
107 calib_file.SetPtrAddress('TriggerOffsetMean', self.tom)
108 calib_file.GetRow(0)
109
110 self.v_bsl = np.zeros(self.npix) # array of baseline values (all ZERO)
111 self.data_saverage_out = None
112 self.maxPos = None
113 self.maxAmp = None
114
115 def next_event(self):
116 """ load the next event from disk and calibrate it
117
118 """
119
120 self.data_file.GetNextRow()
121 self.calibrate_drs_amplitude()
122
123 def calibrate_drs_amplitude(self):
124 """ perform the drs amplitude calibration of the event data
125
126 """
127
128 to_mV = 2000./4096.
129 #: 2D array with amplitude calibrated dat in mV
130 acal_data = self.data * to_mV # convert ADC counts to mV
131
132 # make 2D arrays: row = pixel, col = drs_slice
133 acal_data = np.reshape(acal_data, (self.npix, self.nroi) )
134 blm = np.reshape(self.blm, (self.npix, 1024) )
135 tom = np.reshape(self.tom, (self.npix, 1024) )
136 gm = np.reshape(self.gm, (self.npix, 1024) )
137
138 for pixel in range( self.npix ):
139 # rotate the pixel baseline mean to the Data startCell
140 blm_pixel = np.roll( blm[pixel,:], -self.start_cells[pixel] )
141 acal_data[pixel,:] -= blm_pixel[0:self.nroi]
142 acal_data[pixel,:] -= tom[pixel, 0:self.nroi]
143 acal_data[pixel,:] /= gm[pixel, 0:self.nroi]
144
145 self.acal_data = acal_data * 1907.35
146
147
148 def filter_sliding_average(self, window_size=4):
149 """ sliding average filter
150
151 using:
152 self.acal_data
153 filling array:
154 self.data_saverage_out
155
156 """
157
158 #scipy.signal.lfilter(b, a, x, axis=-1, zi=None)
159 data_saverage_out = self.acal_data.copy()
160 b = np.ones( window_size )
161 a = np.zeros( window_size )
162 a[0] = len(b)
163 data_saverage_out[:,:] = signal.lfilter(b, a, data_saverage_out[:,:])
164
165 #: data output of sliding average filter
166 self.data_saverage_out = data_saverage_out
167
168
169 def filter_CFD(self, length=10, ratio=0.75):
170 """ constant fraction discriminator (implemented as FIR)
171
172 using:
173 self.data_saverage_out
174 filling array:
175 self.data_CFD_out
176
177 """
178
179 if self.data_saverage_out == None:
180 print """error pyfact.filter_CFD was called without
181 prior call to filter_sliding_average
182 variable self.data_saverage_out is needed
183 """
184
185 data_CFD_out = self.data_saverage_out.copy()
186 b = np.zeros(length)
187 a = np.zeros(length)
188 b[0] = -1. * ratio
189 b[length-1] = 1.
190 a[0] = 1.
191 data_CFD_out[:,:] = signal.lfilter(b, a, data_CFD_out[:,:])
192
193 #: data output of the constant fraction discriminator
194 self.data_CFD_out = data_CFD_out
195
196 def find_peak(self, min=30, max=250):
197 """ find maximum in search window
198
199 using:
200 self.data_saverage_out
201 filling arrays:
202 self.maxPos
203 self.maxAmp
204
205 """
206
207 if self.data_saverage_out == None:
208 print 'error pyfact.find_peakMax was called without prior call to filter_sliding_average'
209 print ' variable self.data_saverage_out is needed '
210 pass
211
212 maxPos = np.argmax( self.data_saverage_out[:,min:max], 1)
213 maxAmp = np.max( self.data_saverage_out[:,min:max], 1)
214 self.maxPos = maxPos
215 self.maxAmp = maxAmp
216
217 def sum_around_peak(self, left=13, right=23):
218 """ integrate signal in gate around Peak
219
220 using:
221 self.maxPos
222 self.acal_data
223 filling array:
224 self.sums
225
226 """
227
228 if self.maxPos == None:
229 print 'error pyfact.sum_around_peak was called without prior call of find_peak'
230 print ' variable self.maxPos is needed'
231 pass
232
233 # find left and right limit and sum the amplitudes in the range
234 sums = np.empty(self.npix)
235 for pixel in range(self.npix):
236 min = self.maxPos[pixel]-left
237 max = self.maxPos[pixel]+right
238 sums[pixel] = self.acal_data[pixel,min:max].sum()
239
240 self.sums = sums
241
242 def baseline_read_values(self, file, bsl_hist='bsl_sum/hplt_mean'):
243 """
244
245 open ROOT file with baseline histogram and read baseline values
246 file name of the root file
247 bsl_hist path to the histogram containing the basline values
248
249 """
250
251 try:
252 f = TFile(file)
253 except:
254 print 'Baseline data file could not be read: ', file
255 return
256
257 h = f.Get(bsl_hist)
258
259 for i in range(self.npix):
260 self.v_bsl[i] = h.GetBinContent(i+1)
261
262 f.Close()
263
264 def baseline_correct(self):
265 """ subtract baseline from the data
266
267 """
268
269 for pixel in range(self.npix):
270 self.acal_data[pixel,:] -= self.v_bsl[pixel]
271
272 def info(self):
273 """ print run information
274
275 """
276
277 print 'data file: ', data_file_name
278 print 'calib file: ', calib_file_name
279 print 'calibration file'
280 print 'N baseline_mean: ', self.Nblm
281 print 'N gain mean: ', self.Ngm
282 print 'N TriggeroffsetMean: ', self.Ntom
283
284# --------------------------------------------------------------------------------
285class fnames( object ):
286 """ organize file names of a FACT data run
287
288 """
289
290 def __init__(self, specifier = ['012', '023', '2011', '11', '24'],
291 rpath = '/scratch_nfs/res/bsl/',
292 zipped = True):
293 """
294 specifier : list of strings defined as:
295 [ 'DRS calibration file', 'Data file', 'YYYY', 'MM', 'DD']
296
297 rpath : directory path for the results; YYYYMMDD will be appended to rpath
298 zipped : use zipped (True) or unzipped (Data)
299
300 """
301
302 self.specifier = specifier
303 self.rpath = rpath
304 self.zipped = zipped
305
306 self.make( self.specifier, self.rpath, self.zipped )
307
308
309 def make( self, specifier, rpath, zipped ):
310 """ create (make) the filenames
311
312 names : dictionary of filenames, tags { 'data', 'drscal', 'results' }
313 data : name of the data file
314 drscal : name of the drs calibration file
315 results : radikal of file name(s) for results (to be completed by suffixes)
316 """
317
318 self.specifier = specifier
319
320 if zipped:
321 dpath = '/data00/fact-construction/raw/'
322 ext = '.fits.gz'
323 else:
324 dpath = '/data03/fact-construction/raw/'
325 ext = '.fits'
326
327 year = specifier[2]
328 month = specifier[3]
329 day = specifier[4]
330
331 yyyymmdd = year + month + day
332 dfile = specifier[1]
333 cfile = specifier[0]
334
335 rpath = rpath + yyyymmdd + '/'
336 self.rpath = rpath
337 self.names = {}
338
339 tmp = dpath + year + '/' + month + '/' + day + '/' + yyyymmdd + '_'
340 self.names['data'] = tmp + dfile + ext
341 self.names['drscal'] = tmp + cfile + '.drs' + ext
342 self.names['results'] = rpath + yyyymmdd + '_' + dfile + '_' + cfile
343
344 self.data = self.names['data']
345 self.drscal = self.names['drscal']
346 self.results = self.names['results']
347
348 def info( self ):
349 """ print complete filenames
350
351 """
352
353 print 'file names:'
354 print 'data: ', self.names['data']
355 print 'drs-cal: ', self.names['drscal']
356 print 'results: ', self.names['results']
357
358# end of class definition: fnames( object )
359
360if __name__ == '__main__':
361 """
362 create an instance
363 """
364 data_file_name = '/data03/fact-construction/raw/2011/11/24/20111124_121.fits'
365 calib_file_name = '/data03/fact-construction/raw/2011/11/24/20111124_111.drs.fits'
366 rd = rawdata( data_file_name, calib_file_name )
367 rd.info()
368 rd.next()
369
370# for i in range(10):
371# df.GetNextRow()
372
373# print 'evNum: ', evNum.value
374# print 'start_cells[0:9]: ', start_cells[0:9]
375# print 'evData[0:9]: ', evData[0:9]
Note: See TracBrowser for help on using the repository browser.