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