source: fact/tools/pyscripts/new_pyfact/pyfact.py@ 17974

Last change on this file since 17974 was 17973, checked in by dneise, 10 years ago
deleted private stuff, that accidentally found it's way into pyfact.py
  • Property svn:executable set to *
File size: 9.5 KB
Line 
1#!/usr/bin/python -tt
2#
3# Werner Lustermann, Dominik Neise
4# ETH Zurich, TU Dortmund
5#
6import os
7import sys
8import numpy as np
9import ROOT
10
11########## BUILDING OF THE SHARED OBJECT FILES ###############################
12if __name__ == '__main__' and len(sys.argv) > 1 and 'build' in sys.argv[1]:
13 ROOT.gSystem.AddLinkedLibs("-lz")
14 root_make_string = ROOT.gSystem.GetMakeSharedLib()
15 if not "-std=c++0x" in root_make_string:
16 make_string = root_make_string.replace('$Opt', '$Opt -std=c++0x -D HAVE_ZLIB')
17 ROOT.gSystem.SetMakeSharedLib(make_string)
18 ROOT.gROOT.ProcessLine(".L extern_Mars_mcore/izstream.h+O")
19 ROOT.gROOT.ProcessLine(".L extern_Mars_mcore/fits.h+O")
20 ROOT.gROOT.ProcessLine(".L extern_Mars_mcore/zfits.h+O")
21 ROOT.gROOT.ProcessLine(".L extern_Mars_mcore/factfits.h+O")
22 if not "-std=c++0x" in root_make_string:
23 make_string = root_make_string.replace('$Opt', "$Opt -std=c++0x -D HAVE_ZLIB -D'PACKAGE_NAME=\"PACKAGE_NAME\"' "
24 "-D'PACKAGE_VERSION=\"PACKAGE_VERSION\"' -D'REVISION=\"REVISION\"' ")
25 ROOT.gSystem.SetMakeSharedLib(make_string)
26 ROOT.gROOT.ProcessLine(".L extern_Mars_mcore/DrsCalib.h+O")
27
28 ROOT.gInterpreter.GenerateDictionary("map<string,fits::Entry>","map;string;extern_Mars_mcore/fits.h")
29 ROOT.gInterpreter.GenerateDictionary("pair<string,fits::Entry>","map;string;extern_Mars_mcore/fits.h")
30 ROOT.gInterpreter.GenerateDictionary("map<string,fits::Table::Column>","map;string;extern_Mars_mcore/fits.h")
31 ROOT.gInterpreter.GenerateDictionary("pair<string,fits::Table::Column>","map;string;extern_Mars_mcore/fits.h")
32 ROOT.gInterpreter.GenerateDictionary("vector<DrsCalibrate::Step>","vector;extern_Mars_mcore/DrsCalib.h")
33
34########## USAGE #############################################################
35if __name__ == '__main__' and len(sys.argv) < 3:
36 print """ Usage:
37 ----------------------------------------------------------------------
38 To just build the shared object libs call:
39 python pyfact.py build
40
41 To build (if necessary) and open an example file
42 python -i pyfact.py /path/to/data_file.zfits /path/to/calib_file.drs.fits.gz
43
44 Any of the 3 file 'types': fits.gz zfits fits
45 should be supported.
46
47 To clean all of automatically built files, do something like:
48 rm *.so *.d AutoDict_* extern_Mars_mcore/*.so extern_Mars_mcore/*.d
49 ----------------------------------------------------------------------
50 """
51 sys.exit(1)
52
53######### START OF PYFACT MODULE ############################################
54path = os.path.dirname(os.path.realpath(__file__))
55ROOT.gSystem.Load(path+'/AutoDict_map_string_fits__Entry__cxx.so')
56ROOT.gSystem.Load(path+'/AutoDict_map_string_fits__Table__Column__cxx.so')
57ROOT.gSystem.Load(path+'/AutoDict_pair_string_fits__Entry__cxx.so')
58ROOT.gSystem.Load(path+'/AutoDict_pair_string_fits__Table__Column__cxx.so')
59ROOT.gSystem.Load(path+'/AutoDict_vector_DrsCalibrate__Step__cxx.so')
60ROOT.gSystem.Load(path+'/extern_Mars_mcore/fits_h.so')
61ROOT.gSystem.Load(path+'/extern_Mars_mcore/izstream_h.so')
62ROOT.gSystem.Load(path+'/extern_Mars_mcore/zfits_h.so')
63ROOT.gSystem.Load(path+'/extern_Mars_mcore/factfits_h.so')
64ROOT.gSystem.Load(path+'/extern_Mars_mcore/DrsCalib_h.so')
65del path
66
67class Fits( object ):
68 """ General FITS file access
69
70 Wrapper for factfits class from Mars/mcore/factfits.h
71 (factfits might not be suited to read any FITS file out there, but certainly
72 all FACT FITS files can be read using this class)
73 """
74 __module__ = 'pyfact'
75 def __init__(self, path):
76 """
77 """
78 if not os.path.exists(path):
79 raise IOError(path+' was not found')
80 self.f = ROOT.factfits(path)
81 self._make_header()
82 self._setup_columns()
83
84 def _make_header(self):
85 """
86 """
87 str_to_bool = { 'T':True, 'F':False}
88 type_conversion = { 'I' : int, 'F' : float, 'T' : str, 'B' : str_to_bool.__getitem__}
89
90 self.header = {}
91 self.header_comments = {}
92 for key,entry in self.f.GetKeys():
93 try:
94 self.header[key] = type_conversion[entry.type](entry.value)
95 except KeyError:
96 raise IOError("Error: entry type unknown.\n Is %s, but should be one of: [I,F,T,B]" % (entry.type) )
97 self.header_comments[key] = entry.comment
98
99 def _setup_columns(self):
100 """
101 """
102 col_type_to_np_type_map = { 'L' : 'b1', 'A' : 'a1', 'B' : 'i1',
103 'I' : 'i2', 'J' : 'i4', 'K' : 'i8', 'E' : 'f4', 'D' : 'f8'}
104 self.cols = {}
105 for key,col in self.f.GetColumns():
106 self.cols[key] = np.zeros(col.num, col_type_to_np_type_map[col.type])
107 if col.num != 0:
108 self.f.SetPtrAddress(key, self.cols[key])
109
110 def __iter__(self):
111 return self
112
113 def next(self, row=None):
114 """
115 """
116 if row is None:
117 if self.f.GetNextRow() == False:
118 raise StopIteration
119 else:
120 row = int(row)
121 if self.f.GetRow(row) == False:
122 raise StopIteration
123 return self
124
125class AuxFile( Fits ):
126 """ easy(?) access to FACT aux files
127 """
128 __module__ = 'pyfact'
129 def __init__(self, path, verbose=False):
130 self._verbose = verbose
131 super(AuxFile, self).__init__(path)
132
133 def _setup_columns(self):
134 col_type_to_np_type_map = { 'L' : 'b1', 'A' : 'a1', 'B' : 'i1',
135 'I' : 'i2', 'J' : 'i4', 'K' : 'i8', 'E' : 'f4', 'D' : 'f8'}
136 self._cols = {}
137 self.cols = {}
138 N = self.header['NAXIS2']
139 for key,col in self.f.GetColumns():
140 self._cols[key] = np.zeros(col.num, col_type_to_np_type_map[col.type])
141 self.cols[key] = np.zeros((N, col.num), col_type_to_np_type_map[col.type])
142 if col.num != 0:
143 self.f.SetPtrAddress(key, self._cols[key])
144
145
146 for i,row in enumerate(self):
147 if self._verbose:
148 try:
149 step = int(self._verbose)
150 except:
151 step = 10
152 if i % step == 0:
153 print "reading line", i
154
155 for key in self._cols:
156 self.cols[key][i,:] = self._cols[key]
157
158
159
160
161class RawData( Fits ):
162 """ Special raw data FITS file access (with DRS4 calibration)
163
164 During iteration the C++ method DrsCalibration::Apply is being called.
165 """
166 __module__='pyfact'
167 def __init__(self, data_path, calib_path):
168 """ -constructor-
169 *data_path* : fits or fits.gz file of the data including the path
170 *calib_path* : fits or fits.gz file containing DRS calibration data
171 """
172 super(RawData, self).__init__(data_path)
173 self.cols['CalibData'] = np.zeros( self.cols['Data'].shape, np.float32)
174 self.cols['CalibData2D'] = self.cols['CalibData'].reshape( self.header['NPIX'], -1)
175 if not self.cols['CalibData2D'].base is self.cols['CalibData']:
176 print "Error seomthing went wrong!"
177 self.drs_calibration = ROOT.DrsCalibration()
178 self.drs_calibration.ReadFitsImp( calib_path )
179
180 self.drs_calibrate = ROOT.DrsCalibrate()
181 self.list_of_previous_start_cells = []
182
183 def __iter__(self):
184 """ iterator """
185 return self
186
187 def next(self, row=None):
188 """
189 """
190 super(RawData, self).next(row)
191
192 self.drs_calibration.Apply( self.cols['CalibData'],
193 self.cols['Data'],
194 self.cols['StartCellData'],
195 self.header['NROI'])
196
197 for previous_start_cells in self.list_of_previous_start_cells:
198 self.drs_calibrate.CorrectStep(
199 self.cols['CalibData'],
200 self.header['NPIX'],
201 self.header['NROI'],
202 previous_start_cells,
203 self.cols['StartCellData'],
204 self.header['NROI']+10)
205 self.drs_calibrate.CorrectStep(
206 self.cols['CalibData'],
207 self.header['NPIX'],
208 self.header['NROI'],
209 previous_start_cells,
210 self.cols['StartCellData'],
211 3)
212 self.list_of_previous_start_cells.append(self.cols['StartCellData'])
213 if len(self.list_of_previous_start_cells) > 5:
214 self.list_of_previous_start_cells.pop(0)
215
216 for ch in range(self.header['NPIX']):
217 self.drs_calibrate.RemoveSpikes3(self.cols['CalibData2D'][ch], self.header['NROI'])
218
219 return self
220
221
222
223if __name__ == '__main__':
224 """ Example """
225 print "Example for calibrated raw-file"
226 f = RawData(sys.argv[1], sys.argv[2])
227
228 print "number of events:", f.header['NAXIS2']
229 print "date of observation:", f.header['DATE']
230 print "The files has these cols:", f.cols.keys()
231
232 for counter,row in enumerate(f):
233 print "Event Id:", row.cols['EventNum']
234 print "shape of column 'StartCellData'", row.cols['StartCellData'].shape
235 print "dtype of column 'Data'", row.cols['StartCellData'].dtype
236 if counter > 3:
237 break
238 # get next row
239 f.next()
240 print "Event Id:", f.cols['EventNum']
241 # get another row
242 f.next(10)
243 print "Event Id:", f.cols['EventNum']
244 # Go back again
245 f.next(3)
246 print "Event Id:", f.cols['EventNum']
Note: See TracBrowser for help on using the repository browser.