##// END OF EJS Templates
merge with BLTR and Madrigal modules
Juan C. Espinoza -
r1032:c711a14430f7 merge
parent child
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -0,0 +1,404
1 '''
2
3 $Author: murco $
4 $Id: JROHeaderIO.py 151 2012-10-31 19:00:51Z murco $
5 '''
6 import sys
7 import numpy
8 import copy
9 import datetime
10 from __builtin__ import None
11
12 SPEED_OF_LIGHT = 299792458
13 SPEED_OF_LIGHT = 3e8
14
15 FILE_STRUCTURE = numpy.dtype([ #HEADER 48bytes
16 ('FileMgcNumber','<u4'), #0x23020100
17 ('nFDTdataRecors','<u4'), #No Of FDT data records in this file (0 or more)
18 ('RadarUnitId','<u4'),
19 ('SiteName','<s32'), #Null terminated
20 ])
21
22 RECORD_STRUCTURE = numpy.dtype([ #RECORD HEADER 180+20N bytes
23 ('RecMgcNumber','<u4'), #0x23030001
24 ('RecCounter','<u4'), #Record counter(0,1, ...)
25 ('Off2StartNxtRec','<u4'), #Offset to start of next record form start of this record
26 ('Off2StartData','<u4'), #Offset to start of data from start of this record
27 ('EpTimeStamp','<i4'), #Epoch time stamp of start of acquisition (seconds)
28 ('msCompTimeStamp','<u4'), #Millisecond component of time stamp (0,...,999)
29 ('ExpTagName','<s32'), #Experiment tag name (null terminated)
30 ('ExpComment','<s32'), #Experiment comment (null terminated)
31 ('SiteLatDegrees','<f4'), #Site latitude (from GPS) in degrees (positive implies North)
32 ('SiteLongDegrees','<f4'), #Site longitude (from GPS) in degrees (positive implies East)
33 ('RTCgpsStatus','<u4'), #RTC GPS engine status (0=SEEK, 1=LOCK, 2=NOT FITTED, 3=UNAVAILABLE)
34 ('TransmitFrec','<u4'), #Transmit frequency (Hz)
35 ('ReceiveFrec','<u4'), #Receive frequency
36 ('FirstOsciFrec','<u4'), #First local oscillator frequency (Hz)
37 ('Polarisation','<u4'), #(0="O", 1="E", 2="linear 1", 3="linear2")
38 ('ReceiverFiltSett','<u4'), #Receiver filter settings (0,1,2,3)
39 ('nModesInUse','<u4'), #Number of modes in use (1 or 2)
40 ('DualModeIndex','<u4'), #Dual Mode index number for these data (0 or 1)
41 ('DualModeRange','<u4'), #Dual Mode range correction for these data (m)
42 ('nDigChannels','<u4'), #Number of digital channels acquired (2*N)
43 ('SampResolution','<u4'), #Sampling resolution (meters)
44 ('nRangeGatesSamp','<u4'), #Number of range gates sampled
45 ('StartRangeSamp','<u4'), #Start range of sampling (meters)
46 ('PRFhz','<u4'), #PRF (Hz)
47 ('Integrations','<u4'), #Integrations
48 ('nDataPointsTrsf','<u4'), #Number of data points transformed
49 ('nReceiveBeams','<u4'), #Number of receive beams stored in file (1 or N)
50 ('nSpectAverages','<u4'), #Number of spectral averages
51 ('FFTwindowingInd','<u4'), #FFT windowing index (0 = no window)
52 ('BeamAngleAzim','<f4'), #Beam steer angle (azimuth) in degrees (clockwise from true North)
53 ('BeamAngleZen','<f4'), #Beam steer angle (zenith) in degrees (0=> vertical)
54 ('AntennaCoord','<f24'), #Antenna coordinates (Range(meters), Bearing(degrees)) - N pairs
55 ('RecPhaseCalibr','<f12'), #Receiver phase calibration (degrees) - N values
56 ('RecAmpCalibr','<f12'), #Receiver amplitude calibration (ratio relative to receiver one) - N values
57 ('ReceiverGaindB','<u12'), #Receiver gains in dB - N values
58 ])
59
60
61 class Header(object):
62
63 def __init__(self):
64 raise NotImplementedError
65
66
67 def read(self):
68
69 raise NotImplementedError
70
71 def write(self):
72
73 raise NotImplementedError
74
75 def printInfo(self):
76
77 message = "#"*50 + "\n"
78 message += self.__class__.__name__.upper() + "\n"
79 message += "#"*50 + "\n"
80
81 keyList = self.__dict__.keys()
82 keyList.sort()
83
84 for key in keyList:
85 message += "%s = %s" %(key, self.__dict__[key]) + "\n"
86
87 if "size" not in keyList:
88 attr = getattr(self, "size")
89
90 if attr:
91 message += "%s = %s" %("size", attr) + "\n"
92
93 print message
94
95 class FileHeader(Header):
96
97 FileMgcNumber= None
98 nFDTdataRecors=None #No Of FDT data records in this file (0 or more)
99 RadarUnitId= None
100 SiteName= None
101
102 #__LOCALTIME = None
103
104 def __init__(self, useLocalTime=True):
105
106 self.FileMgcNumber= 0 #0x23020100
107 self.nFDTdataRecors=0 #No Of FDT data records in this file (0 or more)
108 self.RadarUnitId= 0
109 self.SiteName= ""
110 self.size = 48
111
112 #self.useLocalTime = useLocalTime
113
114 def read(self, fp):
115
116 try:
117 header = numpy.fromfile(fp, FILE_STRUCTURE,1)
118 ''' numpy.fromfile(file, dtype, count, sep='')
119 file : file or str
120 Open file object or filename.
121
122 dtype : data-type
123 Data type of the returned array. For binary files, it is used to determine
124 the size and byte-order of the items in the file.
125
126 count : int
127 Number of items to read. -1 means all items (i.e., the complete file).
128
129 sep : str
130 Separator between items if file is a text file. Empty (“”) separator means
131 the file should be treated as binary. Spaces (” ”) in the separator match zero
132 or more whitespace characters. A separator consisting only of spaces must match
133 at least one whitespace.
134
135 '''
136
137 except Exception, e:
138 print "FileHeader: "
139 print eBasicHeader
140 return 0
141
142 self.FileMgcNumber= byte(header['FileMgcNumber'][0])
143 self.nFDTdataRecors=int(header['nFDTdataRecors'][0]) #No Of FDT data records in this file (0 or more)
144 self.RadarUnitId= int(header['RadarUnitId'][0])
145 self.SiteName= char(header['SiteName'][0])
146
147
148 if self.size <48:
149 return 0
150
151 return 1
152
153 def write(self, fp):
154
155 headerTuple = (self.FileMgcNumber,
156 self.nFDTdataRecors,
157 self.RadarUnitId,
158 self.SiteName,
159 self.size)
160
161
162 header = numpy.array(headerTuple, FILE_STRUCTURE)
163 # numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
164 header.tofile(fp)
165 ''' ndarray.tofile(fid, sep, format) Write array to a file as text or binary (default).
166
167 fid : file or str
168 An open file object, or a string containing a filename.
169
170 sep : str
171 Separator between array items for text output. If “” (empty), a binary file is written,
172 equivalent to file.write(a.tobytes()).
173
174 format : str
175 Format string for text file output. Each entry in the array is formatted to text by
176 first converting it to the closest Python type, and then using “format” % item.
177
178 '''
179
180 return 1
181
182
183 class RecordHeader(Header):
184
185 RecMgcNumber=None #0x23030001
186 RecCounter= None
187 Off2StartNxtRec= None
188 EpTimeStamp= None
189 msCompTimeStamp= None
190 ExpTagName= None
191 ExpComment=None
192 SiteLatDegrees=None
193 SiteLongDegrees= None
194 RTCgpsStatus= None
195 TransmitFrec= None
196 ReceiveFrec= None
197 FirstOsciFrec= None
198 Polarisation= None
199 ReceiverFiltSett= None
200 nModesInUse= None
201 DualModeIndex= None
202 DualModeRange= None
203 nDigChannels= None
204 SampResolution= None
205 nRangeGatesSamp= None
206 StartRangeSamp= None
207 PRFhz= None
208 Integrations= None
209 nDataPointsTrsf= None
210 nReceiveBeams= None
211 nSpectAverages= None
212 FFTwindowingInd= None
213 BeamAngleAzim= None
214 BeamAngleZen= None
215 AntennaCoord= None
216 RecPhaseCalibr= None
217 RecAmpCalibr= None
218 ReceiverGaindB= None
219
220 '''size = None
221 nSamples = None
222 nProfiles = None
223 nChannels = None
224 adcResolution = None
225 pciDioBusWidth = None'''
226
227 def __init__(self, RecMgcNumber=None, RecCounter= 0, Off2StartNxtRec= 0,
228 EpTimeStamp= 0, msCompTimeStamp= 0, ExpTagName= None,
229 ExpComment=None, SiteLatDegrees=0, SiteLongDegrees= 0,
230 RTCgpsStatus= 0, TransmitFrec= 0, ReceiveFrec= 0,
231 FirstOsciFrec= 0, Polarisation= 0, ReceiverFiltSett= 0,
232 nModesInUse= 0, DualModeIndex= 0, DualModeRange= 0,
233 nDigChannels= 0, SampResolution= 0, nRangeGatesSamp= 0,
234 StartRangeSamp= 0, PRFhz= 0, Integrations= 0,
235 nDataPointsTrsf= 0, nReceiveBeams= 0, nSpectAverages= 0,
236 FFTwindowingInd= 0, BeamAngleAzim= 0, BeamAngleZen= 0,
237 AntennaCoord= 0, RecPhaseCalibr= 0, RecAmpCalibr= 0,
238 ReceiverGaindB= 0):
239
240 self.RecMgcNumber = RecMgcNumber #0x23030001
241 self.RecCounter = RecCounter
242 self.Off2StartNxtRec = Off2StartNxtRec
243 self.EpTimeStamp = EpTimeStamp
244 self.msCompTimeStamp = msCompTimeStamp
245 self.ExpTagName = ExpTagName
246 self.ExpComment = ExpComment
247 self.SiteLatDegrees = SiteLatDegrees
248 self.SiteLongDegrees = SiteLongDegrees
249 self.RTCgpsStatus = RTCgpsStatus
250 self.TransmitFrec = TransmitFrec
251 self.ReceiveFrec = ReceiveFrec
252 self.FirstOsciFrec = FirstOsciFrec
253 self.Polarisation = Polarisation
254 self.ReceiverFiltSett = ReceiverFiltSett
255 self.nModesInUse = nModesInUse
256 self.DualModeIndex = DualModeIndex
257 self.DualModeRange = DualModeRange
258 self.nDigChannels = nDigChannels
259 self.SampResolution = SampResolution
260 self.nRangeGatesSamp = nRangeGatesSamp
261 self.StartRangeSamp = StartRangeSamp
262 self.PRFhz = PRFhz
263 self.Integrations = Integrations
264 self.nDataPointsTrsf = nDataPointsTrsf
265 self.nReceiveBeams = nReceiveBeams
266 self.nSpectAverages = nSpectAverages
267 self.FFTwindowingInd = FFTwindowingInd
268 self.BeamAngleAzim = BeamAngleAzim
269 self.BeamAngleZen = BeamAngleZen
270 self.AntennaCoord = AntennaCoord
271 self.RecPhaseCalibr = RecPhaseCalibr
272 self.RecAmpCalibr = RecAmpCalibr
273 self.ReceiverGaindB = ReceiverGaindB
274
275
276 def read(self, fp):
277
278 startFp = fp.tell() #The method tell() returns the current position of the file read/write pointer within the file.
279
280 try:
281 header = numpy.fromfile(fp,RECORD_STRUCTURE,1)
282 except Exception, e:
283 print "System Header: " + e
284 return 0
285
286 self.RecMgcNumber = header['RecMgcNumber'][0] #0x23030001
287 self.RecCounter = header['RecCounter'][0]
288 self.Off2StartNxtRec = header['Off2StartNxtRec'][0]
289 self.EpTimeStamp = header['EpTimeStamp'][0]
290 self.msCompTimeStamp = header['msCompTimeStamp'][0]
291 self.ExpTagName = header['ExpTagName'][0]
292 self.ExpComment = header['ExpComment'][0]
293 self.SiteLatDegrees = header['SiteLatDegrees'][0]
294 self.SiteLongDegrees = header['SiteLongDegrees'][0]
295 self.RTCgpsStatus = header['RTCgpsStatus'][0]
296 self.TransmitFrec = header['TransmitFrec'][0]
297 self.ReceiveFrec = header['ReceiveFrec'][0]
298 self.FirstOsciFrec = header['FirstOsciFrec'][0]
299 self.Polarisation = header['Polarisation'][0]
300 self.ReceiverFiltSett = header['ReceiverFiltSett'][0]
301 self.nModesInUse = header['nModesInUse'][0]
302 self.DualModeIndex = header['DualModeIndex'][0]
303 self.DualModeRange = header['DualModeRange'][0]
304 self.nDigChannels = header['nDigChannels'][0]
305 self.SampResolution = header['SampResolution'][0]
306 self.nRangeGatesSamp = header['nRangeGatesSamp'][0]
307 self.StartRangeSamp = header['StartRangeSamp'][0]
308 self.PRFhz = header['PRFhz'][0]
309 self.Integrations = header['Integrations'][0]
310 self.nDataPointsTrsf = header['nDataPointsTrsf'][0]
311 self.nReceiveBeams = header['nReceiveBeams'][0]
312 self.nSpectAverages = header['nSpectAverages'][0]
313 self.FFTwindowingInd = header['FFTwindowingInd'][0]
314 self.BeamAngleAzim = header['BeamAngleAzim'][0]
315 self.BeamAngleZen = header['BeamAngleZen'][0]
316 self.AntennaCoord = header['AntennaCoord'][0]
317 self.RecPhaseCalibr = header['RecPhaseCalibr'][0]
318 self.RecAmpCalibr = header['RecAmpCalibr'][0]
319 self.ReceiverGaindB = header['ReceiverGaindB'][0]
320
321 Self.size = 180+20*3
322
323 endFp = self.size + startFp
324
325 if fp.tell() > endFp:
326 sys.stderr.write("Warning %s: Size value read from System Header is lower than it has to be\n" %fp.name)
327 return 0
328
329 if fp.tell() < endFp:
330 sys.stderr.write("Warning %s: Size value read from System Header size is greater than it has to be\n" %fp.name)
331 return 0
332
333 return 1
334
335 def write(self, fp):
336
337 headerTuple = (self.RecMgcNumber,
338 self.RecCounter,
339 self.Off2StartNxtRec,
340 self.EpTimeStamp,
341 self.msCompTimeStamp,
342 self.ExpTagName,
343 self.ExpComment,
344 self.SiteLatDegrees,
345 self.SiteLongDegrees,
346 self.RTCgpsStatus,
347 self.TransmitFrec,
348 self.ReceiveFrec,
349 self.FirstOsciFrec,
350 self.Polarisation,
351 self.ReceiverFiltSett,
352 self.nModesInUse,
353 self.DualModeIndex,
354 self.DualModeRange,
355 self.nDigChannels,
356 self.SampResolution,
357 self.nRangeGatesSamp,
358 self.StartRangeSamp,
359 self.PRFhz,
360 self.Integrations,
361 self.nDataPointsTrsf,
362 self.nReceiveBeams,
363 self.nSpectAverages,
364 self.FFTwindowingInd,
365 self.BeamAngleAzim,
366 self.BeamAngleZen,
367 self.AntennaCoord,
368 self.RecPhaseCalibr,
369 self.RecAmpCalibr,
370 self.ReceiverGaindB)
371
372 # self.size,self.nSamples,
373 # self.nProfiles,
374 # self.nChannels,
375 # self.adcResolution,
376 # self.pciDioBusWidth
377
378 header = numpy.array(headerTuple,RECORD_STRUCTURE)
379 header.tofile(fp)
380
381 return 1
382
383
384 def get_dtype_index(numpy_dtype):
385
386 index = None
387
388 for i in range(len(NUMPY_DTYPE_LIST)):
389 if numpy_dtype == NUMPY_DTYPE_LIST[i]:
390 index = i
391 break
392
393 return index
394
395 def get_numpy_dtype(index):
396
397 #dtype4 = numpy.dtype([('real','<f4'),('imag','<f4')])
398
399 return NUMPY_DTYPE_LIST[index]
400
401
402 def get_dtype_width(index):
403
404 return DTYPE_WIDTH[index] No newline at end of file
@@ -0,0 +1,469
1 import numpy
2 import datetime
3 import sys
4 import matplotlib
5
6 if 'linux' in sys.platform:
7 matplotlib.use("TKAgg")
8
9 if 'darwin' in sys.platform:
10 matplotlib.use('TKAgg')
11 #Qt4Agg', 'GTK', 'GTKAgg', 'ps', 'agg', 'cairo', 'MacOSX', 'GTKCairo', 'WXAgg', 'template', 'TkAgg', 'GTK3Cairo', 'GTK3Agg', 'svg', 'WebAgg', 'CocoaAgg', 'emf', 'gdk', 'WX'
12 import matplotlib.pyplot
13
14 from mpl_toolkits.axes_grid1 import make_axes_locatable
15 from matplotlib.ticker import FuncFormatter, LinearLocator
16
17 ###########################################
18 #Actualizacion de las funciones del driver
19 ###########################################
20
21 jet_values = matplotlib.pyplot.get_cmap("jet", 100)(numpy.arange(100))[10:90]
22 blu_values = matplotlib.pyplot.get_cmap("seismic_r", 20)(numpy.arange(20))[10:15]
23 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list("jro", numpy.vstack((blu_values, jet_values)))
24 matplotlib.pyplot.register_cmap(cmap=ncmap)
25
26 def createFigure(id, wintitle, width, height, facecolor="w", show=True, dpi = 80):
27
28 matplotlib.pyplot.ioff()
29
30 fig = matplotlib.pyplot.figure(num=id, facecolor=facecolor, figsize=(1.0*width/dpi, 1.0*height/dpi))
31 fig.canvas.manager.set_window_title(wintitle)
32 # fig.canvas.manager.resize(width, height)
33 matplotlib.pyplot.ion()
34
35
36 if show:
37 matplotlib.pyplot.show()
38
39 return fig
40
41 def closeFigure(show=False, fig=None):
42
43 # matplotlib.pyplot.ioff()
44 # matplotlib.pyplot.pause(0)
45
46 if show:
47 matplotlib.pyplot.show()
48
49 if fig != None:
50 matplotlib.pyplot.close(fig)
51 # matplotlib.pyplot.pause(0)
52 # matplotlib.pyplot.ion()
53
54 return
55
56 matplotlib.pyplot.close("all")
57 # matplotlib.pyplot.pause(0)
58 # matplotlib.pyplot.ion()
59
60 return
61
62 def saveFigure(fig, filename):
63
64 # matplotlib.pyplot.ioff()
65 fig.savefig(filename, dpi=matplotlib.pyplot.gcf().dpi)
66 # matplotlib.pyplot.ion()
67
68 def clearFigure(fig):
69
70 fig.clf()
71
72 def setWinTitle(fig, title):
73
74 fig.canvas.manager.set_window_title(title)
75
76 def setTitle(fig, title):
77
78 fig.suptitle(title)
79
80 def createAxes(fig, nrow, ncol, xpos, ypos, colspan, rowspan, polar=False):
81
82 matplotlib.pyplot.ioff()
83 matplotlib.pyplot.figure(fig.number)
84 axes = matplotlib.pyplot.subplot2grid((nrow, ncol),
85 (xpos, ypos),
86 colspan=colspan,
87 rowspan=rowspan,
88 polar=polar)
89
90 axes.grid(True)
91 matplotlib.pyplot.ion()
92 return axes
93
94 def setAxesText(ax, text):
95
96 ax.annotate(text,
97 xy = (.1, .99),
98 xycoords = 'figure fraction',
99 horizontalalignment = 'left',
100 verticalalignment = 'top',
101 fontsize = 10)
102
103 def printLabels(ax, xlabel, ylabel, title):
104
105 ax.set_xlabel(xlabel, size=11)
106 ax.set_ylabel(ylabel, size=11)
107 ax.set_title(title, size=8)
108
109 def createPline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='',
110 ticksize=9, xtick_visible=True, ytick_visible=True,
111 nxticks=4, nyticks=10,
112 grid=None,color='blue'):
113
114 """
115
116 Input:
117 grid : None, 'both', 'x', 'y'
118 """
119
120 matplotlib.pyplot.ioff()
121
122 ax.set_xlim([xmin,xmax])
123 ax.set_ylim([ymin,ymax])
124
125 printLabels(ax, xlabel, ylabel, title)
126
127 ######################################################
128 if (xmax-xmin)<=1:
129 xtickspos = numpy.linspace(xmin,xmax,nxticks)
130 xtickspos = numpy.array([float("%.1f"%i) for i in xtickspos])
131 ax.set_xticks(xtickspos)
132 else:
133 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
134 # xtickspos = numpy.arange(nxticks)*float(xmax-xmin)/float(nxticks) + int(xmin)
135 ax.set_xticks(xtickspos)
136
137 for tick in ax.get_xticklabels():
138 tick.set_visible(xtick_visible)
139
140 for tick in ax.xaxis.get_major_ticks():
141 tick.label.set_fontsize(ticksize)
142
143 ######################################################
144 for tick in ax.get_yticklabels():
145 tick.set_visible(ytick_visible)
146
147 for tick in ax.yaxis.get_major_ticks():
148 tick.label.set_fontsize(ticksize)
149
150 ax.plot(x, y, color=color)
151 iplot = ax.lines[-1]
152
153 ######################################################
154 if '0.' in matplotlib.__version__[0:2]:
155 print "The matplotlib version has to be updated to 1.1 or newer"
156 return iplot
157
158 if '1.0.' in matplotlib.__version__[0:4]:
159 print "The matplotlib version has to be updated to 1.1 or newer"
160 return iplot
161
162 if grid != None:
163 ax.grid(b=True, which='major', axis=grid)
164
165 matplotlib.pyplot.tight_layout()
166
167 matplotlib.pyplot.ion()
168
169 return iplot
170
171 def set_linedata(ax, x, y, idline):
172
173 ax.lines[idline].set_data(x,y)
174
175 def pline(iplot, x, y, xlabel='', ylabel='', title=''):
176
177 ax = iplot.get_axes()
178
179 printLabels(ax, xlabel, ylabel, title)
180
181 set_linedata(ax, x, y, idline=0)
182
183 def addpline(ax, x, y, color, linestyle, lw):
184
185 ax.plot(x,y,color=color,linestyle=linestyle,lw=lw)
186
187
188 def createPcolor(ax, x, y, z, xmin, xmax, ymin, ymax, zmin, zmax,
189 xlabel='', ylabel='', title='', ticksize = 9,
190 colormap='jet',cblabel='', cbsize="5%",
191 XAxisAsTime=False):
192
193 matplotlib.pyplot.ioff()
194
195 divider = make_axes_locatable(ax)
196 ax_cb = divider.new_horizontal(size=cbsize, pad=0.05)
197 fig = ax.get_figure()
198 fig.add_axes(ax_cb)
199
200 ax.set_xlim([xmin,xmax])
201 ax.set_ylim([ymin,ymax])
202
203 printLabels(ax, xlabel, ylabel, title)
204
205 z = numpy.ma.masked_invalid(z)
206 cmap=matplotlib.pyplot.get_cmap(colormap)
207 cmap.set_bad('white',1.)
208 imesh = ax.pcolormesh(x,y,z.T, vmin=zmin, vmax=zmax, cmap=cmap)
209 cb = matplotlib.pyplot.colorbar(imesh, cax=ax_cb)
210 cb.set_label(cblabel)
211
212 # for tl in ax_cb.get_yticklabels():
213 # tl.set_visible(True)
214
215 for tick in ax.yaxis.get_major_ticks():
216 tick.label.set_fontsize(ticksize)
217
218 for tick in ax.xaxis.get_major_ticks():
219 tick.label.set_fontsize(ticksize)
220
221 for tick in cb.ax.get_yticklabels():
222 tick.set_fontsize(ticksize)
223
224 ax_cb.yaxis.tick_right()
225
226 if '0.' in matplotlib.__version__[0:2]:
227 print "The matplotlib version has to be updated to 1.1 or newer"
228 return imesh
229
230 if '1.0.' in matplotlib.__version__[0:4]:
231 print "The matplotlib version has to be updated to 1.1 or newer"
232 return imesh
233
234 matplotlib.pyplot.tight_layout()
235
236 if XAxisAsTime:
237
238 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
239 ax.xaxis.set_major_formatter(FuncFormatter(func))
240 ax.xaxis.set_major_locator(LinearLocator(7))
241 ax.grid(True)
242 matplotlib.pyplot.ion()
243 return imesh
244
245 def pcolor(imesh, z, xlabel='', ylabel='', title=''):
246
247 z = z.T
248 ax = imesh.get_axes()
249 printLabels(ax, xlabel, ylabel, title)
250 imesh.set_array(z.ravel())
251 ax.grid(True)
252
253 def addpcolor(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
254
255 printLabels(ax, xlabel, ylabel, title)
256 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
257 ax.grid(True)
258
259 def addpcolorbuffer(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
260
261 printLabels(ax, xlabel, ylabel, title)
262
263 ax.collections.remove(ax.collections[0])
264
265 z = numpy.ma.masked_invalid(z)
266
267 cmap=matplotlib.pyplot.get_cmap(colormap)
268 cmap.set_bad('white',1.)
269
270 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=cmap)
271 ax.grid(True)
272
273 def createPmultiline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
274 ticksize=9, xtick_visible=True, ytick_visible=True,
275 nxticks=4, nyticks=10,
276 grid=None):
277
278 """
279
280 Input:
281 grid : None, 'both', 'x', 'y'
282 """
283
284 matplotlib.pyplot.ioff()
285
286 lines = ax.plot(x.T, y)
287 leg = ax.legend(lines, legendlabels, loc='upper right')
288 leg.get_frame().set_alpha(0.5)
289 ax.set_xlim([xmin,xmax])
290 ax.set_ylim([ymin,ymax])
291 printLabels(ax, xlabel, ylabel, title)
292
293 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
294 ax.set_xticks(xtickspos)
295
296 for tick in ax.get_xticklabels():
297 tick.set_visible(xtick_visible)
298
299 for tick in ax.xaxis.get_major_ticks():
300 tick.label.set_fontsize(ticksize)
301
302 for tick in ax.get_yticklabels():
303 tick.set_visible(ytick_visible)
304
305 for tick in ax.yaxis.get_major_ticks():
306 tick.label.set_fontsize(ticksize)
307
308 iplot = ax.lines[-1]
309
310 if '0.' in matplotlib.__version__[0:2]:
311 print "The matplotlib version has to be updated to 1.1 or newer"
312 return iplot
313
314 if '1.0.' in matplotlib.__version__[0:4]:
315 print "The matplotlib version has to be updated to 1.1 or newer"
316 return iplot
317
318 if grid != None:
319 ax.grid(b=True, which='major', axis=grid)
320
321 matplotlib.pyplot.tight_layout()
322
323 matplotlib.pyplot.ion()
324
325 return iplot
326
327
328 def pmultiline(iplot, x, y, xlabel='', ylabel='', title=''):
329
330 ax = iplot.get_axes()
331
332 printLabels(ax, xlabel, ylabel, title)
333
334 for i in range(len(ax.lines)):
335 line = ax.lines[i]
336 line.set_data(x[i,:],y)
337
338 def createPmultilineYAxis(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
339 ticksize=9, xtick_visible=True, ytick_visible=True,
340 nxticks=4, nyticks=10, marker='.', markersize=10, linestyle="None",
341 grid=None, XAxisAsTime=False):
342
343 """
344
345 Input:
346 grid : None, 'both', 'x', 'y'
347 """
348
349 matplotlib.pyplot.ioff()
350
351 # lines = ax.plot(x, y.T, marker=marker,markersize=markersize,linestyle=linestyle)
352 lines = ax.plot(x, y.T)
353 # leg = ax.legend(lines, legendlabels, loc=2, bbox_to_anchor=(1.01, 1.00), numpoints=1, handlelength=1.5, \
354 # handletextpad=0.5, borderpad=0.5, labelspacing=0.5, borderaxespad=0.)
355
356 leg = ax.legend(lines, legendlabels,
357 loc='upper right', bbox_to_anchor=(1.16, 1), borderaxespad=0)
358
359 for label in leg.get_texts(): label.set_fontsize(9)
360
361 ax.set_xlim([xmin,xmax])
362 ax.set_ylim([ymin,ymax])
363 printLabels(ax, xlabel, ylabel, title)
364
365 # xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
366 # ax.set_xticks(xtickspos)
367
368 for tick in ax.get_xticklabels():
369 tick.set_visible(xtick_visible)
370
371 for tick in ax.xaxis.get_major_ticks():
372 tick.label.set_fontsize(ticksize)
373
374 for tick in ax.get_yticklabels():
375 tick.set_visible(ytick_visible)
376
377 for tick in ax.yaxis.get_major_ticks():
378 tick.label.set_fontsize(ticksize)
379
380 iplot = ax.lines[-1]
381
382 if '0.' in matplotlib.__version__[0:2]:
383 print "The matplotlib version has to be updated to 1.1 or newer"
384 return iplot
385
386 if '1.0.' in matplotlib.__version__[0:4]:
387 print "The matplotlib version has to be updated to 1.1 or newer"
388 return iplot
389
390 if grid != None:
391 ax.grid(b=True, which='major', axis=grid)
392
393 matplotlib.pyplot.tight_layout()
394
395 if XAxisAsTime:
396
397 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
398 ax.xaxis.set_major_formatter(FuncFormatter(func))
399 ax.xaxis.set_major_locator(LinearLocator(7))
400
401 matplotlib.pyplot.ion()
402
403 return iplot
404
405 def pmultilineyaxis(iplot, x, y, xlabel='', ylabel='', title=''):
406
407 ax = iplot.get_axes()
408
409 printLabels(ax, xlabel, ylabel, title)
410
411 for i in range(len(ax.lines)):
412 line = ax.lines[i]
413 line.set_data(x,y[i,:])
414
415 def createPolar(ax, x, y,
416 xlabel='', ylabel='', title='', ticksize = 9,
417 colormap='jet',cblabel='', cbsize="5%",
418 XAxisAsTime=False):
419
420 matplotlib.pyplot.ioff()
421
422 ax.plot(x,y,'bo', markersize=5)
423 # ax.set_rmax(90)
424 ax.set_ylim(0,90)
425 ax.set_yticks(numpy.arange(0,90,20))
426 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center' ,size='11')
427 # ax.text(0, 50, ylabel, rotation='vertical', va ='center', ha = 'left' ,size='11')
428 # ax.text(100, 100, 'example', ha='left', va='center', rotation='vertical')
429 ax.yaxis.labelpad = 230
430 printLabels(ax, xlabel, ylabel, title)
431 iplot = ax.lines[-1]
432
433 if '0.' in matplotlib.__version__[0:2]:
434 print "The matplotlib version has to be updated to 1.1 or newer"
435 return iplot
436
437 if '1.0.' in matplotlib.__version__[0:4]:
438 print "The matplotlib version has to be updated to 1.1 or newer"
439 return iplot
440
441 # if grid != None:
442 # ax.grid(b=True, which='major', axis=grid)
443
444 matplotlib.pyplot.tight_layout()
445
446 matplotlib.pyplot.ion()
447
448
449 return iplot
450
451 def polar(iplot, x, y, xlabel='', ylabel='', title=''):
452
453 ax = iplot.get_axes()
454
455 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center',size='11')
456 printLabels(ax, xlabel, ylabel, title)
457
458 set_linedata(ax, x, y, idline=0)
459
460 def draw(fig):
461
462 if type(fig) == 'int':
463 raise ValueError, "Error drawing: Fig parameter should be a matplotlib figure object figure"
464
465 fig.canvas.draw()
466
467 def pause(interval=0.000001):
468
469 matplotlib.pyplot.pause(interval)
@@ -0,0 +1,321
1 import os, sys
2 import glob
3 import fnmatch
4 import datetime
5 import time
6 import re
7 import h5py
8 import numpy
9 import matplotlib.pyplot as plt
10
11 import pylab as plb
12 from scipy.optimize import curve_fit
13 from scipy import asarray as ar,exp
14 from scipy import stats
15
16 from duplicity.path import Path
17 from numpy.ma.core import getdata
18
19 SPEED_OF_LIGHT = 299792458
20 SPEED_OF_LIGHT = 3e8
21
22 try:
23 from gevent import sleep
24 except:
25 from time import sleep
26
27 from schainpy.model.data.jrodata import Spectra
28 #from schainpy.model.data.BLTRheaderIO import FileHeader, RecordHeader
29 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
30 #from schainpy.model.io.jroIO_bltr import BLTRReader
31 from numpy import imag, shape, NaN
32
33
34 startFp = open('/home/erick/Documents/MIRA35C/20160117/20160117_0000.zspc',"rb")
35
36
37 FILE_HEADER = numpy.dtype([ #HEADER 1024bytes
38 ('Hname',numpy.str_,32), #Original file name
39 ('Htime',numpy.str_,32), #Date and time when the file was created
40 ('Hoper',numpy.str_,64), #Name of operator who created the file
41 ('Hplace',numpy.str_,128), #Place where the measurements was carried out
42 ('Hdescr',numpy.str_,256), #Description of measurements
43 ('Hdummy',numpy.str_,512), #Reserved space
44 #Main chunk
45 ('Msign','<i4'), #Main chunk signature FZKF or NUIG
46 ('MsizeData','<i4'), #Size of data block main chunk
47 #Processing DSP parameters
48 ('PPARsign','<i4'), #PPAR signature
49 ('PPARsize','<i4'), #PPAR size of block
50 ('PPARprf','<i4'), #Pulse repetition frequency
51 ('PPARpdr','<i4'), #Pulse duration
52 ('PPARsft','<i4'), #FFT length
53 ('PPARavc','<i4'), #Number of spectral (in-coherent) averages
54 ('PPARihp','<i4'), #Number of lowest range gate for moment estimation
55 ('PPARchg','<i4'), #Count for gates for moment estimation
56 ('PPARpol','<i4'), #switch on/off polarimetric measurements. Should be 1.
57 #Service DSP parameters
58 ('SPARatt','<i4'), #STC attenuation on the lowest ranges on/off
59 ('SPARtx','<i4'), #OBSOLETE
60 ('SPARaddGain0','<f4'), #OBSOLETE
61 ('SPARaddGain1','<f4'), #OBSOLETE
62 ('SPARwnd','<i4'), #Debug only. It normal mode it is 0.
63 ('SPARpos','<i4'), #Delay between sync pulse and tx pulse for phase corr, ns
64 ('SPARadd','<i4'), #"add to pulse" to compensate for delay between the leading edge of driver pulse and envelope of the RF signal.
65 ('SPARlen','<i4'), #Time for measuring txn pulse phase. OBSOLETE
66 ('SPARcal','<i4'), #OBSOLETE
67 ('SPARnos','<i4'), #OBSOLETE
68 ('SPARof0','<i4'), #detection threshold
69 ('SPARof1','<i4'), #OBSOLETE
70 ('SPARswt','<i4'), #2nd moment estimation threshold
71 ('SPARsum','<i4'), #OBSOLETE
72 ('SPARosc','<i4'), #flag Oscillosgram mode
73 ('SPARtst','<i4'), #OBSOLETE
74 ('SPARcor','<i4'), #OBSOLETE
75 ('SPARofs','<i4'), #OBSOLETE
76 ('SPARhsn','<i4'), #Hildebrand div noise detection on noise gate
77 ('SPARhsa','<f4'), #Hildebrand div noise detection on all gates
78 ('SPARcalibPow_M','<f4'), #OBSOLETE
79 ('SPARcalibSNR_M','<f4'), #OBSOLETE
80 ('SPARcalibPow_S','<f4'), #OBSOLETE
81 ('SPARcalibSNR_S','<f4'), #OBSOLETE
82 ('SPARrawGate1','<i4'), #Lowest range gate for spectra saving Raw_Gate1 >=5
83 ('SPARrawGate2','<i4'), #Number of range gates with atmospheric signal
84 ('SPARraw','<i4'), #flag - IQ or spectra saving on/off
85 ('SPARprc','<i4'),]) #flag - Moment estimation switched on/off
86
87
88
89 self.Hname= None
90 self.Htime= None
91 self.Hoper= None
92 self.Hplace= None
93 self.Hdescr= None
94 self.Hdummy= None
95
96 self.Msign=None
97 self.MsizeData=None
98
99 self.PPARsign=None
100 self.PPARsize=None
101 self.PPARprf=None
102 self.PPARpdr=None
103 self.PPARsft=None
104 self.PPARavc=None
105 self.PPARihp=None
106 self.PPARchg=None
107 self.PPARpol=None
108 #Service DSP parameters
109 self.SPARatt=None
110 self.SPARtx=None
111 self.SPARaddGain0=None
112 self.SPARaddGain1=None
113 self.SPARwnd=None
114 self.SPARpos=None
115 self.SPARadd=None
116 self.SPARlen=None
117 self.SPARcal=None
118 self.SPARnos=None
119 self.SPARof0=None
120 self.SPARof1=None
121 self.SPARswt=None
122 self.SPARsum=None
123 self.SPARosc=None
124 self.SPARtst=None
125 self.SPARcor=None
126 self.SPARofs=None
127 self.SPARhsn=None
128 self.SPARhsa=None
129 self.SPARcalibPow_M=None
130 self.SPARcalibSNR_M=None
131 self.SPARcalibPow_S=None
132 self.SPARcalibSNR_S=None
133 self.SPARrawGate1=None
134 self.SPARrawGate2=None
135 self.SPARraw=None
136 self.SPARprc=None
137
138
139
140 header = numpy.fromfile(fp, FILE_HEADER,1)
141 ''' numpy.fromfile(file, dtype, count, sep='')
142 file : file or str
143 Open file object or filename.
144
145 dtype : data-type
146 Data type of the returned array. For binary files, it is used to determine
147 the size and byte-order of the items in the file.
148
149 count : int
150 Number of items to read. -1 means all items (i.e., the complete file).
151
152 sep : str
153 Separator between items if file is a text file. Empty ("") separator means
154 the file should be treated as binary. Spaces (" ") in the separator match zero
155 or more whitespace characters. A separator consisting only of spaces must match
156 at least one whitespace.
157
158 '''
159
160 Hname= str(header['Hname'][0])
161 Htime= str(header['Htime'][0])
162 Hoper= str(header['Hoper'][0])
163 Hplace= str(header['Hplace'][0])
164 Hdescr= str(header['Hdescr'][0])
165 Hdummy= str(header['Hdummy'][0])
166
167 Msign=header['Msign'][0]
168 MsizeData=header['MsizeData'][0]
169
170 PPARsign=header['PPARsign'][0]
171 PPARsize=header['PPARsize'][0]
172 PPARprf=header['PPARprf'][0]
173 PPARpdr=header['PPARpdr'][0]
174 PPARsft=header['PPARsft'][0]
175 PPARavc=header['PPARavc'][0]
176 PPARihp=header['PPARihp'][0]
177 PPARchg=header['PPARchg'][0]
178 PPARpol=header['PPARpol'][0]
179 #Service DSP parameters
180 SPARatt=header['SPARatt'][0]
181 SPARtx=header['SPARtx'][0]
182 SPARaddGain0=header['SPARaddGain0'][0]
183 SPARaddGain1=header['SPARaddGain1'][0]
184 SPARwnd=header['SPARwnd'][0]
185 SPARpos=header['SPARpos'][0]
186 SPARadd=header['SPARadd'][0]
187 SPARlen=header['SPARlen'][0]
188 SPARcal=header['SPARcal'][0]
189 SPARnos=header['SPARnos'][0]
190 SPARof0=header['SPARof0'][0]
191 SPARof1=header['SPARof1'][0]
192 SPARswt=header['SPARswt'][0]
193 SPARsum=header['SPARsum'][0]
194 SPARosc=header['SPARosc'][0]
195 SPARtst=header['SPARtst'][0]
196 SPARcor=header['SPARcor'][0]
197 SPARofs=header['SPARofs'][0]
198 SPARhsn=header['SPARhsn'][0]
199 SPARhsa=header['SPARhsa'][0]
200 SPARcalibPow_M=header['SPARcalibPow_M'][0]
201 SPARcalibSNR_M=header['SPARcalibSNR_M'][0]
202 SPARcalibPow_S=header['SPARcalibPow_S'][0]
203 SPARcalibSNR_S=header['SPARcalibSNR_S'][0]
204 SPARrawGate1=header['SPARrawGate1'][0]
205 SPARrawGate2=header['SPARrawGate2'][0]
206 SPARraw=header['SPARraw'][0]
207 SPARprc=header['SPARprc'][0]
208
209
210
211 SRVI_STRUCTURE = numpy.dtype([
212 ('frame_cnt','<u4'),#
213 ('time_t','<u4'), #
214 ('tpow','<f4'), #
215 ('npw1','<f4'), #
216 ('npw2','<f4'), #
217 ('cpw1','<f4'), #
218 ('pcw2','<f4'), #
219 ('ps_err','<u4'), #
220 ('te_err','<u4'), #
221 ('rc_err','<u4'), #
222 ('grs1','<u4'), #
223 ('grs2','<u4'), #
224 ('azipos','<f4'), #
225 ('azivel','<f4'), #
226 ('elvpos','<f4'), #
227 ('elvvel','<f4'), #
228 ('northAngle','<f4'), #
229 ('microsec','<u4'), #
230 ('azisetvel','<f4'), #
231 ('elvsetpos','<f4'), #
232 ('RadarConst','<f4'),]) #
233
234 JUMP_STRUCTURE = numpy.dtype([
235 ('jump','<u140'),#
236 ('SizeOfDataBlock1',numpy.str_,32),#
237 ('jump','<i4'),#
238 ('DataBlockTitleSRVI1',numpy.str_,32),#
239 ('SizeOfSRVI1','<i4'),])#
240
241
242
243 #frame_cnt=0, time_t= 0, tpow=0, npw1=0, npw2=0,
244 #cpw1=0, pcw2=0, ps_err=0, te_err=0, rc_err=0, grs1=0,
245 #grs2=0, azipos=0, azivel=0, elvpos=0, elvvel=0, northangle=0,
246 #microsec=0, azisetvel=0, elvsetpos=0, RadarConst=0
247
248
249 frame_cnt = frame_cnt
250 dwell = time_t
251 tpow = tpow
252 npw1 = npw1
253 npw2 = npw2
254 cpw1 = cpw1
255 pcw2 = pcw2
256 ps_err = ps_err
257 te_err = te_err
258 rc_err = rc_err
259 grs1 = grs1
260 grs2 = grs2
261 azipos = azipos
262 azivel = azivel
263 elvpos = elvpos
264 elvvel = elvvel
265 northAngle = northAngle
266 microsec = microsec
267 azisetvel = azisetvel
268 elvsetpos = elvsetpos
269 RadarConst5 = RadarConst
270
271
272
273 #print fp
274 #startFp = open('/home/erick/Documents/Data/huancayo.20161019.22.fdt',"rb") #The method tell() returns the current position of the file read/write pointer within the file.
275 #startFp = open(fp,"rb") #The method tell() returns the current position of the file read/write pointer within the file.
276 #RecCounter=0
277 #Off2StartNxtRec=811248
278 #print 'OffsetStartHeader ',self.OffsetStartHeader,'RecCounter ', self.RecCounter, 'Off2StartNxtRec ' , self.Off2StartNxtRec
279 #OffRHeader= self.OffsetStartHeader + self.RecCounter*self.Off2StartNxtRec
280 #startFp.seek(OffRHeader, os.SEEK_SET)
281 print 'debe ser 48, RecCounter*811248', self.OffsetStartHeader,self.RecCounter,self.Off2StartNxtRec
282 print 'Posicion del bloque: ',OffRHeader
283
284 header = numpy.fromfile(startFp,SRVI_STRUCTURE,1)
285
286 self.frame_cnt = header['frame_cnt'][0]#
287 self.time_t = header['frame_cnt'][0] #
288 self.tpow = header['frame_cnt'][0] #
289 self.npw1 = header['frame_cnt'][0] #
290 self.npw2 = header['frame_cnt'][0] #
291 self.cpw1 = header['frame_cnt'][0] #
292 self.pcw2 = header['frame_cnt'][0] #
293 self.ps_err = header['frame_cnt'][0] #
294 self.te_err = header['frame_cnt'][0] #
295 self.rc_err = header['frame_cnt'][0] #
296 self.grs1 = header['frame_cnt'][0] #
297 self.grs2 = header['frame_cnt'][0] #
298 self.azipos = header['frame_cnt'][0] #
299 self.azivel = header['frame_cnt'][0] #
300 self.elvpos = header['frame_cnt'][0] #
301 self.elvvel = header['frame_cnt'][0] #
302 self.northAngle = header['frame_cnt'][0] #
303 self.microsec = header['frame_cnt'][0] #
304 self.azisetvel = header['frame_cnt'][0] #
305 self.elvsetpos = header['frame_cnt'][0] #
306 self.RadarConst = header['frame_cnt'][0] #
307
308
309 self.ipp= 0.5*(SPEED_OF_LIGHT/self.PRFhz)
310
311 self.RHsize = 180+20*self.nChannels
312 self.Datasize= self.nProfiles*self.nChannels*self.nHeights*2*4
313 #print 'Datasize',self.Datasize
314 endFp = self.OffsetStartHeader + self.RecCounter*self.Off2StartNxtRec
315
316 print '=============================================='
317
318 print '=============================================='
319
320
321 No newline at end of file
@@ -0,0 +1,362
1 '''
2 Created on Nov 9, 2016
3
4 @author: roj- LouVD
5 '''
6
7
8 import os
9 import sys
10 import time
11 import glob
12 import datetime
13
14 import numpy
15
16 from schainpy.model.proc.jroproc_base import ProcessingUnit
17 from schainpy.model.data.jrodata import Parameters
18 from schainpy.model.io.jroIO_base import JRODataReader, isNumber
19
20 FILE_HEADER_STRUCTURE = numpy.dtype([
21 ('FMN', '<u4'),
22 ('nrec', '<u4'),
23 ('fr_offset', '<u4'),
24 ('id', '<u4'),
25 ('site', 'u1', (32,))
26 ])
27
28 REC_HEADER_STRUCTURE = numpy.dtype([
29 ('rmn', '<u4'),
30 ('rcounter', '<u4'),
31 ('nr_offset', '<u4'),
32 ('tr_offset', '<u4'),
33 ('time', '<u4'),
34 ('time_msec', '<u4'),
35 ('tag', 'u1', (32,)),
36 ('comments', 'u1', (32,)),
37 ('lat', '<f4'),
38 ('lon', '<f4'),
39 ('gps_status', '<u4'),
40 ('freq', '<u4'),
41 ('freq0', '<u4'),
42 ('nchan', '<u4'),
43 ('delta_r', '<u4'),
44 ('nranges', '<u4'),
45 ('r0', '<u4'),
46 ('prf', '<u4'),
47 ('ncoh', '<u4'),
48 ('npoints', '<u4'),
49 ('polarization', '<i4'),
50 ('rx_filter', '<u4'),
51 ('nmodes', '<u4'),
52 ('dmode_index', '<u4'),
53 ('dmode_rngcorr', '<u4'),
54 ('nrxs', '<u4'),
55 ('acf_length', '<u4'),
56 ('acf_lags', '<u4'),
57 ('sea_to_atmos', '<f4'),
58 ('sea_notch', '<u4'),
59 ('lh_sea', '<u4'),
60 ('hh_sea', '<u4'),
61 ('nbins_sea', '<u4'),
62 ('min_snr', '<f4'),
63 ('min_cc', '<f4'),
64 ('max_time_diff', '<f4')
65 ])
66
67 DATA_STRUCTURE = numpy.dtype([
68 ('range', '<u4'),
69 ('status', '<u4'),
70 ('zonal', '<f4'),
71 ('meridional', '<f4'),
72 ('vertical', '<f4'),
73 ('zonal_a', '<f4'),
74 ('meridional_a', '<f4'),
75 ('corrected_fading', '<f4'), # seconds
76 ('uncorrected_fading', '<f4'), # seconds
77 ('time_diff', '<f4'),
78 ('major_axis', '<f4'),
79 ('axial_ratio', '<f4'),
80 ('orientation', '<f4'),
81 ('sea_power', '<u4'),
82 ('sea_algorithm', '<u4')
83 ])
84
85 class BLTRParamReader(JRODataReader, ProcessingUnit):
86 '''
87 Boundary Layer and Tropospheric Radar (BLTR) reader, Wind velocities and SNR from *.sswma files
88 '''
89
90 ext = '.sswma'
91
92 def __init__(self, **kwargs):
93
94 ProcessingUnit.__init__(self , **kwargs)
95
96 self.dataOut = Parameters()
97 self.counter_records = 0
98 self.flagNoMoreFiles = 0
99 self.isConfig = False
100 self.filename = None
101
102 def setup(self,
103 path=None,
104 startDate=None,
105 endDate=None,
106 ext=None,
107 startTime=datetime.time(0, 0, 0),
108 endTime=datetime.time(23, 59, 59),
109 timezone=0,
110 status_value=0,
111 **kwargs):
112
113 self.path = path
114 self.startTime = startTime
115 self.endTime = endTime
116 self.status_value = status_value
117
118 if self.path is None:
119 raise ValueError, "The path is not valid"
120
121 if ext is None:
122 ext = self.ext
123
124 self.search_files(self.path, startDate, endDate, ext)
125 self.timezone = timezone
126 self.fileIndex = 0
127
128 if not self.fileList:
129 raise Warning, "There is no files matching these date in the folder: %s. \n Check 'startDate' and 'endDate' "%(path)
130
131 self.setNextFile()
132
133 def search_files(self, path, startDate, endDate, ext):
134 '''
135 Searching for BLTR rawdata file in path
136 Creating a list of file to proces included in [startDate,endDate]
137
138 Input:
139 path - Path to find BLTR rawdata files
140 startDate - Select file from this date
141 enDate - Select file until this date
142 ext - Extension of the file to read
143
144 '''
145
146 print 'Searching file in %s ' % (path)
147 foldercounter = 0
148 fileList0 = glob.glob1(path, "*%s" % ext)
149 fileList0.sort()
150
151 self.fileList = []
152 self.dateFileList = []
153
154 for thisFile in fileList0:
155 year = thisFile[-14:-10]
156 if not isNumber(year):
157 continue
158
159 month = thisFile[-10:-8]
160 if not isNumber(month):
161 continue
162
163 day = thisFile[-8:-6]
164 if not isNumber(day):
165 continue
166
167 year, month, day = int(year), int(month), int(day)
168 dateFile = datetime.date(year, month, day)
169
170 if (startDate > dateFile) or (endDate < dateFile):
171 continue
172
173 self.fileList.append(thisFile)
174 self.dateFileList.append(dateFile)
175
176 return
177
178 def setNextFile(self):
179
180 file_id = self.fileIndex
181
182 if file_id == len(self.fileList):
183 print '\nNo more files in the folder'
184 print 'Total number of file(s) read : {}'.format(self.fileIndex + 1)
185 self.flagNoMoreFiles = 1
186 return 0
187
188 print '\n[Setting file] (%s) ...' % self.fileList[file_id]
189 filename = os.path.join(self.path, self.fileList[file_id])
190
191 dirname, name = os.path.split(filename)
192 self.siteFile = name.split('.')[0] # 'peru2' ---> Piura - 'peru1' ---> Huancayo or Porcuya
193 if self.filename is not None:
194 self.fp.close()
195 self.filename = filename
196 self.fp = open(self.filename, 'rb')
197 self.header_file = numpy.fromfile(self.fp, FILE_HEADER_STRUCTURE, 1)
198 self.nrecords = self.header_file['nrec'][0]
199 self.sizeOfFile = os.path.getsize(self.filename)
200 self.counter_records = 0
201 self.flagIsNewFile = 0
202 self.fileIndex += 1
203
204 return 1
205
206 def readNextBlock(self):
207
208 while True:
209 if self.counter_records == self.nrecords:
210 self.flagIsNewFile = 1
211 if not self.setNextFile():
212 return 0
213
214 self.readBlock()
215
216 if (self.datatime.time() < self.startTime) or (self.datatime.time() > self.endTime):
217 print "[Reading] Record No. %d/%d -> %s [Skipping]" %(
218 self.counter_records,
219 self.nrecords,
220 self.datatime.ctime())
221 continue
222 break
223
224 print "[Reading] Record No. %d/%d -> %s" %(
225 self.counter_records,
226 self.nrecords,
227 self.datatime.ctime())
228
229 return 1
230
231 def readBlock(self):
232
233 pointer = self.fp.tell()
234 header_rec = numpy.fromfile(self.fp, REC_HEADER_STRUCTURE, 1)
235 self.nchannels = header_rec['nchan'][0]/2
236 self.kchan = header_rec['nrxs'][0]
237 self.nmodes = header_rec['nmodes'][0]
238 self.nranges = header_rec['nranges'][0]
239 self.fp.seek(pointer)
240 self.height = numpy.empty((self.nmodes, self.nranges))
241 self.snr = numpy.empty((self.nmodes, self.nchannels, self.nranges))
242 self.buffer = numpy.empty((self.nmodes, 3, self.nranges))
243
244 for mode in range(self.nmodes):
245 self.readHeader()
246 data = self.readData()
247 self.height[mode] = (data[0] - self.correction) / 1000.
248 self.buffer[mode] = data[1]
249 self.snr[mode] = data[2]
250
251 self.counter_records = self.counter_records + self.nmodes
252
253 return
254
255 def readHeader(self):
256 '''
257 RecordHeader of BLTR rawdata file
258 '''
259
260 header_structure = numpy.dtype(
261 REC_HEADER_STRUCTURE.descr + [
262 ('antenna_coord', 'f4', (2, self.nchannels)),
263 ('rx_gains', 'u4', (self.nchannels,)),
264 ('rx_analysis', 'u4', (self.nchannels,))
265 ]
266 )
267
268 self.header_rec = numpy.fromfile(self.fp, header_structure, 1)
269 self.lat = self.header_rec['lat'][0]
270 self.lon = self.header_rec['lon'][0]
271 self.delta = self.header_rec['delta_r'][0]
272 self.correction = self.header_rec['dmode_rngcorr'][0]
273 self.imode = self.header_rec['dmode_index'][0]
274 self.antenna = self.header_rec['antenna_coord']
275 self.rx_gains = self.header_rec['rx_gains']
276 self.time = self.header_rec['time'][0]
277 tseconds = self.header_rec['time'][0]
278 local_t1 = time.localtime(tseconds)
279 self.year = local_t1.tm_year
280 self.month = local_t1.tm_mon
281 self.day = local_t1.tm_mday
282 self.t = datetime.datetime(self.year, self.month, self.day)
283 self.datatime = datetime.datetime.utcfromtimestamp(self.time)
284
285 def readData(self):
286 '''
287 Reading and filtering data block record of BLTR rawdata file, filtering is according to status_value.
288
289 Input:
290 status_value - Array data is set to NAN for values that are not equal to status_value
291
292 '''
293
294 data_structure = numpy.dtype(
295 DATA_STRUCTURE.descr + [
296 ('rx_saturation', 'u4', (self.nchannels,)),
297 ('chan_offset', 'u4', (2 * self.nchannels,)),
298 ('rx_amp', 'u4', (self.nchannels,)),
299 ('rx_snr', 'f4', (self.nchannels,)),
300 ('cross_snr', 'f4', (self.kchan,)),
301 ('sea_power_relative', 'f4', (self.kchan,))]
302 )
303
304 data = numpy.fromfile(self.fp, data_structure, self.nranges)
305
306 height = data['range']
307 winds = numpy.array((data['zonal'], data['meridional'], data['vertical']))
308 snr = data['rx_snr'].T
309
310 winds[numpy.where(winds == -9999.)] = numpy.nan
311 winds[:, numpy.where(data['status'] != self.status_value)] = numpy.nan
312 snr[numpy.where(snr == -9999.)] = numpy.nan
313 snr[:, numpy.where(data['status'] != self.status_value)] = numpy.nan
314 snr = numpy.power(10, snr / 10)
315
316 return height, winds, snr
317
318 def set_output(self):
319 '''
320 Storing data from databuffer to dataOut object
321 '''
322
323 self.dataOut.data_SNR = self.snr
324 self.dataOut.height = self.height
325 self.dataOut.data_output = self.buffer
326 self.dataOut.utctimeInit = self.time
327 self.dataOut.utctime = self.dataOut.utctimeInit
328 self.dataOut.useLocalTime = False
329 self.dataOut.paramInterval = 157
330 self.dataOut.timezone = self.timezone
331 self.dataOut.site = self.siteFile
332 self.dataOut.nrecords = self.nrecords/self.nmodes
333 self.dataOut.sizeOfFile = self.sizeOfFile
334 self.dataOut.lat = self.lat
335 self.dataOut.lon = self.lon
336 self.dataOut.channelList = range(self.nchannels)
337 self.dataOut.kchan = self.kchan
338 # self.dataOut.nHeights = self.nranges
339 self.dataOut.delta = self.delta
340 self.dataOut.correction = self.correction
341 self.dataOut.nmodes = self.nmodes
342 self.dataOut.imode = self.imode
343 self.dataOut.antenna = self.antenna
344 self.dataOut.rx_gains = self.rx_gains
345 self.dataOut.flagNoData = False
346
347 def getData(self):
348 '''
349 Storing data from databuffer to dataOut object
350 '''
351 if self.flagNoMoreFiles:
352 self.dataOut.flagNoData = True
353 print 'No file left to process'
354 return 0
355
356 if not self.readNextBlock():
357 self.dataOut.flagNoData = True
358 return 0
359
360 self.set_output()
361
362 return 1
This diff has been collapsed as it changes many lines, (1154 lines changed) Show them Hide them
@@ -0,0 +1,1154
1 import os, sys
2 import glob
3 import fnmatch
4 import datetime
5 import time
6 import re
7 import h5py
8 import numpy
9 import matplotlib.pyplot as plt
10
11 import pylab as plb
12 from scipy.optimize import curve_fit
13 from scipy import asarray as ar, exp
14 from scipy import stats
15
16 from numpy.ma.core import getdata
17
18 SPEED_OF_LIGHT = 299792458
19 SPEED_OF_LIGHT = 3e8
20
21 try:
22 from gevent import sleep
23 except:
24 from time import sleep
25
26 from schainpy.model.data.jrodata import Spectra
27 #from schainpy.model.data.BLTRheaderIO import FileHeader, RecordHeader
28 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
29 #from schainpy.model.io.jroIO_bltr import BLTRReader
30 from numpy import imag, shape, NaN
31
32 from jroIO_base import JRODataReader
33
34
35 class Header(object):
36
37 def __init__(self):
38 raise NotImplementedError
39
40
41 def read(self):
42
43 raise NotImplementedError
44
45 def write(self):
46
47 raise NotImplementedError
48
49 def printInfo(self):
50
51 message = "#"*50 + "\n"
52 message += self.__class__.__name__.upper() + "\n"
53 message += "#"*50 + "\n"
54
55 keyList = self.__dict__.keys()
56 keyList.sort()
57
58 for key in keyList:
59 message += "%s = %s" %(key, self.__dict__[key]) + "\n"
60
61 if "size" not in keyList:
62 attr = getattr(self, "size")
63
64 if attr:
65 message += "%s = %s" %("size", attr) + "\n"
66
67 #print message
68
69
70
71
72
73 FILE_STRUCTURE = numpy.dtype([ #HEADER 48bytes
74 ('FileMgcNumber','<u4'), #0x23020100
75 ('nFDTdataRecors','<u4'), #No Of FDT data records in this file (0 or more)
76 ('OffsetStartHeader','<u4'),
77 ('RadarUnitId','<u4'),
78 ('SiteName',numpy.str_,32), #Null terminated
79 ])
80
81 class FileHeaderBLTR(Header):
82
83 def __init__(self):
84
85 self.FileMgcNumber= 0 #0x23020100
86 self.nFDTdataRecors=0 #No Of FDT data records in this file (0 or more)
87 self.RadarUnitId= 0
88 self.OffsetStartHeader=0
89 self.SiteName= ""
90 self.size = 48
91
92 def FHread(self, fp):
93 #try:
94 startFp = open(fp,"rb")
95
96 header = numpy.fromfile(startFp, FILE_STRUCTURE,1)
97
98 print ' '
99 print 'puntero file header', startFp.tell()
100 print ' '
101
102
103 ''' numpy.fromfile(file, dtype, count, sep='')
104 file : file or str
105 Open file object or filename.
106
107 dtype : data-type
108 Data type of the returned array. For binary files, it is used to determine
109 the size and byte-order of the items in the file.
110
111 count : int
112 Number of items to read. -1 means all items (i.e., the complete file).
113
114 sep : str
115 Separator between items if file is a text file. Empty ("") separator means
116 the file should be treated as binary. Spaces (" ") in the separator match zero
117 or more whitespace characters. A separator consisting only of spaces must match
118 at least one whitespace.
119
120 '''
121
122
123
124 self.FileMgcNumber= hex(header['FileMgcNumber'][0])
125 self.nFDTdataRecors=int(header['nFDTdataRecors'][0]) #No Of FDT data records in this file (0 or more)
126 self.RadarUnitId= int(header['RadarUnitId'][0])
127 self.OffsetStartHeader= int(header['OffsetStartHeader'][0])
128 self.SiteName= str(header['SiteName'][0])
129
130 #print 'Numero de bloques', self.nFDTdataRecors
131
132
133 if self.size <48:
134 return 0
135
136 return 1
137
138
139 def write(self, fp):
140
141 headerTuple = (self.FileMgcNumber,
142 self.nFDTdataRecors,
143 self.RadarUnitId,
144 self.SiteName,
145 self.size)
146
147
148 header = numpy.array(headerTuple, FILE_STRUCTURE)
149 # numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
150 header.tofile(fp)
151 ''' ndarray.tofile(fid, sep, format) Write array to a file as text or binary (default).
152
153 fid : file or str
154 An open file object, or a string containing a filename.
155
156 sep : str
157 Separator between array items for text output. If "" (empty), a binary file is written,
158 equivalent to file.write(a.tobytes()).
159
160 format : str
161 Format string for text file output. Each entry in the array is formatted to text by
162 first converting it to the closest Python type, and then using "format" % item.
163
164 '''
165
166 return 1
167
168
169
170
171
172 RECORD_STRUCTURE = numpy.dtype([ #RECORD HEADER 180+20N bytes
173 ('RecMgcNumber','<u4'), #0x23030001
174 ('RecCounter','<u4'), #Record counter(0,1, ...)
175 ('Off2StartNxtRec','<u4'), #Offset to start of next record form start of this record
176 ('Off2StartData','<u4'), #Offset to start of data from start of this record
177 ('nUtime','<i4'), #Epoch time stamp of start of acquisition (seconds)
178 ('nMilisec','<u4'), #Millisecond component of time stamp (0,...,999)
179 ('ExpTagName',numpy.str_,32), #Experiment tag name (null terminated)
180 ('ExpComment',numpy.str_,32), #Experiment comment (null terminated)
181 ('SiteLatDegrees','<f4'), #Site latitude (from GPS) in degrees (positive implies North)
182 ('SiteLongDegrees','<f4'), #Site longitude (from GPS) in degrees (positive implies East)
183 ('RTCgpsStatus','<u4'), #RTC GPS engine status (0=SEEK, 1=LOCK, 2=NOT FITTED, 3=UNAVAILABLE)
184 ('TransmitFrec','<u4'), #Transmit frequency (Hz)
185 ('ReceiveFrec','<u4'), #Receive frequency
186 ('FirstOsciFrec','<u4'), #First local oscillator frequency (Hz)
187 ('Polarisation','<u4'), #(0="O", 1="E", 2="linear 1", 3="linear2")
188 ('ReceiverFiltSett','<u4'), #Receiver filter settings (0,1,2,3)
189 ('nModesInUse','<u4'), #Number of modes in use (1 or 2)
190 ('DualModeIndex','<u4'), #Dual Mode index number for these data (0 or 1)
191 ('DualModeRange','<u4'), #Dual Mode range correction for these data (m)
192 ('nDigChannels','<u4'), #Number of digital channels acquired (2*N)
193 ('SampResolution','<u4'), #Sampling resolution (meters)
194 ('nHeights','<u4'), #Number of range gates sampled
195 ('StartRangeSamp','<u4'), #Start range of sampling (meters)
196 ('PRFhz','<u4'), #PRF (Hz)
197 ('nCohInt','<u4'), #Integrations
198 ('nProfiles','<u4'), #Number of data points transformed
199 ('nChannels','<u4'), #Number of receive beams stored in file (1 or N)
200 ('nIncohInt','<u4'), #Number of spectral averages
201 ('FFTwindowingInd','<u4'), #FFT windowing index (0 = no window)
202 ('BeamAngleAzim','<f4'), #Beam steer angle (azimuth) in degrees (clockwise from true North)
203 ('BeamAngleZen','<f4'), #Beam steer angle (zenith) in degrees (0=> vertical)
204 ('AntennaCoord0','<f4'), #Antenna coordinates (Range(meters), Bearing(degrees)) - N pairs
205 ('AntennaAngl0','<f4'), #Antenna coordinates (Range(meters), Bearing(degrees)) - N pairs
206 ('AntennaCoord1','<f4'), #Antenna coordinates (Range(meters), Bearing(degrees)) - N pairs
207 ('AntennaAngl1','<f4'), #Antenna coordinates (Range(meters), Bearing(degrees)) - N pairs
208 ('AntennaCoord2','<f4'), #Antenna coordinates (Range(meters), Bearing(degrees)) - N pairs
209 ('AntennaAngl2','<f4'), #Antenna coordinates (Range(meters), Bearing(degrees)) - N pairs
210 ('RecPhaseCalibr0','<f4'), #Receiver phase calibration (degrees) - N values
211 ('RecPhaseCalibr1','<f4'), #Receiver phase calibration (degrees) - N values
212 ('RecPhaseCalibr2','<f4'), #Receiver phase calibration (degrees) - N values
213 ('RecAmpCalibr0','<f4'), #Receiver amplitude calibration (ratio relative to receiver one) - N values
214 ('RecAmpCalibr1','<f4'), #Receiver amplitude calibration (ratio relative to receiver one) - N values
215 ('RecAmpCalibr2','<f4'), #Receiver amplitude calibration (ratio relative to receiver one) - N values
216 ('ReceiverGaindB0','<i4'), #Receiver gains in dB - N values
217 ('ReceiverGaindB1','<i4'), #Receiver gains in dB - N values
218 ('ReceiverGaindB2','<i4'), #Receiver gains in dB - N values
219 ])
220
221
222 class RecordHeaderBLTR(Header):
223
224 def __init__(self, RecMgcNumber=None, RecCounter= 0, Off2StartNxtRec= 811248,
225 nUtime= 0, nMilisec= 0, ExpTagName= None,
226 ExpComment=None, SiteLatDegrees=0, SiteLongDegrees= 0,
227 RTCgpsStatus= 0, TransmitFrec= 0, ReceiveFrec= 0,
228 FirstOsciFrec= 0, Polarisation= 0, ReceiverFiltSett= 0,
229 nModesInUse= 0, DualModeIndex= 0, DualModeRange= 0,
230 nDigChannels= 0, SampResolution= 0, nHeights= 0,
231 StartRangeSamp= 0, PRFhz= 0, nCohInt= 0,
232 nProfiles= 0, nChannels= 0, nIncohInt= 0,
233 FFTwindowingInd= 0, BeamAngleAzim= 0, BeamAngleZen= 0,
234 AntennaCoord0= 0, AntennaCoord1= 0, AntennaCoord2= 0,
235 RecPhaseCalibr0= 0, RecPhaseCalibr1= 0, RecPhaseCalibr2= 0,
236 RecAmpCalibr0= 0, RecAmpCalibr1= 0, RecAmpCalibr2= 0,
237 AntennaAngl0=0, AntennaAngl1=0, AntennaAngl2=0,
238 ReceiverGaindB0= 0, ReceiverGaindB1= 0, ReceiverGaindB2= 0, Off2StartData=0, OffsetStartHeader=0):
239
240 self.RecMgcNumber = RecMgcNumber #0x23030001
241 self.RecCounter = RecCounter
242 self.Off2StartNxtRec = Off2StartNxtRec
243 self.Off2StartData = Off2StartData
244 self.nUtime = nUtime
245 self.nMilisec = nMilisec
246 self.ExpTagName = ExpTagName
247 self.ExpComment = ExpComment
248 self.SiteLatDegrees = SiteLatDegrees
249 self.SiteLongDegrees = SiteLongDegrees
250 self.RTCgpsStatus = RTCgpsStatus
251 self.TransmitFrec = TransmitFrec
252 self.ReceiveFrec = ReceiveFrec
253 self.FirstOsciFrec = FirstOsciFrec
254 self.Polarisation = Polarisation
255 self.ReceiverFiltSett = ReceiverFiltSett
256 self.nModesInUse = nModesInUse
257 self.DualModeIndex = DualModeIndex
258 self.DualModeRange = DualModeRange
259 self.nDigChannels = nDigChannels
260 self.SampResolution = SampResolution
261 self.nHeights = nHeights
262 self.StartRangeSamp = StartRangeSamp
263 self.PRFhz = PRFhz
264 self.nCohInt = nCohInt
265 self.nProfiles = nProfiles
266 self.nChannels = nChannels
267 self.nIncohInt = nIncohInt
268 self.FFTwindowingInd = FFTwindowingInd
269 self.BeamAngleAzim = BeamAngleAzim
270 self.BeamAngleZen = BeamAngleZen
271 self.AntennaCoord0 = AntennaCoord0
272 self.AntennaAngl0 = AntennaAngl0
273 self.AntennaAngl1 = AntennaAngl1
274 self.AntennaAngl2 = AntennaAngl2
275 self.AntennaCoord1 = AntennaCoord1
276 self.AntennaCoord2 = AntennaCoord2
277 self.RecPhaseCalibr0 = RecPhaseCalibr0
278 self.RecPhaseCalibr1 = RecPhaseCalibr1
279 self.RecPhaseCalibr2 = RecPhaseCalibr2
280 self.RecAmpCalibr0 = RecAmpCalibr0
281 self.RecAmpCalibr1 = RecAmpCalibr1
282 self.RecAmpCalibr2 = RecAmpCalibr2
283 self.ReceiverGaindB0 = ReceiverGaindB0
284 self.ReceiverGaindB1 = ReceiverGaindB1
285 self.ReceiverGaindB2 = ReceiverGaindB2
286 self.OffsetStartHeader = 48
287
288
289
290 def RHread(self, fp):
291 #print fp
292 #startFp = open('/home/erick/Documents/Data/huancayo.20161019.22.fdt',"rb") #The method tell() returns the current position of the file read/write pointer within the file.
293 startFp = open(fp,"rb") #The method tell() returns the current position of the file read/write pointer within the file.
294 #RecCounter=0
295 #Off2StartNxtRec=811248
296 OffRHeader= self.OffsetStartHeader + self.RecCounter*self.Off2StartNxtRec
297 print ' '
298 print 'puntero Record Header', startFp.tell()
299 print ' '
300
301
302 startFp.seek(OffRHeader, os.SEEK_SET)
303
304 print ' '
305 print 'puntero Record Header con seek', startFp.tell()
306 print ' '
307
308 #print 'Posicion del bloque: ',OffRHeader
309
310 header = numpy.fromfile(startFp,RECORD_STRUCTURE,1)
311
312 print ' '
313 print 'puntero Record Header con seek', startFp.tell()
314 print ' '
315
316 print ' '
317 #
318 #print 'puntero Record Header despues de seek', header.tell()
319 print ' '
320
321 self.RecMgcNumber = hex(header['RecMgcNumber'][0]) #0x23030001
322 self.RecCounter = int(header['RecCounter'][0])
323 self.Off2StartNxtRec = int(header['Off2StartNxtRec'][0])
324 self.Off2StartData = int(header['Off2StartData'][0])
325 self.nUtime = header['nUtime'][0]
326 self.nMilisec = header['nMilisec'][0]
327 self.ExpTagName = str(header['ExpTagName'][0])
328 self.ExpComment = str(header['ExpComment'][0])
329 self.SiteLatDegrees = header['SiteLatDegrees'][0]
330 self.SiteLongDegrees = header['SiteLongDegrees'][0]
331 self.RTCgpsStatus = header['RTCgpsStatus'][0]
332 self.TransmitFrec = header['TransmitFrec'][0]
333 self.ReceiveFrec = header['ReceiveFrec'][0]
334 self.FirstOsciFrec = header['FirstOsciFrec'][0]
335 self.Polarisation = header['Polarisation'][0]
336 self.ReceiverFiltSett = header['ReceiverFiltSett'][0]
337 self.nModesInUse = header['nModesInUse'][0]
338 self.DualModeIndex = header['DualModeIndex'][0]
339 self.DualModeRange = header['DualModeRange'][0]
340 self.nDigChannels = header['nDigChannels'][0]
341 self.SampResolution = header['SampResolution'][0]
342 self.nHeights = header['nHeights'][0]
343 self.StartRangeSamp = header['StartRangeSamp'][0]
344 self.PRFhz = header['PRFhz'][0]
345 self.nCohInt = header['nCohInt'][0]
346 self.nProfiles = header['nProfiles'][0]
347 self.nChannels = header['nChannels'][0]
348 self.nIncohInt = header['nIncohInt'][0]
349 self.FFTwindowingInd = header['FFTwindowingInd'][0]
350 self.BeamAngleAzim = header['BeamAngleAzim'][0]
351 self.BeamAngleZen = header['BeamAngleZen'][0]
352 self.AntennaCoord0 = header['AntennaCoord0'][0]
353 self.AntennaAngl0 = header['AntennaAngl0'][0]
354 self.AntennaCoord1 = header['AntennaCoord1'][0]
355 self.AntennaAngl1 = header['AntennaAngl1'][0]
356 self.AntennaCoord2 = header['AntennaCoord2'][0]
357 self.AntennaAngl2 = header['AntennaAngl2'][0]
358 self.RecPhaseCalibr0 = header['RecPhaseCalibr0'][0]
359 self.RecPhaseCalibr1 = header['RecPhaseCalibr1'][0]
360 self.RecPhaseCalibr2 = header['RecPhaseCalibr2'][0]
361 self.RecAmpCalibr0 = header['RecAmpCalibr0'][0]
362 self.RecAmpCalibr1 = header['RecAmpCalibr1'][0]
363 self.RecAmpCalibr2 = header['RecAmpCalibr2'][0]
364 self.ReceiverGaindB0 = header['ReceiverGaindB0'][0]
365 self.ReceiverGaindB1 = header['ReceiverGaindB1'][0]
366 self.ReceiverGaindB2 = header['ReceiverGaindB2'][0]
367
368 self.ipp= 0.5*(SPEED_OF_LIGHT/self.PRFhz)
369
370 self.RHsize = 180+20*self.nChannels
371 self.Datasize= self.nProfiles*self.nChannels*self.nHeights*2*4
372 #print 'Datasize',self.Datasize
373 endFp = self.OffsetStartHeader + self.RecCounter*self.Off2StartNxtRec
374
375 print '=============================================='
376 print 'RecMgcNumber ',self.RecMgcNumber
377 print 'RecCounter ',self.RecCounter
378 print 'Off2StartNxtRec ',self.Off2StartNxtRec
379 print 'Off2StartData ',self.Off2StartData
380 print 'Range Resolution ',self.SampResolution
381 print 'First Height ',self.StartRangeSamp
382 print 'PRF (Hz) ',self.PRFhz
383 print 'Heights (K) ',self.nHeights
384 print 'Channels (N) ',self.nChannels
385 print 'Profiles (J) ',self.nProfiles
386 print 'iCoh ',self.nCohInt
387 print 'iInCoh ',self.nIncohInt
388 print 'BeamAngleAzim ',self.BeamAngleAzim
389 print 'BeamAngleZen ',self.BeamAngleZen
390
391 #print 'ModoEnUso ',self.DualModeIndex
392 #print 'UtcTime ',self.nUtime
393 #print 'MiliSec ',self.nMilisec
394 #print 'Exp TagName ',self.ExpTagName
395 #print 'Exp Comment ',self.ExpComment
396 #print 'FFT Window Index ',self.FFTwindowingInd
397 #print 'N Dig. Channels ',self.nDigChannels
398 print 'Size de bloque ',self.RHsize
399 print 'DataSize ',self.Datasize
400 print 'BeamAngleAzim ',self.BeamAngleAzim
401 #print 'AntennaCoord0 ',self.AntennaCoord0
402 #print 'AntennaAngl0 ',self.AntennaAngl0
403 #print 'AntennaCoord1 ',self.AntennaCoord1
404 #print 'AntennaAngl1 ',self.AntennaAngl1
405 #print 'AntennaCoord2 ',self.AntennaCoord2
406 #print 'AntennaAngl2 ',self.AntennaAngl2
407 print 'RecPhaseCalibr0 ',self.RecPhaseCalibr0
408 print 'RecPhaseCalibr1 ',self.RecPhaseCalibr1
409 print 'RecPhaseCalibr2 ',self.RecPhaseCalibr2
410 print 'RecAmpCalibr0 ',self.RecAmpCalibr0
411 print 'RecAmpCalibr1 ',self.RecAmpCalibr1
412 print 'RecAmpCalibr2 ',self.RecAmpCalibr2
413 print 'ReceiverGaindB0 ',self.ReceiverGaindB0
414 print 'ReceiverGaindB1 ',self.ReceiverGaindB1
415 print 'ReceiverGaindB2 ',self.ReceiverGaindB2
416 print '=============================================='
417
418 if OffRHeader > endFp:
419 sys.stderr.write("Warning %s: Size value read from System Header is lower than it has to be\n" %fp)
420 return 0
421
422 if OffRHeader < endFp:
423 sys.stderr.write("Warning %s: Size value read from System Header size is greater than it has to be\n" %fp)
424 return 0
425
426 return 1
427
428
429 class BLTRSpectraReader (ProcessingUnit, FileHeaderBLTR, RecordHeaderBLTR, JRODataReader):
430
431 path = None
432 startDate = None
433 endDate = None
434 startTime = None
435 endTime = None
436 walk = None
437 isConfig = False
438
439
440 fileList= None
441
442 #metadata
443 TimeZone= None
444 Interval= None
445 heightList= None
446
447 #data
448 data= None
449 utctime= None
450
451
452
453 def __init__(self, **kwargs):
454
455 #Eliminar de la base la herencia
456 ProcessingUnit.__init__(self, **kwargs)
457
458 #self.isConfig = False
459
460 #self.pts2read_SelfSpectra = 0
461 #self.pts2read_CrossSpectra = 0
462 #self.pts2read_DCchannels = 0
463 #self.datablock = None
464 self.utc = None
465 self.ext = ".fdt"
466 self.optchar = "P"
467 self.fpFile=None
468 self.fp = None
469 self.BlockCounter=0
470 self.dtype = None
471 self.fileSizeByHeader = None
472 self.filenameList = []
473 self.fileSelector = 0
474 self.Off2StartNxtRec=0
475 self.RecCounter=0
476 self.flagNoMoreFiles = 0
477 self.data_spc=None
478 self.data_cspc=None
479 self.data_output=None
480 self.path = None
481 self.OffsetStartHeader=0
482 self.Off2StartData=0
483 self.ipp = 0
484 self.nFDTdataRecors=0
485 self.blocksize = 0
486 self.dataOut = Spectra()
487 self.profileIndex = 1 #Always
488 self.dataOut.flagNoData=False
489 self.dataOut.nRdPairs = 0
490 self.dataOut.pairsList = []
491 self.dataOut.data_spc=None
492 self.dataOut.noise=[]
493 self.dataOut.velocityX=[]
494 self.dataOut.velocityY=[]
495 self.dataOut.velocityV=[]
496
497
498
499 def Files2Read(self, fp):
500 '''
501 Function that indicates the number of .fdt files that exist in the folder to be read.
502 It also creates an organized list with the names of the files to read.
503 '''
504 #self.__checkPath()
505
506 ListaData=os.listdir(fp) #Gets the list of files within the fp address
507 ListaData=sorted(ListaData) #Sort the list of files from least to largest by names
508 nFiles=0 #File Counter
509 FileList=[] #A list is created that will contain the .fdt files
510 for IndexFile in ListaData :
511 if '.fdt' in IndexFile:
512 FileList.append(IndexFile)
513 nFiles+=1
514
515 #print 'Files2Read'
516 #print 'Existen '+str(nFiles)+' archivos .fdt'
517
518 self.filenameList=FileList #List of files from least to largest by names
519
520
521 def run(self, **kwargs):
522 '''
523 This method will be the one that will initiate the data entry, will be called constantly.
524 You should first verify that your Setup () is set up and then continue to acquire
525 the data to be processed with getData ().
526 '''
527 if not self.isConfig:
528 self.setup(**kwargs)
529 self.isConfig = True
530
531 self.getData()
532 #print 'running'
533
534
535 def setup(self, path=None,
536 startDate=None,
537 endDate=None,
538 startTime=None,
539 endTime=None,
540 walk=True,
541 timezone='utc',
542 code = None,
543 online=False,
544 ReadMode=None,
545 **kwargs):
546
547 self.isConfig = True
548
549 self.path=path
550 self.startDate=startDate
551 self.endDate=endDate
552 self.startTime=startTime
553 self.endTime=endTime
554 self.walk=walk
555 self.ReadMode=int(ReadMode)
556
557 pass
558
559
560 def getData(self):
561 '''
562 Before starting this function, you should check that there is still an unread file,
563 If there are still blocks to read or if the data block is empty.
564
565 You should call the file "read".
566
567 '''
568
569 if self.flagNoMoreFiles:
570 self.dataOut.flagNoData = True
571 print 'NoData se vuelve true'
572 return 0
573
574 self.fp=self.path
575 self.Files2Read(self.fp)
576 self.readFile(self.fp)
577 self.dataOut.data_spc = self.data_spc
578 self.dataOut.data_cspc =self.data_cspc
579 self.dataOut.data_output=self.data_output
580
581 print 'self.dataOut.data_output', shape(self.dataOut.data_output)
582
583 #self.removeDC()
584 return self.dataOut.data_spc
585
586
587 def readFile(self,fp):
588 '''
589 You must indicate if you are reading in Online or Offline mode and load the
590 The parameters for this file reading mode.
591
592 Then you must do 2 actions:
593
594 1. Get the BLTR FileHeader.
595 2. Start reading the first block.
596 '''
597
598 #The address of the folder is generated the name of the .fdt file that will be read
599 print "File: ",self.fileSelector+1
600
601 if self.fileSelector < len(self.filenameList):
602
603 self.fpFile=str(fp)+'/'+str(self.filenameList[self.fileSelector])
604 #print self.fpFile
605 fheader = FileHeaderBLTR()
606 fheader.FHread(self.fpFile) #Bltr FileHeader Reading
607 self.nFDTdataRecors=fheader.nFDTdataRecors
608
609 self.readBlock() #Block reading
610 else:
611 print 'readFile FlagNoData becomes true'
612 self.flagNoMoreFiles=True
613 self.dataOut.flagNoData = True
614 return 0
615
616 def getVelRange(self, extrapoints=0):
617 Lambda= SPEED_OF_LIGHT/50000000
618 PRF = self.dataOut.PRF#1./(self.dataOut.ippSeconds * self.dataOut.nCohInt)
619 Vmax=-Lambda/(4.*(1./PRF)*self.dataOut.nCohInt*2.)
620 deltafreq = PRF / (self.nProfiles)
621 deltavel = (Vmax*2) / (self.nProfiles)
622 freqrange = deltafreq*(numpy.arange(self.nProfiles)-self.nProfiles/2.) - deltafreq/2
623 velrange = deltavel*(numpy.arange(self.nProfiles)-self.nProfiles/2.)
624 return velrange
625
626 def readBlock(self):
627 '''
628 It should be checked if the block has data, if it is not passed to the next file.
629
630 Then the following is done:
631
632 1. Read the RecordHeader
633 2. Fill the buffer with the current block number.
634
635 '''
636
637 if self.BlockCounter < self.nFDTdataRecors-2:
638 print self.nFDTdataRecors, 'CONDICION!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
639 if self.ReadMode==1:
640 rheader = RecordHeaderBLTR(RecCounter=self.BlockCounter+1)
641 elif self.ReadMode==0:
642 rheader = RecordHeaderBLTR(RecCounter=self.BlockCounter)
643
644 rheader.RHread(self.fpFile) #Bltr FileHeader Reading
645
646 self.OffsetStartHeader=rheader.OffsetStartHeader
647 self.RecCounter=rheader.RecCounter
648 self.Off2StartNxtRec=rheader.Off2StartNxtRec
649 self.Off2StartData=rheader.Off2StartData
650 self.nProfiles=rheader.nProfiles
651 self.nChannels=rheader.nChannels
652 self.nHeights=rheader.nHeights
653 self.frequency=rheader.TransmitFrec
654 self.DualModeIndex=rheader.DualModeIndex
655
656 self.pairsList =[(0,1),(0,2),(1,2)]
657 self.dataOut.pairsList = self.pairsList
658
659 self.nRdPairs=len(self.dataOut.pairsList)
660 self.dataOut.nRdPairs = self.nRdPairs
661
662 self.__firstHeigth=rheader.StartRangeSamp
663 self.__deltaHeigth=rheader.SampResolution
664 self.dataOut.heightList= self.__firstHeigth + numpy.array(range(self.nHeights))*self.__deltaHeigth
665 self.dataOut.channelList = range(self.nChannels)
666 self.dataOut.nProfiles=rheader.nProfiles
667 self.dataOut.nIncohInt=rheader.nIncohInt
668 self.dataOut.nCohInt=rheader.nCohInt
669 self.dataOut.ippSeconds= 1/float(rheader.PRFhz)
670 self.dataOut.PRF=rheader.PRFhz
671 self.dataOut.nFFTPoints=rheader.nProfiles
672 self.dataOut.utctime=rheader.nUtime
673 self.dataOut.timeZone=0
674 self.dataOut.normFactor= self.dataOut.nProfiles*self.dataOut.nIncohInt*self.dataOut.nCohInt
675 self.dataOut.outputInterval= self.dataOut.ippSeconds * self.dataOut.nCohInt * self.dataOut.nIncohInt * self.nProfiles
676
677 self.data_output=numpy.ones([3,rheader.nHeights])*numpy.NaN
678 print 'self.data_output', shape(self.data_output)
679 self.dataOut.velocityX=[]
680 self.dataOut.velocityY=[]
681 self.dataOut.velocityV=[]
682
683 '''Block Reading, the Block Data is received and Reshape is used to give it
684 shape.
685 '''
686
687 #Procedure to take the pointer to where the date block starts
688 startDATA = open(self.fpFile,"rb")
689 OffDATA= self.OffsetStartHeader + self.RecCounter*self.Off2StartNxtRec+self.Off2StartData
690 startDATA.seek(OffDATA, os.SEEK_SET)
691
692 def moving_average(x, N=2):
693 return numpy.convolve(x, numpy.ones((N,))/N)[(N-1):]
694
695 def gaus(xSamples,a,x0,sigma):
696 return a*exp(-(xSamples-x0)**2/(2*sigma**2))
697
698 def Find(x,value):
699 for index in range(len(x)):
700 if x[index]==value:
701 return index
702
703 def pol2cart(rho, phi):
704 x = rho * numpy.cos(phi)
705 y = rho * numpy.sin(phi)
706 return(x, y)
707
708
709
710
711 if self.DualModeIndex==self.ReadMode:
712
713 self.data_fft = numpy.fromfile( startDATA, [('complex','<c8')],self.nProfiles*self.nChannels*self.nHeights )
714
715 self.data_fft=self.data_fft.astype(numpy.dtype('complex'))
716
717 self.data_block=numpy.reshape(self.data_fft,(self.nHeights, self.nChannels, self.nProfiles ))
718
719 self.data_block = numpy.transpose(self.data_block, (1,2,0))
720
721 copy = self.data_block.copy()
722 spc = copy * numpy.conjugate(copy)
723
724 self.data_spc = numpy.absolute(spc) # valor absoluto o magnitud
725
726 factor = self.dataOut.normFactor
727
728
729 z = self.data_spc.copy()#/factor
730 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
731 #zdB = 10*numpy.log10(z)
732 print ' '
733 print 'Z: '
734 print shape(z)
735 print ' '
736 print ' '
737
738 self.dataOut.data_spc=self.data_spc
739
740 self.noise = self.dataOut.getNoise(ymin_index=80, ymax_index=132)#/factor
741 #noisedB = 10*numpy.log10(self.noise)
742
743
744 ySamples=numpy.ones([3,self.nProfiles])
745 phase=numpy.ones([3,self.nProfiles])
746 CSPCSamples=numpy.ones([3,self.nProfiles],dtype=numpy.complex_)
747 coherence=numpy.ones([3,self.nProfiles])
748 PhaseSlope=numpy.ones(3)
749 PhaseInter=numpy.ones(3)
750
751 '''****** Getting CrossSpectra ******'''
752 cspc=self.data_block.copy()
753 self.data_cspc=self.data_block.copy()
754
755 xFrec=self.getVelRange(1)
756 VelRange=self.getVelRange(1)
757 self.dataOut.VelRange=VelRange
758 #print ' '
759 #print ' '
760 #print 'xFrec',xFrec
761 #print ' '
762 #print ' '
763 #Height=35
764 for i in range(self.nRdPairs):
765
766 chan_index0 = self.dataOut.pairsList[i][0]
767 chan_index1 = self.dataOut.pairsList[i][1]
768
769 self.data_cspc[i,:,:]=cspc[chan_index0,:,:] * numpy.conjugate(cspc[chan_index1,:,:])
770
771
772 '''Getting Eij and Nij'''
773 (AntennaX0,AntennaY0)=pol2cart(rheader.AntennaCoord0, rheader.AntennaAngl0*numpy.pi/180)
774 (AntennaX1,AntennaY1)=pol2cart(rheader.AntennaCoord1, rheader.AntennaAngl1*numpy.pi/180)
775 (AntennaX2,AntennaY2)=pol2cart(rheader.AntennaCoord2, rheader.AntennaAngl2*numpy.pi/180)
776
777 E01=AntennaX0-AntennaX1
778 N01=AntennaY0-AntennaY1
779
780 E02=AntennaX0-AntennaX2
781 N02=AntennaY0-AntennaY2
782
783 E12=AntennaX1-AntennaX2
784 N12=AntennaY1-AntennaY2
785
786 self.ChanDist= numpy.array([[E01, N01],[E02,N02],[E12,N12]])
787
788 self.dataOut.ChanDist = self.ChanDist
789
790
791 # for Height in range(self.nHeights):
792 #
793 # for i in range(self.nRdPairs):
794 #
795 # '''****** Line of Data SPC ******'''
796 # zline=z[i,:,Height]
797 #
798 # '''****** DC is removed ******'''
799 # DC=Find(zline,numpy.amax(zline))
800 # zline[DC]=(zline[DC-1]+zline[DC+1])/2
801 #
802 #
803 # '''****** SPC is normalized ******'''
804 # FactNorm= zline.copy() / numpy.sum(zline.copy())
805 # FactNorm= FactNorm/numpy.sum(FactNorm)
806 #
807 # SmoothSPC=moving_average(FactNorm,N=3)
808 #
809 # xSamples = ar(range(len(SmoothSPC)))
810 # ySamples[i] = SmoothSPC-self.noise[i]
811 #
812 # for i in range(self.nRdPairs):
813 #
814 # '''****** Line of Data CSPC ******'''
815 # cspcLine=self.data_cspc[i,:,Height].copy()
816 #
817 #
818 #
819 # '''****** CSPC is normalized ******'''
820 # chan_index0 = self.dataOut.pairsList[i][0]
821 # chan_index1 = self.dataOut.pairsList[i][1]
822 # CSPCFactor= numpy.sum(ySamples[chan_index0]) * numpy.sum(ySamples[chan_index1])
823 #
824 #
825 # CSPCNorm= cspcLine.copy() / numpy.sqrt(CSPCFactor)
826 #
827 #
828 # CSPCSamples[i] = CSPCNorm-self.noise[i]
829 # coherence[i] = numpy.abs(CSPCSamples[i]) / numpy.sqrt(CSPCFactor)
830 #
831 # '''****** DC is removed ******'''
832 # DC=Find(coherence[i],numpy.amax(coherence[i]))
833 # coherence[i][DC]=(coherence[i][DC-1]+coherence[i][DC+1])/2
834 # coherence[i]= moving_average(coherence[i],N=2)
835 #
836 # phase[i] = moving_average( numpy.arctan2(CSPCSamples[i].imag, CSPCSamples[i].real),N=1)#*180/numpy.pi
837 #
838 #
839 # '''****** Getting fij width ******'''
840 #
841 # yMean=[]
842 # yMean2=[]
843 #
844 # for j in range(len(ySamples[1])):
845 # yMean=numpy.append(yMean,numpy.average([ySamples[0,j],ySamples[1,j],ySamples[2,j]]))
846 #
847 # '''******* Getting fitting Gaussian ******'''
848 # meanGauss=sum(xSamples*yMean) / len(xSamples)
849 # sigma=sum(yMean*(xSamples-meanGauss)**2) / len(xSamples)
850 # #print 'Height',Height,'SNR', meanGauss/sigma**2
851 #
852 # if (abs(meanGauss/sigma**2) > 0.0001) :
853 #
854 # try:
855 # popt,pcov = curve_fit(gaus,xSamples,yMean,p0=[1,meanGauss,sigma])
856 #
857 # if numpy.amax(popt)>numpy.amax(yMean)*0.3:
858 # FitGauss=gaus(xSamples,*popt)
859 #
860 # else:
861 # FitGauss=numpy.ones(len(xSamples))*numpy.mean(yMean)
862 # print 'Verificador: Dentro', Height
863 # except RuntimeError:
864 #
865 # try:
866 # for j in range(len(ySamples[1])):
867 # yMean2=numpy.append(yMean2,numpy.average([ySamples[1,j],ySamples[2,j]]))
868 # popt,pcov = curve_fit(gaus,xSamples,yMean2,p0=[1,meanGauss,sigma])
869 # FitGauss=gaus(xSamples,*popt)
870 # print 'Verificador: Exepcion1', Height
871 # except RuntimeError:
872 #
873 # try:
874 # popt,pcov = curve_fit(gaus,xSamples,ySamples[1],p0=[1,meanGauss,sigma])
875 # FitGauss=gaus(xSamples,*popt)
876 # print 'Verificador: Exepcion2', Height
877 # except RuntimeError:
878 # FitGauss=numpy.ones(len(xSamples))*numpy.mean(yMean)
879 # print 'Verificador: Exepcion3', Height
880 # else:
881 # FitGauss=numpy.ones(len(xSamples))*numpy.mean(yMean)
882 # #print 'Verificador: Fuera', Height
883 #
884 #
885 #
886 # Maximun=numpy.amax(yMean)
887 # eMinus1=Maximun*numpy.exp(-1)
888 #
889 # HWpos=Find(FitGauss,min(FitGauss, key=lambda value:abs(value-eMinus1)))
890 # HalfWidth= xFrec[HWpos]
891 # GCpos=Find(FitGauss, numpy.amax(FitGauss))
892 # Vpos=Find(FactNorm, numpy.amax(FactNorm))
893 # #Vpos=numpy.sum(FactNorm)/len(FactNorm)
894 # #Vpos=Find(FactNorm, min(FactNorm, key=lambda value:abs(value- numpy.mean(FactNorm) )))
895 # #print 'GCpos',GCpos, numpy.amax(FitGauss), 'HWpos',HWpos
896 # '''****** Getting Fij ******'''
897 #
898 # GaussCenter=xFrec[GCpos]
899 # if (GaussCenter<0 and HalfWidth>0) or (GaussCenter>0 and HalfWidth<0):
900 # Fij=abs(GaussCenter)+abs(HalfWidth)+0.0000001
901 # else:
902 # Fij=abs(GaussCenter-HalfWidth)+0.0000001
903 #
904 # '''****** Getting Frecuency range of significant data ******'''
905 #
906 # Rangpos=Find(FitGauss,min(FitGauss, key=lambda value:abs(value-Maximun*0.10)))
907 #
908 # if Rangpos<GCpos:
909 # Range=numpy.array([Rangpos,2*GCpos-Rangpos])
910 # else:
911 # Range=numpy.array([2*GCpos-Rangpos,Rangpos])
912 #
913 # FrecRange=xFrec[Range[0]:Range[1]]
914 #
915 # #print 'FrecRange', FrecRange
916 # '''****** Getting SCPC Slope ******'''
917 #
918 # for i in range(self.nRdPairs):
919 #
920 # if len(FrecRange)>5 and len(FrecRange)<self.nProfiles*0.5:
921 # PhaseRange=moving_average(phase[i,Range[0]:Range[1]],N=3)
922 #
923 # slope, intercept, r_value, p_value, std_err = stats.linregress(FrecRange,PhaseRange)
924 # PhaseSlope[i]=slope
925 # PhaseInter[i]=intercept
926 # else:
927 # PhaseSlope[i]=0
928 # PhaseInter[i]=0
929 #
930 # # plt.figure(i+15)
931 # # plt.title('FASE ( CH%s*CH%s )' %(self.dataOut.pairsList[i][0],self.dataOut.pairsList[i][1]))
932 # # plt.xlabel('Frecuencia (KHz)')
933 # # plt.ylabel('Magnitud')
934 # # #plt.subplot(311+i)
935 # # plt.plot(FrecRange,PhaseRange,'b')
936 # # plt.plot(FrecRange,FrecRange*PhaseSlope[i]+PhaseInter[i],'r')
937 #
938 # #plt.axis([-0.6, 0.2, -3.2, 3.2])
939 #
940 #
941 # '''Getting constant C'''
942 # cC=(Fij*numpy.pi)**2
943 #
944 # # '''Getting Eij and Nij'''
945 # # (AntennaX0,AntennaY0)=pol2cart(rheader.AntennaCoord0, rheader.AntennaAngl0*numpy.pi/180)
946 # # (AntennaX1,AntennaY1)=pol2cart(rheader.AntennaCoord1, rheader.AntennaAngl1*numpy.pi/180)
947 # # (AntennaX2,AntennaY2)=pol2cart(rheader.AntennaCoord2, rheader.AntennaAngl2*numpy.pi/180)
948 # #
949 # # E01=AntennaX0-AntennaX1
950 # # N01=AntennaY0-AntennaY1
951 # #
952 # # E02=AntennaX0-AntennaX2
953 # # N02=AntennaY0-AntennaY2
954 # #
955 # # E12=AntennaX1-AntennaX2
956 # # N12=AntennaY1-AntennaY2
957 #
958 # '''****** Getting constants F and G ******'''
959 # MijEijNij=numpy.array([[E02,N02], [E12,N12]])
960 # MijResult0=(-PhaseSlope[1]*cC) / (2*numpy.pi)
961 # MijResult1=(-PhaseSlope[2]*cC) / (2*numpy.pi)
962 # MijResults=numpy.array([MijResult0,MijResult1])
963 # (cF,cG) = numpy.linalg.solve(MijEijNij, MijResults)
964 #
965 # '''****** Getting constants A, B and H ******'''
966 # W01=numpy.amax(coherence[0])
967 # W02=numpy.amax(coherence[1])
968 # W12=numpy.amax(coherence[2])
969 #
970 # WijResult0=((cF*E01+cG*N01)**2)/cC - numpy.log(W01 / numpy.sqrt(numpy.pi/cC))
971 # WijResult1=((cF*E02+cG*N02)**2)/cC - numpy.log(W02 / numpy.sqrt(numpy.pi/cC))
972 # WijResult2=((cF*E12+cG*N12)**2)/cC - numpy.log(W12 / numpy.sqrt(numpy.pi/cC))
973 #
974 # WijResults=numpy.array([WijResult0, WijResult1, WijResult2])
975 #
976 # WijEijNij=numpy.array([ [E01**2, N01**2, 2*E01*N01] , [E02**2, N02**2, 2*E02*N02] , [E12**2, N12**2, 2*E12*N12] ])
977 # (cA,cB,cH) = numpy.linalg.solve(WijEijNij, WijResults)
978 #
979 # VxVy=numpy.array([[cA,cH],[cH,cB]])
980 #
981 # VxVyResults=numpy.array([-cF,-cG])
982 # (Vx,Vy) = numpy.linalg.solve(VxVy, VxVyResults)
983 # Vzon = Vy
984 # Vmer = Vx
985 # Vmag=numpy.sqrt(Vzon**2+Vmer**2)
986 # Vang=numpy.arctan2(Vmer,Vzon)
987 #
988 # if abs(Vy)<100 and abs(Vy)> 0.:
989 # self.dataOut.velocityX=numpy.append(self.dataOut.velocityX, Vzon) #Vmag
990 # #print 'Vmag',Vmag
991 # else:
992 # self.dataOut.velocityX=numpy.append(self.dataOut.velocityX, NaN)
993 #
994 # if abs(Vx)<100 and abs(Vx) > 0.:
995 # self.dataOut.velocityY=numpy.append(self.dataOut.velocityY, Vmer) #Vang
996 # #print 'Vang',Vang
997 # else:
998 # self.dataOut.velocityY=numpy.append(self.dataOut.velocityY, NaN)
999 #
1000 # if abs(GaussCenter)<2:
1001 # self.dataOut.velocityV=numpy.append(self.dataOut.velocityV, xFrec[Vpos])
1002 #
1003 # else:
1004 # self.dataOut.velocityV=numpy.append(self.dataOut.velocityV, NaN)
1005 #
1006 #
1007 # # print '********************************************'
1008 # # print 'HalfWidth ', HalfWidth
1009 # # print 'Maximun ', Maximun
1010 # # print 'eMinus1 ', eMinus1
1011 # # print 'Rangpos ', Rangpos
1012 # # print 'GaussCenter ',GaussCenter
1013 # # print 'E01 ',E01
1014 # # print 'N01 ',N01
1015 # # print 'E02 ',E02
1016 # # print 'N02 ',N02
1017 # # print 'E12 ',E12
1018 # # print 'N12 ',N12
1019 # #print 'self.dataOut.velocityX ', self.dataOut.velocityX
1020 # # print 'Fij ', Fij
1021 # # print 'cC ', cC
1022 # # print 'cF ', cF
1023 # # print 'cG ', cG
1024 # # print 'cA ', cA
1025 # # print 'cB ', cB
1026 # # print 'cH ', cH
1027 # # print 'Vx ', Vx
1028 # # print 'Vy ', Vy
1029 # # print 'Vmag ', Vmag
1030 # # print 'Vang ', Vang*180/numpy.pi
1031 # # print 'PhaseSlope ',PhaseSlope[0]
1032 # # print 'PhaseSlope ',PhaseSlope[1]
1033 # # print 'PhaseSlope ',PhaseSlope[2]
1034 # # print '********************************************'
1035 # #print 'data_output',shape(self.dataOut.velocityX), shape(self.dataOut.velocityY)
1036 #
1037 # #print 'self.dataOut.velocityX', len(self.dataOut.velocityX)
1038 # #print 'self.dataOut.velocityY', len(self.dataOut.velocityY)
1039 # #print 'self.dataOut.velocityV', self.dataOut.velocityV
1040 #
1041 # self.data_output[0]=numpy.array(self.dataOut.velocityX)
1042 # self.data_output[1]=numpy.array(self.dataOut.velocityY)
1043 # self.data_output[2]=numpy.array(self.dataOut.velocityV)
1044 #
1045 # prin= self.data_output[0][~numpy.isnan(self.data_output[0])]
1046 # print ' '
1047 # print 'VmagAverage',numpy.mean(prin)
1048 # print ' '
1049 # # plt.figure(5)
1050 # # plt.subplot(211)
1051 # # plt.plot(self.dataOut.velocityX,'yo:')
1052 # # plt.subplot(212)
1053 # # plt.plot(self.dataOut.velocityY,'yo:')
1054 #
1055 # # plt.figure(1)
1056 # # # plt.subplot(121)
1057 # # # plt.plot(xFrec,ySamples[0],'k',label='Ch0')
1058 # # # plt.plot(xFrec,ySamples[1],'g',label='Ch1')
1059 # # # plt.plot(xFrec,ySamples[2],'r',label='Ch2')
1060 # # # plt.plot(xFrec,FitGauss,'yo:',label='fit')
1061 # # # plt.legend()
1062 # # plt.title('DATOS A ALTURA DE 2850 METROS')
1063 # #
1064 # # plt.xlabel('Frecuencia (KHz)')
1065 # # plt.ylabel('Magnitud')
1066 # # # plt.subplot(122)
1067 # # # plt.title('Fit for Time Constant')
1068 # # #plt.plot(xFrec,zline)
1069 # # #plt.plot(xFrec,SmoothSPC,'g')
1070 # # plt.plot(xFrec,FactNorm)
1071 # # plt.axis([-4, 4, 0, 0.15])
1072 # # # plt.xlabel('SelfSpectra KHz')
1073 # #
1074 # # plt.figure(10)
1075 # # # plt.subplot(121)
1076 # # plt.plot(xFrec,ySamples[0],'b',label='Ch0')
1077 # # plt.plot(xFrec,ySamples[1],'y',label='Ch1')
1078 # # plt.plot(xFrec,ySamples[2],'r',label='Ch2')
1079 # # # plt.plot(xFrec,FitGauss,'yo:',label='fit')
1080 # # plt.legend()
1081 # # plt.title('SELFSPECTRA EN CANALES')
1082 # #
1083 # # plt.xlabel('Frecuencia (KHz)')
1084 # # plt.ylabel('Magnitud')
1085 # # # plt.subplot(122)
1086 # # # plt.title('Fit for Time Constant')
1087 # # #plt.plot(xFrec,zline)
1088 # # #plt.plot(xFrec,SmoothSPC,'g')
1089 # # # plt.plot(xFrec,FactNorm)
1090 # # # plt.axis([-4, 4, 0, 0.15])
1091 # # # plt.xlabel('SelfSpectra KHz')
1092 # #
1093 # # plt.figure(9)
1094 # #
1095 # #
1096 # # plt.title('DATOS SUAVIZADOS')
1097 # # plt.xlabel('Frecuencia (KHz)')
1098 # # plt.ylabel('Magnitud')
1099 # # plt.plot(xFrec,SmoothSPC,'g')
1100 # #
1101 # # #plt.plot(xFrec,FactNorm)
1102 # # plt.axis([-4, 4, 0, 0.15])
1103 # # # plt.xlabel('SelfSpectra KHz')
1104 # # #
1105 # # plt.figure(2)
1106 # # # #plt.subplot(121)
1107 # # plt.plot(xFrec,yMean,'r',label='Mean SelfSpectra')
1108 # # plt.plot(xFrec,FitGauss,'yo:',label='Ajuste Gaussiano')
1109 # # # plt.plot(xFrec[Rangpos],FitGauss[Find(FitGauss,min(FitGauss, key=lambda value:abs(value-Maximun*0.1)))],'bo')
1110 # # # #plt.plot(xFrec,phase)
1111 # # # plt.xlabel('Suavizado, promediado KHz')
1112 # # plt.title('SELFSPECTRA PROMEDIADO')
1113 # # # #plt.subplot(122)
1114 # # # #plt.plot(xSamples,zline)
1115 # # plt.xlabel('Frecuencia (KHz)')
1116 # # plt.ylabel('Magnitud')
1117 # # plt.legend()
1118 # # #
1119 # # # plt.figure(3)
1120 # # # plt.subplot(311)
1121 # # # #plt.plot(xFrec,phase[0])
1122 # # # plt.plot(xFrec,phase[0],'g')
1123 # # # plt.subplot(312)
1124 # # # plt.plot(xFrec,phase[1],'g')
1125 # # # plt.subplot(313)
1126 # # # plt.plot(xFrec,phase[2],'g')
1127 # # # #plt.plot(xFrec,phase[2])
1128 # # #
1129 # # # plt.figure(4)
1130 # # #
1131 # # # plt.plot(xSamples,coherence[0],'b')
1132 # # # plt.plot(xSamples,coherence[1],'r')
1133 # # # plt.plot(xSamples,coherence[2],'g')
1134 # # plt.show()
1135 # # #
1136 # # # plt.clf()
1137 # # # plt.cla()
1138 # # # plt.close()
1139 #
1140 # print ' '
1141
1142
1143
1144 self.BlockCounter+=2
1145
1146 else:
1147 self.fileSelector+=1
1148 self.BlockCounter=0
1149 print "Next File"
1150
1151
1152
1153
1154
@@ -0,0 +1,243
1 '''
2 Created on Aug 1, 2017
3
4 @author: Juan C. Espinoza
5 '''
6
7 import os
8 import sys
9 import time
10 import json
11 import datetime
12
13 import numpy
14
15 try:
16 import madrigal
17 import madrigal.cedar
18 except:
19 print 'You should install "madrigal library" module if you want to read/write Madrigal data'
20
21 from schainpy.model.proc.jroproc_base import Operation
22 from schainpy.model.data.jrodata import Parameters
23
24 MISSING = -32767
25 DEF_CATALOG = {
26 'principleInvestigator': 'Marco Milla',
27 'expPurpose': None,
28 'expMode': None,
29 'cycleTime': None,
30 'correlativeExp': None,
31 'sciRemarks': None,
32 'instRemarks': None
33 }
34 DEF_HEADER = {
35 'kindatDesc': None,
36 'analyst': 'Jicamarca User',
37 'comments': None,
38 'history': None
39 }
40 MNEMONICS = {
41 10: 'jro',
42 11: 'jbr',
43 840: 'jul',
44 13: 'jas',
45 1000: 'pbr',
46 1001: 'hbr',
47 1002: 'obr',
48 }
49
50 def load_json(obj):
51 '''
52 Parse json as string instead of unicode
53 '''
54
55 if isinstance(obj, str):
56 obj = json.loads(obj)
57
58 return {str(k): load_json(v) if isinstance(v, dict) else str(v) if isinstance(v, unicode) else v
59 for k, v in obj.items()}
60
61
62 class MAD2Writer(Operation):
63
64 def __init__(self, **kwargs):
65
66 Operation.__init__(self, **kwargs)
67 self.dataOut = Parameters()
68 self.path = None
69 self.dataOut = None
70 self.ext = '.dat'
71
72 return
73
74 def run(self, dataOut, path, oneDList, twoDParam='', twoDList='{}', metadata='{}', **kwargs):
75 '''
76 Inputs:
77 path - path where files will be created
78 oneDList - json of one-dimensional parameters in record where keys
79 are Madrigal codes (integers or mnemonics) and values the corresponding
80 dataOut attribute e.g: {
81 'gdlatr': 'lat',
82 'gdlonr': 'lon',
83 'gdlat2':'lat',
84 'glon2':'lon'}
85 twoDParam - independent parameter to get the number of rows e.g:
86 heighList
87 twoDList - json of two-dimensional parameters in record where keys
88 are Madrigal codes (integers or mnemonics) and values the corresponding
89 dataOut attribute if multidimensional array specify as tupple
90 ('attr', pos) e.g: {
91 'gdalt': 'heightList',
92 'vn1p2': ('data_output', 0),
93 'vn2p2': ('data_output', 1),
94 'vn3': ('data_output', 2),
95 'snl': ('data_SNR', 'db')
96 }
97 metadata - json of madrigal metadata (kinst, kindat, catalog and header)
98 '''
99 if not self.isConfig:
100 self.setup(dataOut, path, oneDList, twoDParam, twoDList, metadata, **kwargs)
101 self.isConfig = True
102
103 self.putData()
104 return
105
106 def setup(self, dataOut, path, oneDList, twoDParam, twoDList, metadata, **kwargs):
107 '''
108 Configure Operation
109 '''
110
111 self.dataOut = dataOut
112 self.nmodes = self.dataOut.nmodes
113 self.path = path
114 self.blocks = kwargs.get('blocks', None)
115 self.counter = 0
116 self.oneDList = load_json(oneDList)
117 self.twoDList = load_json(twoDList)
118 self.twoDParam = twoDParam
119 meta = load_json(metadata)
120 self.kinst = meta.get('kinst')
121 self.kindat = meta.get('kindat')
122 self.catalog = meta.get('catalog', DEF_CATALOG)
123 self.header = meta.get('header', DEF_HEADER)
124
125 return
126
127 def setFile(self):
128 '''
129 Create new cedar file object
130 '''
131
132 self.mnemonic = MNEMONICS[self.kinst] #TODO get mnemonic from madrigal
133 date = datetime.datetime.utcfromtimestamp(self.dataOut.utctime)
134
135 filename = '%s%s_%s%s' % (self.mnemonic,
136 date.strftime('%Y%m%d_%H%M%S'),
137 self.dataOut.mode,
138 self.ext)
139
140 self.fullname = os.path.join(self.path, filename)
141
142 if os.path.isfile(self.fullname) :
143 print "Destination path '%s' already exists. Previous file deleted. " %self.fullname
144 os.remove(self.fullname)
145
146 try:
147 print '[Writing] creating file : %s' % (self.fullname)
148 self.cedarObj = madrigal.cedar.MadrigalCedarFile(self.fullname, True)
149 except ValueError, e:
150 print '[Error]: Impossible to create a cedar object with "madrigal.cedar.MadrigalCedarFile" '
151 return
152
153 return 1
154
155 def writeBlock(self):
156 '''
157 Add data records to cedar file taking data from oneDList and twoDList
158 attributes.
159 Allowed parameters in: parcodes.tab
160 '''
161
162 startTime = datetime.datetime.utcfromtimestamp(self.dataOut.utctime)
163 endTime = startTime + datetime.timedelta(seconds=self.dataOut.paramInterval)
164 nrows = len(getattr(self.dataOut, self.twoDParam))
165
166 rec = madrigal.cedar.MadrigalDataRecord(
167 self.kinst,
168 self.kindat,
169 startTime.year,
170 startTime.month,
171 startTime.day,
172 startTime.hour,
173 startTime.minute,
174 startTime.second,
175 startTime.microsecond/10000,
176 endTime.year,
177 endTime.month,
178 endTime.day,
179 endTime.hour,
180 endTime.minute,
181 endTime.second,
182 endTime.microsecond/10000,
183 self.oneDList.keys(),
184 self.twoDList.keys(),
185 nrows
186 )
187
188 # Setting 1d values
189 for key in self.oneDList:
190 rec.set1D(key, getattr(self.dataOut, self.oneDList[key]))
191
192 # Setting 2d values
193 invalid = numpy.isnan(self.dataOut.data_output)
194 self.dataOut.data_output[invalid] = MISSING
195 out = {}
196 for key, value in self.twoDList.items():
197 if isinstance(value, str):
198 out[key] = getattr(self.dataOut, value)
199 elif isinstance(value, tuple):
200 attr, x = value
201 if isinstance(x, (int, float)):
202 out[key] = getattr(self.dataOut, attr)[int(x)]
203 elif x.lower()=='db':
204 tmp = getattr(self.dataOut, attr)
205 SNRavg = numpy.average(tmp, axis=0)
206 out[key] = 10*numpy.log10(SNRavg)
207
208 for n in range(nrows):
209 for key in out:
210 rec.set2D(key, n, out[key][n])
211
212 self.cedarObj.append(rec)
213 self.cedarObj.dump()
214 print '[Writing] Record No. {} (mode {}).'.format(
215 self.counter,
216 self.dataOut.mode
217 )
218
219 def setHeader(self):
220 '''
221 Create an add catalog and header to cedar file
222 '''
223
224 header = madrigal.cedar.CatalogHeaderCreator(self.fullname)
225 header.createCatalog(**self.catalog)
226 header.createHeader(**self.header)
227 header.write()
228
229 def putData(self):
230
231 if self.dataOut.flagNoData:
232 return 0
233
234 if self.counter == 0:
235 self.setFile()
236
237 if self.counter <= self.dataOut.nrecords:
238 self.writeBlock()
239 self.counter += 1
240
241 if self.counter == self.dataOut.nrecords or self.counter == self.blocks:
242 self.setHeader()
243 self.counter = 0
This diff has been collapsed as it changes many lines, (803 lines changed) Show them Hide them
@@ -0,0 +1,803
1 import os, sys
2 import glob
3 import fnmatch
4 import datetime
5 import time
6 import re
7 import h5py
8 import numpy
9 import matplotlib.pyplot as plt
10
11 import pylab as plb
12 from scipy.optimize import curve_fit
13 from scipy import asarray as ar,exp
14 from scipy import stats
15
16 from numpy.ma.core import getdata
17
18 SPEED_OF_LIGHT = 299792458
19 SPEED_OF_LIGHT = 3e8
20
21 try:
22 from gevent import sleep
23 except:
24 from time import sleep
25
26 from schainpy.model.data.jrodata import Spectra
27 #from schainpy.model.data.BLTRheaderIO import FileHeader, RecordHeader
28 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
29 #from schainpy.model.io.jroIO_bltr import BLTRReader
30 from numpy import imag, shape, NaN, empty
31
32
33
34 class Header(object):
35
36 def __init__(self):
37 raise NotImplementedError
38
39
40 def read(self):
41
42 raise NotImplementedError
43
44 def write(self):
45
46 raise NotImplementedError
47
48 def printInfo(self):
49
50 message = "#"*50 + "\n"
51 message += self.__class__.__name__.upper() + "\n"
52 message += "#"*50 + "\n"
53
54 keyList = self.__dict__.keys()
55 keyList.sort()
56
57 for key in keyList:
58 message += "%s = %s" %(key, self.__dict__[key]) + "\n"
59
60 if "size" not in keyList:
61 attr = getattr(self, "size")
62
63 if attr:
64 message += "%s = %s" %("size", attr) + "\n"
65
66 #print message
67
68
69 FILE_HEADER = numpy.dtype([ #HEADER 1024bytes
70 ('Hname','a32'), #Original file name
71 ('Htime',numpy.str_,32), #Date and time when the file was created
72 ('Hoper',numpy.str_,64), #Name of operator who created the file
73 ('Hplace',numpy.str_,128), #Place where the measurements was carried out
74 ('Hdescr',numpy.str_,256), #Description of measurements
75 ('Hdummy',numpy.str_,512), #Reserved space
76 #Main chunk 8bytes
77 ('Msign',numpy.str_,4), #Main chunk signature FZKF or NUIG
78 ('MsizeData','<i4'), #Size of data block main chunk
79 #Processing DSP parameters 36bytes
80 ('PPARsign',numpy.str_,4), #PPAR signature
81 ('PPARsize','<i4'), #PPAR size of block
82 ('PPARprf','<i4'), #Pulse repetition frequency
83 ('PPARpdr','<i4'), #Pulse duration
84 ('PPARsft','<i4'), #FFT length
85 ('PPARavc','<i4'), #Number of spectral (in-coherent) averages
86 ('PPARihp','<i4'), #Number of lowest range gate for moment estimation
87 ('PPARchg','<i4'), #Count for gates for moment estimation
88 ('PPARpol','<i4'), #switch on/off polarimetric measurements. Should be 1.
89 #Service DSP parameters 112bytes
90 ('SPARatt','<i4'), #STC attenuation on the lowest ranges on/off
91 ('SPARtx','<i4'), #OBSOLETE
92 ('SPARaddGain0','<f4'), #OBSOLETE
93 ('SPARaddGain1','<f4'), #OBSOLETE
94 ('SPARwnd','<i4'), #Debug only. It normal mode it is 0.
95 ('SPARpos','<i4'), #Delay between sync pulse and tx pulse for phase corr, ns
96 ('SPARadd','<i4'), #"add to pulse" to compensate for delay between the leading edge of driver pulse and envelope of the RF signal.
97 ('SPARlen','<i4'), #Time for measuring txn pulse phase. OBSOLETE
98 ('SPARcal','<i4'), #OBSOLETE
99 ('SPARnos','<i4'), #OBSOLETE
100 ('SPARof0','<i4'), #detection threshold
101 ('SPARof1','<i4'), #OBSOLETE
102 ('SPARswt','<i4'), #2nd moment estimation threshold
103 ('SPARsum','<i4'), #OBSOLETE
104 ('SPARosc','<i4'), #flag Oscillosgram mode
105 ('SPARtst','<i4'), #OBSOLETE
106 ('SPARcor','<i4'), #OBSOLETE
107 ('SPARofs','<i4'), #OBSOLETE
108 ('SPARhsn','<i4'), #Hildebrand div noise detection on noise gate
109 ('SPARhsa','<f4'), #Hildebrand div noise detection on all gates
110 ('SPARcalibPow_M','<f4'), #OBSOLETE
111 ('SPARcalibSNR_M','<f4'), #OBSOLETE
112 ('SPARcalibPow_S','<f4'), #OBSOLETE
113 ('SPARcalibSNR_S','<f4'), #OBSOLETE
114 ('SPARrawGate1','<i4'), #Lowest range gate for spectra saving Raw_Gate1 >=5
115 ('SPARrawGate2','<i4'), #Number of range gates with atmospheric signal
116 ('SPARraw','<i4'), #flag - IQ or spectra saving on/off
117 ('SPARprc','<i4'),]) #flag - Moment estimation switched on/off
118
119
120
121 class FileHeaderMIRA35c(Header):
122
123 def __init__(self):
124
125 self.Hname= None
126 self.Htime= None
127 self.Hoper= None
128 self.Hplace= None
129 self.Hdescr= None
130 self.Hdummy= None
131
132 self.Msign=None
133 self.MsizeData=None
134
135 self.PPARsign=None
136 self.PPARsize=None
137 self.PPARprf=None
138 self.PPARpdr=None
139 self.PPARsft=None
140 self.PPARavc=None
141 self.PPARihp=None
142 self.PPARchg=None
143 self.PPARpol=None
144 #Service DSP parameters
145 self.SPARatt=None
146 self.SPARtx=None
147 self.SPARaddGain0=None
148 self.SPARaddGain1=None
149 self.SPARwnd=None
150 self.SPARpos=None
151 self.SPARadd=None
152 self.SPARlen=None
153 self.SPARcal=None
154 self.SPARnos=None
155 self.SPARof0=None
156 self.SPARof1=None
157 self.SPARswt=None
158 self.SPARsum=None
159 self.SPARosc=None
160 self.SPARtst=None
161 self.SPARcor=None
162 self.SPARofs=None
163 self.SPARhsn=None
164 self.SPARhsa=None
165 self.SPARcalibPow_M=None
166 self.SPARcalibSNR_M=None
167 self.SPARcalibPow_S=None
168 self.SPARcalibSNR_S=None
169 self.SPARrawGate1=None
170 self.SPARrawGate2=None
171 self.SPARraw=None
172 self.SPARprc=None
173
174 self.FHsize=1180
175
176 def FHread(self, fp):
177
178 header = numpy.fromfile(fp, FILE_HEADER,1)
179 ''' numpy.fromfile(file, dtype, count, sep='')
180 file : file or str
181 Open file object or filename.
182
183 dtype : data-type
184 Data type of the returned array. For binary files, it is used to determine
185 the size and byte-order of the items in the file.
186
187 count : int
188 Number of items to read. -1 means all items (i.e., the complete file).
189
190 sep : str
191 Separator between items if file is a text file. Empty ("") separator means
192 the file should be treated as binary. Spaces (" ") in the separator match zero
193 or more whitespace characters. A separator consisting only of spaces must match
194 at least one whitespace.
195
196 '''
197
198
199 self.Hname= str(header['Hname'][0])
200 self.Htime= str(header['Htime'][0])
201 self.Hoper= str(header['Hoper'][0])
202 self.Hplace= str(header['Hplace'][0])
203 self.Hdescr= str(header['Hdescr'][0])
204 self.Hdummy= str(header['Hdummy'][0])
205 #1024
206
207 self.Msign=str(header['Msign'][0])
208 self.MsizeData=header['MsizeData'][0]
209 #8
210
211 self.PPARsign=str(header['PPARsign'][0])
212 self.PPARsize=header['PPARsize'][0]
213 self.PPARprf=header['PPARprf'][0]
214 self.PPARpdr=header['PPARpdr'][0]
215 self.PPARsft=header['PPARsft'][0]
216 self.PPARavc=header['PPARavc'][0]
217 self.PPARihp=header['PPARihp'][0]
218 self.PPARchg=header['PPARchg'][0]
219 self.PPARpol=header['PPARpol'][0]
220 #Service DSP parameters
221 #36
222
223 self.SPARatt=header['SPARatt'][0]
224 self.SPARtx=header['SPARtx'][0]
225 self.SPARaddGain0=header['SPARaddGain0'][0]
226 self.SPARaddGain1=header['SPARaddGain1'][0]
227 self.SPARwnd=header['SPARwnd'][0]
228 self.SPARpos=header['SPARpos'][0]
229 self.SPARadd=header['SPARadd'][0]
230 self.SPARlen=header['SPARlen'][0]
231 self.SPARcal=header['SPARcal'][0]
232 self.SPARnos=header['SPARnos'][0]
233 self.SPARof0=header['SPARof0'][0]
234 self.SPARof1=header['SPARof1'][0]
235 self.SPARswt=header['SPARswt'][0]
236 self.SPARsum=header['SPARsum'][0]
237 self.SPARosc=header['SPARosc'][0]
238 self.SPARtst=header['SPARtst'][0]
239 self.SPARcor=header['SPARcor'][0]
240 self.SPARofs=header['SPARofs'][0]
241 self.SPARhsn=header['SPARhsn'][0]
242 self.SPARhsa=header['SPARhsa'][0]
243 self.SPARcalibPow_M=header['SPARcalibPow_M'][0]
244 self.SPARcalibSNR_M=header['SPARcalibSNR_M'][0]
245 self.SPARcalibPow_S=header['SPARcalibPow_S'][0]
246 self.SPARcalibSNR_S=header['SPARcalibSNR_S'][0]
247 self.SPARrawGate1=header['SPARrawGate1'][0]
248 self.SPARrawGate2=header['SPARrawGate2'][0]
249 self.SPARraw=header['SPARraw'][0]
250 self.SPARprc=header['SPARprc'][0]
251 #112
252 #1180
253 #print 'Pointer fp header', fp.tell()
254 #print ' '
255 #print 'SPARrawGate'
256 #print self.SPARrawGate2 - self.SPARrawGate1
257
258 #print ' '
259 #print 'Hname'
260 #print self.Hname
261
262 #print ' '
263 #print 'Msign'
264 #print self.Msign
265
266 def write(self, fp):
267
268 headerTuple = (self.Hname,
269 self.Htime,
270 self.Hoper,
271 self.Hplace,
272 self.Hdescr,
273 self.Hdummy)
274
275
276 header = numpy.array(headerTuple, FILE_HEADER)
277 # numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
278 header.tofile(fp)
279 ''' ndarray.tofile(fid, sep, format) Write array to a file as text or binary (default).
280
281 fid : file or str
282 An open file object, or a string containing a filename.
283
284 sep : str
285 Separator between array items for text output. If "" (empty), a binary file is written,
286 equivalent to file.write(a.tobytes()).
287
288 format : str
289 Format string for text file output. Each entry in the array is formatted to text by
290 first converting it to the closest Python type, and then using "format" % item.
291
292 '''
293
294 return 1
295
296 SRVI_HEADER = numpy.dtype([
297 ('SignatureSRVI1',numpy.str_,4),#
298 ('SizeOfDataBlock1','<i4'),#
299 ('DataBlockTitleSRVI1',numpy.str_,4),#
300 ('SizeOfSRVI1','<i4'),])#
301
302 class SRVIHeader(Header):
303 def __init__(self, SignatureSRVI1=0, SizeOfDataBlock1=0, DataBlockTitleSRVI1=0, SizeOfSRVI1=0):
304
305 self.SignatureSRVI1 = SignatureSRVI1
306 self.SizeOfDataBlock1 = SizeOfDataBlock1
307 self.DataBlockTitleSRVI1 = DataBlockTitleSRVI1
308 self.SizeOfSRVI1 = SizeOfSRVI1
309
310 self.SRVIHsize=16
311
312 def SRVIread(self, fp):
313
314 header = numpy.fromfile(fp, SRVI_HEADER,1)
315
316 self.SignatureSRVI1 = str(header['SignatureSRVI1'][0])
317 self.SizeOfDataBlock1 = header['SizeOfDataBlock1'][0]
318 self.DataBlockTitleSRVI1 = str(header['DataBlockTitleSRVI1'][0])
319 self.SizeOfSRVI1 = header['SizeOfSRVI1'][0]
320 #16
321 print 'Pointer fp SRVIheader', fp.tell()
322
323
324 SRVI_STRUCTURE = numpy.dtype([
325 ('frame_cnt','<u4'),#
326 ('time_t','<u4'), #
327 ('tpow','<f4'), #
328 ('npw1','<f4'), #
329 ('npw2','<f4'), #
330 ('cpw1','<f4'), #
331 ('pcw2','<f4'), #
332 ('ps_err','<u4'), #
333 ('te_err','<u4'), #
334 ('rc_err','<u4'), #
335 ('grs1','<u4'), #
336 ('grs2','<u4'), #
337 ('azipos','<f4'), #
338 ('azivel','<f4'), #
339 ('elvpos','<f4'), #
340 ('elvvel','<f4'), #
341 ('northAngle','<f4'), #
342 ('microsec','<u4'), #
343 ('azisetvel','<f4'), #
344 ('elvsetpos','<f4'), #
345 ('RadarConst','<f4'),]) #
346
347
348
349
350 class RecordHeader(Header):
351
352
353 def __init__(self, frame_cnt=0, time_t= 0, tpow=0, npw1=0, npw2=0,
354 cpw1=0, pcw2=0, ps_err=0, te_err=0, rc_err=0, grs1=0,
355 grs2=0, azipos=0, azivel=0, elvpos=0, elvvel=0, northangle=0,
356 microsec=0, azisetvel=0, elvsetpos=0, RadarConst=0 , RecCounter=0, Off2StartNxtRec=0):
357
358
359 self.frame_cnt = frame_cnt
360 self.dwell = time_t
361 self.tpow = tpow
362 self.npw1 = npw1
363 self.npw2 = npw2
364 self.cpw1 = cpw1
365 self.pcw2 = pcw2
366 self.ps_err = ps_err
367 self.te_err = te_err
368 self.rc_err = rc_err
369 self.grs1 = grs1
370 self.grs2 = grs2
371 self.azipos = azipos
372 self.azivel = azivel
373 self.elvpos = elvpos
374 self.elvvel = elvvel
375 self.northAngle = northangle
376 self.microsec = microsec
377 self.azisetvel = azisetvel
378 self.elvsetpos = elvsetpos
379 self.RadarConst = RadarConst
380 self.RHsize=84
381 self.RecCounter = RecCounter
382 self.Off2StartNxtRec=Off2StartNxtRec
383
384 def RHread(self, fp):
385
386 #startFp = open(fp,"rb") #The method tell() returns the current position of the file read/write pointer within the file.
387
388 #OffRHeader= 1180 + self.RecCounter*(self.Off2StartNxtRec)
389 #startFp.seek(OffRHeader, os.SEEK_SET)
390
391 #print 'Posicion del bloque: ',OffRHeader
392
393 header = numpy.fromfile(fp,SRVI_STRUCTURE,1)
394
395 self.frame_cnt = header['frame_cnt'][0]#
396 self.time_t = header['time_t'][0] #
397 self.tpow = header['tpow'][0] #
398 self.npw1 = header['npw1'][0] #
399 self.npw2 = header['npw2'][0] #
400 self.cpw1 = header['cpw1'][0] #
401 self.pcw2 = header['pcw2'][0] #
402 self.ps_err = header['ps_err'][0] #
403 self.te_err = header['te_err'][0] #
404 self.rc_err = header['rc_err'][0] #
405 self.grs1 = header['grs1'][0] #
406 self.grs2 = header['grs2'][0] #
407 self.azipos = header['azipos'][0] #
408 self.azivel = header['azivel'][0] #
409 self.elvpos = header['elvpos'][0] #
410 self.elvvel = header['elvvel'][0] #
411 self.northAngle = header['northAngle'][0] #
412 self.microsec = header['microsec'][0] #
413 self.azisetvel = header['azisetvel'][0] #
414 self.elvsetpos = header['elvsetpos'][0] #
415 self.RadarConst = header['RadarConst'][0] #
416 #84
417
418 #print 'Pointer fp RECheader', fp.tell()
419
420 #self.ipp= 0.5*(SPEED_OF_LIGHT/self.PRFhz)
421
422 #self.RHsize = 180+20*self.nChannels
423 #self.Datasize= self.nProfiles*self.nChannels*self.nHeights*2*4
424 #print 'Datasize',self.Datasize
425 #endFp = self.OffsetStartHeader + self.RecCounter*self.Off2StartNxtRec
426
427 print '=============================================='
428
429 print '=============================================='
430
431
432 return 1
433
434 class MIRA35CReader (ProcessingUnit,FileHeaderMIRA35c,SRVIHeader,RecordHeader):
435
436 path = None
437 startDate = None
438 endDate = None
439 startTime = None
440 endTime = None
441 walk = None
442 isConfig = False
443
444
445 fileList= None
446
447 #metadata
448 TimeZone= None
449 Interval= None
450 heightList= None
451
452 #data
453 data= None
454 utctime= None
455
456
457
458 def __init__(self, **kwargs):
459
460 #Eliminar de la base la herencia
461 ProcessingUnit.__init__(self, **kwargs)
462 self.PointerReader = 0
463 self.FileHeaderFlag = False
464 self.utc = None
465 self.ext = ".zspca"
466 self.optchar = "P"
467 self.fpFile=None
468 self.fp = None
469 self.BlockCounter=0
470 self.dtype = None
471 self.fileSizeByHeader = None
472 self.filenameList = []
473 self.fileSelector = 0
474 self.Off2StartNxtRec=0
475 self.RecCounter=0
476 self.flagNoMoreFiles = 0
477 self.data_spc=None
478 #self.data_cspc=None
479 self.data_output=None
480 self.path = None
481 self.OffsetStartHeader=0
482 self.Off2StartData=0
483 self.ipp = 0
484 self.nFDTdataRecors=0
485 self.blocksize = 0
486 self.dataOut = Spectra()
487 self.profileIndex = 1 #Always
488 self.dataOut.flagNoData=False
489 self.dataOut.nRdPairs = 0
490 self.dataOut.pairsList = []
491 self.dataOut.data_spc=None
492
493 self.dataOut.normFactor=1
494 self.nextfileflag = True
495 self.dataOut.RadarConst = 0
496 self.dataOut.HSDV = []
497 self.dataOut.NPW = []
498 self.dataOut.COFA = []
499 self.dataOut.noise = 0
500
501
502 def Files2Read(self, fp):
503 '''
504 Function that indicates the number of .fdt files that exist in the folder to be read.
505 It also creates an organized list with the names of the files to read.
506 '''
507 #self.__checkPath()
508
509 ListaData=os.listdir(fp) #Gets the list of files within the fp address
510 ListaData=sorted(ListaData) #Sort the list of files from least to largest by names
511 nFiles=0 #File Counter
512 FileList=[] #A list is created that will contain the .fdt files
513 for IndexFile in ListaData :
514 if '.zspca' in IndexFile and '.gz' not in IndexFile:
515 FileList.append(IndexFile)
516 nFiles+=1
517
518 #print 'Files2Read'
519 #print 'Existen '+str(nFiles)+' archivos .fdt'
520
521 self.filenameList=FileList #List of files from least to largest by names
522
523
524 def run(self, **kwargs):
525 '''
526 This method will be the one that will initiate the data entry, will be called constantly.
527 You should first verify that your Setup () is set up and then continue to acquire
528 the data to be processed with getData ().
529 '''
530 if not self.isConfig:
531 self.setup(**kwargs)
532 self.isConfig = True
533
534 self.getData()
535
536
537 def setup(self, path=None,
538 startDate=None,
539 endDate=None,
540 startTime=None,
541 endTime=None,
542 walk=True,
543 timezone='utc',
544 code = None,
545 online=False,
546 ReadMode=None, **kwargs):
547
548 self.isConfig = True
549
550 self.path=path
551 self.startDate=startDate
552 self.endDate=endDate
553 self.startTime=startTime
554 self.endTime=endTime
555 self.walk=walk
556 #self.ReadMode=int(ReadMode)
557
558 pass
559
560
561 def getData(self):
562 '''
563 Before starting this function, you should check that there is still an unread file,
564 If there are still blocks to read or if the data block is empty.
565
566 You should call the file "read".
567
568 '''
569
570 if self.flagNoMoreFiles:
571 self.dataOut.flagNoData = True
572 print 'NoData se vuelve true'
573 return 0
574
575 self.fp=self.path
576 self.Files2Read(self.fp)
577 self.readFile(self.fp)
578
579 self.dataOut.data_spc = self.dataOut_spc#self.data_spc.copy()
580 self.dataOut.RadarConst = self.RadarConst
581 self.dataOut.data_output=self.data_output
582 self.dataOut.noise = self.dataOut.getNoise()
583 #print 'ACAAAAAA', self.dataOut.noise
584 self.dataOut.data_spc = self.dataOut.data_spc+self.dataOut.noise
585 #print 'self.dataOut.noise',self.dataOut.noise
586
587
588 return self.dataOut.data_spc
589
590
591 def readFile(self,fp):
592 '''
593 You must indicate if you are reading in Online or Offline mode and load the
594 The parameters for this file reading mode.
595
596 Then you must do 2 actions:
597
598 1. Get the BLTR FileHeader.
599 2. Start reading the first block.
600 '''
601
602 #The address of the folder is generated the name of the .fdt file that will be read
603 print "File: ",self.fileSelector+1
604
605 if self.fileSelector < len(self.filenameList):
606
607 self.fpFile=str(fp)+'/'+str(self.filenameList[self.fileSelector])
608
609 if self.nextfileflag==True:
610 self.fp = open(self.fpFile,"rb")
611 self.nextfileflag==False
612
613 '''HERE STARTING THE FILE READING'''
614
615
616 self.fheader = FileHeaderMIRA35c()
617 self.fheader.FHread(self.fp) #Bltr FileHeader Reading
618
619
620 self.SPARrawGate1 = self.fheader.SPARrawGate1
621 self.SPARrawGate2 = self.fheader.SPARrawGate2
622 self.Num_Hei = self.SPARrawGate2 - self.SPARrawGate1
623 self.Num_Bins = self.fheader.PPARsft
624 self.dataOut.nFFTPoints = self.fheader.PPARsft
625
626
627 self.Num_inCoh = self.fheader.PPARavc
628 self.dataOut.PRF = self.fheader.PPARprf
629 self.dataOut.frequency = 34.85*10**9
630 self.Lambda = SPEED_OF_LIGHT/self.dataOut.frequency
631 self.dataOut.ippSeconds= 1./float(self.dataOut.PRF)
632
633 pulse_width = self.fheader.PPARpdr * 10**-9
634 self.__deltaHeigth = 0.5 * SPEED_OF_LIGHT * pulse_width
635
636 self.data_spc = numpy.zeros((self.Num_Hei, self.Num_Bins,2))#
637 self.dataOut.HSDV = numpy.zeros((self.Num_Hei, 2))
638
639 self.Ze = numpy.zeros(self.Num_Hei)
640 self.ETA = numpy.zeros(([2,self.Num_Hei]))
641
642
643
644 self.readBlock() #Block reading
645
646 else:
647 print 'readFile FlagNoData becomes true'
648 self.flagNoMoreFiles=True
649 self.dataOut.flagNoData = True
650 self.FileHeaderFlag == True
651 return 0
652
653
654
655 def readBlock(self):
656 '''
657 It should be checked if the block has data, if it is not passed to the next file.
658
659 Then the following is done:
660
661 1. Read the RecordHeader
662 2. Fill the buffer with the current block number.
663
664 '''
665
666 if self.PointerReader > 1180:
667 self.fp.seek(self.PointerReader , os.SEEK_SET)
668 self.FirstPoint = self.PointerReader
669
670 else :
671 self.FirstPoint = 1180
672
673
674
675 self.srviHeader = SRVIHeader()
676
677 self.srviHeader.SRVIread(self.fp) #Se obtiene la cabecera del SRVI
678
679 self.blocksize = self.srviHeader.SizeOfDataBlock1 # Se obtiene el tamao del bloque
680
681 if self.blocksize == 148:
682 print 'blocksize == 148 bug'
683 jump = numpy.fromfile(self.fp,[('jump',numpy.str_,140)] ,1)
684
685 self.srviHeader.SRVIread(self.fp) #Se obtiene la cabecera del SRVI
686
687 if not self.srviHeader.SizeOfSRVI1:
688 self.fileSelector+=1
689 self.nextfileflag==True
690 self.FileHeaderFlag == True
691
692 self.recordheader = RecordHeader()
693 self.recordheader.RHread(self.fp)
694 self.RadarConst = self.recordheader.RadarConst
695 dwell = self.recordheader.time_t
696 npw1 = self.recordheader.npw1
697 npw2 = self.recordheader.npw2
698
699
700 self.dataOut.channelList = range(1)
701 self.dataOut.nIncohInt = self.Num_inCoh
702 self.dataOut.nProfiles = self.Num_Bins
703 self.dataOut.nCohInt = 1
704 self.dataOut.windowOfFilter = 1
705 self.dataOut.utctime = dwell
706 self.dataOut.timeZone=0
707
708 self.dataOut.outputInterval = self.dataOut.getTimeInterval()
709 self.dataOut.heightList = self.SPARrawGate1*self.__deltaHeigth + numpy.array(range(self.Num_Hei))*self.__deltaHeigth
710
711
712
713 self.HSDVsign = numpy.fromfile( self.fp, [('HSDV',numpy.str_,4)],1)
714 self.SizeHSDV = numpy.fromfile( self.fp, [('SizeHSDV','<i4')],1)
715 self.HSDV_Co = numpy.fromfile( self.fp, [('HSDV_Co','<f4')],self.Num_Hei)
716 self.HSDV_Cx = numpy.fromfile( self.fp, [('HSDV_Cx','<f4')],self.Num_Hei)
717
718 self.COFAsign = numpy.fromfile( self.fp, [('COFA',numpy.str_,4)],1)
719 self.SizeCOFA = numpy.fromfile( self.fp, [('SizeCOFA','<i4')],1)
720 self.COFA_Co = numpy.fromfile( self.fp, [('COFA_Co','<f4')],self.Num_Hei)
721 self.COFA_Cx = numpy.fromfile( self.fp, [('COFA_Cx','<f4')],self.Num_Hei)
722
723 self.ZSPCsign = numpy.fromfile(self.fp, [('ZSPCsign',numpy.str_,4)],1)
724 self.SizeZSPC = numpy.fromfile(self.fp, [('SizeZSPC','<i4')],1)
725
726 self.dataOut.HSDV[0]=self.HSDV_Co[:][0]
727 self.dataOut.HSDV[1]=self.HSDV_Cx[:][0]
728
729 for irg in range(self.Num_Hei):
730 nspc = numpy.fromfile(self.fp, [('nspc','int16')],1)[0][0] # Number of spectral sub pieces containing significant power
731
732 for k in range(nspc):
733 binIndex = numpy.fromfile(self.fp, [('binIndex','int16')],1)[0][0] # Index of the spectral bin where the piece is beginning
734 nbins = numpy.fromfile(self.fp, [('nbins','int16')],1)[0][0] # Number of bins of the piece
735
736 #Co_Channel
737 jbin = numpy.fromfile(self.fp, [('jbin','uint16')],nbins)[0][0] # Spectrum piece to be normaliced
738 jmax = numpy.fromfile(self.fp, [('jmax','float32')],1)[0][0] # Maximun piece to be normaliced
739
740
741 self.data_spc[irg,binIndex:binIndex+nbins,0] = self.data_spc[irg,binIndex:binIndex+nbins,0]+jbin/65530.*jmax
742
743 #Cx_Channel
744 jbin = numpy.fromfile(self.fp, [('jbin','uint16')],nbins)[0][0]
745 jmax = numpy.fromfile(self.fp, [('jmax','float32')],1)[0][0]
746
747
748 self.data_spc[irg,binIndex:binIndex+nbins,1] = self.data_spc[irg,binIndex:binIndex+nbins,1]+jbin/65530.*jmax
749
750 for bin in range(self.Num_Bins):
751
752 self.data_spc[:,bin,0] = self.data_spc[:,bin,0] - self.dataOut.HSDV[:,0]
753
754 self.data_spc[:,bin,1] = self.data_spc[:,bin,1] - self.dataOut.HSDV[:,1]
755
756
757 numpy.set_printoptions(threshold='nan')
758
759 self.data_spc = numpy.where(self.data_spc > 0. , self.data_spc, 0)
760
761 self.dataOut.COFA = numpy.array([self.COFA_Co , self.COFA_Cx])
762
763 print ' '
764 print 'SPC',numpy.shape(self.dataOut.data_spc)
765 #print 'SPC',self.dataOut.data_spc
766
767 noinor1 = 713031680
768 noinor2 = 30
769
770 npw1 = 1#0**(npw1/10) * noinor1 * noinor2
771 npw2 = 1#0**(npw2/10) * noinor1 * noinor2
772 self.dataOut.NPW = numpy.array([npw1, npw2])
773
774 print ' '
775
776 self.data_spc = numpy.transpose(self.data_spc, (2,1,0))
777 self.data_spc = numpy.fft.fftshift(self.data_spc, axes = 1)
778
779 self.data_spc = numpy.fliplr(self.data_spc)
780
781 self.data_spc = numpy.where(self.data_spc > 0. , self.data_spc, 0)
782 self.dataOut_spc= numpy.ones([1, self.Num_Bins , self.Num_Hei])
783 self.dataOut_spc[0,:,:] = self.data_spc[0,:,:]
784 #print 'SHAPE', self.dataOut_spc.shape
785 #For nyquist correction:
786 #fix = 20 # ~3m/s
787 #shift = self.Num_Bins/2 + fix
788 #self.data_spc = numpy.array([ self.data_spc[: , self.Num_Bins-shift+1: , :] , self.data_spc[: , 0:self.Num_Bins-shift , :]])
789
790
791
792 '''Block Reading, the Block Data is received and Reshape is used to give it
793 shape.
794 '''
795
796 self.PointerReader = self.fp.tell()
797
798
799
800
801
802
803 No newline at end of file
@@ -0,0 +1,403
1 '''
2 Created on Oct 24, 2016
3
4 @author: roj- LouVD
5 '''
6
7 import numpy
8 import copy
9 import datetime
10 import time
11 from time import gmtime
12
13 from numpy import transpose
14
15 from jroproc_base import ProcessingUnit, Operation
16 from schainpy.model.data.jrodata import Parameters
17
18
19 class BLTRParametersProc(ProcessingUnit):
20 '''
21 Processing unit for BLTR parameters data (winds)
22
23 Inputs:
24 self.dataOut.nmodes - Number of operation modes
25 self.dataOut.nchannels - Number of channels
26 self.dataOut.nranges - Number of ranges
27
28 self.dataOut.data_SNR - SNR array
29 self.dataOut.data_output - Zonal, Vertical and Meridional velocity array
30 self.dataOut.height - Height array (km)
31 self.dataOut.time - Time array (seconds)
32
33 self.dataOut.fileIndex -Index of the file currently read
34 self.dataOut.lat - Latitude coordinate of BLTR location
35
36 self.dataOut.doy - Experiment doy (number of the day in the current year)
37 self.dataOut.month - Experiment month
38 self.dataOut.day - Experiment day
39 self.dataOut.year - Experiment year
40 '''
41
42 def __init__(self, **kwargs):
43 '''
44 Inputs: None
45 '''
46 ProcessingUnit.__init__(self, **kwargs)
47 self.dataOut = Parameters()
48 self.isConfig = False
49
50 def setup(self, mode):
51 '''
52 '''
53 self.dataOut.mode = mode
54
55 def run(self, mode, snr_threshold=None):
56 '''
57 Inputs:
58 mode = High resolution (0) or Low resolution (1) data
59 snr_threshold = snr filter value
60 '''
61
62 if not self.isConfig:
63 self.setup(mode)
64 self.isConfig = True
65
66 if self.dataIn.type == 'Parameters':
67 self.dataOut.copy(self.dataIn)
68
69 self.dataOut.data_output = self.dataOut.data_output[mode]
70 self.dataOut.heightList = self.dataOut.height[0]
71 self.dataOut.data_SNR = self.dataOut.data_SNR[mode]
72
73 if snr_threshold is not None:
74 SNRavg = numpy.average(self.dataOut.data_SNR, axis=0)
75 SNRavgdB = 10*numpy.log10(SNRavg)
76 for i in range(3):
77 self.dataOut.data_output[i][SNRavgdB <= snr_threshold] = numpy.nan
78
79 # TODO
80 class OutliersFilter(Operation):
81
82 def __init__(self, **kwargs):
83 '''
84 '''
85 Operation.__init__(self, **kwargs)
86
87 def run(self, svalue2, method, factor, filter, npoints=9):
88 '''
89 Inputs:
90 svalue - string to select array velocity
91 svalue2 - string to choose axis filtering
92 method - 0 for SMOOTH or 1 for MEDIAN
93 factor - number used to set threshold
94 filter - 1 for data filtering using the standard deviation criteria else 0
95 npoints - number of points for mask filter
96 '''
97
98 print ' Outliers Filter {} {} / threshold = {}'.format(svalue, svalue, factor)
99
100
101 yaxis = self.dataOut.heightList
102 xaxis = numpy.array([[self.dataOut.utctime]])
103
104 # Zonal
105 value_temp = self.dataOut.data_output[0]
106
107 # Zonal
108 value_temp = self.dataOut.data_output[1]
109
110 # Vertical
111 value_temp = numpy.transpose(self.dataOut.data_output[2])
112
113 htemp = yaxis
114 std = value_temp
115 for h in range(len(htemp)):
116 nvalues_valid = len(numpy.where(numpy.isfinite(value_temp[h]))[0])
117 minvalid = npoints
118
119 #only if valid values greater than the minimum required (10%)
120 if nvalues_valid > minvalid:
121
122 if method == 0:
123 #SMOOTH
124 w = value_temp[h] - self.Smooth(input=value_temp[h], width=npoints, edge_truncate=1)
125
126
127 if method == 1:
128 #MEDIAN
129 w = value_temp[h] - self.Median(input=value_temp[h], width = npoints)
130
131 dw = numpy.std(w[numpy.where(numpy.isfinite(w))],ddof = 1)
132
133 threshold = dw*factor
134 value_temp[numpy.where(w > threshold),h] = numpy.nan
135 value_temp[numpy.where(w < -1*threshold),h] = numpy.nan
136
137
138 #At the end
139 if svalue2 == 'inHeight':
140 value_temp = numpy.transpose(value_temp)
141 output_array[:,m] = value_temp
142
143 if svalue == 'zonal':
144 self.dataOut.data_output[0] = output_array
145
146 elif svalue == 'meridional':
147 self.dataOut.data_output[1] = output_array
148
149 elif svalue == 'vertical':
150 self.dataOut.data_output[2] = output_array
151
152 return self.dataOut.data_output
153
154
155 def Median(self,input,width):
156 '''
157 Inputs:
158 input - Velocity array
159 width - Number of points for mask filter
160
161 '''
162
163 if numpy.mod(width,2) == 1:
164 pc = int((width - 1) / 2)
165 cont = 0
166 output = []
167
168 for i in range(len(input)):
169 if i >= pc and i < len(input) - pc:
170 new2 = input[i-pc:i+pc+1]
171 temp = numpy.where(numpy.isfinite(new2))
172 new = new2[temp]
173 value = numpy.median(new)
174 output.append(value)
175
176 output = numpy.array(output)
177 output = numpy.hstack((input[0:pc],output))
178 output = numpy.hstack((output,input[-pc:len(input)]))
179
180 return output
181
182 def Smooth(self,input,width,edge_truncate = None):
183 '''
184 Inputs:
185 input - Velocity array
186 width - Number of points for mask filter
187 edge_truncate - 1 for truncate the convolution product else
188
189 '''
190
191 if numpy.mod(width,2) == 0:
192 real_width = width + 1
193 nzeros = width / 2
194 else:
195 real_width = width
196 nzeros = (width - 1) / 2
197
198 half_width = int(real_width)/2
199 length = len(input)
200
201 gate = numpy.ones(real_width,dtype='float')
202 norm_of_gate = numpy.sum(gate)
203
204 nan_process = 0
205 nan_id = numpy.where(numpy.isnan(input))
206 if len(nan_id[0]) > 0:
207 nan_process = 1
208 pb = numpy.zeros(len(input))
209 pb[nan_id] = 1.
210 input[nan_id] = 0.
211
212 if edge_truncate == True:
213 output = numpy.convolve(input/norm_of_gate,gate,mode='same')
214 elif edge_truncate == False or edge_truncate == None:
215 output = numpy.convolve(input/norm_of_gate,gate,mode='valid')
216 output = numpy.hstack((input[0:half_width],output))
217 output = numpy.hstack((output,input[len(input)-half_width:len(input)]))
218
219 if nan_process:
220 pb = numpy.convolve(pb/norm_of_gate,gate,mode='valid')
221 pb = numpy.hstack((numpy.zeros(half_width),pb))
222 pb = numpy.hstack((pb,numpy.zeros(half_width)))
223 output[numpy.where(pb > 0.9999)] = numpy.nan
224 input[nan_id] = numpy.nan
225 return output
226
227 def Average(self,aver=0,nhaver=1):
228 '''
229 Inputs:
230 aver - Indicates the time period over which is averaged or consensus data
231 nhaver - Indicates the decimation factor in heights
232
233 '''
234 nhpoints = 48
235
236 lat_piura = -5.17
237 lat_huancayo = -12.04
238 lat_porcuya = -5.8
239
240 if '%2.2f'%self.dataOut.lat == '%2.2f'%lat_piura:
241 hcm = 3.
242 if self.dataOut.year == 2003 :
243 if self.dataOut.doy >= 25 and self.dataOut.doy < 64:
244 nhpoints = 12
245
246 elif '%2.2f'%self.dataOut.lat == '%2.2f'%lat_huancayo:
247 hcm = 3.
248 if self.dataOut.year == 2003 :
249 if self.dataOut.doy >= 25 and self.dataOut.doy < 64:
250 nhpoints = 12
251
252
253 elif '%2.2f'%self.dataOut.lat == '%2.2f'%lat_porcuya:
254 hcm = 5.#2
255
256 pdata = 0.2
257 taver = [1,2,3,4,6,8,12,24]
258 t0 = 0
259 tf = 24
260 ntime =(tf-t0)/taver[aver]
261 ti = numpy.arange(ntime)
262 tf = numpy.arange(ntime) + taver[aver]
263
264
265 old_height = self.dataOut.heightList
266
267 if nhaver > 1:
268 num_hei = len(self.dataOut.heightList)/nhaver/self.dataOut.nmodes
269 deltha = 0.05*nhaver
270 minhvalid = pdata*nhaver
271 for im in range(self.dataOut.nmodes):
272 new_height = numpy.arange(num_hei)*deltha + self.dataOut.height[im,0] + deltha/2.
273
274
275 data_fHeigths_List = []
276 data_fZonal_List = []
277 data_fMeridional_List = []
278 data_fVertical_List = []
279 startDTList = []
280
281
282 for i in range(ntime):
283 height = old_height
284
285 start = datetime.datetime(self.dataOut.year,self.dataOut.month,self.dataOut.day) + datetime.timedelta(hours = int(ti[i])) - datetime.timedelta(hours = 5)
286 stop = datetime.datetime(self.dataOut.year,self.dataOut.month,self.dataOut.day) + datetime.timedelta(hours = int(tf[i])) - datetime.timedelta(hours = 5)
287
288
289 limit_sec1 = time.mktime(start.timetuple())
290 limit_sec2 = time.mktime(stop.timetuple())
291
292 t1 = numpy.where(self.f_timesec >= limit_sec1)
293 t2 = numpy.where(self.f_timesec < limit_sec2)
294 time_select = []
295 for val_sec in t1[0]:
296 if val_sec in t2[0]:
297 time_select.append(val_sec)
298
299
300 time_select = numpy.array(time_select,dtype = 'int')
301 minvalid = numpy.ceil(pdata*nhpoints)
302
303 zon_aver = numpy.zeros([self.dataOut.nranges,self.dataOut.nmodes],dtype='f4') + numpy.nan
304 mer_aver = numpy.zeros([self.dataOut.nranges,self.dataOut.nmodes],dtype='f4') + numpy.nan
305 ver_aver = numpy.zeros([self.dataOut.nranges,self.dataOut.nmodes],dtype='f4') + numpy.nan
306
307 if nhaver > 1:
308 new_zon_aver = numpy.zeros([num_hei,self.dataOut.nmodes],dtype='f4') + numpy.nan
309 new_mer_aver = numpy.zeros([num_hei,self.dataOut.nmodes],dtype='f4') + numpy.nan
310 new_ver_aver = numpy.zeros([num_hei,self.dataOut.nmodes],dtype='f4') + numpy.nan
311
312 if len(time_select) > minvalid:
313 time_average = self.f_timesec[time_select]
314
315 for im in range(self.dataOut.nmodes):
316
317 for ih in range(self.dataOut.nranges):
318 if numpy.sum(numpy.isfinite(self.f_zon[time_select,ih,im])) >= minvalid:
319 zon_aver[ih,im] = numpy.nansum(self.f_zon[time_select,ih,im]) / numpy.sum(numpy.isfinite(self.f_zon[time_select,ih,im]))
320
321 if numpy.sum(numpy.isfinite(self.f_mer[time_select,ih,im])) >= minvalid:
322 mer_aver[ih,im] = numpy.nansum(self.f_mer[time_select,ih,im]) / numpy.sum(numpy.isfinite(self.f_mer[time_select,ih,im]))
323
324 if numpy.sum(numpy.isfinite(self.f_ver[time_select,ih,im])) >= minvalid:
325 ver_aver[ih,im] = numpy.nansum(self.f_ver[time_select,ih,im]) / numpy.sum(numpy.isfinite(self.f_ver[time_select,ih,im]))
326
327 if nhaver > 1:
328 for ih in range(num_hei):
329 hvalid = numpy.arange(nhaver) + nhaver*ih
330
331 if numpy.sum(numpy.isfinite(zon_aver[hvalid,im])) >= minvalid:
332 new_zon_aver[ih,im] = numpy.nansum(zon_aver[hvalid,im]) / numpy.sum(numpy.isfinite(zon_aver[hvalid,im]))
333
334 if numpy.sum(numpy.isfinite(mer_aver[hvalid,im])) >= minvalid:
335 new_mer_aver[ih,im] = numpy.nansum(mer_aver[hvalid,im]) / numpy.sum(numpy.isfinite(mer_aver[hvalid,im]))
336
337 if numpy.sum(numpy.isfinite(ver_aver[hvalid,im])) >= minvalid:
338 new_ver_aver[ih,im] = numpy.nansum(ver_aver[hvalid,im]) / numpy.sum(numpy.isfinite(ver_aver[hvalid,im]))
339 if nhaver > 1:
340 zon_aver = new_zon_aver
341 mer_aver = new_mer_aver
342 ver_aver = new_ver_aver
343 height = new_height
344
345
346 tstart = time_average[0]
347 tend = time_average[-1]
348 startTime = time.gmtime(tstart)
349
350 year = startTime.tm_year
351 month = startTime.tm_mon
352 day = startTime.tm_mday
353 hour = startTime.tm_hour
354 minute = startTime.tm_min
355 second = startTime.tm_sec
356
357 startDTList.append(datetime.datetime(year,month,day,hour,minute,second))
358
359
360 o_height = numpy.array([])
361 o_zon_aver = numpy.array([])
362 o_mer_aver = numpy.array([])
363 o_ver_aver = numpy.array([])
364 if self.dataOut.nmodes > 1:
365 for im in range(self.dataOut.nmodes):
366
367 if im == 0:
368 h_select = numpy.where(numpy.bitwise_and(height[0,:] >=0,height[0,:] <= hcm,numpy.isfinite(height[0,:])))
369 else:
370 h_select = numpy.where(numpy.bitwise_and(height[1,:] > hcm,height[1,:] < 20,numpy.isfinite(height[1,:])))
371
372
373 ht = h_select[0]
374
375 o_height = numpy.hstack((o_height,height[im,ht]))
376 o_zon_aver = numpy.hstack((o_zon_aver,zon_aver[ht,im]))
377 o_mer_aver = numpy.hstack((o_mer_aver,mer_aver[ht,im]))
378 o_ver_aver = numpy.hstack((o_ver_aver,ver_aver[ht,im]))
379
380 data_fHeigths_List.append(o_height)
381 data_fZonal_List.append(o_zon_aver)
382 data_fMeridional_List.append(o_mer_aver)
383 data_fVertical_List.append(o_ver_aver)
384
385
386 else:
387 h_select = numpy.where(numpy.bitwise_and(height[0,:] <= hcm,numpy.isfinite(height[0,:])))
388 ht = h_select[0]
389 o_height = numpy.hstack((o_height,height[im,ht]))
390 o_zon_aver = numpy.hstack((o_zon_aver,zon_aver[ht,im]))
391 o_mer_aver = numpy.hstack((o_mer_aver,mer_aver[ht,im]))
392 o_ver_aver = numpy.hstack((o_ver_aver,ver_aver[ht,im]))
393
394 data_fHeigths_List.append(o_height)
395 data_fZonal_List.append(o_zon_aver)
396 data_fMeridional_List.append(o_mer_aver)
397 data_fVertical_List.append(o_ver_aver)
398
399
400 return startDTList, data_fHeigths_List, data_fZonal_List, data_fMeridional_List, data_fVertical_List
401
402
403 No newline at end of file
@@ -1,1220 +1,1229
1 '''
1 '''
2
2
3 $Author: murco $
3 $Author: murco $
4 $Id: JROData.py 173 2012-11-20 15:06:21Z murco $
4 $Id: JROData.py 173 2012-11-20 15:06:21Z murco $
5 '''
5 '''
6
6
7 import copy
7 import copy
8 import numpy
8 import numpy
9 import datetime
9 import datetime
10
10
11 from jroheaderIO import SystemHeader, RadarControllerHeader
11 from jroheaderIO import SystemHeader, RadarControllerHeader
12 from schainpy import cSchain
12 from schainpy import cSchain
13
13
14
14
15 def getNumpyDtype(dataTypeCode):
15 def getNumpyDtype(dataTypeCode):
16
16
17 if dataTypeCode == 0:
17 if dataTypeCode == 0:
18 numpyDtype = numpy.dtype([('real','<i1'),('imag','<i1')])
18 numpyDtype = numpy.dtype([('real','<i1'),('imag','<i1')])
19 elif dataTypeCode == 1:
19 elif dataTypeCode == 1:
20 numpyDtype = numpy.dtype([('real','<i2'),('imag','<i2')])
20 numpyDtype = numpy.dtype([('real','<i2'),('imag','<i2')])
21 elif dataTypeCode == 2:
21 elif dataTypeCode == 2:
22 numpyDtype = numpy.dtype([('real','<i4'),('imag','<i4')])
22 numpyDtype = numpy.dtype([('real','<i4'),('imag','<i4')])
23 elif dataTypeCode == 3:
23 elif dataTypeCode == 3:
24 numpyDtype = numpy.dtype([('real','<i8'),('imag','<i8')])
24 numpyDtype = numpy.dtype([('real','<i8'),('imag','<i8')])
25 elif dataTypeCode == 4:
25 elif dataTypeCode == 4:
26 numpyDtype = numpy.dtype([('real','<f4'),('imag','<f4')])
26 numpyDtype = numpy.dtype([('real','<f4'),('imag','<f4')])
27 elif dataTypeCode == 5:
27 elif dataTypeCode == 5:
28 numpyDtype = numpy.dtype([('real','<f8'),('imag','<f8')])
28 numpyDtype = numpy.dtype([('real','<f8'),('imag','<f8')])
29 else:
29 else:
30 raise ValueError, 'dataTypeCode was not defined'
30 raise ValueError, 'dataTypeCode was not defined'
31
31
32 return numpyDtype
32 return numpyDtype
33
33
34 def getDataTypeCode(numpyDtype):
34 def getDataTypeCode(numpyDtype):
35
35
36 if numpyDtype == numpy.dtype([('real','<i1'),('imag','<i1')]):
36 if numpyDtype == numpy.dtype([('real','<i1'),('imag','<i1')]):
37 datatype = 0
37 datatype = 0
38 elif numpyDtype == numpy.dtype([('real','<i2'),('imag','<i2')]):
38 elif numpyDtype == numpy.dtype([('real','<i2'),('imag','<i2')]):
39 datatype = 1
39 datatype = 1
40 elif numpyDtype == numpy.dtype([('real','<i4'),('imag','<i4')]):
40 elif numpyDtype == numpy.dtype([('real','<i4'),('imag','<i4')]):
41 datatype = 2
41 datatype = 2
42 elif numpyDtype == numpy.dtype([('real','<i8'),('imag','<i8')]):
42 elif numpyDtype == numpy.dtype([('real','<i8'),('imag','<i8')]):
43 datatype = 3
43 datatype = 3
44 elif numpyDtype == numpy.dtype([('real','<f4'),('imag','<f4')]):
44 elif numpyDtype == numpy.dtype([('real','<f4'),('imag','<f4')]):
45 datatype = 4
45 datatype = 4
46 elif numpyDtype == numpy.dtype([('real','<f8'),('imag','<f8')]):
46 elif numpyDtype == numpy.dtype([('real','<f8'),('imag','<f8')]):
47 datatype = 5
47 datatype = 5
48 else:
48 else:
49 datatype = None
49 datatype = None
50
50
51 return datatype
51 return datatype
52
52
53 def hildebrand_sekhon(data, navg):
53 def hildebrand_sekhon(data, navg):
54 """
54 """
55 This method is for the objective determination of the noise level in Doppler spectra. This
55 This method is for the objective determination of the noise level in Doppler spectra. This
56 implementation technique is based on the fact that the standard deviation of the spectral
56 implementation technique is based on the fact that the standard deviation of the spectral
57 densities is equal to the mean spectral density for white Gaussian noise
57 densities is equal to the mean spectral density for white Gaussian noise
58
58
59 Inputs:
59 Inputs:
60 Data : heights
60 Data : heights
61 navg : numbers of averages
61 navg : numbers of averages
62
62
63 Return:
63 Return:
64 -1 : any error
64 -1 : any error
65 anoise : noise's level
65 anoise : noise's level
66 """
66 """
67
67
68 sortdata = numpy.sort(data, axis=None)
68 sortdata = numpy.sort(data, axis=None)
69 # lenOfData = len(sortdata)
69 # lenOfData = len(sortdata)
70 # nums_min = lenOfData*0.2
70 # nums_min = lenOfData*0.2
71 #
71 #
72 # if nums_min <= 5:
72 # if nums_min <= 5:
73 # nums_min = 5
73 # nums_min = 5
74 #
74 #
75 # sump = 0.
75 # sump = 0.
76 #
76 #
77 # sumq = 0.
77 # sumq = 0.
78 #
78 #
79 # j = 0
79 # j = 0
80 #
80 #
81 # cont = 1
81 # cont = 1
82 #
82 #
83 # while((cont==1)and(j<lenOfData)):
83 # while((cont==1)and(j<lenOfData)):
84 #
84 #
85 # sump += sortdata[j]
85 # sump += sortdata[j]
86 #
86 #
87 # sumq += sortdata[j]**2
87 # sumq += sortdata[j]**2
88 #
88 #
89 # if j > nums_min:
89 # if j > nums_min:
90 # rtest = float(j)/(j-1) + 1.0/navg
90 # rtest = float(j)/(j-1) + 1.0/navg
91 # if ((sumq*j) > (rtest*sump**2)):
91 # if ((sumq*j) > (rtest*sump**2)):
92 # j = j - 1
92 # j = j - 1
93 # sump = sump - sortdata[j]
93 # sump = sump - sortdata[j]
94 # sumq = sumq - sortdata[j]**2
94 # sumq = sumq - sortdata[j]**2
95 # cont = 0
95 # cont = 0
96 #
96 #
97 # j += 1
97 # j += 1
98 #
98 #
99 # lnoise = sump /j
99 # lnoise = sump /j
100 #
100 #
101 # return lnoise
101 # return lnoise
102
102
103 return cSchain.hildebrand_sekhon(sortdata, navg)
103 return cSchain.hildebrand_sekhon(sortdata, navg)
104
104
105
105
106 class Beam:
106 class Beam:
107
107
108 def __init__(self):
108 def __init__(self):
109 self.codeList = []
109 self.codeList = []
110 self.azimuthList = []
110 self.azimuthList = []
111 self.zenithList = []
111 self.zenithList = []
112
112
113 class GenericData(object):
113 class GenericData(object):
114
114
115 flagNoData = True
115 flagNoData = True
116
116
117 def copy(self, inputObj=None):
117 def copy(self, inputObj=None):
118
118
119 if inputObj == None:
119 if inputObj == None:
120 return copy.deepcopy(self)
120 return copy.deepcopy(self)
121
121
122 for key in inputObj.__dict__.keys():
122 for key in inputObj.__dict__.keys():
123
123
124 attribute = inputObj.__dict__[key]
124 attribute = inputObj.__dict__[key]
125
125
126 #If this attribute is a tuple or list
126 #If this attribute is a tuple or list
127 if type(inputObj.__dict__[key]) in (tuple, list):
127 if type(inputObj.__dict__[key]) in (tuple, list):
128 self.__dict__[key] = attribute[:]
128 self.__dict__[key] = attribute[:]
129 continue
129 continue
130
130
131 #If this attribute is another object or instance
131 #If this attribute is another object or instance
132 if hasattr(attribute, '__dict__'):
132 if hasattr(attribute, '__dict__'):
133 self.__dict__[key] = attribute.copy()
133 self.__dict__[key] = attribute.copy()
134 continue
134 continue
135
135
136 self.__dict__[key] = inputObj.__dict__[key]
136 self.__dict__[key] = inputObj.__dict__[key]
137
137
138 def deepcopy(self):
138 def deepcopy(self):
139
139
140 return copy.deepcopy(self)
140 return copy.deepcopy(self)
141
141
142 def isEmpty(self):
142 def isEmpty(self):
143
143
144 return self.flagNoData
144 return self.flagNoData
145
145
146 class JROData(GenericData):
146 class JROData(GenericData):
147
147
148 # m_BasicHeader = BasicHeader()
148 # m_BasicHeader = BasicHeader()
149 # m_ProcessingHeader = ProcessingHeader()
149 # m_ProcessingHeader = ProcessingHeader()
150
150
151 systemHeaderObj = SystemHeader()
151 systemHeaderObj = SystemHeader()
152
152
153 radarControllerHeaderObj = RadarControllerHeader()
153 radarControllerHeaderObj = RadarControllerHeader()
154
154
155 # data = None
155 # data = None
156
156
157 type = None
157 type = None
158
158
159 datatype = None #dtype but in string
159 datatype = None #dtype but in string
160
160
161 # dtype = None
161 # dtype = None
162
162
163 # nChannels = None
163 # nChannels = None
164
164
165 # nHeights = None
165 # nHeights = None
166
166
167 nProfiles = None
167 nProfiles = None
168
168
169 heightList = None
169 heightList = None
170
170
171 channelList = None
171 channelList = None
172
172
173 flagDiscontinuousBlock = False
173 flagDiscontinuousBlock = False
174
174
175 useLocalTime = False
175 useLocalTime = False
176
176
177 utctime = None
177 utctime = None
178
178
179 timeZone = None
179 timeZone = None
180
180
181 dstFlag = None
181 dstFlag = None
182
182
183 errorCount = None
183 errorCount = None
184
184
185 blocksize = None
185 blocksize = None
186
186
187 # nCode = None
187 # nCode = None
188 #
188 #
189 # nBaud = None
189 # nBaud = None
190 #
190 #
191 # code = None
191 # code = None
192
192
193 flagDecodeData = False #asumo q la data no esta decodificada
193 flagDecodeData = False #asumo q la data no esta decodificada
194
194
195 flagDeflipData = False #asumo q la data no esta sin flip
195 flagDeflipData = False #asumo q la data no esta sin flip
196
196
197 flagShiftFFT = False
197 flagShiftFFT = False
198
198
199 # ippSeconds = None
199 # ippSeconds = None
200
200
201 # timeInterval = None
201 # timeInterval = None
202
202
203 nCohInt = None
203 nCohInt = None
204
204
205 # noise = None
205 # noise = None
206
206
207 windowOfFilter = 1
207 windowOfFilter = 1
208
208
209 #Speed of ligth
209 #Speed of ligth
210 C = 3e8
210 C = 3e8
211
211
212 frequency = 49.92e6
212 frequency = 49.92e6
213
213
214 realtime = False
214 realtime = False
215
215
216 beacon_heiIndexList = None
216 beacon_heiIndexList = None
217
217
218 last_block = None
218 last_block = None
219
219
220 blocknow = None
220 blocknow = None
221
221
222 azimuth = None
222 azimuth = None
223
223
224 zenith = None
224 zenith = None
225
225
226 beam = Beam()
226 beam = Beam()
227
227
228 profileIndex = None
228 profileIndex = None
229
229
230 def getNoise(self):
230 def getNoise(self):
231
231
232 raise NotImplementedError
232 raise NotImplementedError
233
233
234 def getNChannels(self):
234 def getNChannels(self):
235
235
236 return len(self.channelList)
236 return len(self.channelList)
237
237
238 def getChannelIndexList(self):
238 def getChannelIndexList(self):
239
239
240 return range(self.nChannels)
240 return range(self.nChannels)
241
241
242 def getNHeights(self):
242 def getNHeights(self):
243
243
244 return len(self.heightList)
244 return len(self.heightList)
245
245
246 def getHeiRange(self, extrapoints=0):
246 def getHeiRange(self, extrapoints=0):
247
247
248 heis = self.heightList
248 heis = self.heightList
249 # deltah = self.heightList[1] - self.heightList[0]
249 # deltah = self.heightList[1] - self.heightList[0]
250 #
250 #
251 # heis.append(self.heightList[-1])
251 # heis.append(self.heightList[-1])
252
252
253 return heis
253 return heis
254
254
255 def getDeltaH(self):
255 def getDeltaH(self):
256
256
257 delta = self.heightList[1] - self.heightList[0]
257 delta = self.heightList[1] - self.heightList[0]
258
258
259 return delta
259 return delta
260
260
261 def getltctime(self):
261 def getltctime(self):
262
262
263 if self.useLocalTime:
263 if self.useLocalTime:
264 return self.utctime - self.timeZone*60
264 return self.utctime - self.timeZone*60
265
265
266 return self.utctime
266 return self.utctime
267
267
268 def getDatatime(self):
268 def getDatatime(self):
269
269
270 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
270 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
271 return datatimeValue
271 return datatimeValue
272
272
273 def getTimeRange(self):
273 def getTimeRange(self):
274
274
275 datatime = []
275 datatime = []
276
276
277 datatime.append(self.ltctime)
277 datatime.append(self.ltctime)
278 datatime.append(self.ltctime + self.timeInterval+1)
278 datatime.append(self.ltctime + self.timeInterval+1)
279
279
280 datatime = numpy.array(datatime)
280 datatime = numpy.array(datatime)
281
281
282 return datatime
282 return datatime
283
283
284 def getFmaxTimeResponse(self):
284 def getFmaxTimeResponse(self):
285
285
286 period = (10**-6)*self.getDeltaH()/(0.15)
286 period = (10**-6)*self.getDeltaH()/(0.15)
287
287
288 PRF = 1./(period * self.nCohInt)
288 PRF = 1./(period * self.nCohInt)
289
289
290 fmax = PRF
290 fmax = PRF
291
291
292 return fmax
292 return fmax
293
293
294 def getFmax(self):
294 def getFmax(self):
295
295
296 PRF = 1./(self.ippSeconds * self.nCohInt)
296 PRF = 1./(self.ippSeconds * self.nCohInt)
297
297
298 fmax = PRF
298 fmax = PRF
299
299
300 return fmax
300 return fmax
301
301
302 def getVmax(self):
302 def getVmax(self):
303
303
304 _lambda = self.C/self.frequency
304 _lambda = self.C/self.frequency
305
305
306 vmax = self.getFmax() * _lambda/2
306 vmax = self.getFmax() * _lambda/2
307
307
308 return vmax
308 return vmax
309
309
310 def get_ippSeconds(self):
310 def get_ippSeconds(self):
311 '''
311 '''
312 '''
312 '''
313 return self.radarControllerHeaderObj.ippSeconds
313 return self.radarControllerHeaderObj.ippSeconds
314
314
315 def set_ippSeconds(self, ippSeconds):
315 def set_ippSeconds(self, ippSeconds):
316 '''
316 '''
317 '''
317 '''
318
318
319 self.radarControllerHeaderObj.ippSeconds = ippSeconds
319 self.radarControllerHeaderObj.ippSeconds = ippSeconds
320
320
321 return
321 return
322
322
323 def get_dtype(self):
323 def get_dtype(self):
324 '''
324 '''
325 '''
325 '''
326 return getNumpyDtype(self.datatype)
326 return getNumpyDtype(self.datatype)
327
327
328 def set_dtype(self, numpyDtype):
328 def set_dtype(self, numpyDtype):
329 '''
329 '''
330 '''
330 '''
331
331
332 self.datatype = getDataTypeCode(numpyDtype)
332 self.datatype = getDataTypeCode(numpyDtype)
333
333
334 def get_code(self):
334 def get_code(self):
335 '''
335 '''
336 '''
336 '''
337 return self.radarControllerHeaderObj.code
337 return self.radarControllerHeaderObj.code
338
338
339 def set_code(self, code):
339 def set_code(self, code):
340 '''
340 '''
341 '''
341 '''
342 self.radarControllerHeaderObj.code = code
342 self.radarControllerHeaderObj.code = code
343
343
344 return
344 return
345
345
346 def get_ncode(self):
346 def get_ncode(self):
347 '''
347 '''
348 '''
348 '''
349 return self.radarControllerHeaderObj.nCode
349 return self.radarControllerHeaderObj.nCode
350
350
351 def set_ncode(self, nCode):
351 def set_ncode(self, nCode):
352 '''
352 '''
353 '''
353 '''
354 self.radarControllerHeaderObj.nCode = nCode
354 self.radarControllerHeaderObj.nCode = nCode
355
355
356 return
356 return
357
357
358 def get_nbaud(self):
358 def get_nbaud(self):
359 '''
359 '''
360 '''
360 '''
361 return self.radarControllerHeaderObj.nBaud
361 return self.radarControllerHeaderObj.nBaud
362
362
363 def set_nbaud(self, nBaud):
363 def set_nbaud(self, nBaud):
364 '''
364 '''
365 '''
365 '''
366 self.radarControllerHeaderObj.nBaud = nBaud
366 self.radarControllerHeaderObj.nBaud = nBaud
367
367
368 return
368 return
369
369
370 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
370 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
371 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
371 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
372 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
372 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
373 #noise = property(getNoise, "I'm the 'nHeights' property.")
373 #noise = property(getNoise, "I'm the 'nHeights' property.")
374 datatime = property(getDatatime, "I'm the 'datatime' property")
374 datatime = property(getDatatime, "I'm the 'datatime' property")
375 ltctime = property(getltctime, "I'm the 'ltctime' property")
375 ltctime = property(getltctime, "I'm the 'ltctime' property")
376 ippSeconds = property(get_ippSeconds, set_ippSeconds)
376 ippSeconds = property(get_ippSeconds, set_ippSeconds)
377 dtype = property(get_dtype, set_dtype)
377 dtype = property(get_dtype, set_dtype)
378 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
378 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
379 code = property(get_code, set_code)
379 code = property(get_code, set_code)
380 nCode = property(get_ncode, set_ncode)
380 nCode = property(get_ncode, set_ncode)
381 nBaud = property(get_nbaud, set_nbaud)
381 nBaud = property(get_nbaud, set_nbaud)
382
382
383 class Voltage(JROData):
383 class Voltage(JROData):
384
384
385 #data es un numpy array de 2 dmensiones (canales, alturas)
385 #data es un numpy array de 2 dmensiones (canales, alturas)
386 data = None
386 data = None
387
387
388 def __init__(self):
388 def __init__(self):
389 '''
389 '''
390 Constructor
390 Constructor
391 '''
391 '''
392
392
393 self.useLocalTime = True
393 self.useLocalTime = True
394
394
395 self.radarControllerHeaderObj = RadarControllerHeader()
395 self.radarControllerHeaderObj = RadarControllerHeader()
396
396
397 self.systemHeaderObj = SystemHeader()
397 self.systemHeaderObj = SystemHeader()
398
398
399 self.type = "Voltage"
399 self.type = "Voltage"
400
400
401 self.data = None
401 self.data = None
402
402
403 # self.dtype = None
403 # self.dtype = None
404
404
405 # self.nChannels = 0
405 # self.nChannels = 0
406
406
407 # self.nHeights = 0
407 # self.nHeights = 0
408
408
409 self.nProfiles = None
409 self.nProfiles = None
410
410
411 self.heightList = None
411 self.heightList = None
412
412
413 self.channelList = None
413 self.channelList = None
414
414
415 # self.channelIndexList = None
415 # self.channelIndexList = None
416
416
417 self.flagNoData = True
417 self.flagNoData = True
418
418
419 self.flagDiscontinuousBlock = False
419 self.flagDiscontinuousBlock = False
420
420
421 self.utctime = None
421 self.utctime = None
422
422
423 self.timeZone = None
423 self.timeZone = None
424
424
425 self.dstFlag = None
425 self.dstFlag = None
426
426
427 self.errorCount = None
427 self.errorCount = None
428
428
429 self.nCohInt = None
429 self.nCohInt = None
430
430
431 self.blocksize = None
431 self.blocksize = None
432
432
433 self.flagDecodeData = False #asumo q la data no esta decodificada
433 self.flagDecodeData = False #asumo q la data no esta decodificada
434
434
435 self.flagDeflipData = False #asumo q la data no esta sin flip
435 self.flagDeflipData = False #asumo q la data no esta sin flip
436
436
437 self.flagShiftFFT = False
437 self.flagShiftFFT = False
438
438
439 self.flagDataAsBlock = False #Asumo que la data es leida perfil a perfil
439 self.flagDataAsBlock = False #Asumo que la data es leida perfil a perfil
440
440
441 self.profileIndex = 0
441 self.profileIndex = 0
442
442
443 def getNoisebyHildebrand(self, channel = None):
443 def getNoisebyHildebrand(self, channel = None):
444 """
444 """
445 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
445 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
446
446
447 Return:
447 Return:
448 noiselevel
448 noiselevel
449 """
449 """
450
450
451 if channel != None:
451 if channel != None:
452 data = self.data[channel]
452 data = self.data[channel]
453 nChannels = 1
453 nChannels = 1
454 else:
454 else:
455 data = self.data
455 data = self.data
456 nChannels = self.nChannels
456 nChannels = self.nChannels
457
457
458 noise = numpy.zeros(nChannels)
458 noise = numpy.zeros(nChannels)
459 power = data * numpy.conjugate(data)
459 power = data * numpy.conjugate(data)
460
460
461 for thisChannel in range(nChannels):
461 for thisChannel in range(nChannels):
462 if nChannels == 1:
462 if nChannels == 1:
463 daux = power[:].real
463 daux = power[:].real
464 else:
464 else:
465 daux = power[thisChannel,:].real
465 daux = power[thisChannel,:].real
466 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
466 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
467
467
468 return noise
468 return noise
469
469
470 def getNoise(self, type = 1, channel = None):
470 def getNoise(self, type = 1, channel = None):
471
471
472 if type == 1:
472 if type == 1:
473 noise = self.getNoisebyHildebrand(channel)
473 noise = self.getNoisebyHildebrand(channel)
474
474
475 return noise
475 return noise
476
476
477 def getPower(self, channel = None):
477 def getPower(self, channel = None):
478
478
479 if channel != None:
479 if channel != None:
480 data = self.data[channel]
480 data = self.data[channel]
481 else:
481 else:
482 data = self.data
482 data = self.data
483
483
484 power = data * numpy.conjugate(data)
484 power = data * numpy.conjugate(data)
485 powerdB = 10*numpy.log10(power.real)
485 powerdB = 10*numpy.log10(power.real)
486 powerdB = numpy.squeeze(powerdB)
486 powerdB = numpy.squeeze(powerdB)
487
487
488 return powerdB
488 return powerdB
489
489
490 def getTimeInterval(self):
490 def getTimeInterval(self):
491
491
492 timeInterval = self.ippSeconds * self.nCohInt
492 timeInterval = self.ippSeconds * self.nCohInt
493
493
494 return timeInterval
494 return timeInterval
495
495
496 noise = property(getNoise, "I'm the 'nHeights' property.")
496 noise = property(getNoise, "I'm the 'nHeights' property.")
497 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
497 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
498
498
499 class Spectra(JROData):
499 class Spectra(JROData):
500
500
501 #data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
501 #data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
502 data_spc = None
502 data_spc = None
503
503
504 #data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
504 #data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
505 data_cspc = None
505 data_cspc = None
506
506
507 #data dc es un numpy array de 2 dmensiones (canales, alturas)
507 #data dc es un numpy array de 2 dmensiones (canales, alturas)
508 data_dc = None
508 data_dc = None
509
509
510 #data power
510 #data power
511 data_pwr = None
511 data_pwr = None
512
512
513 nFFTPoints = None
513 nFFTPoints = None
514
514
515 # nPairs = None
515 # nPairs = None
516
516
517 pairsList = None
517 pairsList = None
518
518
519 nIncohInt = None
519 nIncohInt = None
520
520
521 wavelength = None #Necesario para cacular el rango de velocidad desde la frecuencia
521 wavelength = None #Necesario para cacular el rango de velocidad desde la frecuencia
522
522
523 nCohInt = None #se requiere para determinar el valor de timeInterval
523 nCohInt = None #se requiere para determinar el valor de timeInterval
524
524
525 ippFactor = None
525 ippFactor = None
526
526
527 profileIndex = 0
527 profileIndex = 0
528
528
529 plotting = "spectra"
529 plotting = "spectra"
530
530
531 def __init__(self):
531 def __init__(self):
532 '''
532 '''
533 Constructor
533 Constructor
534 '''
534 '''
535
535
536 self.useLocalTime = True
536 self.useLocalTime = True
537
537
538 self.radarControllerHeaderObj = RadarControllerHeader()
538 self.radarControllerHeaderObj = RadarControllerHeader()
539
539
540 self.systemHeaderObj = SystemHeader()
540 self.systemHeaderObj = SystemHeader()
541
541
542 self.type = "Spectra"
542 self.type = "Spectra"
543
543
544 # self.data = None
544 # self.data = None
545
545
546 # self.dtype = None
546 # self.dtype = None
547
547
548 # self.nChannels = 0
548 # self.nChannels = 0
549
549
550 # self.nHeights = 0
550 # self.nHeights = 0
551
551
552 self.nProfiles = None
552 self.nProfiles = None
553
553
554 self.heightList = None
554 self.heightList = None
555
555
556 self.channelList = None
556 self.channelList = None
557
557
558 # self.channelIndexList = None
558 # self.channelIndexList = None
559
559
560 self.pairsList = None
560 self.pairsList = None
561
561
562 self.flagNoData = True
562 self.flagNoData = True
563
563
564 self.flagDiscontinuousBlock = False
564 self.flagDiscontinuousBlock = False
565
565
566 self.utctime = None
566 self.utctime = None
567
567
568 self.nCohInt = None
568 self.nCohInt = None
569
569
570 self.nIncohInt = None
570 self.nIncohInt = None
571
571
572 self.blocksize = None
572 self.blocksize = None
573
573
574 self.nFFTPoints = None
574 self.nFFTPoints = None
575
575
576 self.wavelength = None
576 self.wavelength = None
577
577
578 self.flagDecodeData = False #asumo q la data no esta decodificada
578 self.flagDecodeData = False #asumo q la data no esta decodificada
579
579
580 self.flagDeflipData = False #asumo q la data no esta sin flip
580 self.flagDeflipData = False #asumo q la data no esta sin flip
581
581
582 self.flagShiftFFT = False
582 self.flagShiftFFT = False
583
583
584 self.ippFactor = 1
584 self.ippFactor = 1
585
585
586 #self.noise = None
586 #self.noise = None
587
587
588 self.beacon_heiIndexList = []
588 self.beacon_heiIndexList = []
589
589
590 self.noise_estimation = None
590 self.noise_estimation = None
591
591
592
592
593 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
593 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
594 """
594 """
595 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
595 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
596
596
597 Return:
597 Return:
598 noiselevel
598 noiselevel
599 """
599 """
600
600
601 noise = numpy.zeros(self.nChannels)
601 noise = numpy.zeros(self.nChannels)
602
602
603 for channel in range(self.nChannels):
603 for channel in range(self.nChannels):
604 daux = self.data_spc[channel,xmin_index:xmax_index,ymin_index:ymax_index]
604 daux = self.data_spc[channel,xmin_index:xmax_index,ymin_index:ymax_index]
605 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
605 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
606
606
607 return noise
607 return noise
608
608
609 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
609 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
610
610
611 if self.noise_estimation is not None:
611 if self.noise_estimation is not None:
612 return self.noise_estimation #this was estimated by getNoise Operation defined in jroproc_spectra.py
612 return self.noise_estimation #this was estimated by getNoise Operation defined in jroproc_spectra.py
613 else:
613 else:
614 noise = self.getNoisebyHildebrand(xmin_index, xmax_index, ymin_index, ymax_index)
614 noise = self.getNoisebyHildebrand(xmin_index, xmax_index, ymin_index, ymax_index)
615 return noise
615 return noise
616
616
617 def getFreqRangeTimeResponse(self, extrapoints=0):
617 def getFreqRangeTimeResponse(self, extrapoints=0):
618
618
619 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints*self.ippFactor)
619 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints*self.ippFactor)
620 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
620 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
621
621
622 return freqrange
622 return freqrange
623
623
624 def getAcfRange(self, extrapoints=0):
624 def getAcfRange(self, extrapoints=0):
625
625
626 deltafreq = 10./(self.getFmax() / (self.nFFTPoints*self.ippFactor))
626 deltafreq = 10./(self.getFmax() / (self.nFFTPoints*self.ippFactor))
627 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
627 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
628
628
629 return freqrange
629 return freqrange
630
630
631 def getFreqRange(self, extrapoints=0):
631 def getFreqRange(self, extrapoints=0):
632
632
633 deltafreq = self.getFmax() / (self.nFFTPoints*self.ippFactor)
633 deltafreq = self.getFmax() / (self.nFFTPoints*self.ippFactor)
634 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
634 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
635
635
636 return freqrange
636 return freqrange
637
637
638 def getVelRange(self, extrapoints=0):
638 def getVelRange(self, extrapoints=0):
639
639
640 deltav = self.getVmax() / (self.nFFTPoints*self.ippFactor)
640 deltav = self.getVmax() / (self.nFFTPoints*self.ippFactor)
641 velrange = deltav*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) #- deltav/2
641 velrange = deltav*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) #- deltav/2
642
642
643 return velrange
643 return velrange
644
644
645 def getNPairs(self):
645 def getNPairs(self):
646
646
647 return len(self.pairsList)
647 return len(self.pairsList)
648
648
649 def getPairsIndexList(self):
649 def getPairsIndexList(self):
650
650
651 return range(self.nPairs)
651 return range(self.nPairs)
652
652
653 def getNormFactor(self):
653 def getNormFactor(self):
654
654
655 pwcode = 1
655 pwcode = 1
656
656
657 if self.flagDecodeData:
657 if self.flagDecodeData:
658 pwcode = numpy.sum(self.code[0]**2)
658 pwcode = numpy.sum(self.code[0]**2)
659 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
659 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
660 normFactor = self.nProfiles*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
660 normFactor = self.nProfiles*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
661
661
662 return normFactor
662 return normFactor
663
663
664 def getFlagCspc(self):
664 def getFlagCspc(self):
665
665
666 if self.data_cspc is None:
666 if self.data_cspc is None:
667 return True
667 return True
668
668
669 return False
669 return False
670
670
671 def getFlagDc(self):
671 def getFlagDc(self):
672
672
673 if self.data_dc is None:
673 if self.data_dc is None:
674 return True
674 return True
675
675
676 return False
676 return False
677
677
678 def getTimeInterval(self):
678 def getTimeInterval(self):
679
679
680 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles
680 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles
681
681
682 return timeInterval
682 return timeInterval
683
683
684 def getPower(self):
684 def getPower(self):
685
685
686 factor = self.normFactor
686 factor = self.normFactor
687 z = self.data_spc/factor
687 z = self.data_spc/factor
688 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
688 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
689 avg = numpy.average(z, axis=1)
689 avg = numpy.average(z, axis=1)
690
690
691 return 10*numpy.log10(avg)
691 return 10*numpy.log10(avg)
692
692
693 def getCoherence(self, pairsList=None, phase=False):
693 def getCoherence(self, pairsList=None, phase=False):
694
694
695 z = []
695 z = []
696 if pairsList is None:
696 if pairsList is None:
697 pairsIndexList = self.pairsIndexList
697 pairsIndexList = self.pairsIndexList
698 else:
698 else:
699 pairsIndexList = []
699 pairsIndexList = []
700 for pair in pairsList:
700 for pair in pairsList:
701 if pair not in self.pairsList:
701 if pair not in self.pairsList:
702 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
702 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
703 pairsIndexList.append(self.pairsList.index(pair))
703 pairsIndexList.append(self.pairsList.index(pair))
704 for i in range(len(pairsIndexList)):
704 for i in range(len(pairsIndexList)):
705 pair = self.pairsList[pairsIndexList[i]]
705 pair = self.pairsList[pairsIndexList[i]]
706 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
706 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
707 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
707 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
708 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
708 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
709 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
709 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
710 if phase:
710 if phase:
711 data = numpy.arctan2(avgcoherenceComplex.imag,
711 data = numpy.arctan2(avgcoherenceComplex.imag,
712 avgcoherenceComplex.real)*180/numpy.pi
712 avgcoherenceComplex.real)*180/numpy.pi
713 else:
713 else:
714 data = numpy.abs(avgcoherenceComplex)
714 data = numpy.abs(avgcoherenceComplex)
715
715
716 z.append(data)
716 z.append(data)
717
717
718 return numpy.array(z)
718 return numpy.array(z)
719
719
720 def setValue(self, value):
720 def setValue(self, value):
721
721
722 print "This property should not be initialized"
722 print "This property should not be initialized"
723
723
724 return
724 return
725
725
726 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
726 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
727 pairsIndexList = property(getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
727 pairsIndexList = property(getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
728 normFactor = property(getNormFactor, setValue, "I'm the 'getNormFactor' property.")
728 normFactor = property(getNormFactor, setValue, "I'm the 'getNormFactor' property.")
729 flag_cspc = property(getFlagCspc, setValue)
729 flag_cspc = property(getFlagCspc, setValue)
730 flag_dc = property(getFlagDc, setValue)
730 flag_dc = property(getFlagDc, setValue)
731 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
731 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
732 timeInterval = property(getTimeInterval, setValue, "I'm the 'timeInterval' property")
732 timeInterval = property(getTimeInterval, setValue, "I'm the 'timeInterval' property")
733
733
734 class SpectraHeis(Spectra):
734 class SpectraHeis(Spectra):
735
735
736 data_spc = None
736 data_spc = None
737
737
738 data_cspc = None
738 data_cspc = None
739
739
740 data_dc = None
740 data_dc = None
741
741
742 nFFTPoints = None
742 nFFTPoints = None
743
743
744 # nPairs = None
744 # nPairs = None
745
745
746 pairsList = None
746 pairsList = None
747
747
748 nCohInt = None
748 nCohInt = None
749
749
750 nIncohInt = None
750 nIncohInt = None
751
751
752 def __init__(self):
752 def __init__(self):
753
753
754 self.radarControllerHeaderObj = RadarControllerHeader()
754 self.radarControllerHeaderObj = RadarControllerHeader()
755
755
756 self.systemHeaderObj = SystemHeader()
756 self.systemHeaderObj = SystemHeader()
757
757
758 self.type = "SpectraHeis"
758 self.type = "SpectraHeis"
759
759
760 # self.dtype = None
760 # self.dtype = None
761
761
762 # self.nChannels = 0
762 # self.nChannels = 0
763
763
764 # self.nHeights = 0
764 # self.nHeights = 0
765
765
766 self.nProfiles = None
766 self.nProfiles = None
767
767
768 self.heightList = None
768 self.heightList = None
769
769
770 self.channelList = None
770 self.channelList = None
771
771
772 # self.channelIndexList = None
772 # self.channelIndexList = None
773
773
774 self.flagNoData = True
774 self.flagNoData = True
775
775
776 self.flagDiscontinuousBlock = False
776 self.flagDiscontinuousBlock = False
777
777
778 # self.nPairs = 0
778 # self.nPairs = 0
779
779
780 self.utctime = None
780 self.utctime = None
781
781
782 self.blocksize = None
782 self.blocksize = None
783
783
784 self.profileIndex = 0
784 self.profileIndex = 0
785
785
786 self.nCohInt = 1
786 self.nCohInt = 1
787
787
788 self.nIncohInt = 1
788 self.nIncohInt = 1
789
789
790 def getNormFactor(self):
790 def getNormFactor(self):
791 pwcode = 1
791 pwcode = 1
792 if self.flagDecodeData:
792 if self.flagDecodeData:
793 pwcode = numpy.sum(self.code[0]**2)
793 pwcode = numpy.sum(self.code[0]**2)
794
794
795 normFactor = self.nIncohInt*self.nCohInt*pwcode
795 normFactor = self.nIncohInt*self.nCohInt*pwcode
796
796
797 return normFactor
797 return normFactor
798
798
799 def getTimeInterval(self):
799 def getTimeInterval(self):
800
800
801 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
801 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
802
802
803 return timeInterval
803 return timeInterval
804
804
805 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
805 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
806 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
806 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
807
807
808 class Fits(JROData):
808 class Fits(JROData):
809
809
810 heightList = None
810 heightList = None
811
811
812 channelList = None
812 channelList = None
813
813
814 flagNoData = True
814 flagNoData = True
815
815
816 flagDiscontinuousBlock = False
816 flagDiscontinuousBlock = False
817
817
818 useLocalTime = False
818 useLocalTime = False
819
819
820 utctime = None
820 utctime = None
821
821
822 timeZone = None
822 timeZone = None
823
823
824 # ippSeconds = None
824 # ippSeconds = None
825
825
826 # timeInterval = None
826 # timeInterval = None
827
827
828 nCohInt = None
828 nCohInt = None
829
829
830 nIncohInt = None
830 nIncohInt = None
831
831
832 noise = None
832 noise = None
833
833
834 windowOfFilter = 1
834 windowOfFilter = 1
835
835
836 #Speed of ligth
836 #Speed of ligth
837 C = 3e8
837 C = 3e8
838
838
839 frequency = 49.92e6
839 frequency = 49.92e6
840
840
841 realtime = False
841 realtime = False
842
842
843
843
844 def __init__(self):
844 def __init__(self):
845
845
846 self.type = "Fits"
846 self.type = "Fits"
847
847
848 self.nProfiles = None
848 self.nProfiles = None
849
849
850 self.heightList = None
850 self.heightList = None
851
851
852 self.channelList = None
852 self.channelList = None
853
853
854 # self.channelIndexList = None
854 # self.channelIndexList = None
855
855
856 self.flagNoData = True
856 self.flagNoData = True
857
857
858 self.utctime = None
858 self.utctime = None
859
859
860 self.nCohInt = 1
860 self.nCohInt = 1
861
861
862 self.nIncohInt = 1
862 self.nIncohInt = 1
863
863
864 self.useLocalTime = True
864 self.useLocalTime = True
865
865
866 self.profileIndex = 0
866 self.profileIndex = 0
867
867
868 # self.utctime = None
868 # self.utctime = None
869 # self.timeZone = None
869 # self.timeZone = None
870 # self.ltctime = None
870 # self.ltctime = None
871 # self.timeInterval = None
871 # self.timeInterval = None
872 # self.header = None
872 # self.header = None
873 # self.data_header = None
873 # self.data_header = None
874 # self.data = None
874 # self.data = None
875 # self.datatime = None
875 # self.datatime = None
876 # self.flagNoData = False
876 # self.flagNoData = False
877 # self.expName = ''
877 # self.expName = ''
878 # self.nChannels = None
878 # self.nChannels = None
879 # self.nSamples = None
879 # self.nSamples = None
880 # self.dataBlocksPerFile = None
880 # self.dataBlocksPerFile = None
881 # self.comments = ''
881 # self.comments = ''
882 #
882 #
883
883
884
884
885 def getltctime(self):
885 def getltctime(self):
886
886
887 if self.useLocalTime:
887 if self.useLocalTime:
888 return self.utctime - self.timeZone*60
888 return self.utctime - self.timeZone*60
889
889
890 return self.utctime
890 return self.utctime
891
891
892 def getDatatime(self):
892 def getDatatime(self):
893
893
894 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
894 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
895 return datatime
895 return datatime
896
896
897 def getTimeRange(self):
897 def getTimeRange(self):
898
898
899 datatime = []
899 datatime = []
900
900
901 datatime.append(self.ltctime)
901 datatime.append(self.ltctime)
902 datatime.append(self.ltctime + self.timeInterval)
902 datatime.append(self.ltctime + self.timeInterval)
903
903
904 datatime = numpy.array(datatime)
904 datatime = numpy.array(datatime)
905
905
906 return datatime
906 return datatime
907
907
908 def getHeiRange(self):
908 def getHeiRange(self):
909
909
910 heis = self.heightList
910 heis = self.heightList
911
911
912 return heis
912 return heis
913
913
914 def getNHeights(self):
914 def getNHeights(self):
915
915
916 return len(self.heightList)
916 return len(self.heightList)
917
917
918 def getNChannels(self):
918 def getNChannels(self):
919
919
920 return len(self.channelList)
920 return len(self.channelList)
921
921
922 def getChannelIndexList(self):
922 def getChannelIndexList(self):
923
923
924 return range(self.nChannels)
924 return range(self.nChannels)
925
925
926 def getNoise(self, type = 1):
926 def getNoise(self, type = 1):
927
927
928 #noise = numpy.zeros(self.nChannels)
928 #noise = numpy.zeros(self.nChannels)
929
929
930 if type == 1:
930 if type == 1:
931 noise = self.getNoisebyHildebrand()
931 noise = self.getNoisebyHildebrand()
932
932
933 if type == 2:
933 if type == 2:
934 noise = self.getNoisebySort()
934 noise = self.getNoisebySort()
935
935
936 if type == 3:
936 if type == 3:
937 noise = self.getNoisebyWindow()
937 noise = self.getNoisebyWindow()
938
938
939 return noise
939 return noise
940
940
941 def getTimeInterval(self):
941 def getTimeInterval(self):
942
942
943 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
943 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
944
944
945 return timeInterval
945 return timeInterval
946
946
947 datatime = property(getDatatime, "I'm the 'datatime' property")
947 datatime = property(getDatatime, "I'm the 'datatime' property")
948 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
948 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
949 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
949 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
950 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
950 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
951 noise = property(getNoise, "I'm the 'nHeights' property.")
951 noise = property(getNoise, "I'm the 'nHeights' property.")
952
952
953 ltctime = property(getltctime, "I'm the 'ltctime' property")
953 ltctime = property(getltctime, "I'm the 'ltctime' property")
954 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
954 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
955
955
956
956
957 class Correlation(JROData):
957 class Correlation(JROData):
958
958
959 noise = None
959 noise = None
960
960
961 SNR = None
961 SNR = None
962
962
963 #--------------------------------------------------
963 #--------------------------------------------------
964
964
965 mode = None
965 mode = None
966
966
967 split = False
967 split = False
968
968
969 data_cf = None
969 data_cf = None
970
970
971 lags = None
971 lags = None
972
972
973 lagRange = None
973 lagRange = None
974
974
975 pairsList = None
975 pairsList = None
976
976
977 normFactor = None
977 normFactor = None
978
978
979 #--------------------------------------------------
979 #--------------------------------------------------
980
980
981 # calculateVelocity = None
981 # calculateVelocity = None
982
982
983 nLags = None
983 nLags = None
984
984
985 nPairs = None
985 nPairs = None
986
986
987 nAvg = None
987 nAvg = None
988
988
989
989
990 def __init__(self):
990 def __init__(self):
991 '''
991 '''
992 Constructor
992 Constructor
993 '''
993 '''
994 self.radarControllerHeaderObj = RadarControllerHeader()
994 self.radarControllerHeaderObj = RadarControllerHeader()
995
995
996 self.systemHeaderObj = SystemHeader()
996 self.systemHeaderObj = SystemHeader()
997
997
998 self.type = "Correlation"
998 self.type = "Correlation"
999
999
1000 self.data = None
1000 self.data = None
1001
1001
1002 self.dtype = None
1002 self.dtype = None
1003
1003
1004 self.nProfiles = None
1004 self.nProfiles = None
1005
1005
1006 self.heightList = None
1006 self.heightList = None
1007
1007
1008 self.channelList = None
1008 self.channelList = None
1009
1009
1010 self.flagNoData = True
1010 self.flagNoData = True
1011
1011
1012 self.flagDiscontinuousBlock = False
1012 self.flagDiscontinuousBlock = False
1013
1013
1014 self.utctime = None
1014 self.utctime = None
1015
1015
1016 self.timeZone = None
1016 self.timeZone = None
1017
1017
1018 self.dstFlag = None
1018 self.dstFlag = None
1019
1019
1020 self.errorCount = None
1020 self.errorCount = None
1021
1021
1022 self.blocksize = None
1022 self.blocksize = None
1023
1023
1024 self.flagDecodeData = False #asumo q la data no esta decodificada
1024 self.flagDecodeData = False #asumo q la data no esta decodificada
1025
1025
1026 self.flagDeflipData = False #asumo q la data no esta sin flip
1026 self.flagDeflipData = False #asumo q la data no esta sin flip
1027
1027
1028 self.pairsList = None
1028 self.pairsList = None
1029
1029
1030 self.nPoints = None
1030 self.nPoints = None
1031
1031
1032 def getPairsList(self):
1032 def getPairsList(self):
1033
1033
1034 return self.pairsList
1034 return self.pairsList
1035
1035
1036 def getNoise(self, mode = 2):
1036 def getNoise(self, mode = 2):
1037
1037
1038 indR = numpy.where(self.lagR == 0)[0][0]
1038 indR = numpy.where(self.lagR == 0)[0][0]
1039 indT = numpy.where(self.lagT == 0)[0][0]
1039 indT = numpy.where(self.lagT == 0)[0][0]
1040
1040
1041 jspectra0 = self.data_corr[:,:,indR,:]
1041 jspectra0 = self.data_corr[:,:,indR,:]
1042 jspectra = copy.copy(jspectra0)
1042 jspectra = copy.copy(jspectra0)
1043
1043
1044 num_chan = jspectra.shape[0]
1044 num_chan = jspectra.shape[0]
1045 num_hei = jspectra.shape[2]
1045 num_hei = jspectra.shape[2]
1046
1046
1047 freq_dc = jspectra.shape[1]/2
1047 freq_dc = jspectra.shape[1]/2
1048 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
1048 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
1049
1049
1050 if ind_vel[0]<0:
1050 if ind_vel[0]<0:
1051 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
1051 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
1052
1052
1053 if mode == 1:
1053 if mode == 1:
1054 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
1054 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
1055
1055
1056 if mode == 2:
1056 if mode == 2:
1057
1057
1058 vel = numpy.array([-2,-1,1,2])
1058 vel = numpy.array([-2,-1,1,2])
1059 xx = numpy.zeros([4,4])
1059 xx = numpy.zeros([4,4])
1060
1060
1061 for fil in range(4):
1061 for fil in range(4):
1062 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
1062 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
1063
1063
1064 xx_inv = numpy.linalg.inv(xx)
1064 xx_inv = numpy.linalg.inv(xx)
1065 xx_aux = xx_inv[0,:]
1065 xx_aux = xx_inv[0,:]
1066
1066
1067 for ich in range(num_chan):
1067 for ich in range(num_chan):
1068 yy = jspectra[ich,ind_vel,:]
1068 yy = jspectra[ich,ind_vel,:]
1069 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
1069 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
1070
1070
1071 junkid = jspectra[ich,freq_dc,:]<=0
1071 junkid = jspectra[ich,freq_dc,:]<=0
1072 cjunkid = sum(junkid)
1072 cjunkid = sum(junkid)
1073
1073
1074 if cjunkid.any():
1074 if cjunkid.any():
1075 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
1075 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
1076
1076
1077 noise = jspectra0[:,freq_dc,:] - jspectra[:,freq_dc,:]
1077 noise = jspectra0[:,freq_dc,:] - jspectra[:,freq_dc,:]
1078
1078
1079 return noise
1079 return noise
1080
1080
1081 def getTimeInterval(self):
1081 def getTimeInterval(self):
1082
1082
1083 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
1083 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
1084
1084
1085 return timeInterval
1085 return timeInterval
1086
1086
1087 def splitFunctions(self):
1087 def splitFunctions(self):
1088
1088
1089 pairsList = self.pairsList
1089 pairsList = self.pairsList
1090 ccf_pairs = []
1090 ccf_pairs = []
1091 acf_pairs = []
1091 acf_pairs = []
1092 ccf_ind = []
1092 ccf_ind = []
1093 acf_ind = []
1093 acf_ind = []
1094 for l in range(len(pairsList)):
1094 for l in range(len(pairsList)):
1095 chan0 = pairsList[l][0]
1095 chan0 = pairsList[l][0]
1096 chan1 = pairsList[l][1]
1096 chan1 = pairsList[l][1]
1097
1097
1098 #Obteniendo pares de Autocorrelacion
1098 #Obteniendo pares de Autocorrelacion
1099 if chan0 == chan1:
1099 if chan0 == chan1:
1100 acf_pairs.append(chan0)
1100 acf_pairs.append(chan0)
1101 acf_ind.append(l)
1101 acf_ind.append(l)
1102 else:
1102 else:
1103 ccf_pairs.append(pairsList[l])
1103 ccf_pairs.append(pairsList[l])
1104 ccf_ind.append(l)
1104 ccf_ind.append(l)
1105
1105
1106 data_acf = self.data_cf[acf_ind]
1106 data_acf = self.data_cf[acf_ind]
1107 data_ccf = self.data_cf[ccf_ind]
1107 data_ccf = self.data_cf[ccf_ind]
1108
1108
1109 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1109 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1110
1110
1111 def getNormFactor(self):
1111 def getNormFactor(self):
1112 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1112 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1113 acf_pairs = numpy.array(acf_pairs)
1113 acf_pairs = numpy.array(acf_pairs)
1114 normFactor = numpy.zeros((self.nPairs,self.nHeights))
1114 normFactor = numpy.zeros((self.nPairs,self.nHeights))
1115
1115
1116 for p in range(self.nPairs):
1116 for p in range(self.nPairs):
1117 pair = self.pairsList[p]
1117 pair = self.pairsList[p]
1118
1118
1119 ch0 = pair[0]
1119 ch0 = pair[0]
1120 ch1 = pair[1]
1120 ch1 = pair[1]
1121
1121
1122 ch0_max = numpy.max(data_acf[acf_pairs==ch0,:,:], axis=1)
1122 ch0_max = numpy.max(data_acf[acf_pairs==ch0,:,:], axis=1)
1123 ch1_max = numpy.max(data_acf[acf_pairs==ch1,:,:], axis=1)
1123 ch1_max = numpy.max(data_acf[acf_pairs==ch1,:,:], axis=1)
1124 normFactor[p,:] = numpy.sqrt(ch0_max*ch1_max)
1124 normFactor[p,:] = numpy.sqrt(ch0_max*ch1_max)
1125
1125
1126 return normFactor
1126 return normFactor
1127
1127
1128 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1128 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1129 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1129 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1130
1130
1131 class Parameters(Spectra):
1131 class Parameters(Spectra):
1132
1132
1133 experimentInfo = None #Information about the experiment
1133 experimentInfo = None #Information about the experiment
1134
1134
1135 #Information from previous data
1135 #Information from previous data
1136
1136
1137 inputUnit = None #Type of data to be processed
1137 inputUnit = None #Type of data to be processed
1138
1138
1139 operation = None #Type of operation to parametrize
1139 operation = None #Type of operation to parametrize
1140
1140
1141 #normFactor = None #Normalization Factor
1141 #normFactor = None #Normalization Factor
1142
1142
1143 groupList = None #List of Pairs, Groups, etc
1143 groupList = None #List of Pairs, Groups, etc
1144
1144
1145 #Parameters
1145 #Parameters
1146
1146
1147 data_param = None #Parameters obtained
1147 data_param = None #Parameters obtained
1148
1148
1149 data_pre = None #Data Pre Parametrization
1149 data_pre = None #Data Pre Parametrization
1150
1150
1151 data_SNR = None #Signal to Noise Ratio
1151 data_SNR = None #Signal to Noise Ratio
1152
1152
1153 # heightRange = None #Heights
1153 # heightRange = None #Heights
1154
1154
1155 abscissaList = None #Abscissa, can be velocities, lags or time
1155 abscissaList = None #Abscissa, can be velocities, lags or time
1156
1156
1157 # noise = None #Noise Potency
1157 # noise = None #Noise Potency
1158
1158
1159 utctimeInit = None #Initial UTC time
1159 utctimeInit = None #Initial UTC time
1160
1160
1161 paramInterval = None #Time interval to calculate Parameters in seconds
1161 paramInterval = None #Time interval to calculate Parameters in seconds
1162
1162
1163 useLocalTime = True
1163 useLocalTime = True
1164
1164
1165 #Fitting
1165 #Fitting
1166
1166
1167 data_error = None #Error of the estimation
1167 data_error = None #Error of the estimation
1168
1168
1169 constants = None
1169 constants = None
1170
1170
1171 library = None
1171 library = None
1172
1172
1173 #Output signal
1173 #Output signal
1174
1174
1175 outputInterval = None #Time interval to calculate output signal in seconds
1175 outputInterval = None #Time interval to calculate output signal in seconds
1176
1176
1177 data_output = None #Out signal
1177 data_output = None #Out signal
1178
1178
1179 nAvg = None
1179 nAvg = None
1180
1180
1181 noise_estimation = None
1181 noise_estimation = None
1182
1183 GauSPC = None #Fit gaussian SPC
1182
1184
1183
1185
1184 def __init__(self):
1186 def __init__(self):
1185 '''
1187 '''
1186 Constructor
1188 Constructor
1187 '''
1189 '''
1188 self.radarControllerHeaderObj = RadarControllerHeader()
1190 self.radarControllerHeaderObj = RadarControllerHeader()
1189
1191
1190 self.systemHeaderObj = SystemHeader()
1192 self.systemHeaderObj = SystemHeader()
1191
1193
1192 self.type = "Parameters"
1194 self.type = "Parameters"
1193
1195
1194 def getTimeRange1(self, interval):
1196 def getTimeRange1(self, interval):
1195
1197
1196 datatime = []
1198 datatime = []
1197
1199
1198 if self.useLocalTime:
1200 if self.useLocalTime:
1199 time1 = self.utctimeInit - self.timeZone*60
1201 time1 = self.utctimeInit - self.timeZone*60
1200 else:
1202 else:
1201 time1 = self.utctimeInit
1203 time1 = self.utctimeInit
1202
1204
1203 datatime.append(time1)
1205 datatime.append(time1)
1204 datatime.append(time1 + interval)
1206 datatime.append(time1 + interval)
1205 datatime = numpy.array(datatime)
1207 datatime = numpy.array(datatime)
1206
1208
1207 return datatime
1209 return datatime
1208
1210
1209 def getTimeInterval(self):
1211 def getTimeInterval(self):
1210
1212
1211 if hasattr(self, 'timeInterval1'):
1213 if hasattr(self, 'timeInterval1'):
1212 return self.timeInterval1
1214 return self.timeInterval1
1213 else:
1215 else:
1214 return self.paramInterval
1216 return self.paramInterval
1215
1217
1218 def setValue(self, value):
1219
1220 print "This property should not be initialized"
1221
1222 return
1223
1216 def getNoise(self):
1224 def getNoise(self):
1217
1225
1218 return self.spc_noise
1226 return self.spc_noise
1219
1227
1220 timeInterval = property(getTimeInterval)
1228 timeInterval = property(getTimeInterval)
1229 noise = property(getNoise, setValue, "I'm the 'Noise' property.")
@@ -1,188 +1,188
1 import os
1 import os
2 import datetime
2 import datetime
3 import numpy
3 import numpy
4 import copy
4 import copy
5
5
6 from figure import Figure, isRealtime
6 from figure import Figure, isRealtime
7
7
8 class CorrelationPlot(Figure):
8 class CorrelationPlot(Figure):
9
9
10 isConfig = None
10 isConfig = None
11 __nsubplots = None
11 __nsubplots = None
12
12
13 WIDTHPROF = None
13 WIDTHPROF = None
14 HEIGHTPROF = None
14 HEIGHTPROF = None
15 PREFIX = 'corr'
15 PREFIX = 'corr'
16
16
17 def __init__(self, **kwargs):
17 def __init__(self):
18 Figure.__init__(self, **kwargs)
18
19 self.isConfig = False
19 self.isConfig = False
20 self.__nsubplots = 1
20 self.__nsubplots = 1
21
21
22 self.WIDTH = 280
22 self.WIDTH = 280
23 self.HEIGHT = 250
23 self.HEIGHT = 250
24 self.WIDTHPROF = 120
24 self.WIDTHPROF = 120
25 self.HEIGHTPROF = 0
25 self.HEIGHTPROF = 0
26 self.counter_imagwr = 0
26 self.counter_imagwr = 0
27
27
28 self.PLOT_CODE = 1
28 self.PLOT_CODE = 1
29 self.FTP_WEI = None
29 self.FTP_WEI = None
30 self.EXP_CODE = None
30 self.EXP_CODE = None
31 self.SUB_EXP_CODE = None
31 self.SUB_EXP_CODE = None
32 self.PLOT_POS = None
32 self.PLOT_POS = None
33
33
34 def getSubplots(self):
34 def getSubplots(self):
35
35
36 ncol = int(numpy.sqrt(self.nplots)+0.9)
36 ncol = int(numpy.sqrt(self.nplots)+0.9)
37 nrow = int(self.nplots*1./ncol + 0.9)
37 nrow = int(self.nplots*1./ncol + 0.9)
38
38
39 return nrow, ncol
39 return nrow, ncol
40
40
41 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
41 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
42
42
43 showprofile = False
43 showprofile = False
44 self.__showprofile = showprofile
44 self.__showprofile = showprofile
45 self.nplots = nplots
45 self.nplots = nplots
46
46
47 ncolspan = 1
47 ncolspan = 1
48 colspan = 1
48 colspan = 1
49 if showprofile:
49 if showprofile:
50 ncolspan = 3
50 ncolspan = 3
51 colspan = 2
51 colspan = 2
52 self.__nsubplots = 2
52 self.__nsubplots = 2
53
53
54 self.createFigure(id = id,
54 self.createFigure(id = id,
55 wintitle = wintitle,
55 wintitle = wintitle,
56 widthplot = self.WIDTH + self.WIDTHPROF,
56 widthplot = self.WIDTH + self.WIDTHPROF,
57 heightplot = self.HEIGHT + self.HEIGHTPROF,
57 heightplot = self.HEIGHT + self.HEIGHTPROF,
58 show=show)
58 show=show)
59
59
60 nrow, ncol = self.getSubplots()
60 nrow, ncol = self.getSubplots()
61
61
62 counter = 0
62 counter = 0
63 for y in range(nrow):
63 for y in range(nrow):
64 for x in range(ncol):
64 for x in range(ncol):
65
65
66 if counter >= self.nplots:
66 if counter >= self.nplots:
67 break
67 break
68
68
69 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
69 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
70
70
71 if showprofile:
71 if showprofile:
72 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
72 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
73
73
74 counter += 1
74 counter += 1
75
75
76 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
76 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
77 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
77 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
78 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
78 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
79 server=None, folder=None, username=None, password=None,
79 server=None, folder=None, username=None, password=None,
80 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
80 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
81
81
82 """
82 """
83
83
84 Input:
84 Input:
85 dataOut :
85 dataOut :
86 id :
86 id :
87 wintitle :
87 wintitle :
88 channelList :
88 channelList :
89 showProfile :
89 showProfile :
90 xmin : None,
90 xmin : None,
91 xmax : None,
91 xmax : None,
92 ymin : None,
92 ymin : None,
93 ymax : None,
93 ymax : None,
94 zmin : None,
94 zmin : None,
95 zmax : None
95 zmax : None
96 """
96 """
97
97
98 if dataOut.flagNoData:
98 if dataOut.flagNoData:
99 return None
99 return None
100
100
101 if realtime:
101 if realtime:
102 if not(isRealtime(utcdatatime = dataOut.utctime)):
102 if not(isRealtime(utcdatatime = dataOut.utctime)):
103 print 'Skipping this plot function'
103 print 'Skipping this plot function'
104 return
104 return
105
105
106 if channelList == None:
106 if channelList == None:
107 channelIndexList = dataOut.channelIndexList
107 channelIndexList = dataOut.channelIndexList
108 else:
108 else:
109 channelIndexList = []
109 channelIndexList = []
110 for channel in channelList:
110 for channel in channelList:
111 if channel not in dataOut.channelList:
111 if channel not in dataOut.channelList:
112 raise ValueError, "Channel %d is not in dataOut.channelList"
112 raise ValueError, "Channel %d is not in dataOut.channelList"
113 channelIndexList.append(dataOut.channelList.index(channel))
113 channelIndexList.append(dataOut.channelList.index(channel))
114
114
115 factor = dataOut.normFactor
115 factor = dataOut.normFactor
116 lenfactor = factor.shape[1]
116 lenfactor = factor.shape[1]
117 x = dataOut.getLagTRange(1)
117 x = dataOut.getLagTRange(1)
118 y = dataOut.getHeiRange()
118 y = dataOut.getHeiRange()
119
119
120 z = copy.copy(dataOut.data_corr[:,:,0,:])
120 z = copy.copy(dataOut.data_corr[:,:,0,:])
121 for i in range(dataOut.data_corr.shape[0]):
121 for i in range(dataOut.data_corr.shape[0]):
122 z[i,:,:] = z[i,:,:]/factor[i,:]
122 z[i,:,:] = z[i,:,:]/factor[i,:]
123 zdB = numpy.abs(z)
123 zdB = numpy.abs(z)
124
124
125 avg = numpy.average(z, axis=1)
125 avg = numpy.average(z, axis=1)
126 # avg = numpy.nanmean(z, axis=1)
126 # avg = numpy.nanmean(z, axis=1)
127 # noise = dataOut.noise/factor
127 # noise = dataOut.noise/factor
128
128
129 #thisDatetime = dataOut.datatime
129 #thisDatetime = dataOut.datatime
130 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
130 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
131 title = wintitle + " Correlation"
131 title = wintitle + " Correlation"
132 xlabel = "Lag T (s)"
132 xlabel = "Lag T (s)"
133 ylabel = "Range (Km)"
133 ylabel = "Range (Km)"
134
134
135 if not self.isConfig:
135 if not self.isConfig:
136
136
137 nplots = dataOut.data_corr.shape[0]
137 nplots = dataOut.data_corr.shape[0]
138
138
139 self.setup(id=id,
139 self.setup(id=id,
140 nplots=nplots,
140 nplots=nplots,
141 wintitle=wintitle,
141 wintitle=wintitle,
142 showprofile=showprofile,
142 showprofile=showprofile,
143 show=show)
143 show=show)
144
144
145 if xmin == None: xmin = numpy.nanmin(x)
145 if xmin == None: xmin = numpy.nanmin(x)
146 if xmax == None: xmax = numpy.nanmax(x)
146 if xmax == None: xmax = numpy.nanmax(x)
147 if ymin == None: ymin = numpy.nanmin(y)
147 if ymin == None: ymin = numpy.nanmin(y)
148 if ymax == None: ymax = numpy.nanmax(y)
148 if ymax == None: ymax = numpy.nanmax(y)
149 if zmin == None: zmin = 0
149 if zmin == None: zmin = 0
150 if zmax == None: zmax = 1
150 if zmax == None: zmax = 1
151
151
152 self.FTP_WEI = ftp_wei
152 self.FTP_WEI = ftp_wei
153 self.EXP_CODE = exp_code
153 self.EXP_CODE = exp_code
154 self.SUB_EXP_CODE = sub_exp_code
154 self.SUB_EXP_CODE = sub_exp_code
155 self.PLOT_POS = plot_pos
155 self.PLOT_POS = plot_pos
156
156
157 self.isConfig = True
157 self.isConfig = True
158
158
159 self.setWinTitle(title)
159 self.setWinTitle(title)
160
160
161 for i in range(self.nplots):
161 for i in range(self.nplots):
162 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
162 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
163 title = "Channel %d and %d: : %s" %(dataOut.pairsList[i][0],dataOut.pairsList[i][1] , str_datetime)
163 title = "Channel %d and %d: : %s" %(dataOut.pairsList[i][0],dataOut.pairsList[i][1] , str_datetime)
164 axes = self.axesList[i*self.__nsubplots]
164 axes = self.axesList[i*self.__nsubplots]
165 axes.pcolor(x, y, zdB[i,:,:],
165 axes.pcolor(x, y, zdB[i,:,:],
166 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
166 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
167 xlabel=xlabel, ylabel=ylabel, title=title,
167 xlabel=xlabel, ylabel=ylabel, title=title,
168 ticksize=9, cblabel='')
168 ticksize=9, cblabel='')
169
169
170 # if self.__showprofile:
170 # if self.__showprofile:
171 # axes = self.axesList[i*self.__nsubplots +1]
171 # axes = self.axesList[i*self.__nsubplots +1]
172 # axes.pline(avgdB[i], y,
172 # axes.pline(avgdB[i], y,
173 # xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
173 # xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
174 # xlabel='dB', ylabel='', title='',
174 # xlabel='dB', ylabel='', title='',
175 # ytick_visible=False,
175 # ytick_visible=False,
176 # grid='x')
176 # grid='x')
177 #
177 #
178 # noiseline = numpy.repeat(noisedB[i], len(y))
178 # noiseline = numpy.repeat(noisedB[i], len(y))
179 # axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
179 # axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
180
180
181 self.draw()
181 self.draw()
182
182
183 self.save(figpath=figpath,
183 self.save(figpath=figpath,
184 figfile=figfile,
184 figfile=figfile,
185 save=save,
185 save=save,
186 ftp=ftp,
186 ftp=ftp,
187 wr_period=wr_period,
187 wr_period=wr_period,
188 thisDatetime=thisDatetime)
188 thisDatetime=thisDatetime)
@@ -1,329 +1,328
1 '''
1 '''
2 Created on Jul 9, 2014
2 Created on Jul 9, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import datetime
7 import datetime
8 import numpy
8 import numpy
9
9
10 from figure import Figure, isRealtime
10 from figure import Figure, isRealtime
11 from plotting_codes import *
11 from plotting_codes import *
12
12
13 class SpectraHeisScope(Figure):
13 class SpectraHeisScope(Figure):
14
14
15
15
16 isConfig = None
16 isConfig = None
17 __nsubplots = None
17 __nsubplots = None
18
18
19 WIDTHPROF = None
19 WIDTHPROF = None
20 HEIGHTPROF = None
20 HEIGHTPROF = None
21 PREFIX = 'spc'
21 PREFIX = 'spc'
22
22
23 def __init__(self, **kwargs):
23 def __init__(self):
24
24
25 Figure.__init__(self, **kwargs)
26 self.isConfig = False
25 self.isConfig = False
27 self.__nsubplots = 1
26 self.__nsubplots = 1
28
27
29 self.WIDTH = 230
28 self.WIDTH = 230
30 self.HEIGHT = 250
29 self.HEIGHT = 250
31 self.WIDTHPROF = 120
30 self.WIDTHPROF = 120
32 self.HEIGHTPROF = 0
31 self.HEIGHTPROF = 0
33 self.counter_imagwr = 0
32 self.counter_imagwr = 0
34
33
35 self.PLOT_CODE = SPEC_CODE
34 self.PLOT_CODE = SPEC_CODE
36
35
37 def getSubplots(self):
36 def getSubplots(self):
38
37
39 ncol = int(numpy.sqrt(self.nplots)+0.9)
38 ncol = int(numpy.sqrt(self.nplots)+0.9)
40 nrow = int(self.nplots*1./ncol + 0.9)
39 nrow = int(self.nplots*1./ncol + 0.9)
41
40
42 return nrow, ncol
41 return nrow, ncol
43
42
44 def setup(self, id, nplots, wintitle, show):
43 def setup(self, id, nplots, wintitle, show):
45
44
46 showprofile = False
45 showprofile = False
47 self.__showprofile = showprofile
46 self.__showprofile = showprofile
48 self.nplots = nplots
47 self.nplots = nplots
49
48
50 ncolspan = 1
49 ncolspan = 1
51 colspan = 1
50 colspan = 1
52 if showprofile:
51 if showprofile:
53 ncolspan = 3
52 ncolspan = 3
54 colspan = 2
53 colspan = 2
55 self.__nsubplots = 2
54 self.__nsubplots = 2
56
55
57 self.createFigure(id = id,
56 self.createFigure(id = id,
58 wintitle = wintitle,
57 wintitle = wintitle,
59 widthplot = self.WIDTH + self.WIDTHPROF,
58 widthplot = self.WIDTH + self.WIDTHPROF,
60 heightplot = self.HEIGHT + self.HEIGHTPROF,
59 heightplot = self.HEIGHT + self.HEIGHTPROF,
61 show = show)
60 show = show)
62
61
63 nrow, ncol = self.getSubplots()
62 nrow, ncol = self.getSubplots()
64
63
65 counter = 0
64 counter = 0
66 for y in range(nrow):
65 for y in range(nrow):
67 for x in range(ncol):
66 for x in range(ncol):
68
67
69 if counter >= self.nplots:
68 if counter >= self.nplots:
70 break
69 break
71
70
72 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
71 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
73
72
74 if showprofile:
73 if showprofile:
75 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
74 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
76
75
77 counter += 1
76 counter += 1
78
77
79
78
80 def run(self, dataOut, id, wintitle="", channelList=None,
79 def run(self, dataOut, id, wintitle="", channelList=None,
81 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
80 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
82 figpath='./', figfile=None, ftp=False, wr_period=1, show=True,
81 figpath='./', figfile=None, ftp=False, wr_period=1, show=True,
83 server=None, folder=None, username=None, password=None,
82 server=None, folder=None, username=None, password=None,
84 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
83 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
85
84
86 """
85 """
87
86
88 Input:
87 Input:
89 dataOut :
88 dataOut :
90 id :
89 id :
91 wintitle :
90 wintitle :
92 channelList :
91 channelList :
93 xmin : None,
92 xmin : None,
94 xmax : None,
93 xmax : None,
95 ymin : None,
94 ymin : None,
96 ymax : None,
95 ymax : None,
97 """
96 """
98
97
99 if dataOut.realtime:
98 if dataOut.realtime:
100 if not(isRealtime(utcdatatime = dataOut.utctime)):
99 if not(isRealtime(utcdatatime = dataOut.utctime)):
101 print 'Skipping this plot function'
100 print 'Skipping this plot function'
102 return
101 return
103
102
104 if channelList == None:
103 if channelList == None:
105 channelIndexList = dataOut.channelIndexList
104 channelIndexList = dataOut.channelIndexList
106 else:
105 else:
107 channelIndexList = []
106 channelIndexList = []
108 for channel in channelList:
107 for channel in channelList:
109 if channel not in dataOut.channelList:
108 if channel not in dataOut.channelList:
110 raise ValueError, "Channel %d is not in dataOut.channelList"
109 raise ValueError, "Channel %d is not in dataOut.channelList"
111 channelIndexList.append(dataOut.channelList.index(channel))
110 channelIndexList.append(dataOut.channelList.index(channel))
112
111
113 # x = dataOut.heightList
112 # x = dataOut.heightList
114 c = 3E8
113 c = 3E8
115 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
114 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
116 #deberia cambiar para el caso de 1Mhz y 100KHz
115 #deberia cambiar para el caso de 1Mhz y 100KHz
117 x = numpy.arange(-1*dataOut.nHeights/2.,dataOut.nHeights/2.)*(c/(2*deltaHeight*dataOut.nHeights*1000))
116 x = numpy.arange(-1*dataOut.nHeights/2.,dataOut.nHeights/2.)*(c/(2*deltaHeight*dataOut.nHeights*1000))
118 #para 1Mhz descomentar la siguiente linea
117 #para 1Mhz descomentar la siguiente linea
119 #x= x/(10000.0)
118 #x= x/(10000.0)
120 # y = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
119 # y = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
121 # y = y.real
120 # y = y.real
122 factor = dataOut.normFactor
121 factor = dataOut.normFactor
123 data = dataOut.data_spc / factor
122 data = dataOut.data_spc / factor
124 datadB = 10.*numpy.log10(data)
123 datadB = 10.*numpy.log10(data)
125 y = datadB
124 y = datadB
126
125
127 #thisDatetime = dataOut.datatime
126 #thisDatetime = dataOut.datatime
128 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
127 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
129 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
128 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
130 xlabel = ""
129 xlabel = ""
131 #para 1Mhz descomentar la siguiente linea
130 #para 1Mhz descomentar la siguiente linea
132 #xlabel = "Frequency x 10000"
131 #xlabel = "Frequency x 10000"
133 ylabel = "Intensity (dB)"
132 ylabel = "Intensity (dB)"
134
133
135 if not self.isConfig:
134 if not self.isConfig:
136 nplots = len(channelIndexList)
135 nplots = len(channelIndexList)
137
136
138 self.setup(id=id,
137 self.setup(id=id,
139 nplots=nplots,
138 nplots=nplots,
140 wintitle=wintitle,
139 wintitle=wintitle,
141 show=show)
140 show=show)
142
141
143 if xmin == None: xmin = numpy.nanmin(x)
142 if xmin == None: xmin = numpy.nanmin(x)
144 if xmax == None: xmax = numpy.nanmax(x)
143 if xmax == None: xmax = numpy.nanmax(x)
145 if ymin == None: ymin = numpy.nanmin(y)
144 if ymin == None: ymin = numpy.nanmin(y)
146 if ymax == None: ymax = numpy.nanmax(y)
145 if ymax == None: ymax = numpy.nanmax(y)
147
146
148 self.FTP_WEI = ftp_wei
147 self.FTP_WEI = ftp_wei
149 self.EXP_CODE = exp_code
148 self.EXP_CODE = exp_code
150 self.SUB_EXP_CODE = sub_exp_code
149 self.SUB_EXP_CODE = sub_exp_code
151 self.PLOT_POS = plot_pos
150 self.PLOT_POS = plot_pos
152
151
153 self.isConfig = True
152 self.isConfig = True
154
153
155 self.setWinTitle(title)
154 self.setWinTitle(title)
156
155
157 for i in range(len(self.axesList)):
156 for i in range(len(self.axesList)):
158 ychannel = y[i,:]
157 ychannel = y[i,:]
159 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
158 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
160 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[channelIndexList[i]], numpy.max(ychannel), str_datetime)
159 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[channelIndexList[i]], numpy.max(ychannel), str_datetime)
161 axes = self.axesList[i]
160 axes = self.axesList[i]
162 axes.pline(x, ychannel,
161 axes.pline(x, ychannel,
163 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
162 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
164 xlabel=xlabel, ylabel=ylabel, title=title, grid='both')
163 xlabel=xlabel, ylabel=ylabel, title=title, grid='both')
165
164
166
165
167 self.draw()
166 self.draw()
168
167
169 self.save(figpath=figpath,
168 self.save(figpath=figpath,
170 figfile=figfile,
169 figfile=figfile,
171 save=save,
170 save=save,
172 ftp=ftp,
171 ftp=ftp,
173 wr_period=wr_period,
172 wr_period=wr_period,
174 thisDatetime=thisDatetime)
173 thisDatetime=thisDatetime)
175
174
176 class RTIfromSpectraHeis(Figure):
175 class RTIfromSpectraHeis(Figure):
177
176
178 isConfig = None
177 isConfig = None
179 __nsubplots = None
178 __nsubplots = None
180
179
181 PREFIX = 'rtinoise'
180 PREFIX = 'rtinoise'
182
181
183 def __init__(self, **kwargs):
182 def __init__(self):
184 Figure.__init__(self, **kwargs)
183
185 self.timerange = 24*60*60
184 self.timerange = 24*60*60
186 self.isConfig = False
185 self.isConfig = False
187 self.__nsubplots = 1
186 self.__nsubplots = 1
188
187
189 self.WIDTH = 820
188 self.WIDTH = 820
190 self.HEIGHT = 200
189 self.HEIGHT = 200
191 self.WIDTHPROF = 120
190 self.WIDTHPROF = 120
192 self.HEIGHTPROF = 0
191 self.HEIGHTPROF = 0
193 self.counter_imagwr = 0
192 self.counter_imagwr = 0
194 self.xdata = None
193 self.xdata = None
195 self.ydata = None
194 self.ydata = None
196 self.figfile = None
195 self.figfile = None
197
196
198 self.PLOT_CODE = RTI_CODE
197 self.PLOT_CODE = RTI_CODE
199
198
200 def getSubplots(self):
199 def getSubplots(self):
201
200
202 ncol = 1
201 ncol = 1
203 nrow = 1
202 nrow = 1
204
203
205 return nrow, ncol
204 return nrow, ncol
206
205
207 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
206 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
208
207
209 self.__showprofile = showprofile
208 self.__showprofile = showprofile
210 self.nplots = nplots
209 self.nplots = nplots
211
210
212 ncolspan = 7
211 ncolspan = 7
213 colspan = 6
212 colspan = 6
214 self.__nsubplots = 2
213 self.__nsubplots = 2
215
214
216 self.createFigure(id = id,
215 self.createFigure(id = id,
217 wintitle = wintitle,
216 wintitle = wintitle,
218 widthplot = self.WIDTH+self.WIDTHPROF,
217 widthplot = self.WIDTH+self.WIDTHPROF,
219 heightplot = self.HEIGHT+self.HEIGHTPROF,
218 heightplot = self.HEIGHT+self.HEIGHTPROF,
220 show = show)
219 show = show)
221
220
222 nrow, ncol = self.getSubplots()
221 nrow, ncol = self.getSubplots()
223
222
224 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
223 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
225
224
226
225
227 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
226 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
228 xmin=None, xmax=None, ymin=None, ymax=None,
227 xmin=None, xmax=None, ymin=None, ymax=None,
229 timerange=None,
228 timerange=None,
230 save=False, figpath='./', figfile=None, ftp=False, wr_period=1, show=True,
229 save=False, figpath='./', figfile=None, ftp=False, wr_period=1, show=True,
231 server=None, folder=None, username=None, password=None,
230 server=None, folder=None, username=None, password=None,
232 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
231 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
233
232
234 if channelList == None:
233 if channelList == None:
235 channelIndexList = dataOut.channelIndexList
234 channelIndexList = dataOut.channelIndexList
236 channelList = dataOut.channelList
235 channelList = dataOut.channelList
237 else:
236 else:
238 channelIndexList = []
237 channelIndexList = []
239 for channel in channelList:
238 for channel in channelList:
240 if channel not in dataOut.channelList:
239 if channel not in dataOut.channelList:
241 raise ValueError, "Channel %d is not in dataOut.channelList"
240 raise ValueError, "Channel %d is not in dataOut.channelList"
242 channelIndexList.append(dataOut.channelList.index(channel))
241 channelIndexList.append(dataOut.channelList.index(channel))
243
242
244 if timerange != None:
243 if timerange != None:
245 self.timerange = timerange
244 self.timerange = timerange
246
245
247 x = dataOut.getTimeRange()
246 x = dataOut.getTimeRange()
248 y = dataOut.getHeiRange()
247 y = dataOut.getHeiRange()
249
248
250 factor = dataOut.normFactor
249 factor = dataOut.normFactor
251 data = dataOut.data_spc / factor
250 data = dataOut.data_spc / factor
252 data = numpy.average(data,axis=1)
251 data = numpy.average(data,axis=1)
253 datadB = 10*numpy.log10(data)
252 datadB = 10*numpy.log10(data)
254
253
255 # factor = dataOut.normFactor
254 # factor = dataOut.normFactor
256 # noise = dataOut.getNoise()/factor
255 # noise = dataOut.getNoise()/factor
257 # noisedB = 10*numpy.log10(noise)
256 # noisedB = 10*numpy.log10(noise)
258
257
259 #thisDatetime = dataOut.datatime
258 #thisDatetime = dataOut.datatime
260 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
259 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
261 title = wintitle + " RTI: %s" %(thisDatetime.strftime("%d-%b-%Y"))
260 title = wintitle + " RTI: %s" %(thisDatetime.strftime("%d-%b-%Y"))
262 xlabel = "Local Time"
261 xlabel = "Local Time"
263 ylabel = "Intensity (dB)"
262 ylabel = "Intensity (dB)"
264
263
265 if not self.isConfig:
264 if not self.isConfig:
266
265
267 nplots = 1
266 nplots = 1
268
267
269 self.setup(id=id,
268 self.setup(id=id,
270 nplots=nplots,
269 nplots=nplots,
271 wintitle=wintitle,
270 wintitle=wintitle,
272 showprofile=showprofile,
271 showprofile=showprofile,
273 show=show)
272 show=show)
274
273
275 self.tmin, self.tmax = self.getTimeLim(x, xmin, xmax)
274 self.tmin, self.tmax = self.getTimeLim(x, xmin, xmax)
276
275
277 if ymin == None: ymin = numpy.nanmin(datadB)
276 if ymin == None: ymin = numpy.nanmin(datadB)
278 if ymax == None: ymax = numpy.nanmax(datadB)
277 if ymax == None: ymax = numpy.nanmax(datadB)
279
278
280 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
279 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
281 self.isConfig = True
280 self.isConfig = True
282 self.figfile = figfile
281 self.figfile = figfile
283 self.xdata = numpy.array([])
282 self.xdata = numpy.array([])
284 self.ydata = numpy.array([])
283 self.ydata = numpy.array([])
285
284
286 self.FTP_WEI = ftp_wei
285 self.FTP_WEI = ftp_wei
287 self.EXP_CODE = exp_code
286 self.EXP_CODE = exp_code
288 self.SUB_EXP_CODE = sub_exp_code
287 self.SUB_EXP_CODE = sub_exp_code
289 self.PLOT_POS = plot_pos
288 self.PLOT_POS = plot_pos
290
289
291 self.setWinTitle(title)
290 self.setWinTitle(title)
292
291
293
292
294 # title = "RTI %s" %(thisDatetime.strftime("%d-%b-%Y"))
293 # title = "RTI %s" %(thisDatetime.strftime("%d-%b-%Y"))
295 title = "RTI - %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
294 title = "RTI - %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
296
295
297 legendlabels = ["channel %d"%idchannel for idchannel in channelList]
296 legendlabels = ["channel %d"%idchannel for idchannel in channelList]
298 axes = self.axesList[0]
297 axes = self.axesList[0]
299
298
300 self.xdata = numpy.hstack((self.xdata, x[0:1]))
299 self.xdata = numpy.hstack((self.xdata, x[0:1]))
301
300
302 if len(self.ydata)==0:
301 if len(self.ydata)==0:
303 self.ydata = datadB[channelIndexList].reshape(-1,1)
302 self.ydata = datadB[channelIndexList].reshape(-1,1)
304 else:
303 else:
305 self.ydata = numpy.hstack((self.ydata, datadB[channelIndexList].reshape(-1,1)))
304 self.ydata = numpy.hstack((self.ydata, datadB[channelIndexList].reshape(-1,1)))
306
305
307
306
308 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
307 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
309 xmin=self.tmin, xmax=self.tmax, ymin=ymin, ymax=ymax,
308 xmin=self.tmin, xmax=self.tmax, ymin=ymin, ymax=ymax,
310 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='.', markersize=8, linestyle="solid", grid='both',
309 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='.', markersize=8, linestyle="solid", grid='both',
311 XAxisAsTime=True
310 XAxisAsTime=True
312 )
311 )
313
312
314 self.draw()
313 self.draw()
315
314
316 update_figfile = False
315 update_figfile = False
317
316
318 if dataOut.ltctime >= self.tmax:
317 if dataOut.ltctime >= self.tmax:
319 self.counter_imagwr = wr_period
318 self.counter_imagwr = wr_period
320 self.isConfig = False
319 self.isConfig = False
321 update_figfile = True
320 update_figfile = True
322
321
323 self.save(figpath=figpath,
322 self.save(figpath=figpath,
324 figfile=figfile,
323 figfile=figfile,
325 save=save,
324 save=save,
326 ftp=ftp,
325 ftp=ftp,
327 wr_period=wr_period,
326 wr_period=wr_period,
328 thisDatetime=thisDatetime,
327 thisDatetime=thisDatetime,
329 update_figfile=update_figfile)
328 update_figfile=update_figfile)
@@ -1,1945 +1,2154
1 import os
1 import os
2 import datetime
2 import datetime
3 import numpy
3 import numpy
4 import inspect
4 import inspect
5 from figure import Figure, isRealtime, isTimeInHourRange
5 from figure import Figure, isRealtime, isTimeInHourRange
6 from plotting_codes import *
6 from plotting_codes import *
7
7
8
8
9 class FitGauPlot(Figure):
10
11 isConfig = None
12 __nsubplots = None
13
14 WIDTHPROF = None
15 HEIGHTPROF = None
16 PREFIX = 'fitgau'
17
18 def __init__(self, **kwargs):
19 Figure.__init__(self, **kwargs)
20 self.isConfig = False
21 self.__nsubplots = 1
22
23 self.WIDTH = 250
24 self.HEIGHT = 250
25 self.WIDTHPROF = 120
26 self.HEIGHTPROF = 0
27 self.counter_imagwr = 0
28
29 self.PLOT_CODE = SPEC_CODE
30
31 self.FTP_WEI = None
32 self.EXP_CODE = None
33 self.SUB_EXP_CODE = None
34 self.PLOT_POS = None
35
36 self.__xfilter_ena = False
37 self.__yfilter_ena = False
38
39 def getSubplots(self):
40
41 ncol = int(numpy.sqrt(self.nplots)+0.9)
42 nrow = int(self.nplots*1./ncol + 0.9)
43
44 return nrow, ncol
45
46 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
47
48 self.__showprofile = showprofile
49 self.nplots = nplots
50
51 ncolspan = 1
52 colspan = 1
53 if showprofile:
54 ncolspan = 3
55 colspan = 2
56 self.__nsubplots = 2
57
58 self.createFigure(id = id,
59 wintitle = wintitle,
60 widthplot = self.WIDTH + self.WIDTHPROF,
61 heightplot = self.HEIGHT + self.HEIGHTPROF,
62 show=show)
63
64 nrow, ncol = self.getSubplots()
65
66 counter = 0
67 for y in range(nrow):
68 for x in range(ncol):
69
70 if counter >= self.nplots:
71 break
72
73 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
74
75 if showprofile:
76 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
77
78 counter += 1
79
80 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
81 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
82 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
83 server=None, folder=None, username=None, password=None,
84 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
85 xaxis="frequency", colormap='jet', normFactor=None , GauSelector = 1):
86
87 """
88
89 Input:
90 dataOut :
91 id :
92 wintitle :
93 channelList :
94 showProfile :
95 xmin : None,
96 xmax : None,
97 ymin : None,
98 ymax : None,
99 zmin : None,
100 zmax : None
101 """
102 if realtime:
103 if not(isRealtime(utcdatatime = dataOut.utctime)):
104 print 'Skipping this plot function'
105 return
106
107 if channelList == None:
108 channelIndexList = dataOut.channelIndexList
109 else:
110 channelIndexList = []
111 for channel in channelList:
112 if channel not in dataOut.channelList:
113 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
114 channelIndexList.append(dataOut.channelList.index(channel))
115
116 # if normFactor is None:
117 # factor = dataOut.normFactor
118 # else:
119 # factor = normFactor
120 if xaxis == "frequency":
121 x = dataOut.spc_range[0]
122 xlabel = "Frequency (kHz)"
123
124 elif xaxis == "time":
125 x = dataOut.spc_range[1]
126 xlabel = "Time (ms)"
127
128 else:
129 x = dataOut.spc_range[2]
130 xlabel = "Velocity (m/s)"
131
132 ylabel = "Range (Km)"
133
134 y = dataOut.getHeiRange()
135
136 z = dataOut.GauSPC[:,GauSelector,:,:] #GauSelector] #dataOut.data_spc/factor
137 print 'GausSPC', z[0,32,10:40]
138 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
139 zdB = 10*numpy.log10(z)
140
141 avg = numpy.average(z, axis=1)
142 avgdB = 10*numpy.log10(avg)
143
144 noise = dataOut.spc_noise
145 noisedB = 10*numpy.log10(noise)
146
147 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
148 title = wintitle + " Spectra"
149 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
150 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
151
152 if not self.isConfig:
153
154 nplots = len(channelIndexList)
155
156 self.setup(id=id,
157 nplots=nplots,
158 wintitle=wintitle,
159 showprofile=showprofile,
160 show=show)
161
162 if xmin == None: xmin = numpy.nanmin(x)
163 if xmax == None: xmax = numpy.nanmax(x)
164 if ymin == None: ymin = numpy.nanmin(y)
165 if ymax == None: ymax = numpy.nanmax(y)
166 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
167 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
168
169 self.FTP_WEI = ftp_wei
170 self.EXP_CODE = exp_code
171 self.SUB_EXP_CODE = sub_exp_code
172 self.PLOT_POS = plot_pos
173
174 self.isConfig = True
175
176 self.setWinTitle(title)
177
178 for i in range(self.nplots):
179 index = channelIndexList[i]
180 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
181 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
182 if len(dataOut.beam.codeList) != 0:
183 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
184
185 axes = self.axesList[i*self.__nsubplots]
186 axes.pcolor(x, y, zdB[index,:,:],
187 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
188 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
189 ticksize=9, cblabel='')
190
191 if self.__showprofile:
192 axes = self.axesList[i*self.__nsubplots +1]
193 axes.pline(avgdB[index,:], y,
194 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
195 xlabel='dB', ylabel='', title='',
196 ytick_visible=False,
197 grid='x')
198
199 noiseline = numpy.repeat(noisedB[index], len(y))
200 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
201
202 self.draw()
203
204 if figfile == None:
205 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
206 name = str_datetime
207 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
208 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
209 figfile = self.getFilename(name)
210
211 self.save(figpath=figpath,
212 figfile=figfile,
213 save=save,
214 ftp=ftp,
215 wr_period=wr_period,
216 thisDatetime=thisDatetime)
217
218
219
9 class MomentsPlot(Figure):
220 class MomentsPlot(Figure):
10
221
11 isConfig = None
222 isConfig = None
12 __nsubplots = None
223 __nsubplots = None
13
224
14 WIDTHPROF = None
225 WIDTHPROF = None
15 HEIGHTPROF = None
226 HEIGHTPROF = None
16 PREFIX = 'prm'
227 PREFIX = 'prm'
17
228
18 def __init__(self, **kwargs):
229 def __init__(self, **kwargs):
19 Figure.__init__(self, **kwargs)
230 Figure.__init__(self, **kwargs)
20 self.isConfig = False
231 self.isConfig = False
21 self.__nsubplots = 1
232 self.__nsubplots = 1
22
233
23 self.WIDTH = 280
234 self.WIDTH = 280
24 self.HEIGHT = 250
235 self.HEIGHT = 250
25 self.WIDTHPROF = 120
236 self.WIDTHPROF = 120
26 self.HEIGHTPROF = 0
237 self.HEIGHTPROF = 0
27 self.counter_imagwr = 0
238 self.counter_imagwr = 0
28
239
29 self.PLOT_CODE = MOMENTS_CODE
240 self.PLOT_CODE = MOMENTS_CODE
30
241
31 self.FTP_WEI = None
242 self.FTP_WEI = None
32 self.EXP_CODE = None
243 self.EXP_CODE = None
33 self.SUB_EXP_CODE = None
244 self.SUB_EXP_CODE = None
34 self.PLOT_POS = None
245 self.PLOT_POS = None
35
246
36 def getSubplots(self):
247 def getSubplots(self):
37
248
38 ncol = int(numpy.sqrt(self.nplots)+0.9)
249 ncol = int(numpy.sqrt(self.nplots)+0.9)
39 nrow = int(self.nplots*1./ncol + 0.9)
250 nrow = int(self.nplots*1./ncol + 0.9)
40
251
41 return nrow, ncol
252 return nrow, ncol
42
253
43 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
254 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
44
255
45 self.__showprofile = showprofile
256 self.__showprofile = showprofile
46 self.nplots = nplots
257 self.nplots = nplots
47
258
48 ncolspan = 1
259 ncolspan = 1
49 colspan = 1
260 colspan = 1
50 if showprofile:
261 if showprofile:
51 ncolspan = 3
262 ncolspan = 3
52 colspan = 2
263 colspan = 2
53 self.__nsubplots = 2
264 self.__nsubplots = 2
54
265
55 self.createFigure(id = id,
266 self.createFigure(id = id,
56 wintitle = wintitle,
267 wintitle = wintitle,
57 widthplot = self.WIDTH + self.WIDTHPROF,
268 widthplot = self.WIDTH + self.WIDTHPROF,
58 heightplot = self.HEIGHT + self.HEIGHTPROF,
269 heightplot = self.HEIGHT + self.HEIGHTPROF,
59 show=show)
270 show=show)
60
271
61 nrow, ncol = self.getSubplots()
272 nrow, ncol = self.getSubplots()
62
273
63 counter = 0
274 counter = 0
64 for y in range(nrow):
275 for y in range(nrow):
65 for x in range(ncol):
276 for x in range(ncol):
66
277
67 if counter >= self.nplots:
278 if counter >= self.nplots:
68 break
279 break
69
280
70 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
281 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
71
282
72 if showprofile:
283 if showprofile:
73 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
284 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
74
285
75 counter += 1
286 counter += 1
76
287
77 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
288 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
78 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
289 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
79 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
290 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
80 server=None, folder=None, username=None, password=None,
291 server=None, folder=None, username=None, password=None,
81 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
292 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
82
293
83 """
294 """
84
295
85 Input:
296 Input:
86 dataOut :
297 dataOut :
87 id :
298 id :
88 wintitle :
299 wintitle :
89 channelList :
300 channelList :
90 showProfile :
301 showProfile :
91 xmin : None,
302 xmin : None,
92 xmax : None,
303 xmax : None,
93 ymin : None,
304 ymin : None,
94 ymax : None,
305 ymax : None,
95 zmin : None,
306 zmin : None,
96 zmax : None
307 zmax : None
97 """
308 """
98
309
99 if dataOut.flagNoData:
310 if dataOut.flagNoData:
100 return None
311 return None
101
312
102 if realtime:
313 if realtime:
103 if not(isRealtime(utcdatatime = dataOut.utctime)):
314 if not(isRealtime(utcdatatime = dataOut.utctime)):
104 print 'Skipping this plot function'
315 print 'Skipping this plot function'
105 return
316 return
106
317
107 if channelList == None:
318 if channelList == None:
108 channelIndexList = dataOut.channelIndexList
319 channelIndexList = dataOut.channelIndexList
109 else:
320 else:
110 channelIndexList = []
321 channelIndexList = []
111 for channel in channelList:
322 for channel in channelList:
112 if channel not in dataOut.channelList:
323 if channel not in dataOut.channelList:
113 raise ValueError, "Channel %d is not in dataOut.channelList"
324 raise ValueError, "Channel %d is not in dataOut.channelList"
114 channelIndexList.append(dataOut.channelList.index(channel))
325 channelIndexList.append(dataOut.channelList.index(channel))
115
326
116 factor = dataOut.normFactor
327 factor = dataOut.normFactor
117 x = dataOut.abscissaList
328 x = dataOut.abscissaList
118 y = dataOut.heightList
329 y = dataOut.heightList
119
330
120 z = dataOut.data_pre[channelIndexList,:,:]/factor
331 z = dataOut.data_pre[channelIndexList,:,:]/factor
121 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
332 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
122 avg = numpy.average(z, axis=1)
333 avg = numpy.average(z, axis=1)
123 noise = dataOut.noise/factor
334 noise = dataOut.noise/factor
124
335
125 zdB = 10*numpy.log10(z)
336 zdB = 10*numpy.log10(z)
126 avgdB = 10*numpy.log10(avg)
337 avgdB = 10*numpy.log10(avg)
127 noisedB = 10*numpy.log10(noise)
338 noisedB = 10*numpy.log10(noise)
128
339
129 #thisDatetime = dataOut.datatime
340 #thisDatetime = dataOut.datatime
130 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
341 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
131 title = wintitle + " Parameters"
342 title = wintitle + " Parameters"
132 xlabel = "Velocity (m/s)"
343 xlabel = "Velocity (m/s)"
133 ylabel = "Range (Km)"
344 ylabel = "Range (Km)"
134
345
135 update_figfile = False
346 update_figfile = False
136
347
137 if not self.isConfig:
348 if not self.isConfig:
138
349
139 nplots = len(channelIndexList)
350 nplots = len(channelIndexList)
140
351
141 self.setup(id=id,
352 self.setup(id=id,
142 nplots=nplots,
353 nplots=nplots,
143 wintitle=wintitle,
354 wintitle=wintitle,
144 showprofile=showprofile,
355 showprofile=showprofile,
145 show=show)
356 show=show)
146
357
147 if xmin == None: xmin = numpy.nanmin(x)
358 if xmin == None: xmin = numpy.nanmin(x)
148 if xmax == None: xmax = numpy.nanmax(x)
359 if xmax == None: xmax = numpy.nanmax(x)
149 if ymin == None: ymin = numpy.nanmin(y)
360 if ymin == None: ymin = numpy.nanmin(y)
150 if ymax == None: ymax = numpy.nanmax(y)
361 if ymax == None: ymax = numpy.nanmax(y)
151 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
362 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
152 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
363 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
153
364
154 self.FTP_WEI = ftp_wei
365 self.FTP_WEI = ftp_wei
155 self.EXP_CODE = exp_code
366 self.EXP_CODE = exp_code
156 self.SUB_EXP_CODE = sub_exp_code
367 self.SUB_EXP_CODE = sub_exp_code
157 self.PLOT_POS = plot_pos
368 self.PLOT_POS = plot_pos
158
369
159 self.isConfig = True
370 self.isConfig = True
160 update_figfile = True
371 update_figfile = True
161
372
162 self.setWinTitle(title)
373 self.setWinTitle(title)
163
374
164 for i in range(self.nplots):
375 for i in range(self.nplots):
165 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
376 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
166 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
377 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
167 axes = self.axesList[i*self.__nsubplots]
378 axes = self.axesList[i*self.__nsubplots]
168 axes.pcolor(x, y, zdB[i,:,:],
379 axes.pcolor(x, y, zdB[i,:,:],
169 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
380 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
170 xlabel=xlabel, ylabel=ylabel, title=title,
381 xlabel=xlabel, ylabel=ylabel, title=title,
171 ticksize=9, cblabel='')
382 ticksize=9, cblabel='')
172 #Mean Line
383 #Mean Line
173 mean = dataOut.data_param[i, 1, :]
384 mean = dataOut.data_param[i, 1, :]
174 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
385 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
175
386
176 if self.__showprofile:
387 if self.__showprofile:
177 axes = self.axesList[i*self.__nsubplots +1]
388 axes = self.axesList[i*self.__nsubplots +1]
178 axes.pline(avgdB[i], y,
389 axes.pline(avgdB[i], y,
179 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
390 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
180 xlabel='dB', ylabel='', title='',
391 xlabel='dB', ylabel='', title='',
181 ytick_visible=False,
392 ytick_visible=False,
182 grid='x')
393 grid='x')
183
394
184 noiseline = numpy.repeat(noisedB[i], len(y))
395 noiseline = numpy.repeat(noisedB[i], len(y))
185 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
396 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
186
397
187 self.draw()
398 self.draw()
188
399
189 self.save(figpath=figpath,
400 self.save(figpath=figpath,
190 figfile=figfile,
401 figfile=figfile,
191 save=save,
402 save=save,
192 ftp=ftp,
403 ftp=ftp,
193 wr_period=wr_period,
404 wr_period=wr_period,
194 thisDatetime=thisDatetime)
405 thisDatetime=thisDatetime)
195
406
196
407
197
408
198 class SkyMapPlot(Figure):
409 class SkyMapPlot(Figure):
199
410
200 __isConfig = None
411 __isConfig = None
201 __nsubplots = None
412 __nsubplots = None
202
413
203 WIDTHPROF = None
414 WIDTHPROF = None
204 HEIGHTPROF = None
415 HEIGHTPROF = None
205 PREFIX = 'mmap'
416 PREFIX = 'mmap'
206
417
207 def __init__(self, **kwargs):
418 def __init__(self, **kwargs):
208 Figure.__init__(self, **kwargs)
419 Figure.__init__(self, **kwargs)
209 self.isConfig = False
420 self.isConfig = False
210 self.__nsubplots = 1
421 self.__nsubplots = 1
211
422
212 # self.WIDTH = 280
423 # self.WIDTH = 280
213 # self.HEIGHT = 250
424 # self.HEIGHT = 250
214 self.WIDTH = 600
425 self.WIDTH = 600
215 self.HEIGHT = 600
426 self.HEIGHT = 600
216 self.WIDTHPROF = 120
427 self.WIDTHPROF = 120
217 self.HEIGHTPROF = 0
428 self.HEIGHTPROF = 0
218 self.counter_imagwr = 0
429 self.counter_imagwr = 0
219
430
220 self.PLOT_CODE = MSKYMAP_CODE
431 self.PLOT_CODE = MSKYMAP_CODE
221
432
222 self.FTP_WEI = None
433 self.FTP_WEI = None
223 self.EXP_CODE = None
434 self.EXP_CODE = None
224 self.SUB_EXP_CODE = None
435 self.SUB_EXP_CODE = None
225 self.PLOT_POS = None
436 self.PLOT_POS = None
226
437
227 def getSubplots(self):
438 def getSubplots(self):
228
439
229 ncol = int(numpy.sqrt(self.nplots)+0.9)
440 ncol = int(numpy.sqrt(self.nplots)+0.9)
230 nrow = int(self.nplots*1./ncol + 0.9)
441 nrow = int(self.nplots*1./ncol + 0.9)
231
442
232 return nrow, ncol
443 return nrow, ncol
233
444
234 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
445 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
235
446
236 self.__showprofile = showprofile
447 self.__showprofile = showprofile
237 self.nplots = nplots
448 self.nplots = nplots
238
449
239 ncolspan = 1
450 ncolspan = 1
240 colspan = 1
451 colspan = 1
241
452
242 self.createFigure(id = id,
453 self.createFigure(id = id,
243 wintitle = wintitle,
454 wintitle = wintitle,
244 widthplot = self.WIDTH, #+ self.WIDTHPROF,
455 widthplot = self.WIDTH, #+ self.WIDTHPROF,
245 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
456 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
246 show=show)
457 show=show)
247
458
248 nrow, ncol = 1,1
459 nrow, ncol = 1,1
249 counter = 0
460 counter = 0
250 x = 0
461 x = 0
251 y = 0
462 y = 0
252 self.addAxes(1, 1, 0, 0, 1, 1, True)
463 self.addAxes(1, 1, 0, 0, 1, 1, True)
253
464
254 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
465 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
255 tmin=0, tmax=24, timerange=None,
466 tmin=0, tmax=24, timerange=None,
256 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
467 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
257 server=None, folder=None, username=None, password=None,
468 server=None, folder=None, username=None, password=None,
258 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
469 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
259
470
260 """
471 """
261
472
262 Input:
473 Input:
263 dataOut :
474 dataOut :
264 id :
475 id :
265 wintitle :
476 wintitle :
266 channelList :
477 channelList :
267 showProfile :
478 showProfile :
268 xmin : None,
479 xmin : None,
269 xmax : None,
480 xmax : None,
270 ymin : None,
481 ymin : None,
271 ymax : None,
482 ymax : None,
272 zmin : None,
483 zmin : None,
273 zmax : None
484 zmax : None
274 """
485 """
275
486
276 arrayParameters = dataOut.data_param
487 arrayParameters = dataOut.data_param
277 error = arrayParameters[:,-1]
488 error = arrayParameters[:,-1]
278 indValid = numpy.where(error == 0)[0]
489 indValid = numpy.where(error == 0)[0]
279 finalMeteor = arrayParameters[indValid,:]
490 finalMeteor = arrayParameters[indValid,:]
280 finalAzimuth = finalMeteor[:,3]
491 finalAzimuth = finalMeteor[:,3]
281 finalZenith = finalMeteor[:,4]
492 finalZenith = finalMeteor[:,4]
282
493
283 x = finalAzimuth*numpy.pi/180
494 x = finalAzimuth*numpy.pi/180
284 y = finalZenith
495 y = finalZenith
285 x1 = [dataOut.ltctime, dataOut.ltctime]
496 x1 = [dataOut.ltctime, dataOut.ltctime]
286
497
287 #thisDatetime = dataOut.datatime
498 #thisDatetime = dataOut.datatime
288 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
499 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
289 title = wintitle + " Parameters"
500 title = wintitle + " Parameters"
290 xlabel = "Zonal Zenith Angle (deg) "
501 xlabel = "Zonal Zenith Angle (deg) "
291 ylabel = "Meridional Zenith Angle (deg)"
502 ylabel = "Meridional Zenith Angle (deg)"
292 update_figfile = False
503 update_figfile = False
293
504
294 if not self.isConfig:
505 if not self.isConfig:
295
506
296 nplots = 1
507 nplots = 1
297
508
298 self.setup(id=id,
509 self.setup(id=id,
299 nplots=nplots,
510 nplots=nplots,
300 wintitle=wintitle,
511 wintitle=wintitle,
301 showprofile=showprofile,
512 showprofile=showprofile,
302 show=show)
513 show=show)
303
514
304 if self.xmin is None and self.xmax is None:
515 if self.xmin is None and self.xmax is None:
305 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
516 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
306
517
307 if timerange != None:
518 if timerange != None:
308 self.timerange = timerange
519 self.timerange = timerange
309 else:
520 else:
310 self.timerange = self.xmax - self.xmin
521 self.timerange = self.xmax - self.xmin
311
522
312 self.FTP_WEI = ftp_wei
523 self.FTP_WEI = ftp_wei
313 self.EXP_CODE = exp_code
524 self.EXP_CODE = exp_code
314 self.SUB_EXP_CODE = sub_exp_code
525 self.SUB_EXP_CODE = sub_exp_code
315 self.PLOT_POS = plot_pos
526 self.PLOT_POS = plot_pos
316 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
527 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
317 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
528 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
318 self.isConfig = True
529 self.isConfig = True
319 update_figfile = True
530 update_figfile = True
320
531
321 self.setWinTitle(title)
532 self.setWinTitle(title)
322
533
323 i = 0
534 i = 0
324 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
535 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
325
536
326 axes = self.axesList[i*self.__nsubplots]
537 axes = self.axesList[i*self.__nsubplots]
327 nevents = axes.x_buffer.shape[0] + x.shape[0]
538 nevents = axes.x_buffer.shape[0] + x.shape[0]
328 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
539 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
329 axes.polar(x, y,
540 axes.polar(x, y,
330 title=title, xlabel=xlabel, ylabel=ylabel,
541 title=title, xlabel=xlabel, ylabel=ylabel,
331 ticksize=9, cblabel='')
542 ticksize=9, cblabel='')
332
543
333 self.draw()
544 self.draw()
334
545
335 self.save(figpath=figpath,
546 self.save(figpath=figpath,
336 figfile=figfile,
547 figfile=figfile,
337 save=save,
548 save=save,
338 ftp=ftp,
549 ftp=ftp,
339 wr_period=wr_period,
550 wr_period=wr_period,
340 thisDatetime=thisDatetime,
551 thisDatetime=thisDatetime,
341 update_figfile=update_figfile)
552 update_figfile=update_figfile)
342
553
343 if dataOut.ltctime >= self.xmax:
554 if dataOut.ltctime >= self.xmax:
344 self.isConfigmagwr = wr_period
555 self.isConfigmagwr = wr_period
345 self.isConfig = False
556 self.isConfig = False
346 update_figfile = True
557 update_figfile = True
347 axes.__firsttime = True
558 axes.__firsttime = True
348 self.xmin += self.timerange
559 self.xmin += self.timerange
349 self.xmax += self.timerange
560 self.xmax += self.timerange
350
561
351
562
352
563
353
564
354 class WindProfilerPlot(Figure):
565 class WindProfilerPlot(Figure):
355
566
356 __isConfig = None
567 __isConfig = None
357 __nsubplots = None
568 __nsubplots = None
358
569
359 WIDTHPROF = None
570 WIDTHPROF = None
360 HEIGHTPROF = None
571 HEIGHTPROF = None
361 PREFIX = 'wind'
572 PREFIX = 'wind'
362
573
363 def __init__(self, **kwargs):
574 def __init__(self, **kwargs):
364 Figure.__init__(self, **kwargs)
575 Figure.__init__(self, **kwargs)
365 self.timerange = None
576 self.timerange = None
366 self.isConfig = False
577 self.isConfig = False
367 self.__nsubplots = 1
578 self.__nsubplots = 1
368
579
369 self.WIDTH = 800
580 self.WIDTH = 800
370 self.HEIGHT = 300
581 self.HEIGHT = 300
371 self.WIDTHPROF = 120
582 self.WIDTHPROF = 120
372 self.HEIGHTPROF = 0
583 self.HEIGHTPROF = 0
373 self.counter_imagwr = 0
584 self.counter_imagwr = 0
374
585
375 self.PLOT_CODE = WIND_CODE
586 self.PLOT_CODE = WIND_CODE
376
587
377 self.FTP_WEI = None
588 self.FTP_WEI = None
378 self.EXP_CODE = None
589 self.EXP_CODE = None
379 self.SUB_EXP_CODE = None
590 self.SUB_EXP_CODE = None
380 self.PLOT_POS = None
591 self.PLOT_POS = None
381 self.tmin = None
592 self.tmin = None
382 self.tmax = None
593 self.tmax = None
383
594
384 self.xmin = None
595 self.xmin = None
385 self.xmax = None
596 self.xmax = None
386
597
387 self.figfile = None
598 self.figfile = None
388
599
389 def getSubplots(self):
600 def getSubplots(self):
390
601
391 ncol = 1
602 ncol = 1
392 nrow = self.nplots
603 nrow = self.nplots
393
604
394 return nrow, ncol
605 return nrow, ncol
395
606
396 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
607 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
397
608
398 self.__showprofile = showprofile
609 self.__showprofile = showprofile
399 self.nplots = nplots
610 self.nplots = nplots
400
611
401 ncolspan = 1
612 ncolspan = 1
402 colspan = 1
613 colspan = 1
403
614
404 self.createFigure(id = id,
615 self.createFigure(id = id,
405 wintitle = wintitle,
616 wintitle = wintitle,
406 widthplot = self.WIDTH + self.WIDTHPROF,
617 widthplot = self.WIDTH + self.WIDTHPROF,
407 heightplot = self.HEIGHT + self.HEIGHTPROF,
618 heightplot = self.HEIGHT + self.HEIGHTPROF,
408 show=show)
619 show=show)
409
620
410 nrow, ncol = self.getSubplots()
621 nrow, ncol = self.getSubplots()
411
622
412 counter = 0
623 counter = 0
413 for y in range(nrow):
624 for y in range(nrow):
414 if counter >= self.nplots:
625 if counter >= self.nplots:
415 break
626 break
416
627
417 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
628 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
418 counter += 1
629 counter += 1
419
630
420 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
631 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
421 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
632 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
422 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
633 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
423 timerange=None, SNRthresh = None,
634 timerange=None, SNRthresh = None,
424 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
635 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
425 server=None, folder=None, username=None, password=None,
636 server=None, folder=None, username=None, password=None,
426 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
637 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
427 """
638 """
428
639
429 Input:
640 Input:
430 dataOut :
641 dataOut :
431 id :
642 id :
432 wintitle :
643 wintitle :
433 channelList :
644 channelList :
434 showProfile :
645 showProfile :
435 xmin : None,
646 xmin : None,
436 xmax : None,
647 xmax : None,
437 ymin : None,
648 ymin : None,
438 ymax : None,
649 ymax : None,
439 zmin : None,
650 zmin : None,
440 zmax : None
651 zmax : None
441 """
652 """
442
653
443 # if timerange is not None:
654 # if timerange is not None:
444 # self.timerange = timerange
655 # self.timerange = timerange
445 #
656 #
446 # tmin = None
657 # tmin = None
447 # tmax = None
658 # tmax = None
448
659
449
660 x = dataOut.getTimeRange1(dataOut.paramInterval)
450 x = dataOut.getTimeRange1(dataOut.outputInterval)
661 y = dataOut.heightList
451 y = dataOut.heightList
662 z = dataOut.data_output.copy()
452 z = dataOut.data_output.copy()
453 nplots = z.shape[0] #Number of wind dimensions estimated
663 nplots = z.shape[0] #Number of wind dimensions estimated
454 nplotsw = nplots
664 nplotsw = nplots
455
665
456
666
457 #If there is a SNR function defined
667 #If there is a SNR function defined
458 if dataOut.data_SNR is not None:
668 if dataOut.data_SNR is not None:
459 nplots += 1
669 nplots += 1
460 SNR = dataOut.data_SNR
670 SNR = dataOut.data_SNR
461 SNRavg = numpy.average(SNR, axis=0)
671 SNRavg = numpy.average(SNR, axis=0)
462
672
463 SNRdB = 10*numpy.log10(SNR)
673 SNRdB = 10*numpy.log10(SNR)
464 SNRavgdB = 10*numpy.log10(SNRavg)
674 SNRavgdB = 10*numpy.log10(SNRavg)
465
675
466 if SNRthresh == None: SNRthresh = -5.0
676 if SNRthresh == None: SNRthresh = -5.0
467 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
677 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
468
678
469 for i in range(nplotsw):
679 for i in range(nplotsw):
470 z[i,ind] = numpy.nan
680 z[i,ind] = numpy.nan
471
681
472 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
682 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
473 #thisDatetime = datetime.datetime.now()
683 #thisDatetime = datetime.datetime.now()
474 title = wintitle + "Wind"
684 title = wintitle + "Wind"
475 xlabel = ""
685 xlabel = ""
476 ylabel = "Height (km)"
686 ylabel = "Height (km)"
477 update_figfile = False
687 update_figfile = False
478
688
479 if not self.isConfig:
689 if not self.isConfig:
480
690
481 self.setup(id=id,
691 self.setup(id=id,
482 nplots=nplots,
692 nplots=nplots,
483 wintitle=wintitle,
693 wintitle=wintitle,
484 showprofile=showprofile,
694 showprofile=showprofile,
485 show=show)
695 show=show)
486
696
487 if timerange is not None:
697 if timerange is not None:
488 self.timerange = timerange
698 self.timerange = timerange
489
699
490 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
700 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
491
701
492 if ymin == None: ymin = numpy.nanmin(y)
702 if ymin == None: ymin = numpy.nanmin(y)
493 if ymax == None: ymax = numpy.nanmax(y)
703 if ymax == None: ymax = numpy.nanmax(y)
494
704
495 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
705 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
496 #if numpy.isnan(zmax): zmax = 50
706 #if numpy.isnan(zmax): zmax = 50
497 if zmin == None: zmin = -zmax
707 if zmin == None: zmin = -zmax
498
708
499 if nplotsw == 3:
709 if nplotsw == 3:
500 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
710 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
501 if zmin_ver == None: zmin_ver = -zmax_ver
711 if zmin_ver == None: zmin_ver = -zmax_ver
502
712
503 if dataOut.data_SNR is not None:
713 if dataOut.data_SNR is not None:
504 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
714 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
505 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
715 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
506
716
507
717
508 self.FTP_WEI = ftp_wei
718 self.FTP_WEI = ftp_wei
509 self.EXP_CODE = exp_code
719 self.EXP_CODE = exp_code
510 self.SUB_EXP_CODE = sub_exp_code
720 self.SUB_EXP_CODE = sub_exp_code
511 self.PLOT_POS = plot_pos
721 self.PLOT_POS = plot_pos
512
722
513 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
723 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
514 self.isConfig = True
724 self.isConfig = True
515 self.figfile = figfile
725 self.figfile = figfile
516 update_figfile = True
726 update_figfile = True
517
727
518 self.setWinTitle(title)
728 self.setWinTitle(title)
519
729
520 if ((self.xmax - x[1]) < (x[1]-x[0])):
730 if ((self.xmax - x[1]) < (x[1]-x[0])):
521 x[1] = self.xmax
731 x[1] = self.xmax
522
732
523 strWind = ['Zonal', 'Meridional', 'Vertical']
733 strWind = ['Zonal', 'Meridional', 'Vertical']
524 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
734 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
525 zmaxVector = [zmax, zmax, zmax_ver]
735 zmaxVector = [zmax, zmax, zmax_ver]
526 zminVector = [zmin, zmin, zmin_ver]
736 zminVector = [zmin, zmin, zmin_ver]
527 windFactor = [1,1,100]
737 windFactor = [1,1,100]
528
738
529 for i in range(nplotsw):
739 for i in range(nplotsw):
530
740
531 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
741 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
532 axes = self.axesList[i*self.__nsubplots]
742 axes = self.axesList[i*self.__nsubplots]
533
743
534 z1 = z[i,:].reshape((1,-1))*windFactor[i]
744 z1 = z[i,:].reshape((1,-1))*windFactor[i]
535 #z1=numpy.ma.masked_where(z1==0.,z1)
745 #z1=numpy.ma.masked_where(z1==0.,z1)
536
746
537 axes.pcolorbuffer(x, y, z1,
747 axes.pcolorbuffer(x, y, z1,
538 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
748 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
539 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
749 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
540 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
750 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
541
751
542 if dataOut.data_SNR is not None:
752 if dataOut.data_SNR is not None:
543 i += 1
753 i += 1
544 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
754 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
545 axes = self.axesList[i*self.__nsubplots]
755 axes = self.axesList[i*self.__nsubplots]
546 SNRavgdB = SNRavgdB.reshape((1,-1))
756 SNRavgdB = SNRavgdB.reshape((1,-1))
547 axes.pcolorbuffer(x, y, SNRavgdB,
757 axes.pcolorbuffer(x, y, SNRavgdB,
548 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
758 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
549 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
759 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
550 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
760 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
551
761
552 self.draw()
762 self.draw()
553
763
554 self.save(figpath=figpath,
764 self.save(figpath=figpath,
555 figfile=figfile,
765 figfile=figfile,
556 save=save,
766 save=save,
557 ftp=ftp,
767 ftp=ftp,
558 wr_period=wr_period,
768 wr_period=wr_period,
559 thisDatetime=thisDatetime,
769 thisDatetime=thisDatetime,
560 update_figfile=update_figfile)
770 update_figfile=update_figfile)
561
771
562 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
772 if dataOut.ltctime + dataOut.paramInterval >= self.xmax:
563 self.counter_imagwr = wr_period
773 self.counter_imagwr = wr_period
564 self.isConfig = False
774 self.isConfig = False
565 update_figfile = True
775 update_figfile = True
566
776
567
777
568 class ParametersPlot(Figure):
778 class ParametersPlot(Figure):
569
779
570 __isConfig = None
780 __isConfig = None
571 __nsubplots = None
781 __nsubplots = None
572
782
573 WIDTHPROF = None
783 WIDTHPROF = None
574 HEIGHTPROF = None
784 HEIGHTPROF = None
575 PREFIX = 'param'
785 PREFIX = 'param'
576
786
577 nplots = None
787 nplots = None
578 nchan = None
788 nchan = None
579
789
580 def __init__(self, **kwargs):
790 def __init__(self, **kwargs):
581 Figure.__init__(self, **kwargs)
791 Figure.__init__(self, **kwargs)
582 self.timerange = None
792 self.timerange = None
583 self.isConfig = False
793 self.isConfig = False
584 self.__nsubplots = 1
794 self.__nsubplots = 1
585
795
586 self.WIDTH = 800
796 self.WIDTH = 800
587 self.HEIGHT = 180
797 self.HEIGHT = 180
588 self.WIDTHPROF = 120
798 self.WIDTHPROF = 120
589 self.HEIGHTPROF = 0
799 self.HEIGHTPROF = 0
590 self.counter_imagwr = 0
800 self.counter_imagwr = 0
591
801
592 self.PLOT_CODE = RTI_CODE
802 self.PLOT_CODE = RTI_CODE
593
803
594 self.FTP_WEI = None
804 self.FTP_WEI = None
595 self.EXP_CODE = None
805 self.EXP_CODE = None
596 self.SUB_EXP_CODE = None
806 self.SUB_EXP_CODE = None
597 self.PLOT_POS = None
807 self.PLOT_POS = None
598 self.tmin = None
808 self.tmin = None
599 self.tmax = None
809 self.tmax = None
600
810
601 self.xmin = None
811 self.xmin = None
602 self.xmax = None
812 self.xmax = None
603
813
604 self.figfile = None
814 self.figfile = None
605
815
606 def getSubplots(self):
816 def getSubplots(self):
607
817
608 ncol = 1
818 ncol = 1
609 nrow = self.nplots
819 nrow = self.nplots
610
820
611 return nrow, ncol
821 return nrow, ncol
612
822
613 def setup(self, id, nplots, wintitle, show=True):
823 def setup(self, id, nplots, wintitle, show=True):
614
824
615 self.nplots = nplots
825 self.nplots = nplots
616
826
617 ncolspan = 1
827 ncolspan = 1
618 colspan = 1
828 colspan = 1
619
829
620 self.createFigure(id = id,
830 self.createFigure(id = id,
621 wintitle = wintitle,
831 wintitle = wintitle,
622 widthplot = self.WIDTH + self.WIDTHPROF,
832 widthplot = self.WIDTH + self.WIDTHPROF,
623 heightplot = self.HEIGHT + self.HEIGHTPROF,
833 heightplot = self.HEIGHT + self.HEIGHTPROF,
624 show=show)
834 show=show)
625
835
626 nrow, ncol = self.getSubplots()
836 nrow, ncol = self.getSubplots()
627
837
628 counter = 0
838 counter = 0
629 for y in range(nrow):
839 for y in range(nrow):
630 for x in range(ncol):
840 for x in range(ncol):
631
841
632 if counter >= self.nplots:
842 if counter >= self.nplots:
633 break
843 break
634
844
635 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
845 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
636
846
637 counter += 1
847 counter += 1
638
848
639 def run(self, dataOut, id, wintitle="", channelList=None, paramIndex = 0, colormap=True,
849 def run(self, dataOut, id, wintitle="", channelList=None, paramIndex = 0, colormap="jet",
640 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
850 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
641 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
851 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
642 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
852 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
643 server=None, folder=None, username=None, password=None,
853 server=None, folder=None, username=None, password=None,
644 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
854 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, HEIGHT=None):
645 """
855 """
646
856
647 Input:
857 Input:
648 dataOut :
858 dataOut :
649 id :
859 id :
650 wintitle :
860 wintitle :
651 channelList :
861 channelList :
652 showProfile :
862 showProfile :
653 xmin : None,
863 xmin : None,
654 xmax : None,
864 xmax : None,
655 ymin : None,
865 ymin : None,
656 ymax : None,
866 ymax : None,
657 zmin : None,
867 zmin : None,
658 zmax : None
868 zmax : None
659 """
869 """
660
870
661 if colormap:
871 if HEIGHT is not None:
662 colormap="jet"
872 self.HEIGHT = HEIGHT
663 else:
873
664 colormap="RdBu_r"
874
665
666 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
875 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
667 return
876 return
668
877
669 if channelList == None:
878 if channelList == None:
670 channelIndexList = range(dataOut.data_param.shape[0])
879 channelIndexList = range(dataOut.data_param.shape[0])
671 else:
880 else:
672 channelIndexList = []
881 channelIndexList = []
673 for channel in channelList:
882 for channel in channelList:
674 if channel not in dataOut.channelList:
883 if channel not in dataOut.channelList:
675 raise ValueError, "Channel %d is not in dataOut.channelList"
884 raise ValueError, "Channel %d is not in dataOut.channelList"
676 channelIndexList.append(dataOut.channelList.index(channel))
885 channelIndexList.append(dataOut.channelList.index(channel))
677
886
678 x = dataOut.getTimeRange1(dataOut.paramInterval)
887 x = dataOut.getTimeRange1(dataOut.paramInterval)
679 y = dataOut.getHeiRange()
888 y = dataOut.getHeiRange()
680
889
681 if dataOut.data_param.ndim == 3:
890 if dataOut.data_param.ndim == 3:
682 z = dataOut.data_param[channelIndexList,paramIndex,:]
891 z = dataOut.data_param[channelIndexList,paramIndex,:]
683 else:
892 else:
684 z = dataOut.data_param[channelIndexList,:]
893 z = dataOut.data_param[channelIndexList,:]
685
894
686 if showSNR:
895 if showSNR:
687 #SNR data
896 #SNR data
688 SNRarray = dataOut.data_SNR[channelIndexList,:]
897 SNRarray = dataOut.data_SNR[channelIndexList,:]
689 SNRdB = 10*numpy.log10(SNRarray)
898 SNRdB = 10*numpy.log10(SNRarray)
690 ind = numpy.where(SNRdB < SNRthresh)
899 ind = numpy.where(SNRdB < SNRthresh)
691 z[ind] = numpy.nan
900 z[ind] = numpy.nan
692
901
693 thisDatetime = dataOut.datatime
902 thisDatetime = dataOut.datatime
694 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
903 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
695 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
904 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
696 xlabel = ""
905 xlabel = ""
697 ylabel = "Range (Km)"
906 ylabel = "Range (Km)"
698
907
699 update_figfile = False
908 update_figfile = False
700
909
701 if not self.isConfig:
910 if not self.isConfig:
702
911
703 nchan = len(channelIndexList)
912 nchan = len(channelIndexList)
704 self.nchan = nchan
913 self.nchan = nchan
705 self.plotFact = 1
914 self.plotFact = 1
706 nplots = nchan
915 nplots = nchan
707
916
708 if showSNR:
917 if showSNR:
709 nplots = nchan*2
918 nplots = nchan*2
710 self.plotFact = 2
919 self.plotFact = 2
711 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
920 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
712 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
921 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
713
922
714 self.setup(id=id,
923 self.setup(id=id,
715 nplots=nplots,
924 nplots=nplots,
716 wintitle=wintitle,
925 wintitle=wintitle,
717 show=show)
926 show=show)
718
927
719 if timerange != None:
928 if timerange != None:
720 self.timerange = timerange
929 self.timerange = timerange
721
930
722 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
931 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
723
932
724 if ymin == None: ymin = numpy.nanmin(y)
933 if ymin == None: ymin = numpy.nanmin(y)
725 if ymax == None: ymax = numpy.nanmax(y)
934 if ymax == None: ymax = numpy.nanmax(y)
726 if zmin == None: zmin = numpy.nanmin(z)
935 if zmin == None: zmin = numpy.nanmin(z)
727 if zmax == None: zmax = numpy.nanmax(z)
936 if zmax == None: zmax = numpy.nanmax(z)
728
937
729 self.FTP_WEI = ftp_wei
938 self.FTP_WEI = ftp_wei
730 self.EXP_CODE = exp_code
939 self.EXP_CODE = exp_code
731 self.SUB_EXP_CODE = sub_exp_code
940 self.SUB_EXP_CODE = sub_exp_code
732 self.PLOT_POS = plot_pos
941 self.PLOT_POS = plot_pos
733
942
734 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
943 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
735 self.isConfig = True
944 self.isConfig = True
736 self.figfile = figfile
945 self.figfile = figfile
737 update_figfile = True
946 update_figfile = True
738
947
739 self.setWinTitle(title)
948 self.setWinTitle(title)
740
949
741 for i in range(self.nchan):
950 for i in range(self.nchan):
742 index = channelIndexList[i]
951 index = channelIndexList[i]
743 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
952 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
744 axes = self.axesList[i*self.plotFact]
953 axes = self.axesList[i*self.plotFact]
745 z1 = z[i,:].reshape((1,-1))
954 z1 = z[i,:].reshape((1,-1))
746 axes.pcolorbuffer(x, y, z1,
955 axes.pcolorbuffer(x, y, z1,
747 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
956 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
748 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
957 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
749 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
958 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
750
959
751 if showSNR:
960 if showSNR:
752 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
961 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
753 axes = self.axesList[i*self.plotFact + 1]
962 axes = self.axesList[i*self.plotFact + 1]
754 SNRdB1 = SNRdB[i,:].reshape((1,-1))
963 SNRdB1 = SNRdB[i,:].reshape((1,-1))
755 axes.pcolorbuffer(x, y, SNRdB1,
964 axes.pcolorbuffer(x, y, SNRdB1,
756 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
965 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
757 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
966 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
758 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
967 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
759
968
760
969
761 self.draw()
970 self.draw()
762
971
763 if dataOut.ltctime >= self.xmax:
972 if dataOut.ltctime >= self.xmax:
764 self.counter_imagwr = wr_period
973 self.counter_imagwr = wr_period
765 self.isConfig = False
974 self.isConfig = False
766 update_figfile = True
975 update_figfile = True
767
976
768 self.save(figpath=figpath,
977 self.save(figpath=figpath,
769 figfile=figfile,
978 figfile=figfile,
770 save=save,
979 save=save,
771 ftp=ftp,
980 ftp=ftp,
772 wr_period=wr_period,
981 wr_period=wr_period,
773 thisDatetime=thisDatetime,
982 thisDatetime=thisDatetime,
774 update_figfile=update_figfile)
983 update_figfile=update_figfile)
775
984
776
985
777
986
778 class Parameters1Plot(Figure):
987 class Parameters1Plot(Figure):
779
988
780 __isConfig = None
989 __isConfig = None
781 __nsubplots = None
990 __nsubplots = None
782
991
783 WIDTHPROF = None
992 WIDTHPROF = None
784 HEIGHTPROF = None
993 HEIGHTPROF = None
785 PREFIX = 'prm'
994 PREFIX = 'prm'
786
995
787 def __init__(self, **kwargs):
996 def __init__(self, **kwargs):
788 Figure.__init__(self, **kwargs)
997 Figure.__init__(self, **kwargs)
789 self.timerange = 2*60*60
998 self.timerange = 2*60*60
790 self.isConfig = False
999 self.isConfig = False
791 self.__nsubplots = 1
1000 self.__nsubplots = 1
792
1001
793 self.WIDTH = 800
1002 self.WIDTH = 800
794 self.HEIGHT = 180
1003 self.HEIGHT = 180
795 self.WIDTHPROF = 120
1004 self.WIDTHPROF = 120
796 self.HEIGHTPROF = 0
1005 self.HEIGHTPROF = 0
797 self.counter_imagwr = 0
1006 self.counter_imagwr = 0
798
1007
799 self.PLOT_CODE = PARMS_CODE
1008 self.PLOT_CODE = PARMS_CODE
800
1009
801 self.FTP_WEI = None
1010 self.FTP_WEI = None
802 self.EXP_CODE = None
1011 self.EXP_CODE = None
803 self.SUB_EXP_CODE = None
1012 self.SUB_EXP_CODE = None
804 self.PLOT_POS = None
1013 self.PLOT_POS = None
805 self.tmin = None
1014 self.tmin = None
806 self.tmax = None
1015 self.tmax = None
807
1016
808 self.xmin = None
1017 self.xmin = None
809 self.xmax = None
1018 self.xmax = None
810
1019
811 self.figfile = None
1020 self.figfile = None
812
1021
813 def getSubplots(self):
1022 def getSubplots(self):
814
1023
815 ncol = 1
1024 ncol = 1
816 nrow = self.nplots
1025 nrow = self.nplots
817
1026
818 return nrow, ncol
1027 return nrow, ncol
819
1028
820 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1029 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
821
1030
822 self.__showprofile = showprofile
1031 self.__showprofile = showprofile
823 self.nplots = nplots
1032 self.nplots = nplots
824
1033
825 ncolspan = 1
1034 ncolspan = 1
826 colspan = 1
1035 colspan = 1
827
1036
828 self.createFigure(id = id,
1037 self.createFigure(id = id,
829 wintitle = wintitle,
1038 wintitle = wintitle,
830 widthplot = self.WIDTH + self.WIDTHPROF,
1039 widthplot = self.WIDTH + self.WIDTHPROF,
831 heightplot = self.HEIGHT + self.HEIGHTPROF,
1040 heightplot = self.HEIGHT + self.HEIGHTPROF,
832 show=show)
1041 show=show)
833
1042
834 nrow, ncol = self.getSubplots()
1043 nrow, ncol = self.getSubplots()
835
1044
836 counter = 0
1045 counter = 0
837 for y in range(nrow):
1046 for y in range(nrow):
838 for x in range(ncol):
1047 for x in range(ncol):
839
1048
840 if counter >= self.nplots:
1049 if counter >= self.nplots:
841 break
1050 break
842
1051
843 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1052 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
844
1053
845 if showprofile:
1054 if showprofile:
846 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1055 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
847
1056
848 counter += 1
1057 counter += 1
849
1058
850 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
1059 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
851 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
1060 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
852 parameterIndex = None, onlyPositive = False,
1061 parameterIndex = None, onlyPositive = False,
853 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
1062 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
854 DOP = True,
1063 DOP = True,
855 zlabel = "", parameterName = "", parameterObject = "data_param",
1064 zlabel = "", parameterName = "", parameterObject = "data_param",
856 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1065 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
857 server=None, folder=None, username=None, password=None,
1066 server=None, folder=None, username=None, password=None,
858 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1067 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
859 #print inspect.getargspec(self.run).args
1068 #print inspect.getargspec(self.run).args
860 """
1069 """
861
1070
862 Input:
1071 Input:
863 dataOut :
1072 dataOut :
864 id :
1073 id :
865 wintitle :
1074 wintitle :
866 channelList :
1075 channelList :
867 showProfile :
1076 showProfile :
868 xmin : None,
1077 xmin : None,
869 xmax : None,
1078 xmax : None,
870 ymin : None,
1079 ymin : None,
871 ymax : None,
1080 ymax : None,
872 zmin : None,
1081 zmin : None,
873 zmax : None
1082 zmax : None
874 """
1083 """
875
1084
876 data_param = getattr(dataOut, parameterObject)
1085 data_param = getattr(dataOut, parameterObject)
877
1086
878 if channelList == None:
1087 if channelList == None:
879 channelIndexList = numpy.arange(data_param.shape[0])
1088 channelIndexList = numpy.arange(data_param.shape[0])
880 else:
1089 else:
881 channelIndexList = numpy.array(channelList)
1090 channelIndexList = numpy.array(channelList)
882
1091
883 nchan = len(channelIndexList) #Number of channels being plotted
1092 nchan = len(channelIndexList) #Number of channels being plotted
884
1093
885 if nchan < 1:
1094 if nchan < 1:
886 return
1095 return
887
1096
888 nGraphsByChannel = 0
1097 nGraphsByChannel = 0
889
1098
890 if SNR:
1099 if SNR:
891 nGraphsByChannel += 1
1100 nGraphsByChannel += 1
892 if DOP:
1101 if DOP:
893 nGraphsByChannel += 1
1102 nGraphsByChannel += 1
894
1103
895 if nGraphsByChannel < 1:
1104 if nGraphsByChannel < 1:
896 return
1105 return
897
1106
898 nplots = nGraphsByChannel*nchan
1107 nplots = nGraphsByChannel*nchan
899
1108
900 if timerange is not None:
1109 if timerange is not None:
901 self.timerange = timerange
1110 self.timerange = timerange
902
1111
903 #tmin = None
1112 #tmin = None
904 #tmax = None
1113 #tmax = None
905 if parameterIndex == None:
1114 if parameterIndex == None:
906 parameterIndex = 1
1115 parameterIndex = 1
907
1116
908 x = dataOut.getTimeRange1(dataOut.paramInterval)
1117 x = dataOut.getTimeRange1(dataOut.paramInterval)
909 y = dataOut.heightList
1118 y = dataOut.heightList
910 z = data_param[channelIndexList,parameterIndex,:].copy()
1119 z = data_param[channelIndexList,parameterIndex,:].copy()
911
1120
912 zRange = dataOut.abscissaList
1121 zRange = dataOut.abscissaList
913 # nChannels = z.shape[0] #Number of wind dimensions estimated
1122 # nChannels = z.shape[0] #Number of wind dimensions estimated
914 # thisDatetime = dataOut.datatime
1123 # thisDatetime = dataOut.datatime
915
1124
916 if dataOut.data_SNR is not None:
1125 if dataOut.data_SNR is not None:
917 SNRarray = dataOut.data_SNR[channelIndexList,:]
1126 SNRarray = dataOut.data_SNR[channelIndexList,:]
918 SNRdB = 10*numpy.log10(SNRarray)
1127 SNRdB = 10*numpy.log10(SNRarray)
919 # SNRavgdB = 10*numpy.log10(SNRavg)
1128 # SNRavgdB = 10*numpy.log10(SNRavg)
920 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
1129 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
921 z[ind] = numpy.nan
1130 z[ind] = numpy.nan
922
1131
923 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1132 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
924 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
1133 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
925 xlabel = ""
1134 xlabel = ""
926 ylabel = "Range (Km)"
1135 ylabel = "Range (Km)"
927
1136
928 if (SNR and not onlySNR): nplots = 2*nplots
1137 if (SNR and not onlySNR): nplots = 2*nplots
929
1138
930 if onlyPositive:
1139 if onlyPositive:
931 colormap = "jet"
1140 colormap = "jet"
932 zmin = 0
1141 zmin = 0
933 else: colormap = "RdBu_r"
1142 else: colormap = "RdBu_r"
934
1143
935 if not self.isConfig:
1144 if not self.isConfig:
936
1145
937 self.setup(id=id,
1146 self.setup(id=id,
938 nplots=nplots,
1147 nplots=nplots,
939 wintitle=wintitle,
1148 wintitle=wintitle,
940 showprofile=showprofile,
1149 showprofile=showprofile,
941 show=show)
1150 show=show)
942
1151
943 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1152 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
944
1153
945 if ymin == None: ymin = numpy.nanmin(y)
1154 if ymin == None: ymin = numpy.nanmin(y)
946 if ymax == None: ymax = numpy.nanmax(y)
1155 if ymax == None: ymax = numpy.nanmax(y)
947 if zmin == None: zmin = numpy.nanmin(zRange)
1156 if zmin == None: zmin = numpy.nanmin(zRange)
948 if zmax == None: zmax = numpy.nanmax(zRange)
1157 if zmax == None: zmax = numpy.nanmax(zRange)
949
1158
950 if SNR:
1159 if SNR:
951 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
1160 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
952 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
1161 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
953
1162
954 self.FTP_WEI = ftp_wei
1163 self.FTP_WEI = ftp_wei
955 self.EXP_CODE = exp_code
1164 self.EXP_CODE = exp_code
956 self.SUB_EXP_CODE = sub_exp_code
1165 self.SUB_EXP_CODE = sub_exp_code
957 self.PLOT_POS = plot_pos
1166 self.PLOT_POS = plot_pos
958
1167
959 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1168 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
960 self.isConfig = True
1169 self.isConfig = True
961 self.figfile = figfile
1170 self.figfile = figfile
962
1171
963 self.setWinTitle(title)
1172 self.setWinTitle(title)
964
1173
965 if ((self.xmax - x[1]) < (x[1]-x[0])):
1174 if ((self.xmax - x[1]) < (x[1]-x[0])):
966 x[1] = self.xmax
1175 x[1] = self.xmax
967
1176
968 for i in range(nchan):
1177 for i in range(nchan):
969
1178
970 if (SNR and not onlySNR): j = 2*i
1179 if (SNR and not onlySNR): j = 2*i
971 else: j = i
1180 else: j = i
972
1181
973 j = nGraphsByChannel*i
1182 j = nGraphsByChannel*i
974
1183
975 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1184 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
976 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
1185 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
977
1186
978 if not onlySNR:
1187 if not onlySNR:
979 axes = self.axesList[j*self.__nsubplots]
1188 axes = self.axesList[j*self.__nsubplots]
980 z1 = z[i,:].reshape((1,-1))
1189 z1 = z[i,:].reshape((1,-1))
981 axes.pcolorbuffer(x, y, z1,
1190 axes.pcolorbuffer(x, y, z1,
982 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
1191 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
983 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
1192 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
984 ticksize=9, cblabel=zlabel, cbsize="1%")
1193 ticksize=9, cblabel=zlabel, cbsize="1%")
985
1194
986 if DOP:
1195 if DOP:
987 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1196 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
988
1197
989 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1198 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
990 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
1199 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
991 axes = self.axesList[j]
1200 axes = self.axesList[j]
992 z1 = z[i,:].reshape((1,-1))
1201 z1 = z[i,:].reshape((1,-1))
993 axes.pcolorbuffer(x, y, z1,
1202 axes.pcolorbuffer(x, y, z1,
994 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
1203 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
995 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
1204 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
996 ticksize=9, cblabel=zlabel, cbsize="1%")
1205 ticksize=9, cblabel=zlabel, cbsize="1%")
997
1206
998 if SNR:
1207 if SNR:
999 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1208 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1000 axes = self.axesList[(j)*self.__nsubplots]
1209 axes = self.axesList[(j)*self.__nsubplots]
1001 if not onlySNR:
1210 if not onlySNR:
1002 axes = self.axesList[(j + 1)*self.__nsubplots]
1211 axes = self.axesList[(j + 1)*self.__nsubplots]
1003
1212
1004 axes = self.axesList[(j + nGraphsByChannel-1)]
1213 axes = self.axesList[(j + nGraphsByChannel-1)]
1005
1214
1006 z1 = SNRdB[i,:].reshape((1,-1))
1215 z1 = SNRdB[i,:].reshape((1,-1))
1007 axes.pcolorbuffer(x, y, z1,
1216 axes.pcolorbuffer(x, y, z1,
1008 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1217 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1009 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1218 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1010 ticksize=9, cblabel=zlabel, cbsize="1%")
1219 ticksize=9, cblabel=zlabel, cbsize="1%")
1011
1220
1012
1221
1013
1222
1014 self.draw()
1223 self.draw()
1015
1224
1016 if x[1] >= self.axesList[0].xmax:
1225 if x[1] >= self.axesList[0].xmax:
1017 self.counter_imagwr = wr_period
1226 self.counter_imagwr = wr_period
1018 self.isConfig = False
1227 self.isConfig = False
1019 self.figfile = None
1228 self.figfile = None
1020
1229
1021 self.save(figpath=figpath,
1230 self.save(figpath=figpath,
1022 figfile=figfile,
1231 figfile=figfile,
1023 save=save,
1232 save=save,
1024 ftp=ftp,
1233 ftp=ftp,
1025 wr_period=wr_period,
1234 wr_period=wr_period,
1026 thisDatetime=thisDatetime,
1235 thisDatetime=thisDatetime,
1027 update_figfile=False)
1236 update_figfile=False)
1028
1237
1029 class SpectralFittingPlot(Figure):
1238 class SpectralFittingPlot(Figure):
1030
1239
1031 __isConfig = None
1240 __isConfig = None
1032 __nsubplots = None
1241 __nsubplots = None
1033
1242
1034 WIDTHPROF = None
1243 WIDTHPROF = None
1035 HEIGHTPROF = None
1244 HEIGHTPROF = None
1036 PREFIX = 'prm'
1245 PREFIX = 'prm'
1037
1246
1038
1247
1039 N = None
1248 N = None
1040 ippSeconds = None
1249 ippSeconds = None
1041
1250
1042 def __init__(self, **kwargs):
1251 def __init__(self, **kwargs):
1043 Figure.__init__(self, **kwargs)
1252 Figure.__init__(self, **kwargs)
1044 self.isConfig = False
1253 self.isConfig = False
1045 self.__nsubplots = 1
1254 self.__nsubplots = 1
1046
1255
1047 self.PLOT_CODE = SPECFIT_CODE
1256 self.PLOT_CODE = SPECFIT_CODE
1048
1257
1049 self.WIDTH = 450
1258 self.WIDTH = 450
1050 self.HEIGHT = 250
1259 self.HEIGHT = 250
1051 self.WIDTHPROF = 0
1260 self.WIDTHPROF = 0
1052 self.HEIGHTPROF = 0
1261 self.HEIGHTPROF = 0
1053
1262
1054 def getSubplots(self):
1263 def getSubplots(self):
1055
1264
1056 ncol = int(numpy.sqrt(self.nplots)+0.9)
1265 ncol = int(numpy.sqrt(self.nplots)+0.9)
1057 nrow = int(self.nplots*1./ncol + 0.9)
1266 nrow = int(self.nplots*1./ncol + 0.9)
1058
1267
1059 return nrow, ncol
1268 return nrow, ncol
1060
1269
1061 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1270 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1062
1271
1063 showprofile = False
1272 showprofile = False
1064 self.__showprofile = showprofile
1273 self.__showprofile = showprofile
1065 self.nplots = nplots
1274 self.nplots = nplots
1066
1275
1067 ncolspan = 5
1276 ncolspan = 5
1068 colspan = 4
1277 colspan = 4
1069 if showprofile:
1278 if showprofile:
1070 ncolspan = 5
1279 ncolspan = 5
1071 colspan = 4
1280 colspan = 4
1072 self.__nsubplots = 2
1281 self.__nsubplots = 2
1073
1282
1074 self.createFigure(id = id,
1283 self.createFigure(id = id,
1075 wintitle = wintitle,
1284 wintitle = wintitle,
1076 widthplot = self.WIDTH + self.WIDTHPROF,
1285 widthplot = self.WIDTH + self.WIDTHPROF,
1077 heightplot = self.HEIGHT + self.HEIGHTPROF,
1286 heightplot = self.HEIGHT + self.HEIGHTPROF,
1078 show=show)
1287 show=show)
1079
1288
1080 nrow, ncol = self.getSubplots()
1289 nrow, ncol = self.getSubplots()
1081
1290
1082 counter = 0
1291 counter = 0
1083 for y in range(nrow):
1292 for y in range(nrow):
1084 for x in range(ncol):
1293 for x in range(ncol):
1085
1294
1086 if counter >= self.nplots:
1295 if counter >= self.nplots:
1087 break
1296 break
1088
1297
1089 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1298 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1090
1299
1091 if showprofile:
1300 if showprofile:
1092 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1301 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1093
1302
1094 counter += 1
1303 counter += 1
1095
1304
1096 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1305 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1097 xmin=None, xmax=None, ymin=None, ymax=None,
1306 xmin=None, xmax=None, ymin=None, ymax=None,
1098 save=False, figpath='./', figfile=None, show=True):
1307 save=False, figpath='./', figfile=None, show=True):
1099
1308
1100 """
1309 """
1101
1310
1102 Input:
1311 Input:
1103 dataOut :
1312 dataOut :
1104 id :
1313 id :
1105 wintitle :
1314 wintitle :
1106 channelList :
1315 channelList :
1107 showProfile :
1316 showProfile :
1108 xmin : None,
1317 xmin : None,
1109 xmax : None,
1318 xmax : None,
1110 zmin : None,
1319 zmin : None,
1111 zmax : None
1320 zmax : None
1112 """
1321 """
1113
1322
1114 if cutHeight==None:
1323 if cutHeight==None:
1115 h=270
1324 h=270
1116 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1325 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1117 cutHeight = dataOut.heightList[heightindex]
1326 cutHeight = dataOut.heightList[heightindex]
1118
1327
1119 factor = dataOut.normFactor
1328 factor = dataOut.normFactor
1120 x = dataOut.abscissaList[:-1]
1329 x = dataOut.abscissaList[:-1]
1121 #y = dataOut.getHeiRange()
1330 #y = dataOut.getHeiRange()
1122
1331
1123 z = dataOut.data_pre[:,:,heightindex]/factor
1332 z = dataOut.data_pre[:,:,heightindex]/factor
1124 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1333 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1125 avg = numpy.average(z, axis=1)
1334 avg = numpy.average(z, axis=1)
1126 listChannels = z.shape[0]
1335 listChannels = z.shape[0]
1127
1336
1128 #Reconstruct Function
1337 #Reconstruct Function
1129 if fit==True:
1338 if fit==True:
1130 groupArray = dataOut.groupList
1339 groupArray = dataOut.groupList
1131 listChannels = groupArray.reshape((groupArray.size))
1340 listChannels = groupArray.reshape((groupArray.size))
1132 listChannels.sort()
1341 listChannels.sort()
1133 spcFitLine = numpy.zeros(z.shape)
1342 spcFitLine = numpy.zeros(z.shape)
1134 constants = dataOut.constants
1343 constants = dataOut.constants
1135
1344
1136 nGroups = groupArray.shape[0]
1345 nGroups = groupArray.shape[0]
1137 nChannels = groupArray.shape[1]
1346 nChannels = groupArray.shape[1]
1138 nProfiles = z.shape[1]
1347 nProfiles = z.shape[1]
1139
1348
1140 for f in range(nGroups):
1349 for f in range(nGroups):
1141 groupChann = groupArray[f,:]
1350 groupChann = groupArray[f,:]
1142 p = dataOut.data_param[f,:,heightindex]
1351 p = dataOut.data_param[f,:,heightindex]
1143 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1352 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1144 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1353 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1145 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1354 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1146 spcFitLine[groupChann,:] = fitLineAux
1355 spcFitLine[groupChann,:] = fitLineAux
1147 # spcFitLine = spcFitLine/factor
1356 # spcFitLine = spcFitLine/factor
1148
1357
1149 z = z[listChannels,:]
1358 z = z[listChannels,:]
1150 spcFitLine = spcFitLine[listChannels,:]
1359 spcFitLine = spcFitLine[listChannels,:]
1151 spcFitLinedB = 10*numpy.log10(spcFitLine)
1360 spcFitLinedB = 10*numpy.log10(spcFitLine)
1152
1361
1153 zdB = 10*numpy.log10(z)
1362 zdB = 10*numpy.log10(z)
1154 #thisDatetime = dataOut.datatime
1363 #thisDatetime = dataOut.datatime
1155 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1364 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1156 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1365 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1157 xlabel = "Velocity (m/s)"
1366 xlabel = "Velocity (m/s)"
1158 ylabel = "Spectrum"
1367 ylabel = "Spectrum"
1159
1368
1160 if not self.isConfig:
1369 if not self.isConfig:
1161
1370
1162 nplots = listChannels.size
1371 nplots = listChannels.size
1163
1372
1164 self.setup(id=id,
1373 self.setup(id=id,
1165 nplots=nplots,
1374 nplots=nplots,
1166 wintitle=wintitle,
1375 wintitle=wintitle,
1167 showprofile=showprofile,
1376 showprofile=showprofile,
1168 show=show)
1377 show=show)
1169
1378
1170 if xmin == None: xmin = numpy.nanmin(x)
1379 if xmin == None: xmin = numpy.nanmin(x)
1171 if xmax == None: xmax = numpy.nanmax(x)
1380 if xmax == None: xmax = numpy.nanmax(x)
1172 if ymin == None: ymin = numpy.nanmin(zdB)
1381 if ymin == None: ymin = numpy.nanmin(zdB)
1173 if ymax == None: ymax = numpy.nanmax(zdB)+2
1382 if ymax == None: ymax = numpy.nanmax(zdB)+2
1174
1383
1175 self.isConfig = True
1384 self.isConfig = True
1176
1385
1177 self.setWinTitle(title)
1386 self.setWinTitle(title)
1178 for i in range(self.nplots):
1387 for i in range(self.nplots):
1179 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1388 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1180 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1389 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1181 axes = self.axesList[i*self.__nsubplots]
1390 axes = self.axesList[i*self.__nsubplots]
1182 if fit == False:
1391 if fit == False:
1183 axes.pline(x, zdB[i,:],
1392 axes.pline(x, zdB[i,:],
1184 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1393 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1185 xlabel=xlabel, ylabel=ylabel, title=title
1394 xlabel=xlabel, ylabel=ylabel, title=title
1186 )
1395 )
1187 if fit == True:
1396 if fit == True:
1188 fitline=spcFitLinedB[i,:]
1397 fitline=spcFitLinedB[i,:]
1189 y=numpy.vstack([zdB[i,:],fitline] )
1398 y=numpy.vstack([zdB[i,:],fitline] )
1190 legendlabels=['Data','Fitting']
1399 legendlabels=['Data','Fitting']
1191 axes.pmultilineyaxis(x, y,
1400 axes.pmultilineyaxis(x, y,
1192 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1401 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1193 xlabel=xlabel, ylabel=ylabel, title=title,
1402 xlabel=xlabel, ylabel=ylabel, title=title,
1194 legendlabels=legendlabels, marker=None,
1403 legendlabels=legendlabels, marker=None,
1195 linestyle='solid', grid='both')
1404 linestyle='solid', grid='both')
1196
1405
1197 self.draw()
1406 self.draw()
1198
1407
1199 self.save(figpath=figpath,
1408 self.save(figpath=figpath,
1200 figfile=figfile,
1409 figfile=figfile,
1201 save=save,
1410 save=save,
1202 ftp=ftp,
1411 ftp=ftp,
1203 wr_period=wr_period,
1412 wr_period=wr_period,
1204 thisDatetime=thisDatetime)
1413 thisDatetime=thisDatetime)
1205
1414
1206
1415
1207 class EWDriftsPlot(Figure):
1416 class EWDriftsPlot(Figure):
1208
1417
1209 __isConfig = None
1418 __isConfig = None
1210 __nsubplots = None
1419 __nsubplots = None
1211
1420
1212 WIDTHPROF = None
1421 WIDTHPROF = None
1213 HEIGHTPROF = None
1422 HEIGHTPROF = None
1214 PREFIX = 'drift'
1423 PREFIX = 'drift'
1215
1424
1216 def __init__(self, **kwargs):
1425 def __init__(self, **kwargs):
1217 Figure.__init__(self, **kwargs)
1426 Figure.__init__(self, **kwargs)
1218 self.timerange = 2*60*60
1427 self.timerange = 2*60*60
1219 self.isConfig = False
1428 self.isConfig = False
1220 self.__nsubplots = 1
1429 self.__nsubplots = 1
1221
1430
1222 self.WIDTH = 800
1431 self.WIDTH = 800
1223 self.HEIGHT = 150
1432 self.HEIGHT = 150
1224 self.WIDTHPROF = 120
1433 self.WIDTHPROF = 120
1225 self.HEIGHTPROF = 0
1434 self.HEIGHTPROF = 0
1226 self.counter_imagwr = 0
1435 self.counter_imagwr = 0
1227
1436
1228 self.PLOT_CODE = EWDRIFT_CODE
1437 self.PLOT_CODE = EWDRIFT_CODE
1229
1438
1230 self.FTP_WEI = None
1439 self.FTP_WEI = None
1231 self.EXP_CODE = None
1440 self.EXP_CODE = None
1232 self.SUB_EXP_CODE = None
1441 self.SUB_EXP_CODE = None
1233 self.PLOT_POS = None
1442 self.PLOT_POS = None
1234 self.tmin = None
1443 self.tmin = None
1235 self.tmax = None
1444 self.tmax = None
1236
1445
1237 self.xmin = None
1446 self.xmin = None
1238 self.xmax = None
1447 self.xmax = None
1239
1448
1240 self.figfile = None
1449 self.figfile = None
1241
1450
1242 def getSubplots(self):
1451 def getSubplots(self):
1243
1452
1244 ncol = 1
1453 ncol = 1
1245 nrow = self.nplots
1454 nrow = self.nplots
1246
1455
1247 return nrow, ncol
1456 return nrow, ncol
1248
1457
1249 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1458 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1250
1459
1251 self.__showprofile = showprofile
1460 self.__showprofile = showprofile
1252 self.nplots = nplots
1461 self.nplots = nplots
1253
1462
1254 ncolspan = 1
1463 ncolspan = 1
1255 colspan = 1
1464 colspan = 1
1256
1465
1257 self.createFigure(id = id,
1466 self.createFigure(id = id,
1258 wintitle = wintitle,
1467 wintitle = wintitle,
1259 widthplot = self.WIDTH + self.WIDTHPROF,
1468 widthplot = self.WIDTH + self.WIDTHPROF,
1260 heightplot = self.HEIGHT + self.HEIGHTPROF,
1469 heightplot = self.HEIGHT + self.HEIGHTPROF,
1261 show=show)
1470 show=show)
1262
1471
1263 nrow, ncol = self.getSubplots()
1472 nrow, ncol = self.getSubplots()
1264
1473
1265 counter = 0
1474 counter = 0
1266 for y in range(nrow):
1475 for y in range(nrow):
1267 if counter >= self.nplots:
1476 if counter >= self.nplots:
1268 break
1477 break
1269
1478
1270 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1479 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1271 counter += 1
1480 counter += 1
1272
1481
1273 def run(self, dataOut, id, wintitle="", channelList=None,
1482 def run(self, dataOut, id, wintitle="", channelList=None,
1274 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1483 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1275 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1484 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1276 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1485 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1277 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1486 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1278 server=None, folder=None, username=None, password=None,
1487 server=None, folder=None, username=None, password=None,
1279 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1488 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1280 """
1489 """
1281
1490
1282 Input:
1491 Input:
1283 dataOut :
1492 dataOut :
1284 id :
1493 id :
1285 wintitle :
1494 wintitle :
1286 channelList :
1495 channelList :
1287 showProfile :
1496 showProfile :
1288 xmin : None,
1497 xmin : None,
1289 xmax : None,
1498 xmax : None,
1290 ymin : None,
1499 ymin : None,
1291 ymax : None,
1500 ymax : None,
1292 zmin : None,
1501 zmin : None,
1293 zmax : None
1502 zmax : None
1294 """
1503 """
1295
1504
1296 if timerange is not None:
1505 if timerange is not None:
1297 self.timerange = timerange
1506 self.timerange = timerange
1298
1507
1299 tmin = None
1508 tmin = None
1300 tmax = None
1509 tmax = None
1301
1510
1302 x = dataOut.getTimeRange1(dataOut.outputInterval)
1511 x = dataOut.getTimeRange1(dataOut.outputInterval)
1303 # y = dataOut.heightList
1512 # y = dataOut.heightList
1304 y = dataOut.heightList
1513 y = dataOut.heightList
1305
1514
1306 z = dataOut.data_output
1515 z = dataOut.data_output
1307 nplots = z.shape[0] #Number of wind dimensions estimated
1516 nplots = z.shape[0] #Number of wind dimensions estimated
1308 nplotsw = nplots
1517 nplotsw = nplots
1309
1518
1310 #If there is a SNR function defined
1519 #If there is a SNR function defined
1311 if dataOut.data_SNR is not None:
1520 if dataOut.data_SNR is not None:
1312 nplots += 1
1521 nplots += 1
1313 SNR = dataOut.data_SNR
1522 SNR = dataOut.data_SNR
1314
1523
1315 if SNR_1:
1524 if SNR_1:
1316 SNR += 1
1525 SNR += 1
1317
1526
1318 SNRavg = numpy.average(SNR, axis=0)
1527 SNRavg = numpy.average(SNR, axis=0)
1319
1528
1320 SNRdB = 10*numpy.log10(SNR)
1529 SNRdB = 10*numpy.log10(SNR)
1321 SNRavgdB = 10*numpy.log10(SNRavg)
1530 SNRavgdB = 10*numpy.log10(SNRavg)
1322
1531
1323 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1532 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1324
1533
1325 for i in range(nplotsw):
1534 for i in range(nplotsw):
1326 z[i,ind] = numpy.nan
1535 z[i,ind] = numpy.nan
1327
1536
1328
1537
1329 showprofile = False
1538 showprofile = False
1330 # thisDatetime = dataOut.datatime
1539 # thisDatetime = dataOut.datatime
1331 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1540 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1332 title = wintitle + " EW Drifts"
1541 title = wintitle + " EW Drifts"
1333 xlabel = ""
1542 xlabel = ""
1334 ylabel = "Height (Km)"
1543 ylabel = "Height (Km)"
1335
1544
1336 if not self.isConfig:
1545 if not self.isConfig:
1337
1546
1338 self.setup(id=id,
1547 self.setup(id=id,
1339 nplots=nplots,
1548 nplots=nplots,
1340 wintitle=wintitle,
1549 wintitle=wintitle,
1341 showprofile=showprofile,
1550 showprofile=showprofile,
1342 show=show)
1551 show=show)
1343
1552
1344 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1553 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1345
1554
1346 if ymin == None: ymin = numpy.nanmin(y)
1555 if ymin == None: ymin = numpy.nanmin(y)
1347 if ymax == None: ymax = numpy.nanmax(y)
1556 if ymax == None: ymax = numpy.nanmax(y)
1348
1557
1349 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1558 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1350 if zminZonal == None: zminZonal = -zmaxZonal
1559 if zminZonal == None: zminZonal = -zmaxZonal
1351 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1560 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1352 if zminVertical == None: zminVertical = -zmaxVertical
1561 if zminVertical == None: zminVertical = -zmaxVertical
1353
1562
1354 if dataOut.data_SNR is not None:
1563 if dataOut.data_SNR is not None:
1355 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1564 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1356 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1565 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1357
1566
1358 self.FTP_WEI = ftp_wei
1567 self.FTP_WEI = ftp_wei
1359 self.EXP_CODE = exp_code
1568 self.EXP_CODE = exp_code
1360 self.SUB_EXP_CODE = sub_exp_code
1569 self.SUB_EXP_CODE = sub_exp_code
1361 self.PLOT_POS = plot_pos
1570 self.PLOT_POS = plot_pos
1362
1571
1363 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1572 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1364 self.isConfig = True
1573 self.isConfig = True
1365
1574
1366
1575
1367 self.setWinTitle(title)
1576 self.setWinTitle(title)
1368
1577
1369 if ((self.xmax - x[1]) < (x[1]-x[0])):
1578 if ((self.xmax - x[1]) < (x[1]-x[0])):
1370 x[1] = self.xmax
1579 x[1] = self.xmax
1371
1580
1372 strWind = ['Zonal','Vertical']
1581 strWind = ['Zonal','Vertical']
1373 strCb = 'Velocity (m/s)'
1582 strCb = 'Velocity (m/s)'
1374 zmaxVector = [zmaxZonal, zmaxVertical]
1583 zmaxVector = [zmaxZonal, zmaxVertical]
1375 zminVector = [zminZonal, zminVertical]
1584 zminVector = [zminZonal, zminVertical]
1376
1585
1377 for i in range(nplotsw):
1586 for i in range(nplotsw):
1378
1587
1379 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1588 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1380 axes = self.axesList[i*self.__nsubplots]
1589 axes = self.axesList[i*self.__nsubplots]
1381
1590
1382 z1 = z[i,:].reshape((1,-1))
1591 z1 = z[i,:].reshape((1,-1))
1383
1592
1384 axes.pcolorbuffer(x, y, z1,
1593 axes.pcolorbuffer(x, y, z1,
1385 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1594 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1386 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1595 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1387 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1596 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1388
1597
1389 if dataOut.data_SNR is not None:
1598 if dataOut.data_SNR is not None:
1390 i += 1
1599 i += 1
1391 if SNR_1:
1600 if SNR_1:
1392 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1601 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1393 else:
1602 else:
1394 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1603 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1395 axes = self.axesList[i*self.__nsubplots]
1604 axes = self.axesList[i*self.__nsubplots]
1396 SNRavgdB = SNRavgdB.reshape((1,-1))
1605 SNRavgdB = SNRavgdB.reshape((1,-1))
1397
1606
1398 axes.pcolorbuffer(x, y, SNRavgdB,
1607 axes.pcolorbuffer(x, y, SNRavgdB,
1399 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1608 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1400 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1609 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1401 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1610 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1402
1611
1403 self.draw()
1612 self.draw()
1404
1613
1405 if x[1] >= self.axesList[0].xmax:
1614 if x[1] >= self.axesList[0].xmax:
1406 self.counter_imagwr = wr_period
1615 self.counter_imagwr = wr_period
1407 self.isConfig = False
1616 self.isConfig = False
1408 self.figfile = None
1617 self.figfile = None
1409
1618
1410
1619
1411
1620
1412
1621
1413 class PhasePlot(Figure):
1622 class PhasePlot(Figure):
1414
1623
1415 __isConfig = None
1624 __isConfig = None
1416 __nsubplots = None
1625 __nsubplots = None
1417
1626
1418 PREFIX = 'mphase'
1627 PREFIX = 'mphase'
1419
1628
1420 def __init__(self, **kwargs):
1629 def __init__(self, **kwargs):
1421 Figure.__init__(self, **kwargs)
1630 Figure.__init__(self, **kwargs)
1422 self.timerange = 24*60*60
1631 self.timerange = 24*60*60
1423 self.isConfig = False
1632 self.isConfig = False
1424 self.__nsubplots = 1
1633 self.__nsubplots = 1
1425 self.counter_imagwr = 0
1634 self.counter_imagwr = 0
1426 self.WIDTH = 600
1635 self.WIDTH = 600
1427 self.HEIGHT = 300
1636 self.HEIGHT = 300
1428 self.WIDTHPROF = 120
1637 self.WIDTHPROF = 120
1429 self.HEIGHTPROF = 0
1638 self.HEIGHTPROF = 0
1430 self.xdata = None
1639 self.xdata = None
1431 self.ydata = None
1640 self.ydata = None
1432
1641
1433 self.PLOT_CODE = MPHASE_CODE
1642 self.PLOT_CODE = MPHASE_CODE
1434
1643
1435 self.FTP_WEI = None
1644 self.FTP_WEI = None
1436 self.EXP_CODE = None
1645 self.EXP_CODE = None
1437 self.SUB_EXP_CODE = None
1646 self.SUB_EXP_CODE = None
1438 self.PLOT_POS = None
1647 self.PLOT_POS = None
1439
1648
1440
1649
1441 self.filename_phase = None
1650 self.filename_phase = None
1442
1651
1443 self.figfile = None
1652 self.figfile = None
1444
1653
1445 def getSubplots(self):
1654 def getSubplots(self):
1446
1655
1447 ncol = 1
1656 ncol = 1
1448 nrow = 1
1657 nrow = 1
1449
1658
1450 return nrow, ncol
1659 return nrow, ncol
1451
1660
1452 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1661 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1453
1662
1454 self.__showprofile = showprofile
1663 self.__showprofile = showprofile
1455 self.nplots = nplots
1664 self.nplots = nplots
1456
1665
1457 ncolspan = 7
1666 ncolspan = 7
1458 colspan = 6
1667 colspan = 6
1459 self.__nsubplots = 2
1668 self.__nsubplots = 2
1460
1669
1461 self.createFigure(id = id,
1670 self.createFigure(id = id,
1462 wintitle = wintitle,
1671 wintitle = wintitle,
1463 widthplot = self.WIDTH+self.WIDTHPROF,
1672 widthplot = self.WIDTH+self.WIDTHPROF,
1464 heightplot = self.HEIGHT+self.HEIGHTPROF,
1673 heightplot = self.HEIGHT+self.HEIGHTPROF,
1465 show=show)
1674 show=show)
1466
1675
1467 nrow, ncol = self.getSubplots()
1676 nrow, ncol = self.getSubplots()
1468
1677
1469 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1678 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1470
1679
1471
1680
1472 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1681 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1473 xmin=None, xmax=None, ymin=None, ymax=None,
1682 xmin=None, xmax=None, ymin=None, ymax=None,
1474 timerange=None,
1683 timerange=None,
1475 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1684 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1476 server=None, folder=None, username=None, password=None,
1685 server=None, folder=None, username=None, password=None,
1477 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1686 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1478
1687
1479
1688
1480 tmin = None
1689 tmin = None
1481 tmax = None
1690 tmax = None
1482 x = dataOut.getTimeRange1(dataOut.outputInterval)
1691 x = dataOut.getTimeRange1(dataOut.outputInterval)
1483 y = dataOut.getHeiRange()
1692 y = dataOut.getHeiRange()
1484
1693
1485
1694
1486 #thisDatetime = dataOut.datatime
1695 #thisDatetime = dataOut.datatime
1487 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1696 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1488 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1697 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1489 xlabel = "Local Time"
1698 xlabel = "Local Time"
1490 ylabel = "Phase"
1699 ylabel = "Phase"
1491
1700
1492
1701
1493 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1702 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1494 phase_beacon = dataOut.data_output
1703 phase_beacon = dataOut.data_output
1495 update_figfile = False
1704 update_figfile = False
1496
1705
1497 if not self.isConfig:
1706 if not self.isConfig:
1498
1707
1499 self.nplots = phase_beacon.size
1708 self.nplots = phase_beacon.size
1500
1709
1501 self.setup(id=id,
1710 self.setup(id=id,
1502 nplots=self.nplots,
1711 nplots=self.nplots,
1503 wintitle=wintitle,
1712 wintitle=wintitle,
1504 showprofile=showprofile,
1713 showprofile=showprofile,
1505 show=show)
1714 show=show)
1506
1715
1507 if timerange is not None:
1716 if timerange is not None:
1508 self.timerange = timerange
1717 self.timerange = timerange
1509
1718
1510 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1719 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1511
1720
1512 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1721 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1513 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1722 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1514
1723
1515 self.FTP_WEI = ftp_wei
1724 self.FTP_WEI = ftp_wei
1516 self.EXP_CODE = exp_code
1725 self.EXP_CODE = exp_code
1517 self.SUB_EXP_CODE = sub_exp_code
1726 self.SUB_EXP_CODE = sub_exp_code
1518 self.PLOT_POS = plot_pos
1727 self.PLOT_POS = plot_pos
1519
1728
1520 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1729 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1521 self.isConfig = True
1730 self.isConfig = True
1522 self.figfile = figfile
1731 self.figfile = figfile
1523 self.xdata = numpy.array([])
1732 self.xdata = numpy.array([])
1524 self.ydata = numpy.array([])
1733 self.ydata = numpy.array([])
1525
1734
1526 #open file beacon phase
1735 #open file beacon phase
1527 path = '%s%03d' %(self.PREFIX, self.id)
1736 path = '%s%03d' %(self.PREFIX, self.id)
1528 beacon_file = os.path.join(path,'%s.txt'%self.name)
1737 beacon_file = os.path.join(path,'%s.txt'%self.name)
1529 self.filename_phase = os.path.join(figpath,beacon_file)
1738 self.filename_phase = os.path.join(figpath,beacon_file)
1530 update_figfile = True
1739 update_figfile = True
1531
1740
1532
1741
1533 #store data beacon phase
1742 #store data beacon phase
1534 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1743 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1535
1744
1536 self.setWinTitle(title)
1745 self.setWinTitle(title)
1537
1746
1538
1747
1539 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1748 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1540
1749
1541 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1750 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1542
1751
1543 axes = self.axesList[0]
1752 axes = self.axesList[0]
1544
1753
1545 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1754 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1546
1755
1547 if len(self.ydata)==0:
1756 if len(self.ydata)==0:
1548 self.ydata = phase_beacon.reshape(-1,1)
1757 self.ydata = phase_beacon.reshape(-1,1)
1549 else:
1758 else:
1550 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1759 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1551
1760
1552
1761
1553 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1762 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1554 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1763 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1555 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1764 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1556 XAxisAsTime=True, grid='both'
1765 XAxisAsTime=True, grid='both'
1557 )
1766 )
1558
1767
1559 self.draw()
1768 self.draw()
1560
1769
1561 self.save(figpath=figpath,
1770 self.save(figpath=figpath,
1562 figfile=figfile,
1771 figfile=figfile,
1563 save=save,
1772 save=save,
1564 ftp=ftp,
1773 ftp=ftp,
1565 wr_period=wr_period,
1774 wr_period=wr_period,
1566 thisDatetime=thisDatetime,
1775 thisDatetime=thisDatetime,
1567 update_figfile=update_figfile)
1776 update_figfile=update_figfile)
1568
1777
1569 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1778 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1570 self.counter_imagwr = wr_period
1779 self.counter_imagwr = wr_period
1571 self.isConfig = False
1780 self.isConfig = False
1572 update_figfile = True
1781 update_figfile = True
1573
1782
1574
1783
1575
1784
1576 class NSMeteorDetection1Plot(Figure):
1785 class NSMeteorDetection1Plot(Figure):
1577
1786
1578 isConfig = None
1787 isConfig = None
1579 __nsubplots = None
1788 __nsubplots = None
1580
1789
1581 WIDTHPROF = None
1790 WIDTHPROF = None
1582 HEIGHTPROF = None
1791 HEIGHTPROF = None
1583 PREFIX = 'nsm'
1792 PREFIX = 'nsm'
1584
1793
1585 zminList = None
1794 zminList = None
1586 zmaxList = None
1795 zmaxList = None
1587 cmapList = None
1796 cmapList = None
1588 titleList = None
1797 titleList = None
1589 nPairs = None
1798 nPairs = None
1590 nChannels = None
1799 nChannels = None
1591 nParam = None
1800 nParam = None
1592
1801
1593 def __init__(self, **kwargs):
1802 def __init__(self, **kwargs):
1594 Figure.__init__(self, **kwargs)
1803 Figure.__init__(self, **kwargs)
1595 self.isConfig = False
1804 self.isConfig = False
1596 self.__nsubplots = 1
1805 self.__nsubplots = 1
1597
1806
1598 self.WIDTH = 750
1807 self.WIDTH = 750
1599 self.HEIGHT = 250
1808 self.HEIGHT = 250
1600 self.WIDTHPROF = 120
1809 self.WIDTHPROF = 120
1601 self.HEIGHTPROF = 0
1810 self.HEIGHTPROF = 0
1602 self.counter_imagwr = 0
1811 self.counter_imagwr = 0
1603
1812
1604 self.PLOT_CODE = SPEC_CODE
1813 self.PLOT_CODE = SPEC_CODE
1605
1814
1606 self.FTP_WEI = None
1815 self.FTP_WEI = None
1607 self.EXP_CODE = None
1816 self.EXP_CODE = None
1608 self.SUB_EXP_CODE = None
1817 self.SUB_EXP_CODE = None
1609 self.PLOT_POS = None
1818 self.PLOT_POS = None
1610
1819
1611 self.__xfilter_ena = False
1820 self.__xfilter_ena = False
1612 self.__yfilter_ena = False
1821 self.__yfilter_ena = False
1613
1822
1614 def getSubplots(self):
1823 def getSubplots(self):
1615
1824
1616 ncol = 3
1825 ncol = 3
1617 nrow = int(numpy.ceil(self.nplots/3.0))
1826 nrow = int(numpy.ceil(self.nplots/3.0))
1618
1827
1619 return nrow, ncol
1828 return nrow, ncol
1620
1829
1621 def setup(self, id, nplots, wintitle, show=True):
1830 def setup(self, id, nplots, wintitle, show=True):
1622
1831
1623 self.nplots = nplots
1832 self.nplots = nplots
1624
1833
1625 ncolspan = 1
1834 ncolspan = 1
1626 colspan = 1
1835 colspan = 1
1627
1836
1628 self.createFigure(id = id,
1837 self.createFigure(id = id,
1629 wintitle = wintitle,
1838 wintitle = wintitle,
1630 widthplot = self.WIDTH + self.WIDTHPROF,
1839 widthplot = self.WIDTH + self.WIDTHPROF,
1631 heightplot = self.HEIGHT + self.HEIGHTPROF,
1840 heightplot = self.HEIGHT + self.HEIGHTPROF,
1632 show=show)
1841 show=show)
1633
1842
1634 nrow, ncol = self.getSubplots()
1843 nrow, ncol = self.getSubplots()
1635
1844
1636 counter = 0
1845 counter = 0
1637 for y in range(nrow):
1846 for y in range(nrow):
1638 for x in range(ncol):
1847 for x in range(ncol):
1639
1848
1640 if counter >= self.nplots:
1849 if counter >= self.nplots:
1641 break
1850 break
1642
1851
1643 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1852 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1644
1853
1645 counter += 1
1854 counter += 1
1646
1855
1647 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1856 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1648 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1857 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1649 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1858 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1650 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1859 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1651 server=None, folder=None, username=None, password=None,
1860 server=None, folder=None, username=None, password=None,
1652 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1861 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1653 xaxis="frequency"):
1862 xaxis="frequency"):
1654
1863
1655 """
1864 """
1656
1865
1657 Input:
1866 Input:
1658 dataOut :
1867 dataOut :
1659 id :
1868 id :
1660 wintitle :
1869 wintitle :
1661 channelList :
1870 channelList :
1662 showProfile :
1871 showProfile :
1663 xmin : None,
1872 xmin : None,
1664 xmax : None,
1873 xmax : None,
1665 ymin : None,
1874 ymin : None,
1666 ymax : None,
1875 ymax : None,
1667 zmin : None,
1876 zmin : None,
1668 zmax : None
1877 zmax : None
1669 """
1878 """
1670 #SEPARAR EN DOS PLOTS
1879 #SEPARAR EN DOS PLOTS
1671 nParam = dataOut.data_param.shape[1] - 3
1880 nParam = dataOut.data_param.shape[1] - 3
1672
1881
1673 utctime = dataOut.data_param[0,0]
1882 utctime = dataOut.data_param[0,0]
1674 tmet = dataOut.data_param[:,1].astype(int)
1883 tmet = dataOut.data_param[:,1].astype(int)
1675 hmet = dataOut.data_param[:,2].astype(int)
1884 hmet = dataOut.data_param[:,2].astype(int)
1676
1885
1677 x = dataOut.abscissaList
1886 x = dataOut.abscissaList
1678 y = dataOut.heightList
1887 y = dataOut.heightList
1679
1888
1680 z = numpy.zeros((nParam, y.size, x.size - 1))
1889 z = numpy.zeros((nParam, y.size, x.size - 1))
1681 z[:,:] = numpy.nan
1890 z[:,:] = numpy.nan
1682 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1891 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1683 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1892 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1684
1893
1685 xlabel = "Time (s)"
1894 xlabel = "Time (s)"
1686 ylabel = "Range (km)"
1895 ylabel = "Range (km)"
1687
1896
1688 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1897 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1689
1898
1690 if not self.isConfig:
1899 if not self.isConfig:
1691
1900
1692 nplots = nParam
1901 nplots = nParam
1693
1902
1694 self.setup(id=id,
1903 self.setup(id=id,
1695 nplots=nplots,
1904 nplots=nplots,
1696 wintitle=wintitle,
1905 wintitle=wintitle,
1697 show=show)
1906 show=show)
1698
1907
1699 if xmin is None: xmin = numpy.nanmin(x)
1908 if xmin is None: xmin = numpy.nanmin(x)
1700 if xmax is None: xmax = numpy.nanmax(x)
1909 if xmax is None: xmax = numpy.nanmax(x)
1701 if ymin is None: ymin = numpy.nanmin(y)
1910 if ymin is None: ymin = numpy.nanmin(y)
1702 if ymax is None: ymax = numpy.nanmax(y)
1911 if ymax is None: ymax = numpy.nanmax(y)
1703 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1912 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1704 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1913 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1705 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1914 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1706 if vmin is None: vmin = -vmax
1915 if vmin is None: vmin = -vmax
1707 if wmin is None: wmin = 0
1916 if wmin is None: wmin = 0
1708 if wmax is None: wmax = 50
1917 if wmax is None: wmax = 50
1709
1918
1710 pairsList = dataOut.groupList
1919 pairsList = dataOut.groupList
1711 self.nPairs = len(dataOut.groupList)
1920 self.nPairs = len(dataOut.groupList)
1712
1921
1713 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1922 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1714 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1923 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1715 titleList = ["SNR","Radial Velocity","Coherence"]
1924 titleList = ["SNR","Radial Velocity","Coherence"]
1716 cmapList = ["jet","RdBu_r","jet"]
1925 cmapList = ["jet","RdBu_r","jet"]
1717
1926
1718 for i in range(self.nPairs):
1927 for i in range(self.nPairs):
1719 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1928 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1720 titleList = titleList + [strAux1]
1929 titleList = titleList + [strAux1]
1721 cmapList = cmapList + ["RdBu_r"]
1930 cmapList = cmapList + ["RdBu_r"]
1722
1931
1723 self.zminList = zminList
1932 self.zminList = zminList
1724 self.zmaxList = zmaxList
1933 self.zmaxList = zmaxList
1725 self.cmapList = cmapList
1934 self.cmapList = cmapList
1726 self.titleList = titleList
1935 self.titleList = titleList
1727
1936
1728 self.FTP_WEI = ftp_wei
1937 self.FTP_WEI = ftp_wei
1729 self.EXP_CODE = exp_code
1938 self.EXP_CODE = exp_code
1730 self.SUB_EXP_CODE = sub_exp_code
1939 self.SUB_EXP_CODE = sub_exp_code
1731 self.PLOT_POS = plot_pos
1940 self.PLOT_POS = plot_pos
1732
1941
1733 self.isConfig = True
1942 self.isConfig = True
1734
1943
1735 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1944 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1736
1945
1737 for i in range(nParam):
1946 for i in range(nParam):
1738 title = self.titleList[i] + ": " +str_datetime
1947 title = self.titleList[i] + ": " +str_datetime
1739 axes = self.axesList[i]
1948 axes = self.axesList[i]
1740 axes.pcolor(x, y, z[i,:].T,
1949 axes.pcolor(x, y, z[i,:].T,
1741 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1950 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1742 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1951 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1743 self.draw()
1952 self.draw()
1744
1953
1745 if figfile == None:
1954 if figfile == None:
1746 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1955 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1747 name = str_datetime
1956 name = str_datetime
1748 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1957 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1749 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1958 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1750 figfile = self.getFilename(name)
1959 figfile = self.getFilename(name)
1751
1960
1752 self.save(figpath=figpath,
1961 self.save(figpath=figpath,
1753 figfile=figfile,
1962 figfile=figfile,
1754 save=save,
1963 save=save,
1755 ftp=ftp,
1964 ftp=ftp,
1756 wr_period=wr_period,
1965 wr_period=wr_period,
1757 thisDatetime=thisDatetime)
1966 thisDatetime=thisDatetime)
1758
1967
1759
1968
1760 class NSMeteorDetection2Plot(Figure):
1969 class NSMeteorDetection2Plot(Figure):
1761
1970
1762 isConfig = None
1971 isConfig = None
1763 __nsubplots = None
1972 __nsubplots = None
1764
1973
1765 WIDTHPROF = None
1974 WIDTHPROF = None
1766 HEIGHTPROF = None
1975 HEIGHTPROF = None
1767 PREFIX = 'nsm'
1976 PREFIX = 'nsm'
1768
1977
1769 zminList = None
1978 zminList = None
1770 zmaxList = None
1979 zmaxList = None
1771 cmapList = None
1980 cmapList = None
1772 titleList = None
1981 titleList = None
1773 nPairs = None
1982 nPairs = None
1774 nChannels = None
1983 nChannels = None
1775 nParam = None
1984 nParam = None
1776
1985
1777 def __init__(self, **kwargs):
1986 def __init__(self, **kwargs):
1778 Figure.__init__(self, **kwargs)
1987 Figure.__init__(self, **kwargs)
1779 self.isConfig = False
1988 self.isConfig = False
1780 self.__nsubplots = 1
1989 self.__nsubplots = 1
1781
1990
1782 self.WIDTH = 750
1991 self.WIDTH = 750
1783 self.HEIGHT = 250
1992 self.HEIGHT = 250
1784 self.WIDTHPROF = 120
1993 self.WIDTHPROF = 120
1785 self.HEIGHTPROF = 0
1994 self.HEIGHTPROF = 0
1786 self.counter_imagwr = 0
1995 self.counter_imagwr = 0
1787
1996
1788 self.PLOT_CODE = SPEC_CODE
1997 self.PLOT_CODE = SPEC_CODE
1789
1998
1790 self.FTP_WEI = None
1999 self.FTP_WEI = None
1791 self.EXP_CODE = None
2000 self.EXP_CODE = None
1792 self.SUB_EXP_CODE = None
2001 self.SUB_EXP_CODE = None
1793 self.PLOT_POS = None
2002 self.PLOT_POS = None
1794
2003
1795 self.__xfilter_ena = False
2004 self.__xfilter_ena = False
1796 self.__yfilter_ena = False
2005 self.__yfilter_ena = False
1797
2006
1798 def getSubplots(self):
2007 def getSubplots(self):
1799
2008
1800 ncol = 3
2009 ncol = 3
1801 nrow = int(numpy.ceil(self.nplots/3.0))
2010 nrow = int(numpy.ceil(self.nplots/3.0))
1802
2011
1803 return nrow, ncol
2012 return nrow, ncol
1804
2013
1805 def setup(self, id, nplots, wintitle, show=True):
2014 def setup(self, id, nplots, wintitle, show=True):
1806
2015
1807 self.nplots = nplots
2016 self.nplots = nplots
1808
2017
1809 ncolspan = 1
2018 ncolspan = 1
1810 colspan = 1
2019 colspan = 1
1811
2020
1812 self.createFigure(id = id,
2021 self.createFigure(id = id,
1813 wintitle = wintitle,
2022 wintitle = wintitle,
1814 widthplot = self.WIDTH + self.WIDTHPROF,
2023 widthplot = self.WIDTH + self.WIDTHPROF,
1815 heightplot = self.HEIGHT + self.HEIGHTPROF,
2024 heightplot = self.HEIGHT + self.HEIGHTPROF,
1816 show=show)
2025 show=show)
1817
2026
1818 nrow, ncol = self.getSubplots()
2027 nrow, ncol = self.getSubplots()
1819
2028
1820 counter = 0
2029 counter = 0
1821 for y in range(nrow):
2030 for y in range(nrow):
1822 for x in range(ncol):
2031 for x in range(ncol):
1823
2032
1824 if counter >= self.nplots:
2033 if counter >= self.nplots:
1825 break
2034 break
1826
2035
1827 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
2036 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1828
2037
1829 counter += 1
2038 counter += 1
1830
2039
1831 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
2040 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1832 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
2041 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1833 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
2042 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1834 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
2043 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1835 server=None, folder=None, username=None, password=None,
2044 server=None, folder=None, username=None, password=None,
1836 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
2045 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1837 xaxis="frequency"):
2046 xaxis="frequency"):
1838
2047
1839 """
2048 """
1840
2049
1841 Input:
2050 Input:
1842 dataOut :
2051 dataOut :
1843 id :
2052 id :
1844 wintitle :
2053 wintitle :
1845 channelList :
2054 channelList :
1846 showProfile :
2055 showProfile :
1847 xmin : None,
2056 xmin : None,
1848 xmax : None,
2057 xmax : None,
1849 ymin : None,
2058 ymin : None,
1850 ymax : None,
2059 ymax : None,
1851 zmin : None,
2060 zmin : None,
1852 zmax : None
2061 zmax : None
1853 """
2062 """
1854 #Rebuild matrix
2063 #Rebuild matrix
1855 utctime = dataOut.data_param[0,0]
2064 utctime = dataOut.data_param[0,0]
1856 cmet = dataOut.data_param[:,1].astype(int)
2065 cmet = dataOut.data_param[:,1].astype(int)
1857 tmet = dataOut.data_param[:,2].astype(int)
2066 tmet = dataOut.data_param[:,2].astype(int)
1858 hmet = dataOut.data_param[:,3].astype(int)
2067 hmet = dataOut.data_param[:,3].astype(int)
1859
2068
1860 nParam = 3
2069 nParam = 3
1861 nChan = len(dataOut.groupList)
2070 nChan = len(dataOut.groupList)
1862 x = dataOut.abscissaList
2071 x = dataOut.abscissaList
1863 y = dataOut.heightList
2072 y = dataOut.heightList
1864
2073
1865 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
2074 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
1866 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
2075 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
1867 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
2076 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
1868 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
2077 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
1869
2078
1870 xlabel = "Time (s)"
2079 xlabel = "Time (s)"
1871 ylabel = "Range (km)"
2080 ylabel = "Range (km)"
1872
2081
1873 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
2082 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1874
2083
1875 if not self.isConfig:
2084 if not self.isConfig:
1876
2085
1877 nplots = nParam*nChan
2086 nplots = nParam*nChan
1878
2087
1879 self.setup(id=id,
2088 self.setup(id=id,
1880 nplots=nplots,
2089 nplots=nplots,
1881 wintitle=wintitle,
2090 wintitle=wintitle,
1882 show=show)
2091 show=show)
1883
2092
1884 if xmin is None: xmin = numpy.nanmin(x)
2093 if xmin is None: xmin = numpy.nanmin(x)
1885 if xmax is None: xmax = numpy.nanmax(x)
2094 if xmax is None: xmax = numpy.nanmax(x)
1886 if ymin is None: ymin = numpy.nanmin(y)
2095 if ymin is None: ymin = numpy.nanmin(y)
1887 if ymax is None: ymax = numpy.nanmax(y)
2096 if ymax is None: ymax = numpy.nanmax(y)
1888 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
2097 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1889 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
2098 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1890 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
2099 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1891 if vmin is None: vmin = -vmax
2100 if vmin is None: vmin = -vmax
1892 if wmin is None: wmin = 0
2101 if wmin is None: wmin = 0
1893 if wmax is None: wmax = 50
2102 if wmax is None: wmax = 50
1894
2103
1895 self.nChannels = nChan
2104 self.nChannels = nChan
1896
2105
1897 zminList = []
2106 zminList = []
1898 zmaxList = []
2107 zmaxList = []
1899 titleList = []
2108 titleList = []
1900 cmapList = []
2109 cmapList = []
1901 for i in range(self.nChannels):
2110 for i in range(self.nChannels):
1902 strAux1 = "SNR Channel "+ str(i)
2111 strAux1 = "SNR Channel "+ str(i)
1903 strAux2 = "Radial Velocity Channel "+ str(i)
2112 strAux2 = "Radial Velocity Channel "+ str(i)
1904 strAux3 = "Spectral Width Channel "+ str(i)
2113 strAux3 = "Spectral Width Channel "+ str(i)
1905
2114
1906 titleList = titleList + [strAux1,strAux2,strAux3]
2115 titleList = titleList + [strAux1,strAux2,strAux3]
1907 cmapList = cmapList + ["jet","RdBu_r","jet"]
2116 cmapList = cmapList + ["jet","RdBu_r","jet"]
1908 zminList = zminList + [SNRmin,vmin,wmin]
2117 zminList = zminList + [SNRmin,vmin,wmin]
1909 zmaxList = zmaxList + [SNRmax,vmax,wmax]
2118 zmaxList = zmaxList + [SNRmax,vmax,wmax]
1910
2119
1911 self.zminList = zminList
2120 self.zminList = zminList
1912 self.zmaxList = zmaxList
2121 self.zmaxList = zmaxList
1913 self.cmapList = cmapList
2122 self.cmapList = cmapList
1914 self.titleList = titleList
2123 self.titleList = titleList
1915
2124
1916 self.FTP_WEI = ftp_wei
2125 self.FTP_WEI = ftp_wei
1917 self.EXP_CODE = exp_code
2126 self.EXP_CODE = exp_code
1918 self.SUB_EXP_CODE = sub_exp_code
2127 self.SUB_EXP_CODE = sub_exp_code
1919 self.PLOT_POS = plot_pos
2128 self.PLOT_POS = plot_pos
1920
2129
1921 self.isConfig = True
2130 self.isConfig = True
1922
2131
1923 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
2132 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1924
2133
1925 for i in range(self.nplots):
2134 for i in range(self.nplots):
1926 title = self.titleList[i] + ": " +str_datetime
2135 title = self.titleList[i] + ": " +str_datetime
1927 axes = self.axesList[i]
2136 axes = self.axesList[i]
1928 axes.pcolor(x, y, z[i,:].T,
2137 axes.pcolor(x, y, z[i,:].T,
1929 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
2138 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1930 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
2139 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1931 self.draw()
2140 self.draw()
1932
2141
1933 if figfile == None:
2142 if figfile == None:
1934 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
2143 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1935 name = str_datetime
2144 name = str_datetime
1936 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
2145 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1937 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
2146 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1938 figfile = self.getFilename(name)
2147 figfile = self.getFilename(name)
1939
2148
1940 self.save(figpath=figpath,
2149 self.save(figpath=figpath,
1941 figfile=figfile,
2150 figfile=figfile,
1942 save=save,
2151 save=save,
1943 ftp=ftp,
2152 ftp=ftp,
1944 wr_period=wr_period,
2153 wr_period=wr_period,
1945 thisDatetime=thisDatetime)
2154 thisDatetime=thisDatetime)
@@ -1,1534 +1,1541
1 '''
1 '''
2 Created on Jul 9, 2014
2 Created on Jul 9, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import datetime
7 import datetime
8 import numpy
8 import numpy
9
9
10 from figure import Figure, isRealtime, isTimeInHourRange
10 from figure import Figure, isRealtime, isTimeInHourRange
11 from plotting_codes import *
11 from plotting_codes import *
12
12
13 class SpectraPlot(Figure):
13 class SpectraPlot(Figure):
14
14
15 isConfig = None
15 isConfig = None
16 __nsubplots = None
16 __nsubplots = None
17
17
18 WIDTHPROF = None
18 WIDTHPROF = None
19 HEIGHTPROF = None
19 HEIGHTPROF = None
20 PREFIX = 'spc'
20 PREFIX = 'spc'
21
21
22 def __init__(self, **kwargs):
22 def __init__(self, **kwargs):
23 Figure.__init__(self, **kwargs)
23 Figure.__init__(self, **kwargs)
24 self.isConfig = False
24 self.isConfig = False
25 self.__nsubplots = 1
25 self.__nsubplots = 1
26
26
27 self.WIDTH = 250
27 self.WIDTH = 250
28 self.HEIGHT = 250
28 self.HEIGHT = 250
29 self.WIDTHPROF = 120
29 self.WIDTHPROF = 120
30 self.HEIGHTPROF = 0
30 self.HEIGHTPROF = 0
31 self.counter_imagwr = 0
31 self.counter_imagwr = 0
32
32
33 self.PLOT_CODE = SPEC_CODE
33 self.PLOT_CODE = SPEC_CODE
34
34
35 self.FTP_WEI = None
35 self.FTP_WEI = None
36 self.EXP_CODE = None
36 self.EXP_CODE = None
37 self.SUB_EXP_CODE = None
37 self.SUB_EXP_CODE = None
38 self.PLOT_POS = None
38 self.PLOT_POS = None
39
39
40 self.__xfilter_ena = False
40 self.__xfilter_ena = False
41 self.__yfilter_ena = False
41 self.__yfilter_ena = False
42
42
43 def getSubplots(self):
43 def getSubplots(self):
44
44
45 ncol = int(numpy.sqrt(self.nplots)+0.9)
45 ncol = int(numpy.sqrt(self.nplots)+0.9)
46 nrow = int(self.nplots*1./ncol + 0.9)
46 nrow = int(self.nplots*1./ncol + 0.9)
47
47
48 return nrow, ncol
48 return nrow, ncol
49
49
50 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
50 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
51
51
52 self.__showprofile = showprofile
52 self.__showprofile = showprofile
53 self.nplots = nplots
53 self.nplots = nplots
54
54
55 ncolspan = 1
55 ncolspan = 1
56 colspan = 1
56 colspan = 1
57 if showprofile:
57 if showprofile:
58 ncolspan = 3
58 ncolspan = 3
59 colspan = 2
59 colspan = 2
60 self.__nsubplots = 2
60 self.__nsubplots = 2
61
61
62 self.createFigure(id = id,
62 self.createFigure(id = id,
63 wintitle = wintitle,
63 wintitle = wintitle,
64 widthplot = self.WIDTH + self.WIDTHPROF,
64 widthplot = self.WIDTH + self.WIDTHPROF,
65 heightplot = self.HEIGHT + self.HEIGHTPROF,
65 heightplot = self.HEIGHT + self.HEIGHTPROF,
66 show=show)
66 show=show)
67
67
68 nrow, ncol = self.getSubplots()
68 nrow, ncol = self.getSubplots()
69
69
70 counter = 0
70 counter = 0
71 for y in range(nrow):
71 for y in range(nrow):
72 for x in range(ncol):
72 for x in range(ncol):
73
73
74 if counter >= self.nplots:
74 if counter >= self.nplots:
75 break
75 break
76
76
77 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
77 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
78
78
79 if showprofile:
79 if showprofile:
80 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
80 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
81
81
82 counter += 1
82 counter += 1
83
83
84 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
84 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
85 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
85 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
86 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
86 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
87 server=None, folder=None, username=None, password=None,
87 server=None, folder=None, username=None, password=None,
88 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
88 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
89 xaxis="velocity", **kwargs):
89 xaxis="frequency", colormap='jet', normFactor=None):
90
90
91 """
91 """
92
92
93 Input:
93 Input:
94 dataOut :
94 dataOut :
95 id :
95 id :
96 wintitle :
96 wintitle :
97 channelList :
97 channelList :
98 showProfile :
98 showProfile :
99 xmin : None,
99 xmin : None,
100 xmax : None,
100 xmax : None,
101 ymin : None,
101 ymin : None,
102 ymax : None,
102 ymax : None,
103 zmin : None,
103 zmin : None,
104 zmax : None
104 zmax : None
105 """
105 """
106
107 colormap = kwargs.get('colormap','jet')
108
109 if realtime:
106 if realtime:
110 if not(isRealtime(utcdatatime = dataOut.utctime)):
107 if not(isRealtime(utcdatatime = dataOut.utctime)):
111 print 'Skipping this plot function'
108 print 'Skipping this plot function'
112 return
109 return
113
110
114 if channelList == None:
111 if channelList == None:
115 channelIndexList = dataOut.channelIndexList
112 channelIndexList = dataOut.channelIndexList
116 else:
113 else:
117 channelIndexList = []
114 channelIndexList = []
118 for channel in channelList:
115 for channel in channelList:
119 if channel not in dataOut.channelList:
116 if channel not in dataOut.channelList:
120 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
117 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
121 channelIndexList.append(dataOut.channelList.index(channel))
118 channelIndexList.append(dataOut.channelList.index(channel))
122
119
123 factor = dataOut.normFactor
120 if normFactor is None:
124
121 factor = dataOut.normFactor
122 else:
123 factor = normFactor
125 if xaxis == "frequency":
124 if xaxis == "frequency":
126 x = dataOut.getFreqRange(1)/1000.
125 x = dataOut.getFreqRange(1)/1000.
127 xlabel = "Frequency (kHz)"
126 xlabel = "Frequency (kHz)"
128
127
129 elif xaxis == "time":
128 elif xaxis == "time":
130 x = dataOut.getAcfRange(1)
129 x = dataOut.getAcfRange(1)
131 xlabel = "Time (ms)"
130 xlabel = "Time (ms)"
132
131
133 else:
132 else:
134 x = dataOut.getVelRange(1)
133 x = dataOut.getVelRange(1)
135 xlabel = "Velocity (m/s)"
134 xlabel = "Velocity (m/s)"
136
135
137 ylabel = "Range (Km)"
136 ylabel = "Range (Km)"
138
137
139 y = dataOut.getHeiRange()
138 y = dataOut.getHeiRange()
140
139
141 z = dataOut.data_spc/factor
140 z = dataOut.data_spc/factor
142 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
141 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
143 zdB = 10*numpy.log10(z)
142 zdB = 10*numpy.log10(z)
144
143
145 avg = numpy.average(z, axis=1)
144 avg = numpy.average(z, axis=1)
146 avgdB = 10*numpy.log10(avg)
145 avgdB = 10*numpy.log10(avg)
147
146
148 noise = dataOut.getNoise()/factor
147 noise = dataOut.getNoise()/factor
149 noisedB = 10*numpy.log10(noise)
148 noisedB = 10*numpy.log10(noise)
150
149
151 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
150 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
152 title = wintitle + " Spectra"
151 title = wintitle + " Spectra"
153 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
152 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
154 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
153 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
155
154
156 if not self.isConfig:
155 if not self.isConfig:
157
156
158 nplots = len(channelIndexList)
157 nplots = len(channelIndexList)
159
158
160 self.setup(id=id,
159 self.setup(id=id,
161 nplots=nplots,
160 nplots=nplots,
162 wintitle=wintitle,
161 wintitle=wintitle,
163 showprofile=showprofile,
162 showprofile=showprofile,
164 show=show)
163 show=show)
165
164
166 if xmin == None: xmin = numpy.nanmin(x)
165 if xmin == None: xmin = numpy.nanmin(x)
167 if xmax == None: xmax = numpy.nanmax(x)
166 if xmax == None: xmax = numpy.nanmax(x)
168 if ymin == None: ymin = numpy.nanmin(y)
167 if ymin == None: ymin = numpy.nanmin(y)
169 if ymax == None: ymax = numpy.nanmax(y)
168 if ymax == None: ymax = numpy.nanmax(y)
170 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
169 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
171 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
170 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
172
171
173 self.FTP_WEI = ftp_wei
172 self.FTP_WEI = ftp_wei
174 self.EXP_CODE = exp_code
173 self.EXP_CODE = exp_code
175 self.SUB_EXP_CODE = sub_exp_code
174 self.SUB_EXP_CODE = sub_exp_code
176 self.PLOT_POS = plot_pos
175 self.PLOT_POS = plot_pos
177
176
178 self.isConfig = True
177 self.isConfig = True
179
178
180 self.setWinTitle(title)
179 self.setWinTitle(title)
181
180
182 for i in range(self.nplots):
181 for i in range(self.nplots):
183 index = channelIndexList[i]
182 index = channelIndexList[i]
184 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
183 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
185 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
184 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
186 if len(dataOut.beam.codeList) != 0:
185 if len(dataOut.beam.codeList) != 0:
187 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
186 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
188
187
189 axes = self.axesList[i*self.__nsubplots]
188 axes = self.axesList[i*self.__nsubplots]
190 axes.pcolor(x, y, zdB[index,:,:],
189 axes.pcolor(x, y, zdB[index,:,:],
191 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
190 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
192 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
191 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
193 ticksize=9, cblabel='')
192 ticksize=9, cblabel='')
194
193
195 if self.__showprofile:
194 if self.__showprofile:
196 axes = self.axesList[i*self.__nsubplots +1]
195 axes = self.axesList[i*self.__nsubplots +1]
197 axes.pline(avgdB[index,:], y,
196 axes.pline(avgdB[index,:], y,
198 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
197 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
199 xlabel='dB', ylabel='', title='',
198 xlabel='dB', ylabel='', title='',
200 ytick_visible=False,
199 ytick_visible=False,
201 grid='x')
200 grid='x')
202
201
203 noiseline = numpy.repeat(noisedB[index], len(y))
202 noiseline = numpy.repeat(noisedB[index], len(y))
204 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
203 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
205
204
206 self.draw()
205 self.draw()
207
206
208 if figfile == None:
207 if figfile == None:
209 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
208 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
210 name = str_datetime
209 name = str_datetime
211 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
210 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
212 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
211 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
213 figfile = self.getFilename(name)
212 figfile = self.getFilename(name)
214
213
215 self.save(figpath=figpath,
214 self.save(figpath=figpath,
216 figfile=figfile,
215 figfile=figfile,
217 save=save,
216 save=save,
218 ftp=ftp,
217 ftp=ftp,
219 wr_period=wr_period,
218 wr_period=wr_period,
220 thisDatetime=thisDatetime)
219 thisDatetime=thisDatetime)
221
220
222 class CrossSpectraPlot(Figure):
221 class CrossSpectraPlot(Figure):
223
222
224 isConfig = None
223 isConfig = None
225 __nsubplots = None
224 __nsubplots = None
226
225
227 WIDTH = None
226 WIDTH = None
228 HEIGHT = None
227 HEIGHT = None
229 WIDTHPROF = None
228 WIDTHPROF = None
230 HEIGHTPROF = None
229 HEIGHTPROF = None
231 PREFIX = 'cspc'
230 PREFIX = 'cspc'
232
231
233 def __init__(self, **kwargs):
232 def __init__(self, **kwargs):
234 Figure.__init__(self, **kwargs)
233 Figure.__init__(self, **kwargs)
235 self.isConfig = False
234 self.isConfig = False
236 self.__nsubplots = 4
235 self.__nsubplots = 4
237 self.counter_imagwr = 0
236 self.counter_imagwr = 0
238 self.WIDTH = 250
237 self.WIDTH = 250
239 self.HEIGHT = 250
238 self.HEIGHT = 250
240 self.WIDTHPROF = 0
239 self.WIDTHPROF = 0
241 self.HEIGHTPROF = 0
240 self.HEIGHTPROF = 0
242
241
243 self.PLOT_CODE = CROSS_CODE
242 self.PLOT_CODE = CROSS_CODE
244 self.FTP_WEI = None
243 self.FTP_WEI = None
245 self.EXP_CODE = None
244 self.EXP_CODE = None
246 self.SUB_EXP_CODE = None
245 self.SUB_EXP_CODE = None
247 self.PLOT_POS = None
246 self.PLOT_POS = None
248
247
249 def getSubplots(self):
248 def getSubplots(self):
250
249
251 ncol = 4
250 ncol = 4
252 nrow = self.nplots
251 nrow = self.nplots
253
252
254 return nrow, ncol
253 return nrow, ncol
255
254
256 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
255 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
257
256
258 self.__showprofile = showprofile
257 self.__showprofile = showprofile
259 self.nplots = nplots
258 self.nplots = nplots
260
259
261 ncolspan = 1
260 ncolspan = 1
262 colspan = 1
261 colspan = 1
263
262
264 self.createFigure(id = id,
263 self.createFigure(id = id,
265 wintitle = wintitle,
264 wintitle = wintitle,
266 widthplot = self.WIDTH + self.WIDTHPROF,
265 widthplot = self.WIDTH + self.WIDTHPROF,
267 heightplot = self.HEIGHT + self.HEIGHTPROF,
266 heightplot = self.HEIGHT + self.HEIGHTPROF,
268 show=True)
267 show=True)
269
268
270 nrow, ncol = self.getSubplots()
269 nrow, ncol = self.getSubplots()
271
270
272 counter = 0
271 counter = 0
273 for y in range(nrow):
272 for y in range(nrow):
274 for x in range(ncol):
273 for x in range(ncol):
275 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
274 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
276
275
277 counter += 1
276 counter += 1
278
277
279 def run(self, dataOut, id, wintitle="", pairsList=None,
278 def run(self, dataOut, id, wintitle="", pairsList=None,
280 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
279 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
281 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
280 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
282 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
281 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
283 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
282 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
284 server=None, folder=None, username=None, password=None,
283 server=None, folder=None, username=None, password=None,
285 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0,
284 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None,
286 xaxis='frequency'):
285 xaxis='frequency'):
287
286
288 """
287 """
289
288
290 Input:
289 Input:
291 dataOut :
290 dataOut :
292 id :
291 id :
293 wintitle :
292 wintitle :
294 channelList :
293 channelList :
295 showProfile :
294 showProfile :
296 xmin : None,
295 xmin : None,
297 xmax : None,
296 xmax : None,
298 ymin : None,
297 ymin : None,
299 ymax : None,
298 ymax : None,
300 zmin : None,
299 zmin : None,
301 zmax : None
300 zmax : None
302 """
301 """
303
302
304 if pairsList == None:
303 if pairsList == None:
305 pairsIndexList = dataOut.pairsIndexList
304 pairsIndexList = dataOut.pairsIndexList
306 else:
305 else:
307 pairsIndexList = []
306 pairsIndexList = []
308 for pair in pairsList:
307 for pair in pairsList:
309 if pair not in dataOut.pairsList:
308 if pair not in dataOut.pairsList:
310 raise ValueError, "Pair %s is not in dataOut.pairsList" %str(pair)
309 raise ValueError, "Pair %s is not in dataOut.pairsList" %str(pair)
311 pairsIndexList.append(dataOut.pairsList.index(pair))
310 pairsIndexList.append(dataOut.pairsList.index(pair))
312
311
313 if not pairsIndexList:
312 if not pairsIndexList:
314 return
313 return
315
314
316 if len(pairsIndexList) > 4:
315 if len(pairsIndexList) > 4:
317 pairsIndexList = pairsIndexList[0:4]
316 pairsIndexList = pairsIndexList[0:4]
318
317
319 factor = dataOut.normFactor
318 if normFactor is None:
319 factor = dataOut.normFactor
320 else:
321 factor = normFactor
320 x = dataOut.getVelRange(1)
322 x = dataOut.getVelRange(1)
321 y = dataOut.getHeiRange()
323 y = dataOut.getHeiRange()
322 z = dataOut.data_spc[:,:,:]/factor
324 z = dataOut.data_spc[:,:,:]/factor
323 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
325 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
324
326
325 noise = dataOut.noise/factor
327 noise = dataOut.noise/factor
326
328
327 zdB = 10*numpy.log10(z)
329 zdB = 10*numpy.log10(z)
328 noisedB = 10*numpy.log10(noise)
330 noisedB = 10*numpy.log10(noise)
329
331
330 if coh_min == None:
332 if coh_min == None:
331 coh_min = 0.0
333 coh_min = 0.0
332 if coh_max == None:
334 if coh_max == None:
333 coh_max = 1.0
335 coh_max = 1.0
334
336
335 if phase_min == None:
337 if phase_min == None:
336 phase_min = -180
338 phase_min = -180
337 if phase_max == None:
339 if phase_max == None:
338 phase_max = 180
340 phase_max = 180
339
341
340 #thisDatetime = dataOut.datatime
342 #thisDatetime = dataOut.datatime
341 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
343 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
342 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
344 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
343 # xlabel = "Velocity (m/s)"
345 # xlabel = "Velocity (m/s)"
344 ylabel = "Range (Km)"
346 ylabel = "Range (Km)"
345
347
346 if xaxis == "frequency":
348 if xaxis == "frequency":
347 x = dataOut.getFreqRange(1)/1000.
349 x = dataOut.getFreqRange(1)/1000.
348 xlabel = "Frequency (kHz)"
350 xlabel = "Frequency (kHz)"
349
351
350 elif xaxis == "time":
352 elif xaxis == "time":
351 x = dataOut.getAcfRange(1)
353 x = dataOut.getAcfRange(1)
352 xlabel = "Time (ms)"
354 xlabel = "Time (ms)"
353
355
354 else:
356 else:
355 x = dataOut.getVelRange(1)
357 x = dataOut.getVelRange(1)
356 xlabel = "Velocity (m/s)"
358 xlabel = "Velocity (m/s)"
357
359
358 if not self.isConfig:
360 if not self.isConfig:
359
361
360 nplots = len(pairsIndexList)
362 nplots = len(pairsIndexList)
361
363
362 self.setup(id=id,
364 self.setup(id=id,
363 nplots=nplots,
365 nplots=nplots,
364 wintitle=wintitle,
366 wintitle=wintitle,
365 showprofile=False,
367 showprofile=False,
366 show=show)
368 show=show)
367
369
368 avg = numpy.abs(numpy.average(z, axis=1))
370 avg = numpy.abs(numpy.average(z, axis=1))
369 avgdB = 10*numpy.log10(avg)
371 avgdB = 10*numpy.log10(avg)
370
372
371 if xmin == None: xmin = numpy.nanmin(x)
373 if xmin == None: xmin = numpy.nanmin(x)
372 if xmax == None: xmax = numpy.nanmax(x)
374 if xmax == None: xmax = numpy.nanmax(x)
373 if ymin == None: ymin = numpy.nanmin(y)
375 if ymin == None: ymin = numpy.nanmin(y)
374 if ymax == None: ymax = numpy.nanmax(y)
376 if ymax == None: ymax = numpy.nanmax(y)
375 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
377 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
376 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
378 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
377
379
378 self.FTP_WEI = ftp_wei
380 self.FTP_WEI = ftp_wei
379 self.EXP_CODE = exp_code
381 self.EXP_CODE = exp_code
380 self.SUB_EXP_CODE = sub_exp_code
382 self.SUB_EXP_CODE = sub_exp_code
381 self.PLOT_POS = plot_pos
383 self.PLOT_POS = plot_pos
382
384
383 self.isConfig = True
385 self.isConfig = True
384
386
385 self.setWinTitle(title)
387 self.setWinTitle(title)
386
388
387 for i in range(self.nplots):
389 for i in range(self.nplots):
388 pair = dataOut.pairsList[pairsIndexList[i]]
390 pair = dataOut.pairsList[pairsIndexList[i]]
389
391
390 chan_index0 = dataOut.channelList.index(pair[0])
392 chan_index0 = dataOut.channelList.index(pair[0])
391 chan_index1 = dataOut.channelList.index(pair[1])
393 chan_index1 = dataOut.channelList.index(pair[1])
392
394
393 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
395 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
394 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
396 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
395 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
397 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
396 axes0 = self.axesList[i*self.__nsubplots]
398 axes0 = self.axesList[i*self.__nsubplots]
397 axes0.pcolor(x, y, zdB,
399 axes0.pcolor(x, y, zdB,
398 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
400 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
399 xlabel=xlabel, ylabel=ylabel, title=title,
401 xlabel=xlabel, ylabel=ylabel, title=title,
400 ticksize=9, colormap=power_cmap, cblabel='')
402 ticksize=9, colormap=power_cmap, cblabel='')
401
403
402 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
404 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
403 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
405 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
404 axes0 = self.axesList[i*self.__nsubplots+1]
406 axes0 = self.axesList[i*self.__nsubplots+1]
405 axes0.pcolor(x, y, zdB,
407 axes0.pcolor(x, y, zdB,
406 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
408 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
407 xlabel=xlabel, ylabel=ylabel, title=title,
409 xlabel=xlabel, ylabel=ylabel, title=title,
408 ticksize=9, colormap=power_cmap, cblabel='')
410 ticksize=9, colormap=power_cmap, cblabel='')
409
411
410 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:])
412 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:])
411 coherence = numpy.abs(coherenceComplex)
413 coherence = numpy.abs(coherenceComplex)
412 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
414 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
413 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
415 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
414
416
415 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
417 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
416 axes0 = self.axesList[i*self.__nsubplots+2]
418 axes0 = self.axesList[i*self.__nsubplots+2]
417 axes0.pcolor(x, y, coherence,
419 axes0.pcolor(x, y, coherence,
418 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
420 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
419 xlabel=xlabel, ylabel=ylabel, title=title,
421 xlabel=xlabel, ylabel=ylabel, title=title,
420 ticksize=9, colormap=coherence_cmap, cblabel='')
422 ticksize=9, colormap=coherence_cmap, cblabel='')
421
423
422 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
424 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
423 axes0 = self.axesList[i*self.__nsubplots+3]
425 axes0 = self.axesList[i*self.__nsubplots+3]
424 axes0.pcolor(x, y, phase,
426 axes0.pcolor(x, y, phase,
425 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
427 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
426 xlabel=xlabel, ylabel=ylabel, title=title,
428 xlabel=xlabel, ylabel=ylabel, title=title,
427 ticksize=9, colormap=phase_cmap, cblabel='')
429 ticksize=9, colormap=phase_cmap, cblabel='')
428
430
429
431
430
432
431 self.draw()
433 self.draw()
432
434
433 self.save(figpath=figpath,
435 self.save(figpath=figpath,
434 figfile=figfile,
436 figfile=figfile,
435 save=save,
437 save=save,
436 ftp=ftp,
438 ftp=ftp,
437 wr_period=wr_period,
439 wr_period=wr_period,
438 thisDatetime=thisDatetime)
440 thisDatetime=thisDatetime)
439
441
440
442
441 class RTIPlot(Figure):
443 class RTIPlot(Figure):
442
444
443 __isConfig = None
445 __isConfig = None
444 __nsubplots = None
446 __nsubplots = None
445
447
446 WIDTHPROF = None
448 WIDTHPROF = None
447 HEIGHTPROF = None
449 HEIGHTPROF = None
448 PREFIX = 'rti'
450 PREFIX = 'rti'
449
451
450 def __init__(self, **kwargs):
452 def __init__(self, **kwargs):
451
453
452 Figure.__init__(self, **kwargs)
454 Figure.__init__(self, **kwargs)
453 self.timerange = None
455 self.timerange = None
454 self.isConfig = False
456 self.isConfig = False
455 self.__nsubplots = 1
457 self.__nsubplots = 1
456
458
457 self.WIDTH = 800
459 self.WIDTH = 800
458 self.HEIGHT = 180
460 self.HEIGHT = 180
459 self.WIDTHPROF = 120
461 self.WIDTHPROF = 120
460 self.HEIGHTPROF = 0
462 self.HEIGHTPROF = 0
461 self.counter_imagwr = 0
463 self.counter_imagwr = 0
462
464
463 self.PLOT_CODE = RTI_CODE
465 self.PLOT_CODE = RTI_CODE
464
466
465 self.FTP_WEI = None
467 self.FTP_WEI = None
466 self.EXP_CODE = None
468 self.EXP_CODE = None
467 self.SUB_EXP_CODE = None
469 self.SUB_EXP_CODE = None
468 self.PLOT_POS = None
470 self.PLOT_POS = None
469 self.tmin = None
471 self.tmin = None
470 self.tmax = None
472 self.tmax = None
471
473
472 self.xmin = None
474 self.xmin = None
473 self.xmax = None
475 self.xmax = None
474
476
475 self.figfile = None
477 self.figfile = None
476
478
477 def getSubplots(self):
479 def getSubplots(self):
478
480
479 ncol = 1
481 ncol = 1
480 nrow = self.nplots
482 nrow = self.nplots
481
483
482 return nrow, ncol
484 return nrow, ncol
483
485
484 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
486 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
485
487
486 self.__showprofile = showprofile
488 self.__showprofile = showprofile
487 self.nplots = nplots
489 self.nplots = nplots
488
490
489 ncolspan = 1
491 ncolspan = 1
490 colspan = 1
492 colspan = 1
491 if showprofile:
493 if showprofile:
492 ncolspan = 7
494 ncolspan = 7
493 colspan = 6
495 colspan = 6
494 self.__nsubplots = 2
496 self.__nsubplots = 2
495
497
496 self.createFigure(id = id,
498 self.createFigure(id = id,
497 wintitle = wintitle,
499 wintitle = wintitle,
498 widthplot = self.WIDTH + self.WIDTHPROF,
500 widthplot = self.WIDTH + self.WIDTHPROF,
499 heightplot = self.HEIGHT + self.HEIGHTPROF,
501 heightplot = self.HEIGHT + self.HEIGHTPROF,
500 show=show)
502 show=show)
501
503
502 nrow, ncol = self.getSubplots()
504 nrow, ncol = self.getSubplots()
503
505
504 counter = 0
506 counter = 0
505 for y in range(nrow):
507 for y in range(nrow):
506 for x in range(ncol):
508 for x in range(ncol):
507
509
508 if counter >= self.nplots:
510 if counter >= self.nplots:
509 break
511 break
510
512
511 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
513 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
512
514
513 if showprofile:
515 if showprofile:
514 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
516 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
515
517
516 counter += 1
518 counter += 1
517
519
518 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
520 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
519 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
521 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
520 timerange=None,
522 timerange=None, colormap='jet',
521 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
523 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
522 server=None, folder=None, username=None, password=None,
524 server=None, folder=None, username=None, password=None,
523 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, **kwargs):
525 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None, HEIGHT=None):
524
526
525 """
527 """
526
528
527 Input:
529 Input:
528 dataOut :
530 dataOut :
529 id :
531 id :
530 wintitle :
532 wintitle :
531 channelList :
533 channelList :
532 showProfile :
534 showProfile :
533 xmin : None,
535 xmin : None,
534 xmax : None,
536 xmax : None,
535 ymin : None,
537 ymin : None,
536 ymax : None,
538 ymax : None,
537 zmin : None,
539 zmin : None,
538 zmax : None
540 zmax : None
539 """
541 """
540
542
541 colormap = kwargs.get('colormap', 'jet')
543 #colormap = kwargs.get('colormap', 'jet')
544 if HEIGHT is not None:
545 self.HEIGHT = HEIGHT
546
542 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
547 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
543 return
548 return
544
549
545 if channelList == None:
550 if channelList == None:
546 channelIndexList = dataOut.channelIndexList
551 channelIndexList = dataOut.channelIndexList
547 else:
552 else:
548 channelIndexList = []
553 channelIndexList = []
549 for channel in channelList:
554 for channel in channelList:
550 if channel not in dataOut.channelList:
555 if channel not in dataOut.channelList:
551 raise ValueError, "Channel %d is not in dataOut.channelList"
556 raise ValueError, "Channel %d is not in dataOut.channelList"
552 channelIndexList.append(dataOut.channelList.index(channel))
557 channelIndexList.append(dataOut.channelList.index(channel))
553
558
554 if hasattr(dataOut, 'normFactor'):
559 if normFactor is None:
555 factor = dataOut.normFactor
560 factor = dataOut.normFactor
556 else:
561 else:
557 factor = 1
562 factor = normFactor
558
563
559 # factor = dataOut.normFactor
564 # factor = dataOut.normFactor
560 x = dataOut.getTimeRange()
565 x = dataOut.getTimeRange()
561 y = dataOut.getHeiRange()
566 y = dataOut.getHeiRange()
562
567
563 # z = dataOut.data_spc/factor
568 z = dataOut.data_spc/factor
564 # z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
569 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
565 # avg = numpy.average(z, axis=1)
570 avg = numpy.average(z, axis=1)
566 # avgdB = 10.*numpy.log10(avg)
571 avgdB = 10.*numpy.log10(avg)
567 avgdB = dataOut.getPower()
572 # avgdB = dataOut.getPower()
573
568
574
569 thisDatetime = dataOut.datatime
575 thisDatetime = dataOut.datatime
570 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
576 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
571 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
577 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
572 xlabel = ""
578 xlabel = ""
573 ylabel = "Range (Km)"
579 ylabel = "Range (Km)"
574
580
575 update_figfile = False
581 update_figfile = False
576
582
577 if dataOut.ltctime >= self.xmax:
583 if dataOut.ltctime >= self.xmax:
578 self.counter_imagwr = wr_period
584 self.counter_imagwr = wr_period
579 self.isConfig = False
585 self.isConfig = False
580 update_figfile = True
586 update_figfile = True
581
587
582 if not self.isConfig:
588 if not self.isConfig:
583
589
584 nplots = len(channelIndexList)
590 nplots = len(channelIndexList)
585
591
586 self.setup(id=id,
592 self.setup(id=id,
587 nplots=nplots,
593 nplots=nplots,
588 wintitle=wintitle,
594 wintitle=wintitle,
589 showprofile=showprofile,
595 showprofile=showprofile,
590 show=show)
596 show=show)
591
597
592 if timerange != None:
598 if timerange != None:
593 self.timerange = timerange
599 self.timerange = timerange
594
600
595 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
601 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
596
602
597 noise = dataOut.noise/factor
603 noise = dataOut.noise/factor
598 noisedB = 10*numpy.log10(noise)
604 noisedB = 10*numpy.log10(noise)
599
605
600 if ymin == None: ymin = numpy.nanmin(y)
606 if ymin == None: ymin = numpy.nanmin(y)
601 if ymax == None: ymax = numpy.nanmax(y)
607 if ymax == None: ymax = numpy.nanmax(y)
602 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
608 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
603 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
609 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
604
610
605 self.FTP_WEI = ftp_wei
611 self.FTP_WEI = ftp_wei
606 self.EXP_CODE = exp_code
612 self.EXP_CODE = exp_code
607 self.SUB_EXP_CODE = sub_exp_code
613 self.SUB_EXP_CODE = sub_exp_code
608 self.PLOT_POS = plot_pos
614 self.PLOT_POS = plot_pos
609
615
610 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
616 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
611 self.isConfig = True
617 self.isConfig = True
612 self.figfile = figfile
618 self.figfile = figfile
613 update_figfile = True
619 update_figfile = True
614
620
615 self.setWinTitle(title)
621 self.setWinTitle(title)
616
622
617 for i in range(self.nplots):
623 for i in range(self.nplots):
618 index = channelIndexList[i]
624 index = channelIndexList[i]
619 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
625 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
620 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
626 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
621 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
627 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
622 axes = self.axesList[i*self.__nsubplots]
628 axes = self.axesList[i*self.__nsubplots]
623 zdB = avgdB[index].reshape((1,-1))
629 zdB = avgdB[index].reshape((1,-1))
624 axes.pcolorbuffer(x, y, zdB,
630 axes.pcolorbuffer(x, y, zdB,
625 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
631 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
626 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
632 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
627 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
633 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
628
634
629 if self.__showprofile:
635 if self.__showprofile:
630 axes = self.axesList[i*self.__nsubplots +1]
636 axes = self.axesList[i*self.__nsubplots +1]
631 axes.pline(avgdB[index], y,
637 axes.pline(avgdB[index], y,
632 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
638 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
633 xlabel='dB', ylabel='', title='',
639 xlabel='dB', ylabel='', title='',
634 ytick_visible=False,
640 ytick_visible=False,
635 grid='x')
641 grid='x')
636
642
637 self.draw()
643 self.draw()
638
644
639 self.save(figpath=figpath,
645 self.save(figpath=figpath,
640 figfile=figfile,
646 figfile=figfile,
641 save=save,
647 save=save,
642 ftp=ftp,
648 ftp=ftp,
643 wr_period=wr_period,
649 wr_period=wr_period,
644 thisDatetime=thisDatetime,
650 thisDatetime=thisDatetime,
645 update_figfile=update_figfile)
651 update_figfile=update_figfile)
646
652
647 class CoherenceMap(Figure):
653 class CoherenceMap(Figure):
648 isConfig = None
654 isConfig = None
649 __nsubplots = None
655 __nsubplots = None
650
656
651 WIDTHPROF = None
657 WIDTHPROF = None
652 HEIGHTPROF = None
658 HEIGHTPROF = None
653 PREFIX = 'cmap'
659 PREFIX = 'cmap'
654
660
655 def __init__(self, **kwargs):
661 def __init__(self, **kwargs):
656 Figure.__init__(self, **kwargs)
662 Figure.__init__(self, **kwargs)
657 self.timerange = 2*60*60
663 self.timerange = 2*60*60
658 self.isConfig = False
664 self.isConfig = False
659 self.__nsubplots = 1
665 self.__nsubplots = 1
660
666
661 self.WIDTH = 800
667 self.WIDTH = 800
662 self.HEIGHT = 180
668 self.HEIGHT = 180
663 self.WIDTHPROF = 120
669 self.WIDTHPROF = 120
664 self.HEIGHTPROF = 0
670 self.HEIGHTPROF = 0
665 self.counter_imagwr = 0
671 self.counter_imagwr = 0
666
672
667 self.PLOT_CODE = COH_CODE
673 self.PLOT_CODE = COH_CODE
668
674
669 self.FTP_WEI = None
675 self.FTP_WEI = None
670 self.EXP_CODE = None
676 self.EXP_CODE = None
671 self.SUB_EXP_CODE = None
677 self.SUB_EXP_CODE = None
672 self.PLOT_POS = None
678 self.PLOT_POS = None
673 self.counter_imagwr = 0
679 self.counter_imagwr = 0
674
680
675 self.xmin = None
681 self.xmin = None
676 self.xmax = None
682 self.xmax = None
677
683
678 def getSubplots(self):
684 def getSubplots(self):
679 ncol = 1
685 ncol = 1
680 nrow = self.nplots*2
686 nrow = self.nplots*2
681
687
682 return nrow, ncol
688 return nrow, ncol
683
689
684 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
690 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
685 self.__showprofile = showprofile
691 self.__showprofile = showprofile
686 self.nplots = nplots
692 self.nplots = nplots
687
693
688 ncolspan = 1
694 ncolspan = 1
689 colspan = 1
695 colspan = 1
690 if showprofile:
696 if showprofile:
691 ncolspan = 7
697 ncolspan = 7
692 colspan = 6
698 colspan = 6
693 self.__nsubplots = 2
699 self.__nsubplots = 2
694
700
695 self.createFigure(id = id,
701 self.createFigure(id = id,
696 wintitle = wintitle,
702 wintitle = wintitle,
697 widthplot = self.WIDTH + self.WIDTHPROF,
703 widthplot = self.WIDTH + self.WIDTHPROF,
698 heightplot = self.HEIGHT + self.HEIGHTPROF,
704 heightplot = self.HEIGHT + self.HEIGHTPROF,
699 show=True)
705 show=True)
700
706
701 nrow, ncol = self.getSubplots()
707 nrow, ncol = self.getSubplots()
702
708
703 for y in range(nrow):
709 for y in range(nrow):
704 for x in range(ncol):
710 for x in range(ncol):
705
711
706 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
712 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
707
713
708 if showprofile:
714 if showprofile:
709 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
715 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
710
716
711 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
717 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
712 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
718 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
713 timerange=None, phase_min=None, phase_max=None,
719 timerange=None, phase_min=None, phase_max=None,
714 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
720 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
715 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
721 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
716 server=None, folder=None, username=None, password=None,
722 server=None, folder=None, username=None, password=None,
717 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
723 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
718
724
719 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
725 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
720 return
726 return
721
727
722 if pairsList == None:
728 if pairsList == None:
723 pairsIndexList = dataOut.pairsIndexList
729 pairsIndexList = dataOut.pairsIndexList
724 else:
730 else:
725 pairsIndexList = []
731 pairsIndexList = []
726 for pair in pairsList:
732 for pair in pairsList:
727 if pair not in dataOut.pairsList:
733 if pair not in dataOut.pairsList:
728 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
734 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
729 pairsIndexList.append(dataOut.pairsList.index(pair))
735 pairsIndexList.append(dataOut.pairsList.index(pair))
730
736
731 if pairsIndexList == []:
737 if pairsIndexList == []:
732 return
738 return
733
739
734 if len(pairsIndexList) > 4:
740 if len(pairsIndexList) > 4:
735 pairsIndexList = pairsIndexList[0:4]
741 pairsIndexList = pairsIndexList[0:4]
736
742
737 if phase_min == None:
743 if phase_min == None:
738 phase_min = -180
744 phase_min = -180
739 if phase_max == None:
745 if phase_max == None:
740 phase_max = 180
746 phase_max = 180
741
747
742 x = dataOut.getTimeRange()
748 x = dataOut.getTimeRange()
743 y = dataOut.getHeiRange()
749 y = dataOut.getHeiRange()
744
750
745 thisDatetime = dataOut.datatime
751 thisDatetime = dataOut.datatime
746
752
747 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
753 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
748 xlabel = ""
754 xlabel = ""
749 ylabel = "Range (Km)"
755 ylabel = "Range (Km)"
750 update_figfile = False
756 update_figfile = False
751
757
752 if not self.isConfig:
758 if not self.isConfig:
753 nplots = len(pairsIndexList)
759 nplots = len(pairsIndexList)
754 self.setup(id=id,
760 self.setup(id=id,
755 nplots=nplots,
761 nplots=nplots,
756 wintitle=wintitle,
762 wintitle=wintitle,
757 showprofile=showprofile,
763 showprofile=showprofile,
758 show=show)
764 show=show)
759
765
760 if timerange != None:
766 if timerange != None:
761 self.timerange = timerange
767 self.timerange = timerange
762
768
763 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
769 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
764
770
765 if ymin == None: ymin = numpy.nanmin(y)
771 if ymin == None: ymin = numpy.nanmin(y)
766 if ymax == None: ymax = numpy.nanmax(y)
772 if ymax == None: ymax = numpy.nanmax(y)
767 if zmin == None: zmin = 0.
773 if zmin == None: zmin = 0.
768 if zmax == None: zmax = 1.
774 if zmax == None: zmax = 1.
769
775
770 self.FTP_WEI = ftp_wei
776 self.FTP_WEI = ftp_wei
771 self.EXP_CODE = exp_code
777 self.EXP_CODE = exp_code
772 self.SUB_EXP_CODE = sub_exp_code
778 self.SUB_EXP_CODE = sub_exp_code
773 self.PLOT_POS = plot_pos
779 self.PLOT_POS = plot_pos
774
780
775 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
781 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
776
782
777 self.isConfig = True
783 self.isConfig = True
778 update_figfile = True
784 update_figfile = True
779
785
780 self.setWinTitle(title)
786 self.setWinTitle(title)
781
787
782 for i in range(self.nplots):
788 for i in range(self.nplots):
783
789
784 pair = dataOut.pairsList[pairsIndexList[i]]
790 pair = dataOut.pairsList[pairsIndexList[i]]
785
791
786 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
792 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
787 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
793 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
788 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
794 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
789
795
790
796
791 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
797 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
792 coherence = numpy.abs(avgcoherenceComplex)
798 coherence = numpy.abs(avgcoherenceComplex)
793
799
794 z = coherence.reshape((1,-1))
800 z = coherence.reshape((1,-1))
795
801
796 counter = 0
802 counter = 0
797
803
798 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
804 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
799 axes = self.axesList[i*self.__nsubplots*2]
805 axes = self.axesList[i*self.__nsubplots*2]
800 axes.pcolorbuffer(x, y, z,
806 axes.pcolorbuffer(x, y, z,
801 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
807 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
802 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
808 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
803 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
809 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
804
810
805 if self.__showprofile:
811 if self.__showprofile:
806 counter += 1
812 counter += 1
807 axes = self.axesList[i*self.__nsubplots*2 + counter]
813 axes = self.axesList[i*self.__nsubplots*2 + counter]
808 axes.pline(coherence, y,
814 axes.pline(coherence, y,
809 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
815 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
810 xlabel='', ylabel='', title='', ticksize=7,
816 xlabel='', ylabel='', title='', ticksize=7,
811 ytick_visible=False, nxticks=5,
817 ytick_visible=False, nxticks=5,
812 grid='x')
818 grid='x')
813
819
814 counter += 1
820 counter += 1
815
821
816 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
822 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
817
823
818 z = phase.reshape((1,-1))
824 z = phase.reshape((1,-1))
819
825
820 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
826 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
821 axes = self.axesList[i*self.__nsubplots*2 + counter]
827 axes = self.axesList[i*self.__nsubplots*2 + counter]
822 axes.pcolorbuffer(x, y, z,
828 axes.pcolorbuffer(x, y, z,
823 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
829 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
824 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
830 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
825 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
831 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
826
832
827 if self.__showprofile:
833 if self.__showprofile:
828 counter += 1
834 counter += 1
829 axes = self.axesList[i*self.__nsubplots*2 + counter]
835 axes = self.axesList[i*self.__nsubplots*2 + counter]
830 axes.pline(phase, y,
836 axes.pline(phase, y,
831 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
837 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
832 xlabel='', ylabel='', title='', ticksize=7,
838 xlabel='', ylabel='', title='', ticksize=7,
833 ytick_visible=False, nxticks=4,
839 ytick_visible=False, nxticks=4,
834 grid='x')
840 grid='x')
835
841
836 self.draw()
842 self.draw()
837
843
838 if dataOut.ltctime >= self.xmax:
844 if dataOut.ltctime >= self.xmax:
839 self.counter_imagwr = wr_period
845 self.counter_imagwr = wr_period
840 self.isConfig = False
846 self.isConfig = False
841 update_figfile = True
847 update_figfile = True
842
848
843 self.save(figpath=figpath,
849 self.save(figpath=figpath,
844 figfile=figfile,
850 figfile=figfile,
845 save=save,
851 save=save,
846 ftp=ftp,
852 ftp=ftp,
847 wr_period=wr_period,
853 wr_period=wr_period,
848 thisDatetime=thisDatetime,
854 thisDatetime=thisDatetime,
849 update_figfile=update_figfile)
855 update_figfile=update_figfile)
850
856
851 class PowerProfilePlot(Figure):
857 class PowerProfilePlot(Figure):
852
858
853 isConfig = None
859 isConfig = None
854 __nsubplots = None
860 __nsubplots = None
855
861
856 WIDTHPROF = None
862 WIDTHPROF = None
857 HEIGHTPROF = None
863 HEIGHTPROF = None
858 PREFIX = 'spcprofile'
864 PREFIX = 'spcprofile'
859
865
860 def __init__(self, **kwargs):
866 def __init__(self, **kwargs):
861 Figure.__init__(self, **kwargs)
867 Figure.__init__(self, **kwargs)
862 self.isConfig = False
868 self.isConfig = False
863 self.__nsubplots = 1
869 self.__nsubplots = 1
864
870
865 self.PLOT_CODE = POWER_CODE
871 self.PLOT_CODE = POWER_CODE
866
872
867 self.WIDTH = 300
873 self.WIDTH = 300
868 self.HEIGHT = 500
874 self.HEIGHT = 500
869 self.counter_imagwr = 0
875 self.counter_imagwr = 0
870
876
871 def getSubplots(self):
877 def getSubplots(self):
872 ncol = 1
878 ncol = 1
873 nrow = 1
879 nrow = 1
874
880
875 return nrow, ncol
881 return nrow, ncol
876
882
877 def setup(self, id, nplots, wintitle, show):
883 def setup(self, id, nplots, wintitle, show):
878
884
879 self.nplots = nplots
885 self.nplots = nplots
880
886
881 ncolspan = 1
887 ncolspan = 1
882 colspan = 1
888 colspan = 1
883
889
884 self.createFigure(id = id,
890 self.createFigure(id = id,
885 wintitle = wintitle,
891 wintitle = wintitle,
886 widthplot = self.WIDTH,
892 widthplot = self.WIDTH,
887 heightplot = self.HEIGHT,
893 heightplot = self.HEIGHT,
888 show=show)
894 show=show)
889
895
890 nrow, ncol = self.getSubplots()
896 nrow, ncol = self.getSubplots()
891
897
892 counter = 0
898 counter = 0
893 for y in range(nrow):
899 for y in range(nrow):
894 for x in range(ncol):
900 for x in range(ncol):
895 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
901 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
896
902
897 def run(self, dataOut, id, wintitle="", channelList=None,
903 def run(self, dataOut, id, wintitle="", channelList=None,
898 xmin=None, xmax=None, ymin=None, ymax=None,
904 xmin=None, xmax=None, ymin=None, ymax=None,
899 save=False, figpath='./', figfile=None, show=True,
905 save=False, figpath='./', figfile=None, show=True,
900 ftp=False, wr_period=1, server=None,
906 ftp=False, wr_period=1, server=None,
901 folder=None, username=None, password=None):
907 folder=None, username=None, password=None):
902
908
903
909
904 if channelList == None:
910 if channelList == None:
905 channelIndexList = dataOut.channelIndexList
911 channelIndexList = dataOut.channelIndexList
906 channelList = dataOut.channelList
912 channelList = dataOut.channelList
907 else:
913 else:
908 channelIndexList = []
914 channelIndexList = []
909 for channel in channelList:
915 for channel in channelList:
910 if channel not in dataOut.channelList:
916 if channel not in dataOut.channelList:
911 raise ValueError, "Channel %d is not in dataOut.channelList"
917 raise ValueError, "Channel %d is not in dataOut.channelList"
912 channelIndexList.append(dataOut.channelList.index(channel))
918 channelIndexList.append(dataOut.channelList.index(channel))
913
919
914 factor = dataOut.normFactor
920 factor = dataOut.normFactor
915
921
916 y = dataOut.getHeiRange()
922 y = dataOut.getHeiRange()
917
923
918 #for voltage
924 #for voltage
919 if dataOut.type == 'Voltage':
925 if dataOut.type == 'Voltage':
920 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
926 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
921 x = x.real
927 x = x.real
922 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
928 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
923
929
924 #for spectra
930 #for spectra
925 if dataOut.type == 'Spectra':
931 if dataOut.type == 'Spectra':
926 x = dataOut.data_spc[channelIndexList,:,:]/factor
932 x = dataOut.data_spc[channelIndexList,:,:]/factor
927 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
933 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
928 x = numpy.average(x, axis=1)
934 x = numpy.average(x, axis=1)
929
935
930
936
931 xdB = 10*numpy.log10(x)
937 xdB = 10*numpy.log10(x)
932
938
933 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
939 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
934 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
940 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
935 xlabel = "dB"
941 xlabel = "dB"
936 ylabel = "Range (Km)"
942 ylabel = "Range (Km)"
937
943
938 if not self.isConfig:
944 if not self.isConfig:
939
945
940 nplots = 1
946 nplots = 1
941
947
942 self.setup(id=id,
948 self.setup(id=id,
943 nplots=nplots,
949 nplots=nplots,
944 wintitle=wintitle,
950 wintitle=wintitle,
945 show=show)
951 show=show)
946
952
947 if ymin == None: ymin = numpy.nanmin(y)
953 if ymin == None: ymin = numpy.nanmin(y)
948 if ymax == None: ymax = numpy.nanmax(y)
954 if ymax == None: ymax = numpy.nanmax(y)
949 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
955 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
950 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
956 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
951
957
952 self.isConfig = True
958 self.isConfig = True
953
959
954 self.setWinTitle(title)
960 self.setWinTitle(title)
955
961
956 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
962 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
957 axes = self.axesList[0]
963 axes = self.axesList[0]
958
964
959 legendlabels = ["channel %d"%x for x in channelList]
965 legendlabels = ["channel %d"%x for x in channelList]
960 axes.pmultiline(xdB, y,
966 axes.pmultiline(xdB, y,
961 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
967 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
962 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
968 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
963 ytick_visible=True, nxticks=5,
969 ytick_visible=True, nxticks=5,
964 grid='x')
970 grid='x')
965
971
966 self.draw()
972 self.draw()
967
973
968 self.save(figpath=figpath,
974 self.save(figpath=figpath,
969 figfile=figfile,
975 figfile=figfile,
970 save=save,
976 save=save,
971 ftp=ftp,
977 ftp=ftp,
972 wr_period=wr_period,
978 wr_period=wr_period,
973 thisDatetime=thisDatetime)
979 thisDatetime=thisDatetime)
974
980
975 class SpectraCutPlot(Figure):
981 class SpectraCutPlot(Figure):
976
982
977 isConfig = None
983 isConfig = None
978 __nsubplots = None
984 __nsubplots = None
979
985
980 WIDTHPROF = None
986 WIDTHPROF = None
981 HEIGHTPROF = None
987 HEIGHTPROF = None
982 PREFIX = 'spc_cut'
988 PREFIX = 'spc_cut'
983
989
984 def __init__(self, **kwargs):
990 def __init__(self, **kwargs):
985 Figure.__init__(self, **kwargs)
991 Figure.__init__(self, **kwargs)
986 self.isConfig = False
992 self.isConfig = False
987 self.__nsubplots = 1
993 self.__nsubplots = 1
988
994
989 self.PLOT_CODE = POWER_CODE
995 self.PLOT_CODE = POWER_CODE
990
996
991 self.WIDTH = 700
997 self.WIDTH = 700
992 self.HEIGHT = 500
998 self.HEIGHT = 500
993 self.counter_imagwr = 0
999 self.counter_imagwr = 0
994
1000
995 def getSubplots(self):
1001 def getSubplots(self):
996 ncol = 1
1002 ncol = 1
997 nrow = 1
1003 nrow = 1
998
1004
999 return nrow, ncol
1005 return nrow, ncol
1000
1006
1001 def setup(self, id, nplots, wintitle, show):
1007 def setup(self, id, nplots, wintitle, show):
1002
1008
1003 self.nplots = nplots
1009 self.nplots = nplots
1004
1010
1005 ncolspan = 1
1011 ncolspan = 1
1006 colspan = 1
1012 colspan = 1
1007
1013
1008 self.createFigure(id = id,
1014 self.createFigure(id = id,
1009 wintitle = wintitle,
1015 wintitle = wintitle,
1010 widthplot = self.WIDTH,
1016 widthplot = self.WIDTH,
1011 heightplot = self.HEIGHT,
1017 heightplot = self.HEIGHT,
1012 show=show)
1018 show=show)
1013
1019
1014 nrow, ncol = self.getSubplots()
1020 nrow, ncol = self.getSubplots()
1015
1021
1016 counter = 0
1022 counter = 0
1017 for y in range(nrow):
1023 for y in range(nrow):
1018 for x in range(ncol):
1024 for x in range(ncol):
1019 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1025 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1020
1026
1021 def run(self, dataOut, id, wintitle="", channelList=None,
1027 def run(self, dataOut, id, wintitle="", channelList=None,
1022 xmin=None, xmax=None, ymin=None, ymax=None,
1028 xmin=None, xmax=None, ymin=None, ymax=None,
1023 save=False, figpath='./', figfile=None, show=True,
1029 save=False, figpath='./', figfile=None, show=True,
1024 ftp=False, wr_period=1, server=None,
1030 ftp=False, wr_period=1, server=None,
1025 folder=None, username=None, password=None,
1031 folder=None, username=None, password=None,
1026 xaxis="frequency"):
1032 xaxis="frequency"):
1027
1033
1028
1034
1029 if channelList == None:
1035 if channelList == None:
1030 channelIndexList = dataOut.channelIndexList
1036 channelIndexList = dataOut.channelIndexList
1031 channelList = dataOut.channelList
1037 channelList = dataOut.channelList
1032 else:
1038 else:
1033 channelIndexList = []
1039 channelIndexList = []
1034 for channel in channelList:
1040 for channel in channelList:
1035 if channel not in dataOut.channelList:
1041 if channel not in dataOut.channelList:
1036 raise ValueError, "Channel %d is not in dataOut.channelList"
1042 raise ValueError, "Channel %d is not in dataOut.channelList"
1037 channelIndexList.append(dataOut.channelList.index(channel))
1043 channelIndexList.append(dataOut.channelList.index(channel))
1038
1044
1039 factor = dataOut.normFactor
1045 factor = dataOut.normFactor
1040
1046
1041 y = dataOut.getHeiRange()
1047 y = dataOut.getHeiRange()
1042
1048
1043 z = dataOut.data_spc/factor
1049 z = dataOut.data_spc/factor
1044 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1050 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1045
1051
1046 hei_index = numpy.arange(25)*3 + 20
1052 hei_index = numpy.arange(25)*3 + 20
1047
1053
1048 if xaxis == "frequency":
1054 if xaxis == "frequency":
1049 x = dataOut.getFreqRange()/1000.
1055 x = dataOut.getFreqRange()/1000.
1050 zdB = 10*numpy.log10(z[0,:,hei_index])
1056 zdB = 10*numpy.log10(z[0,:,hei_index])
1051 xlabel = "Frequency (kHz)"
1057 xlabel = "Frequency (kHz)"
1052 ylabel = "Power (dB)"
1058 ylabel = "Power (dB)"
1053
1059
1054 elif xaxis == "time":
1060 elif xaxis == "time":
1055 x = dataOut.getAcfRange()
1061 x = dataOut.getAcfRange()
1056 zdB = z[0,:,hei_index]
1062 zdB = z[0,:,hei_index]
1057 xlabel = "Time (ms)"
1063 xlabel = "Time (ms)"
1058 ylabel = "ACF"
1064 ylabel = "ACF"
1059
1065
1060 else:
1066 else:
1061 x = dataOut.getVelRange()
1067 x = dataOut.getVelRange()
1062 zdB = 10*numpy.log10(z[0,:,hei_index])
1068 zdB = 10*numpy.log10(z[0,:,hei_index])
1063 xlabel = "Velocity (m/s)"
1069 xlabel = "Velocity (m/s)"
1064 ylabel = "Power (dB)"
1070 ylabel = "Power (dB)"
1065
1071
1066 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1072 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1067 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1073 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1068
1074
1069 if not self.isConfig:
1075 if not self.isConfig:
1070
1076
1071 nplots = 1
1077 nplots = 1
1072
1078
1073 self.setup(id=id,
1079 self.setup(id=id,
1074 nplots=nplots,
1080 nplots=nplots,
1075 wintitle=wintitle,
1081 wintitle=wintitle,
1076 show=show)
1082 show=show)
1077
1083
1078 if xmin == None: xmin = numpy.nanmin(x)*0.9
1084 if xmin == None: xmin = numpy.nanmin(x)*0.9
1079 if xmax == None: xmax = numpy.nanmax(x)*1.1
1085 if xmax == None: xmax = numpy.nanmax(x)*1.1
1080 if ymin == None: ymin = numpy.nanmin(zdB)
1086 if ymin == None: ymin = numpy.nanmin(zdB)
1081 if ymax == None: ymax = numpy.nanmax(zdB)
1087 if ymax == None: ymax = numpy.nanmax(zdB)
1082
1088
1083 self.isConfig = True
1089 self.isConfig = True
1084
1090
1085 self.setWinTitle(title)
1091 self.setWinTitle(title)
1086
1092
1087 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1093 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1088 axes = self.axesList[0]
1094 axes = self.axesList[0]
1089
1095
1090 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1096 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1091
1097
1092 axes.pmultilineyaxis( x, zdB,
1098 axes.pmultilineyaxis( x, zdB,
1093 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1099 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1094 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1100 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1095 ytick_visible=True, nxticks=5,
1101 ytick_visible=True, nxticks=5,
1096 grid='x')
1102 grid='x')
1097
1103
1098 self.draw()
1104 self.draw()
1099
1105
1100 self.save(figpath=figpath,
1106 self.save(figpath=figpath,
1101 figfile=figfile,
1107 figfile=figfile,
1102 save=save,
1108 save=save,
1103 ftp=ftp,
1109 ftp=ftp,
1104 wr_period=wr_period,
1110 wr_period=wr_period,
1105 thisDatetime=thisDatetime)
1111 thisDatetime=thisDatetime)
1106
1112
1107 class Noise(Figure):
1113 class Noise(Figure):
1108
1114
1109 isConfig = None
1115 isConfig = None
1110 __nsubplots = None
1116 __nsubplots = None
1111
1117
1112 PREFIX = 'noise'
1118 PREFIX = 'noise'
1113
1119
1120
1114 def __init__(self, **kwargs):
1121 def __init__(self, **kwargs):
1115 Figure.__init__(self, **kwargs)
1122 Figure.__init__(self, **kwargs)
1116 self.timerange = 24*60*60
1123 self.timerange = 24*60*60
1117 self.isConfig = False
1124 self.isConfig = False
1118 self.__nsubplots = 1
1125 self.__nsubplots = 1
1119 self.counter_imagwr = 0
1126 self.counter_imagwr = 0
1120 self.WIDTH = 800
1127 self.WIDTH = 800
1121 self.HEIGHT = 400
1128 self.HEIGHT = 400
1122 self.WIDTHPROF = 120
1129 self.WIDTHPROF = 120
1123 self.HEIGHTPROF = 0
1130 self.HEIGHTPROF = 0
1124 self.xdata = None
1131 self.xdata = None
1125 self.ydata = None
1132 self.ydata = None
1126
1133
1127 self.PLOT_CODE = NOISE_CODE
1134 self.PLOT_CODE = NOISE_CODE
1128
1135
1129 self.FTP_WEI = None
1136 self.FTP_WEI = None
1130 self.EXP_CODE = None
1137 self.EXP_CODE = None
1131 self.SUB_EXP_CODE = None
1138 self.SUB_EXP_CODE = None
1132 self.PLOT_POS = None
1139 self.PLOT_POS = None
1133 self.figfile = None
1140 self.figfile = None
1134
1141
1135 self.xmin = None
1142 self.xmin = None
1136 self.xmax = None
1143 self.xmax = None
1137
1144
1138 def getSubplots(self):
1145 def getSubplots(self):
1139
1146
1140 ncol = 1
1147 ncol = 1
1141 nrow = 1
1148 nrow = 1
1142
1149
1143 return nrow, ncol
1150 return nrow, ncol
1144
1151
1145 def openfile(self, filename):
1152 def openfile(self, filename):
1146 dirname = os.path.dirname(filename)
1153 dirname = os.path.dirname(filename)
1147
1154
1148 if not os.path.exists(dirname):
1155 if not os.path.exists(dirname):
1149 os.mkdir(dirname)
1156 os.mkdir(dirname)
1150
1157
1151 f = open(filename,'w+')
1158 f = open(filename,'w+')
1152 f.write('\n\n')
1159 f.write('\n\n')
1153 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1160 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1154 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1161 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1155 f.close()
1162 f.close()
1156
1163
1157 def save_data(self, filename_phase, data, data_datetime):
1164 def save_data(self, filename_phase, data, data_datetime):
1158
1165
1159 f=open(filename_phase,'a')
1166 f=open(filename_phase,'a')
1160
1167
1161 timetuple_data = data_datetime.timetuple()
1168 timetuple_data = data_datetime.timetuple()
1162 day = str(timetuple_data.tm_mday)
1169 day = str(timetuple_data.tm_mday)
1163 month = str(timetuple_data.tm_mon)
1170 month = str(timetuple_data.tm_mon)
1164 year = str(timetuple_data.tm_year)
1171 year = str(timetuple_data.tm_year)
1165 hour = str(timetuple_data.tm_hour)
1172 hour = str(timetuple_data.tm_hour)
1166 minute = str(timetuple_data.tm_min)
1173 minute = str(timetuple_data.tm_min)
1167 second = str(timetuple_data.tm_sec)
1174 second = str(timetuple_data.tm_sec)
1168
1175
1169 data_msg = ''
1176 data_msg = ''
1170 for i in range(len(data)):
1177 for i in range(len(data)):
1171 data_msg += str(data[i]) + ' '
1178 data_msg += str(data[i]) + ' '
1172
1179
1173 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1180 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1174 f.close()
1181 f.close()
1175
1182
1176
1183
1177 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1184 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1178
1185
1179 self.__showprofile = showprofile
1186 self.__showprofile = showprofile
1180 self.nplots = nplots
1187 self.nplots = nplots
1181
1188
1182 ncolspan = 7
1189 ncolspan = 7
1183 colspan = 6
1190 colspan = 6
1184 self.__nsubplots = 2
1191 self.__nsubplots = 2
1185
1192
1186 self.createFigure(id = id,
1193 self.createFigure(id = id,
1187 wintitle = wintitle,
1194 wintitle = wintitle,
1188 widthplot = self.WIDTH+self.WIDTHPROF,
1195 widthplot = self.WIDTH+self.WIDTHPROF,
1189 heightplot = self.HEIGHT+self.HEIGHTPROF,
1196 heightplot = self.HEIGHT+self.HEIGHTPROF,
1190 show=show)
1197 show=show)
1191
1198
1192 nrow, ncol = self.getSubplots()
1199 nrow, ncol = self.getSubplots()
1193
1200
1194 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1201 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1195
1202
1196
1203
1197 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1204 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1198 xmin=None, xmax=None, ymin=None, ymax=None,
1205 xmin=None, xmax=None, ymin=None, ymax=None,
1199 timerange=None,
1206 timerange=None,
1200 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1207 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1201 server=None, folder=None, username=None, password=None,
1208 server=None, folder=None, username=None, password=None,
1202 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1209 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1203
1210
1204 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1211 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1205 return
1212 return
1206
1213
1207 if channelList == None:
1214 if channelList == None:
1208 channelIndexList = dataOut.channelIndexList
1215 channelIndexList = dataOut.channelIndexList
1209 channelList = dataOut.channelList
1216 channelList = dataOut.channelList
1210 else:
1217 else:
1211 channelIndexList = []
1218 channelIndexList = []
1212 for channel in channelList:
1219 for channel in channelList:
1213 if channel not in dataOut.channelList:
1220 if channel not in dataOut.channelList:
1214 raise ValueError, "Channel %d is not in dataOut.channelList"
1221 raise ValueError, "Channel %d is not in dataOut.channelList"
1215 channelIndexList.append(dataOut.channelList.index(channel))
1222 channelIndexList.append(dataOut.channelList.index(channel))
1216
1223
1217 x = dataOut.getTimeRange()
1224 x = dataOut.getTimeRange()
1218 #y = dataOut.getHeiRange()
1225 #y = dataOut.getHeiRange()
1219 factor = dataOut.normFactor
1226 factor = dataOut.normFactor
1220 noise = dataOut.noise[channelIndexList]/factor
1227 noise = dataOut.noise[channelIndexList]/factor
1221 noisedB = 10*numpy.log10(noise)
1228 noisedB = 10*numpy.log10(noise)
1222
1229
1223 thisDatetime = dataOut.datatime
1230 thisDatetime = dataOut.datatime
1224
1231
1225 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1232 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1226 xlabel = ""
1233 xlabel = ""
1227 ylabel = "Intensity (dB)"
1234 ylabel = "Intensity (dB)"
1228 update_figfile = False
1235 update_figfile = False
1229
1236
1230 if not self.isConfig:
1237 if not self.isConfig:
1231
1238
1232 nplots = 1
1239 nplots = 1
1233
1240
1234 self.setup(id=id,
1241 self.setup(id=id,
1235 nplots=nplots,
1242 nplots=nplots,
1236 wintitle=wintitle,
1243 wintitle=wintitle,
1237 showprofile=showprofile,
1244 showprofile=showprofile,
1238 show=show)
1245 show=show)
1239
1246
1240 if timerange != None:
1247 if timerange != None:
1241 self.timerange = timerange
1248 self.timerange = timerange
1242
1249
1243 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1250 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1244
1251
1245 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1252 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1246 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1253 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1247
1254
1248 self.FTP_WEI = ftp_wei
1255 self.FTP_WEI = ftp_wei
1249 self.EXP_CODE = exp_code
1256 self.EXP_CODE = exp_code
1250 self.SUB_EXP_CODE = sub_exp_code
1257 self.SUB_EXP_CODE = sub_exp_code
1251 self.PLOT_POS = plot_pos
1258 self.PLOT_POS = plot_pos
1252
1259
1253
1260
1254 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1261 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1255 self.isConfig = True
1262 self.isConfig = True
1256 self.figfile = figfile
1263 self.figfile = figfile
1257 self.xdata = numpy.array([])
1264 self.xdata = numpy.array([])
1258 self.ydata = numpy.array([])
1265 self.ydata = numpy.array([])
1259
1266
1260 update_figfile = True
1267 update_figfile = True
1261
1268
1262 #open file beacon phase
1269 #open file beacon phase
1263 path = '%s%03d' %(self.PREFIX, self.id)
1270 path = '%s%03d' %(self.PREFIX, self.id)
1264 noise_file = os.path.join(path,'%s.txt'%self.name)
1271 noise_file = os.path.join(path,'%s.txt'%self.name)
1265 self.filename_noise = os.path.join(figpath,noise_file)
1272 self.filename_noise = os.path.join(figpath,noise_file)
1266
1273
1267 self.setWinTitle(title)
1274 self.setWinTitle(title)
1268
1275
1269 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1276 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1270
1277
1271 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1278 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1272 axes = self.axesList[0]
1279 axes = self.axesList[0]
1273
1280
1274 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1281 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1275
1282
1276 if len(self.ydata)==0:
1283 if len(self.ydata)==0:
1277 self.ydata = noisedB.reshape(-1,1)
1284 self.ydata = noisedB.reshape(-1,1)
1278 else:
1285 else:
1279 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1286 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1280
1287
1281
1288
1282 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1289 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1283 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1290 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1284 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1291 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1285 XAxisAsTime=True, grid='both'
1292 XAxisAsTime=True, grid='both'
1286 )
1293 )
1287
1294
1288 self.draw()
1295 self.draw()
1289
1296
1290 if dataOut.ltctime >= self.xmax:
1297 if dataOut.ltctime >= self.xmax:
1291 self.counter_imagwr = wr_period
1298 self.counter_imagwr = wr_period
1292 self.isConfig = False
1299 self.isConfig = False
1293 update_figfile = True
1300 update_figfile = True
1294
1301
1295 self.save(figpath=figpath,
1302 self.save(figpath=figpath,
1296 figfile=figfile,
1303 figfile=figfile,
1297 save=save,
1304 save=save,
1298 ftp=ftp,
1305 ftp=ftp,
1299 wr_period=wr_period,
1306 wr_period=wr_period,
1300 thisDatetime=thisDatetime,
1307 thisDatetime=thisDatetime,
1301 update_figfile=update_figfile)
1308 update_figfile=update_figfile)
1302
1309
1303 #store data beacon phase
1310 #store data beacon phase
1304 if save:
1311 if save:
1305 self.save_data(self.filename_noise, noisedB, thisDatetime)
1312 self.save_data(self.filename_noise, noisedB, thisDatetime)
1306
1313
1307 class BeaconPhase(Figure):
1314 class BeaconPhase(Figure):
1308
1315
1309 __isConfig = None
1316 __isConfig = None
1310 __nsubplots = None
1317 __nsubplots = None
1311
1318
1312 PREFIX = 'beacon_phase'
1319 PREFIX = 'beacon_phase'
1313
1320
1314 def __init__(self, **kwargs):
1321 def __init__(self, **kwargs):
1315 Figure.__init__(self, **kwargs)
1322 Figure.__init__(self, **kwargs)
1316 self.timerange = 24*60*60
1323 self.timerange = 24*60*60
1317 self.isConfig = False
1324 self.isConfig = False
1318 self.__nsubplots = 1
1325 self.__nsubplots = 1
1319 self.counter_imagwr = 0
1326 self.counter_imagwr = 0
1320 self.WIDTH = 800
1327 self.WIDTH = 800
1321 self.HEIGHT = 400
1328 self.HEIGHT = 400
1322 self.WIDTHPROF = 120
1329 self.WIDTHPROF = 120
1323 self.HEIGHTPROF = 0
1330 self.HEIGHTPROF = 0
1324 self.xdata = None
1331 self.xdata = None
1325 self.ydata = None
1332 self.ydata = None
1326
1333
1327 self.PLOT_CODE = BEACON_CODE
1334 self.PLOT_CODE = BEACON_CODE
1328
1335
1329 self.FTP_WEI = None
1336 self.FTP_WEI = None
1330 self.EXP_CODE = None
1337 self.EXP_CODE = None
1331 self.SUB_EXP_CODE = None
1338 self.SUB_EXP_CODE = None
1332 self.PLOT_POS = None
1339 self.PLOT_POS = None
1333
1340
1334 self.filename_phase = None
1341 self.filename_phase = None
1335
1342
1336 self.figfile = None
1343 self.figfile = None
1337
1344
1338 self.xmin = None
1345 self.xmin = None
1339 self.xmax = None
1346 self.xmax = None
1340
1347
1341 def getSubplots(self):
1348 def getSubplots(self):
1342
1349
1343 ncol = 1
1350 ncol = 1
1344 nrow = 1
1351 nrow = 1
1345
1352
1346 return nrow, ncol
1353 return nrow, ncol
1347
1354
1348 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1355 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1349
1356
1350 self.__showprofile = showprofile
1357 self.__showprofile = showprofile
1351 self.nplots = nplots
1358 self.nplots = nplots
1352
1359
1353 ncolspan = 7
1360 ncolspan = 7
1354 colspan = 6
1361 colspan = 6
1355 self.__nsubplots = 2
1362 self.__nsubplots = 2
1356
1363
1357 self.createFigure(id = id,
1364 self.createFigure(id = id,
1358 wintitle = wintitle,
1365 wintitle = wintitle,
1359 widthplot = self.WIDTH+self.WIDTHPROF,
1366 widthplot = self.WIDTH+self.WIDTHPROF,
1360 heightplot = self.HEIGHT+self.HEIGHTPROF,
1367 heightplot = self.HEIGHT+self.HEIGHTPROF,
1361 show=show)
1368 show=show)
1362
1369
1363 nrow, ncol = self.getSubplots()
1370 nrow, ncol = self.getSubplots()
1364
1371
1365 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1372 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1366
1373
1367 def save_phase(self, filename_phase):
1374 def save_phase(self, filename_phase):
1368 f = open(filename_phase,'w+')
1375 f = open(filename_phase,'w+')
1369 f.write('\n\n')
1376 f.write('\n\n')
1370 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1377 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1371 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1378 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1372 f.close()
1379 f.close()
1373
1380
1374 def save_data(self, filename_phase, data, data_datetime):
1381 def save_data(self, filename_phase, data, data_datetime):
1375 f=open(filename_phase,'a')
1382 f=open(filename_phase,'a')
1376 timetuple_data = data_datetime.timetuple()
1383 timetuple_data = data_datetime.timetuple()
1377 day = str(timetuple_data.tm_mday)
1384 day = str(timetuple_data.tm_mday)
1378 month = str(timetuple_data.tm_mon)
1385 month = str(timetuple_data.tm_mon)
1379 year = str(timetuple_data.tm_year)
1386 year = str(timetuple_data.tm_year)
1380 hour = str(timetuple_data.tm_hour)
1387 hour = str(timetuple_data.tm_hour)
1381 minute = str(timetuple_data.tm_min)
1388 minute = str(timetuple_data.tm_min)
1382 second = str(timetuple_data.tm_sec)
1389 second = str(timetuple_data.tm_sec)
1383 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1390 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1384 f.close()
1391 f.close()
1385
1392
1386
1393
1387 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1394 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1388 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1395 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1389 timerange=None,
1396 timerange=None,
1390 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1397 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1391 server=None, folder=None, username=None, password=None,
1398 server=None, folder=None, username=None, password=None,
1392 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1399 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1393
1400
1394 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1401 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1395 return
1402 return
1396
1403
1397 if pairsList == None:
1404 if pairsList == None:
1398 pairsIndexList = dataOut.pairsIndexList[:10]
1405 pairsIndexList = dataOut.pairsIndexList[:10]
1399 else:
1406 else:
1400 pairsIndexList = []
1407 pairsIndexList = []
1401 for pair in pairsList:
1408 for pair in pairsList:
1402 if pair not in dataOut.pairsList:
1409 if pair not in dataOut.pairsList:
1403 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
1410 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
1404 pairsIndexList.append(dataOut.pairsList.index(pair))
1411 pairsIndexList.append(dataOut.pairsList.index(pair))
1405
1412
1406 if pairsIndexList == []:
1413 if pairsIndexList == []:
1407 return
1414 return
1408
1415
1409 # if len(pairsIndexList) > 4:
1416 # if len(pairsIndexList) > 4:
1410 # pairsIndexList = pairsIndexList[0:4]
1417 # pairsIndexList = pairsIndexList[0:4]
1411
1418
1412 hmin_index = None
1419 hmin_index = None
1413 hmax_index = None
1420 hmax_index = None
1414
1421
1415 if hmin != None and hmax != None:
1422 if hmin != None and hmax != None:
1416 indexes = numpy.arange(dataOut.nHeights)
1423 indexes = numpy.arange(dataOut.nHeights)
1417 hmin_list = indexes[dataOut.heightList >= hmin]
1424 hmin_list = indexes[dataOut.heightList >= hmin]
1418 hmax_list = indexes[dataOut.heightList <= hmax]
1425 hmax_list = indexes[dataOut.heightList <= hmax]
1419
1426
1420 if hmin_list.any():
1427 if hmin_list.any():
1421 hmin_index = hmin_list[0]
1428 hmin_index = hmin_list[0]
1422
1429
1423 if hmax_list.any():
1430 if hmax_list.any():
1424 hmax_index = hmax_list[-1]+1
1431 hmax_index = hmax_list[-1]+1
1425
1432
1426 x = dataOut.getTimeRange()
1433 x = dataOut.getTimeRange()
1427 #y = dataOut.getHeiRange()
1434 #y = dataOut.getHeiRange()
1428
1435
1429
1436
1430 thisDatetime = dataOut.datatime
1437 thisDatetime = dataOut.datatime
1431
1438
1432 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1439 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1433 xlabel = "Local Time"
1440 xlabel = "Local Time"
1434 ylabel = "Phase (degrees)"
1441 ylabel = "Phase (degrees)"
1435
1442
1436 update_figfile = False
1443 update_figfile = False
1437
1444
1438 nplots = len(pairsIndexList)
1445 nplots = len(pairsIndexList)
1439 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1446 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1440 phase_beacon = numpy.zeros(len(pairsIndexList))
1447 phase_beacon = numpy.zeros(len(pairsIndexList))
1441 for i in range(nplots):
1448 for i in range(nplots):
1442 pair = dataOut.pairsList[pairsIndexList[i]]
1449 pair = dataOut.pairsList[pairsIndexList[i]]
1443 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1450 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1444 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1451 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1445 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1452 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1446 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1453 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1447 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1454 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1448
1455
1449 #print "Phase %d%d" %(pair[0], pair[1])
1456 #print "Phase %d%d" %(pair[0], pair[1])
1450 #print phase[dataOut.beacon_heiIndexList]
1457 #print phase[dataOut.beacon_heiIndexList]
1451
1458
1452 if dataOut.beacon_heiIndexList:
1459 if dataOut.beacon_heiIndexList:
1453 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1460 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1454 else:
1461 else:
1455 phase_beacon[i] = numpy.average(phase)
1462 phase_beacon[i] = numpy.average(phase)
1456
1463
1457 if not self.isConfig:
1464 if not self.isConfig:
1458
1465
1459 nplots = len(pairsIndexList)
1466 nplots = len(pairsIndexList)
1460
1467
1461 self.setup(id=id,
1468 self.setup(id=id,
1462 nplots=nplots,
1469 nplots=nplots,
1463 wintitle=wintitle,
1470 wintitle=wintitle,
1464 showprofile=showprofile,
1471 showprofile=showprofile,
1465 show=show)
1472 show=show)
1466
1473
1467 if timerange != None:
1474 if timerange != None:
1468 self.timerange = timerange
1475 self.timerange = timerange
1469
1476
1470 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1477 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1471
1478
1472 if ymin == None: ymin = 0
1479 if ymin == None: ymin = 0
1473 if ymax == None: ymax = 360
1480 if ymax == None: ymax = 360
1474
1481
1475 self.FTP_WEI = ftp_wei
1482 self.FTP_WEI = ftp_wei
1476 self.EXP_CODE = exp_code
1483 self.EXP_CODE = exp_code
1477 self.SUB_EXP_CODE = sub_exp_code
1484 self.SUB_EXP_CODE = sub_exp_code
1478 self.PLOT_POS = plot_pos
1485 self.PLOT_POS = plot_pos
1479
1486
1480 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1487 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1481 self.isConfig = True
1488 self.isConfig = True
1482 self.figfile = figfile
1489 self.figfile = figfile
1483 self.xdata = numpy.array([])
1490 self.xdata = numpy.array([])
1484 self.ydata = numpy.array([])
1491 self.ydata = numpy.array([])
1485
1492
1486 update_figfile = True
1493 update_figfile = True
1487
1494
1488 #open file beacon phase
1495 #open file beacon phase
1489 path = '%s%03d' %(self.PREFIX, self.id)
1496 path = '%s%03d' %(self.PREFIX, self.id)
1490 beacon_file = os.path.join(path,'%s.txt'%self.name)
1497 beacon_file = os.path.join(path,'%s.txt'%self.name)
1491 self.filename_phase = os.path.join(figpath,beacon_file)
1498 self.filename_phase = os.path.join(figpath,beacon_file)
1492 #self.save_phase(self.filename_phase)
1499 #self.save_phase(self.filename_phase)
1493
1500
1494
1501
1495 #store data beacon phase
1502 #store data beacon phase
1496 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1503 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1497
1504
1498 self.setWinTitle(title)
1505 self.setWinTitle(title)
1499
1506
1500
1507
1501 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1508 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1502
1509
1503 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1510 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1504
1511
1505 axes = self.axesList[0]
1512 axes = self.axesList[0]
1506
1513
1507 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1514 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1508
1515
1509 if len(self.ydata)==0:
1516 if len(self.ydata)==0:
1510 self.ydata = phase_beacon.reshape(-1,1)
1517 self.ydata = phase_beacon.reshape(-1,1)
1511 else:
1518 else:
1512 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1519 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1513
1520
1514
1521
1515 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1522 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1516 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1523 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1517 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1524 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1518 XAxisAsTime=True, grid='both'
1525 XAxisAsTime=True, grid='both'
1519 )
1526 )
1520
1527
1521 self.draw()
1528 self.draw()
1522
1529
1523 if dataOut.ltctime >= self.xmax:
1530 if dataOut.ltctime >= self.xmax:
1524 self.counter_imagwr = wr_period
1531 self.counter_imagwr = wr_period
1525 self.isConfig = False
1532 self.isConfig = False
1526 update_figfile = True
1533 update_figfile = True
1527
1534
1528 self.save(figpath=figpath,
1535 self.save(figpath=figpath,
1529 figfile=figfile,
1536 figfile=figfile,
1530 save=save,
1537 save=save,
1531 ftp=ftp,
1538 ftp=ftp,
1532 wr_period=wr_period,
1539 wr_period=wr_period,
1533 thisDatetime=thisDatetime,
1540 thisDatetime=thisDatetime,
1534 update_figfile=update_figfile)
1541 update_figfile=update_figfile)
@@ -1,468 +1,481
1 import numpy
1 import numpy
2 import datetime
2 import datetime
3 import sys
3 import sys
4 import matplotlib
4 import matplotlib
5
5
6 if 'linux' in sys.platform:
6 if 'linux' in sys.platform:
7 matplotlib.use("TKAgg")
7 matplotlib.use("TKAgg")
8
8
9 if 'darwin' in sys.platform:
9 if 'darwin' in sys.platform:
10 matplotlib.use('TKAgg')
10 matplotlib.use('TKAgg')
11 #Qt4Agg', 'GTK', 'GTKAgg', 'ps', 'agg', 'cairo', 'MacOSX', 'GTKCairo', 'WXAgg', 'template', 'TkAgg', 'GTK3Cairo', 'GTK3Agg', 'svg', 'WebAgg', 'CocoaAgg', 'emf', 'gdk', 'WX'
11 #Qt4Agg', 'GTK', 'GTKAgg', 'ps', 'agg', 'cairo', 'MacOSX', 'GTKCairo', 'WXAgg', 'template', 'TkAgg', 'GTK3Cairo', 'GTK3Agg', 'svg', 'WebAgg', 'CocoaAgg', 'emf', 'gdk', 'WX'
12 import matplotlib.pyplot
12 import matplotlib.pyplot
13
13
14 from mpl_toolkits.axes_grid1 import make_axes_locatable
14 from mpl_toolkits.axes_grid1 import make_axes_locatable
15 from matplotlib.ticker import FuncFormatter, LinearLocator
15 from matplotlib.ticker import FuncFormatter, LinearLocator
16
16
17 ###########################################
17 ###########################################
18 #Actualizacion de las funciones del driver
18 #Actualizacion de las funciones del driver
19 ###########################################
19 ###########################################
20
20
21 # create jro colormap
21 # create jro colormap
22
22
23 jet_values = matplotlib.pyplot.get_cmap("jet", 100)(numpy.arange(100))[10:90]
23 jet_values = matplotlib.pyplot.get_cmap("jet", 100)(numpy.arange(100))[10:90]
24 blu_values = matplotlib.pyplot.get_cmap("seismic_r", 20)(numpy.arange(20))[10:15]
24 blu_values = matplotlib.pyplot.get_cmap("seismic_r", 20)(numpy.arange(20))[10:15]
25 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list("jro", numpy.vstack((blu_values, jet_values)))
25 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list("jro", numpy.vstack((blu_values, jet_values)))
26 matplotlib.pyplot.register_cmap(cmap=ncmap)
26 matplotlib.pyplot.register_cmap(cmap=ncmap)
27
27
28 def createFigure(id, wintitle, width, height, facecolor="w", show=True, dpi = 80):
28 def createFigure(id, wintitle, width, height, facecolor="w", show=True, dpi = 80):
29
29
30 matplotlib.pyplot.ioff()
30 matplotlib.pyplot.ioff()
31
31
32 fig = matplotlib.pyplot.figure(num=id, facecolor=facecolor, figsize=(1.0*width/dpi, 1.0*height/dpi))
32 fig = matplotlib.pyplot.figure(num=id, facecolor=facecolor, figsize=(1.0*width/dpi, 1.0*height/dpi))
33 fig.canvas.manager.set_window_title(wintitle)
33 fig.canvas.manager.set_window_title(wintitle)
34 # fig.canvas.manager.resize(width, height)
34 # fig.canvas.manager.resize(width, height)
35 matplotlib.pyplot.ion()
35 matplotlib.pyplot.ion()
36
36
37 if show:
37 if show:
38 matplotlib.pyplot.show()
38 matplotlib.pyplot.show()
39
39
40 return fig
40 return fig
41
41
42 def closeFigure(show=False, fig=None):
42 def closeFigure(show=False, fig=None):
43
43
44 # matplotlib.pyplot.ioff()
44 # matplotlib.pyplot.ioff()
45 # matplotlib.pyplot.pause(0)
45 # matplotlib.pyplot.pause(0)
46
46
47 if show:
47 if show:
48 matplotlib.pyplot.show()
48 matplotlib.pyplot.show()
49
49
50 if fig != None:
50 if fig != None:
51 matplotlib.pyplot.close(fig)
51 matplotlib.pyplot.close(fig)
52 # matplotlib.pyplot.pause(0)
52 # matplotlib.pyplot.pause(0)
53 # matplotlib.pyplot.ion()
53 # matplotlib.pyplot.ion()
54
54
55 return
55 return
56
56
57 matplotlib.pyplot.close("all")
57 matplotlib.pyplot.close("all")
58 # matplotlib.pyplot.pause(0)
58 # matplotlib.pyplot.pause(0)
59 # matplotlib.pyplot.ion()
59 # matplotlib.pyplot.ion()
60
60
61 return
61 return
62
62
63 def saveFigure(fig, filename):
63 def saveFigure(fig, filename):
64
64
65 # matplotlib.pyplot.ioff()
65 # matplotlib.pyplot.ioff()
66 fig.savefig(filename, dpi=matplotlib.pyplot.gcf().dpi)
66 fig.savefig(filename, dpi=matplotlib.pyplot.gcf().dpi)
67 # matplotlib.pyplot.ion()
67 # matplotlib.pyplot.ion()
68
68
69 def clearFigure(fig):
69 def clearFigure(fig):
70
70
71 fig.clf()
71 fig.clf()
72
72
73 def setWinTitle(fig, title):
73 def setWinTitle(fig, title):
74
74
75 fig.canvas.manager.set_window_title(title)
75 fig.canvas.manager.set_window_title(title)
76
76
77 def setTitle(fig, title):
77 def setTitle(fig, title):
78
78
79 fig.suptitle(title)
79 fig.suptitle(title)
80
80
81 def createAxes(fig, nrow, ncol, xpos, ypos, colspan, rowspan, polar=False):
81 def createAxes(fig, nrow, ncol, xpos, ypos, colspan, rowspan, polar=False):
82
82
83 matplotlib.pyplot.ioff()
83 matplotlib.pyplot.ioff()
84 matplotlib.pyplot.figure(fig.number)
84 matplotlib.pyplot.figure(fig.number)
85 axes = matplotlib.pyplot.subplot2grid((nrow, ncol),
85 axes = matplotlib.pyplot.subplot2grid((nrow, ncol),
86 (xpos, ypos),
86 (xpos, ypos),
87 colspan=colspan,
87 colspan=colspan,
88 rowspan=rowspan,
88 rowspan=rowspan,
89 polar=polar)
89 polar=polar)
90
90
91 axes.grid(True)
92
91 matplotlib.pyplot.ion()
93 matplotlib.pyplot.ion()
92 return axes
94 return axes
93
95
94 def setAxesText(ax, text):
96 def setAxesText(ax, text):
95
97
96 ax.annotate(text,
98 ax.annotate(text,
97 xy = (.1, .99),
99 xy = (.1, .99),
98 xycoords = 'figure fraction',
100 xycoords = 'figure fraction',
99 horizontalalignment = 'left',
101 horizontalalignment = 'left',
100 verticalalignment = 'top',
102 verticalalignment = 'top',
101 fontsize = 10)
103 fontsize = 10)
102
104
103 def printLabels(ax, xlabel, ylabel, title):
105 def printLabels(ax, xlabel, ylabel, title):
104
106
105 ax.set_xlabel(xlabel, size=11)
107 ax.set_xlabel(xlabel, size=11)
106 ax.set_ylabel(ylabel, size=11)
108 ax.set_ylabel(ylabel, size=11)
107 ax.set_title(title, size=8)
109 ax.set_title(title, size=8)
108
110
109 def createPline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='',
111 def createPline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='',
110 ticksize=9, xtick_visible=True, ytick_visible=True,
112 ticksize=9, xtick_visible=True, ytick_visible=True,
111 nxticks=4, nyticks=10,
113 nxticks=4, nyticks=10,
112 grid=None,color='blue'):
114 grid=None,color='blue'):
113
115
114 """
116 """
115
117
116 Input:
118 Input:
117 grid : None, 'both', 'x', 'y'
119 grid : None, 'both', 'x', 'y'
118 """
120 """
119
121
120 matplotlib.pyplot.ioff()
122 matplotlib.pyplot.ioff()
121
123
122 ax.set_xlim([xmin,xmax])
124 ax.set_xlim([xmin,xmax])
123 ax.set_ylim([ymin,ymax])
125 ax.set_ylim([ymin,ymax])
124
126
125 printLabels(ax, xlabel, ylabel, title)
127 printLabels(ax, xlabel, ylabel, title)
126
128
127 ######################################################
129 ######################################################
128 if (xmax-xmin)<=1:
130 if (xmax-xmin)<=1:
129 xtickspos = numpy.linspace(xmin,xmax,nxticks)
131 xtickspos = numpy.linspace(xmin,xmax,nxticks)
130 xtickspos = numpy.array([float("%.1f"%i) for i in xtickspos])
132 xtickspos = numpy.array([float("%.1f"%i) for i in xtickspos])
131 ax.set_xticks(xtickspos)
133 ax.set_xticks(xtickspos)
132 else:
134 else:
133 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
135 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
134 # xtickspos = numpy.arange(nxticks)*float(xmax-xmin)/float(nxticks) + int(xmin)
136 # xtickspos = numpy.arange(nxticks)*float(xmax-xmin)/float(nxticks) + int(xmin)
135 ax.set_xticks(xtickspos)
137 ax.set_xticks(xtickspos)
136
138
137 for tick in ax.get_xticklabels():
139 for tick in ax.get_xticklabels():
138 tick.set_visible(xtick_visible)
140 tick.set_visible(xtick_visible)
139
141
140 for tick in ax.xaxis.get_major_ticks():
142 for tick in ax.xaxis.get_major_ticks():
141 tick.label.set_fontsize(ticksize)
143 tick.label.set_fontsize(ticksize)
142
144
143 ######################################################
145 ######################################################
144 for tick in ax.get_yticklabels():
146 for tick in ax.get_yticklabels():
145 tick.set_visible(ytick_visible)
147 tick.set_visible(ytick_visible)
146
148
147 for tick in ax.yaxis.get_major_ticks():
149 for tick in ax.yaxis.get_major_ticks():
148 tick.label.set_fontsize(ticksize)
150 tick.label.set_fontsize(ticksize)
149
151
150 ax.plot(x, y, color=color)
152 ax.plot(x, y, color=color)
151 iplot = ax.lines[-1]
153 iplot = ax.lines[-1]
152
154
153 ######################################################
155 ######################################################
154 if '0.' in matplotlib.__version__[0:2]:
156 if '0.' in matplotlib.__version__[0:2]:
155 print "The matplotlib version has to be updated to 1.1 or newer"
157 print "The matplotlib version has to be updated to 1.1 or newer"
156 return iplot
158 return iplot
157
159
158 if '1.0.' in matplotlib.__version__[0:4]:
160 if '1.0.' in matplotlib.__version__[0:4]:
159 print "The matplotlib version has to be updated to 1.1 or newer"
161 print "The matplotlib version has to be updated to 1.1 or newer"
160 return iplot
162 return iplot
161
163
162 if grid != None:
164 if grid != None:
163 ax.grid(b=True, which='major', axis=grid)
165 ax.grid(b=True, which='major', axis=grid)
164
166
165 matplotlib.pyplot.tight_layout()
167 matplotlib.pyplot.tight_layout()
166
168
167 matplotlib.pyplot.ion()
169 matplotlib.pyplot.ion()
168
170
169 return iplot
171 return iplot
170
172
171 def set_linedata(ax, x, y, idline):
173 def set_linedata(ax, x, y, idline):
172
174
173 ax.lines[idline].set_data(x,y)
175 ax.lines[idline].set_data(x,y)
174
176
175 def pline(iplot, x, y, xlabel='', ylabel='', title=''):
177 def pline(iplot, x, y, xlabel='', ylabel='', title=''):
176
178
177 ax = iplot.axes
179 ax = iplot.get_axes()
178
180
179 printLabels(ax, xlabel, ylabel, title)
181 printLabels(ax, xlabel, ylabel, title)
180
182
181 set_linedata(ax, x, y, idline=0)
183 set_linedata(ax, x, y, idline=0)
182
184
183 def addpline(ax, x, y, color, linestyle, lw):
185 def addpline(ax, x, y, color, linestyle, lw):
184
186
185 ax.plot(x,y,color=color,linestyle=linestyle,lw=lw)
187 ax.plot(x,y,color=color,linestyle=linestyle,lw=lw)
186
188
187
189
188 def createPcolor(ax, x, y, z, xmin, xmax, ymin, ymax, zmin, zmax,
190 def createPcolor(ax, x, y, z, xmin, xmax, ymin, ymax, zmin, zmax,
189 xlabel='', ylabel='', title='', ticksize = 9,
191 xlabel='', ylabel='', title='', ticksize = 9,
190 colormap='jet',cblabel='', cbsize="5%",
192 colormap='jet',cblabel='', cbsize="5%",
191 XAxisAsTime=False):
193 XAxisAsTime=False):
192
194
193 matplotlib.pyplot.ioff()
195 matplotlib.pyplot.ioff()
194
196
195 divider = make_axes_locatable(ax)
197 divider = make_axes_locatable(ax)
196 ax_cb = divider.new_horizontal(size=cbsize, pad=0.05)
198 ax_cb = divider.new_horizontal(size=cbsize, pad=0.05)
197 fig = ax.get_figure()
199 fig = ax.get_figure()
198 fig.add_axes(ax_cb)
200 fig.add_axes(ax_cb)
199
201
200 ax.set_xlim([xmin,xmax])
202 ax.set_xlim([xmin,xmax])
201 ax.set_ylim([ymin,ymax])
203 ax.set_ylim([ymin,ymax])
202
204
203 printLabels(ax, xlabel, ylabel, title)
205 printLabels(ax, xlabel, ylabel, title)
204
206
205 z = numpy.ma.masked_invalid(z)
207 z = numpy.ma.masked_invalid(z)
206 cmap=matplotlib.pyplot.get_cmap(colormap)
208 cmap=matplotlib.pyplot.get_cmap(colormap)
207 cmap.set_bad('black', 1.)
209 cmap.set_bad('white',1.)
208 imesh = ax.pcolormesh(x,y,z.T, vmin=zmin, vmax=zmax, cmap=cmap)
210 imesh = ax.pcolormesh(x,y,z.T, vmin=zmin, vmax=zmax, cmap=cmap)
209 cb = matplotlib.pyplot.colorbar(imesh, cax=ax_cb)
211 cb = matplotlib.pyplot.colorbar(imesh, cax=ax_cb)
210 cb.set_label(cblabel)
212 cb.set_label(cblabel)
211
213
212 # for tl in ax_cb.get_yticklabels():
214 # for tl in ax_cb.get_yticklabels():
213 # tl.set_visible(True)
215 # tl.set_visible(True)
214
216
215 for tick in ax.yaxis.get_major_ticks():
217 for tick in ax.yaxis.get_major_ticks():
216 tick.label.set_fontsize(ticksize)
218 tick.label.set_fontsize(ticksize)
217
219
218 for tick in ax.xaxis.get_major_ticks():
220 for tick in ax.xaxis.get_major_ticks():
219 tick.label.set_fontsize(ticksize)
221 tick.label.set_fontsize(ticksize)
220
222
221 for tick in cb.ax.get_yticklabels():
223 for tick in cb.ax.get_yticklabels():
222 tick.set_fontsize(ticksize)
224 tick.set_fontsize(ticksize)
223
225
224 ax_cb.yaxis.tick_right()
226 ax_cb.yaxis.tick_right()
225
227
226 if '0.' in matplotlib.__version__[0:2]:
228 if '0.' in matplotlib.__version__[0:2]:
227 print "The matplotlib version has to be updated to 1.1 or newer"
229 print "The matplotlib version has to be updated to 1.1 or newer"
228 return imesh
230 return imesh
229
231
230 if '1.0.' in matplotlib.__version__[0:4]:
232 if '1.0.' in matplotlib.__version__[0:4]:
231 print "The matplotlib version has to be updated to 1.1 or newer"
233 print "The matplotlib version has to be updated to 1.1 or newer"
232 return imesh
234 return imesh
233
235
234 matplotlib.pyplot.tight_layout()
236 matplotlib.pyplot.tight_layout()
235
237
236 if XAxisAsTime:
238 if XAxisAsTime:
237
239
238 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
240 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
239 ax.xaxis.set_major_formatter(FuncFormatter(func))
241 ax.xaxis.set_major_formatter(FuncFormatter(func))
240 ax.xaxis.set_major_locator(LinearLocator(7))
242 ax.xaxis.set_major_locator(LinearLocator(7))
241
243
244 ax.grid(True)
242 matplotlib.pyplot.ion()
245 matplotlib.pyplot.ion()
243 return imesh
246 return imesh
244
247
245 def pcolor(imesh, z, xlabel='', ylabel='', title=''):
248 def pcolor(imesh, z, xlabel='', ylabel='', title=''):
246
249
250 z = numpy.ma.masked_invalid(z)
251
252 cmap=matplotlib.pyplot.get_cmap('jet')
253 cmap.set_bad('white',1.)
254
247 z = z.T
255 z = z.T
248 ax = imesh.axes
256 ax = imesh.get_axes()
249 printLabels(ax, xlabel, ylabel, title)
257 printLabels(ax, xlabel, ylabel, title)
250 imesh.set_array(z.ravel())
258 imesh.set_array(z.ravel())
259 ax.grid(True)
260
251
261
252 def addpcolor(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
262 def addpcolor(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
253
263
254 printLabels(ax, xlabel, ylabel, title)
264 printLabels(ax, xlabel, ylabel, title)
255
265 z = numpy.ma.masked_invalid(z)
266 cmap=matplotlib.pyplot.get_cmap(colormap)
267 cmap.set_bad('white',1.)
256 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
268 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
269 ax.grid(True)
257
270
258 def addpcolorbuffer(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
271 def addpcolorbuffer(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
259
272
260 printLabels(ax, xlabel, ylabel, title)
273 printLabels(ax, xlabel, ylabel, title)
261
274
262 ax.collections.remove(ax.collections[0])
275 ax.collections.remove(ax.collections[0])
263
276
264 z = numpy.ma.masked_invalid(z)
277 z = numpy.ma.masked_invalid(z)
265
278
266 cmap=matplotlib.pyplot.get_cmap(colormap)
279 cmap=matplotlib.pyplot.get_cmap(colormap)
267 cmap.set_bad('black', 1.)
280 cmap.set_bad('white',1.)
268
269
281
270 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=cmap)
282 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=cmap)
283 ax.grid(True)
284
271
285
272 def createPmultiline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
286 def createPmultiline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
273 ticksize=9, xtick_visible=True, ytick_visible=True,
287 ticksize=9, xtick_visible=True, ytick_visible=True,
274 nxticks=4, nyticks=10,
288 nxticks=4, nyticks=10,
275 grid=None):
289 grid=None):
276
290
277 """
291 """
278
292
279 Input:
293 Input:
280 grid : None, 'both', 'x', 'y'
294 grid : None, 'both', 'x', 'y'
281 """
295 """
282
296
283 matplotlib.pyplot.ioff()
297 matplotlib.pyplot.ioff()
284
298
285 lines = ax.plot(x.T, y)
299 lines = ax.plot(x.T, y)
286 leg = ax.legend(lines, legendlabels, loc='upper right')
300 leg = ax.legend(lines, legendlabels, loc='upper right')
287 leg.get_frame().set_alpha(0.5)
301 leg.get_frame().set_alpha(0.5)
288 ax.set_xlim([xmin,xmax])
302 ax.set_xlim([xmin,xmax])
289 ax.set_ylim([ymin,ymax])
303 ax.set_ylim([ymin,ymax])
290 printLabels(ax, xlabel, ylabel, title)
304 printLabels(ax, xlabel, ylabel, title)
291
305
292 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
306 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
293 ax.set_xticks(xtickspos)
307 ax.set_xticks(xtickspos)
294
308
295 for tick in ax.get_xticklabels():
309 for tick in ax.get_xticklabels():
296 tick.set_visible(xtick_visible)
310 tick.set_visible(xtick_visible)
297
311
298 for tick in ax.xaxis.get_major_ticks():
312 for tick in ax.xaxis.get_major_ticks():
299 tick.label.set_fontsize(ticksize)
313 tick.label.set_fontsize(ticksize)
300
314
301 for tick in ax.get_yticklabels():
315 for tick in ax.get_yticklabels():
302 tick.set_visible(ytick_visible)
316 tick.set_visible(ytick_visible)
303
317
304 for tick in ax.yaxis.get_major_ticks():
318 for tick in ax.yaxis.get_major_ticks():
305 tick.label.set_fontsize(ticksize)
319 tick.label.set_fontsize(ticksize)
306
320
307 iplot = ax.lines[-1]
321 iplot = ax.lines[-1]
308
322
309 if '0.' in matplotlib.__version__[0:2]:
323 if '0.' in matplotlib.__version__[0:2]:
310 print "The matplotlib version has to be updated to 1.1 or newer"
324 print "The matplotlib version has to be updated to 1.1 or newer"
311 return iplot
325 return iplot
312
326
313 if '1.0.' in matplotlib.__version__[0:4]:
327 if '1.0.' in matplotlib.__version__[0:4]:
314 print "The matplotlib version has to be updated to 1.1 or newer"
328 print "The matplotlib version has to be updated to 1.1 or newer"
315 return iplot
329 return iplot
316
330
317 if grid != None:
331 if grid != None:
318 ax.grid(b=True, which='major', axis=grid)
332 ax.grid(b=True, which='major', axis=grid)
319
333
320 matplotlib.pyplot.tight_layout()
334 matplotlib.pyplot.tight_layout()
321
335
322 matplotlib.pyplot.ion()
336 matplotlib.pyplot.ion()
323
337
324 return iplot
338 return iplot
325
339
326
340
327 def pmultiline(iplot, x, y, xlabel='', ylabel='', title=''):
341 def pmultiline(iplot, x, y, xlabel='', ylabel='', title=''):
328
342
329 ax = iplot.axes
343 ax = iplot.get_axes()
330
344
331 printLabels(ax, xlabel, ylabel, title)
345 printLabels(ax, xlabel, ylabel, title)
332
346
333 for i in range(len(ax.lines)):
347 for i in range(len(ax.lines)):
334 line = ax.lines[i]
348 line = ax.lines[i]
335 line.set_data(x[i,:],y)
349 line.set_data(x[i,:],y)
336
350
337 def createPmultilineYAxis(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
351 def createPmultilineYAxis(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
338 ticksize=9, xtick_visible=True, ytick_visible=True,
352 ticksize=9, xtick_visible=True, ytick_visible=True,
339 nxticks=4, nyticks=10, marker='.', markersize=10, linestyle="None",
353 nxticks=4, nyticks=10, marker='.', markersize=10, linestyle="None",
340 grid=None, XAxisAsTime=False):
354 grid=None, XAxisAsTime=False):
341
355
342 """
356 """
343
357
344 Input:
358 Input:
345 grid : None, 'both', 'x', 'y'
359 grid : None, 'both', 'x', 'y'
346 """
360 """
347
361
348 matplotlib.pyplot.ioff()
362 matplotlib.pyplot.ioff()
349
363
350 # lines = ax.plot(x, y.T, marker=marker,markersize=markersize,linestyle=linestyle)
364 # lines = ax.plot(x, y.T, marker=marker,markersize=markersize,linestyle=linestyle)
351 lines = ax.plot(x, y.T)
365 lines = ax.plot(x, y.T)
352 # leg = ax.legend(lines, legendlabels, loc=2, bbox_to_anchor=(1.01, 1.00), numpoints=1, handlelength=1.5, \
366 # leg = ax.legend(lines, legendlabels, loc=2, bbox_to_anchor=(1.01, 1.00), numpoints=1, handlelength=1.5, \
353 # handletextpad=0.5, borderpad=0.5, labelspacing=0.5, borderaxespad=0.)
367 # handletextpad=0.5, borderpad=0.5, labelspacing=0.5, borderaxespad=0.)
354
368
355 leg = ax.legend(lines, legendlabels,
369 leg = ax.legend(lines, legendlabels,
356 loc='upper right', bbox_to_anchor=(1.16, 1), borderaxespad=0)
370 loc='upper right', bbox_to_anchor=(1.16, 1), borderaxespad=0)
357
371
358 for label in leg.get_texts(): label.set_fontsize(9)
372 for label in leg.get_texts(): label.set_fontsize(9)
359
373
360 ax.set_xlim([xmin,xmax])
374 ax.set_xlim([xmin,xmax])
361 ax.set_ylim([ymin,ymax])
375 ax.set_ylim([ymin,ymax])
362 printLabels(ax, xlabel, ylabel, title)
376 printLabels(ax, xlabel, ylabel, title)
363
377
364 # xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
378 # xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
365 # ax.set_xticks(xtickspos)
379 # ax.set_xticks(xtickspos)
366
380
367 for tick in ax.get_xticklabels():
381 for tick in ax.get_xticklabels():
368 tick.set_visible(xtick_visible)
382 tick.set_visible(xtick_visible)
369
383
370 for tick in ax.xaxis.get_major_ticks():
384 for tick in ax.xaxis.get_major_ticks():
371 tick.label.set_fontsize(ticksize)
385 tick.label.set_fontsize(ticksize)
372
386
373 for tick in ax.get_yticklabels():
387 for tick in ax.get_yticklabels():
374 tick.set_visible(ytick_visible)
388 tick.set_visible(ytick_visible)
375
389
376 for tick in ax.yaxis.get_major_ticks():
390 for tick in ax.yaxis.get_major_ticks():
377 tick.label.set_fontsize(ticksize)
391 tick.label.set_fontsize(ticksize)
378
392
379 iplot = ax.lines[-1]
393 iplot = ax.lines[-1]
380
394
381 if '0.' in matplotlib.__version__[0:2]:
395 if '0.' in matplotlib.__version__[0:2]:
382 print "The matplotlib version has to be updated to 1.1 or newer"
396 print "The matplotlib version has to be updated to 1.1 or newer"
383 return iplot
397 return iplot
384
398
385 if '1.0.' in matplotlib.__version__[0:4]:
399 if '1.0.' in matplotlib.__version__[0:4]:
386 print "The matplotlib version has to be updated to 1.1 or newer"
400 print "The matplotlib version has to be updated to 1.1 or newer"
387 return iplot
401 return iplot
388
402
389 if grid != None:
403 if grid != None:
390 ax.grid(b=True, which='major', axis=grid)
404 ax.grid(b=True, which='major', axis=grid)
391
405
392 matplotlib.pyplot.tight_layout()
406 matplotlib.pyplot.tight_layout()
393
407
394 if XAxisAsTime:
408 if XAxisAsTime:
395
409
396 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
410 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
397 ax.xaxis.set_major_formatter(FuncFormatter(func))
411 ax.xaxis.set_major_formatter(FuncFormatter(func))
398 ax.xaxis.set_major_locator(LinearLocator(7))
412 ax.xaxis.set_major_locator(LinearLocator(7))
399
413
400 matplotlib.pyplot.ion()
414 matplotlib.pyplot.ion()
401
415
402 return iplot
416 return iplot
403
417
404 def pmultilineyaxis(iplot, x, y, xlabel='', ylabel='', title=''):
418 def pmultilineyaxis(iplot, x, y, xlabel='', ylabel='', title=''):
405
419
406 ax = iplot.axes
420 ax = iplot.get_axes()
407
408 printLabels(ax, xlabel, ylabel, title)
421 printLabels(ax, xlabel, ylabel, title)
409
422
410 for i in range(len(ax.lines)):
423 for i in range(len(ax.lines)):
411 line = ax.lines[i]
424 line = ax.lines[i]
412 line.set_data(x,y[i,:])
425 line.set_data(x,y[i,:])
413
426
414 def createPolar(ax, x, y,
427 def createPolar(ax, x, y,
415 xlabel='', ylabel='', title='', ticksize = 9,
428 xlabel='', ylabel='', title='', ticksize = 9,
416 colormap='jet',cblabel='', cbsize="5%",
429 colormap='jet',cblabel='', cbsize="5%",
417 XAxisAsTime=False):
430 XAxisAsTime=False):
418
431
419 matplotlib.pyplot.ioff()
432 matplotlib.pyplot.ioff()
420
433
421 ax.plot(x,y,'bo', markersize=5)
434 ax.plot(x,y,'bo', markersize=5)
422 # ax.set_rmax(90)
435 # ax.set_rmax(90)
423 ax.set_ylim(0,90)
436 ax.set_ylim(0,90)
424 ax.set_yticks(numpy.arange(0,90,20))
437 ax.set_yticks(numpy.arange(0,90,20))
425 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center' ,size='11')
438 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center' ,size='11')
426 # ax.text(0, 50, ylabel, rotation='vertical', va ='center', ha = 'left' ,size='11')
439 # ax.text(0, 50, ylabel, rotation='vertical', va ='center', ha = 'left' ,size='11')
427 # ax.text(100, 100, 'example', ha='left', va='center', rotation='vertical')
440 # ax.text(100, 100, 'example', ha='left', va='center', rotation='vertical')
428 ax.yaxis.labelpad = 40
441 ax.yaxis.labelpad = 230
429 printLabels(ax, xlabel, ylabel, title)
442 printLabels(ax, xlabel, ylabel, title)
430 iplot = ax.lines[-1]
443 iplot = ax.lines[-1]
431
444
432 if '0.' in matplotlib.__version__[0:2]:
445 if '0.' in matplotlib.__version__[0:2]:
433 print "The matplotlib version has to be updated to 1.1 or newer"
446 print "The matplotlib version has to be updated to 1.1 or newer"
434 return iplot
447 return iplot
435
448
436 if '1.0.' in matplotlib.__version__[0:4]:
449 if '1.0.' in matplotlib.__version__[0:4]:
437 print "The matplotlib version has to be updated to 1.1 or newer"
450 print "The matplotlib version has to be updated to 1.1 or newer"
438 return iplot
451 return iplot
439
452
440 # if grid != None:
453 # if grid != None:
441 # ax.grid(b=True, which='major', axis=grid)
454 # ax.grid(b=True, which='major', axis=grid)
442
455
443 matplotlib.pyplot.tight_layout()
456 matplotlib.pyplot.tight_layout()
444
457
445 matplotlib.pyplot.ion()
458 matplotlib.pyplot.ion()
446
459
447
460
448 return iplot
461 return iplot
449
462
450 def polar(iplot, x, y, xlabel='', ylabel='', title=''):
463 def polar(iplot, x, y, xlabel='', ylabel='', title=''):
451
464
452 ax = iplot.axes
465 ax = iplot.get_axes()
453
466
454 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center',size='11')
467 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center',size='11')
455 printLabels(ax, xlabel, ylabel, title)
468 printLabels(ax, xlabel, ylabel, title)
456
469
457 set_linedata(ax, x, y, idline=0)
470 set_linedata(ax, x, y, idline=0)
458
471
459 def draw(fig):
472 def draw(fig):
460
473
461 if type(fig) == 'int':
474 if type(fig) == 'int':
462 raise ValueError, "Error drawing: Fig parameter should be a matplotlib figure object figure"
475 raise ValueError, "Error drawing: Fig parameter should be a matplotlib figure object figure"
463
476
464 fig.canvas.draw()
477 fig.canvas.draw()
465
478
466 def pause(interval=0.000001):
479 def pause(interval=0.000001):
467
480
468 matplotlib.pyplot.pause(interval)
481 matplotlib.pyplot.pause(interval)
@@ -1,14 +1,21
1 '''
1 '''
2
2
3 $Author: murco $
3 $Author: murco $
4 $Id: JRODataIO.py 169 2012-11-19 21:57:03Z murco $
4 $Id: JRODataIO.py 169 2012-11-19 21:57:03Z murco $
5 '''
5 '''
6
6
7 from jroIO_voltage import *
7 from jroIO_voltage import *
8 from jroIO_spectra import *
8 from jroIO_spectra import *
9 from jroIO_heispectra import *
9 from jroIO_heispectra import *
10 from jroIO_usrp import *
10 from jroIO_usrp import *
11
11
12 from jroIO_kamisr import *
12 from jroIO_kamisr import *
13 from jroIO_param import *
13 from jroIO_param import *
14 from jroIO_hf import *
14 from jroIO_hf import *
15
16 from jroIO_madrigal import *
17
18 from bltrIO_param import *
19 from jroIO_bltr import *
20 from jroIO_mira35c import *
21
@@ -1,1813 +1,1814
1 '''
1 '''
2 Created on Jul 2, 2014
2 Created on Jul 2, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import sys
7 import sys
8 import glob
8 import glob
9 import time
9 import time
10 import numpy
10 import numpy
11 import fnmatch
11 import fnmatch
12 import inspect
12 import inspect
13 import time, datetime
13 import time, datetime
14 import traceback
14 import traceback
15 import zmq
15 import zmq
16
16
17 try:
17 try:
18 from gevent import sleep
18 from gevent import sleep
19 except:
19 except:
20 from time import sleep
20 from time import sleep
21
21
22 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
22 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
23 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
23 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
24
24
25 LOCALTIME = True
25 LOCALTIME = True
26
26
27 def isNumber(cad):
27 def isNumber(cad):
28 """
28 """
29 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
29 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
30
30
31 Excepciones:
31 Excepciones:
32 Si un determinado string no puede ser convertido a numero
32 Si un determinado string no puede ser convertido a numero
33 Input:
33 Input:
34 str, string al cual se le analiza para determinar si convertible a un numero o no
34 str, string al cual se le analiza para determinar si convertible a un numero o no
35
35
36 Return:
36 Return:
37 True : si el string es uno numerico
37 True : si el string es uno numerico
38 False : no es un string numerico
38 False : no es un string numerico
39 """
39 """
40 try:
40 try:
41 float( cad )
41 float( cad )
42 return True
42 return True
43 except:
43 except:
44 return False
44 return False
45
45
46 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
46 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
47 """
47 """
48 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
48 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
49
49
50 Inputs:
50 Inputs:
51 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
51 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
52
52
53 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
53 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
54 segundos contados desde 01/01/1970.
54 segundos contados desde 01/01/1970.
55 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
55 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
56 segundos contados desde 01/01/1970.
56 segundos contados desde 01/01/1970.
57
57
58 Return:
58 Return:
59 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
59 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
60 fecha especificado, de lo contrario retorna False.
60 fecha especificado, de lo contrario retorna False.
61
61
62 Excepciones:
62 Excepciones:
63 Si el archivo no existe o no puede ser abierto
63 Si el archivo no existe o no puede ser abierto
64 Si la cabecera no puede ser leida.
64 Si la cabecera no puede ser leida.
65
65
66 """
66 """
67 basicHeaderObj = BasicHeader(LOCALTIME)
67 basicHeaderObj = BasicHeader(LOCALTIME)
68
68
69 try:
69 try:
70 fp = open(filename,'rb')
70 fp = open(filename,'rb')
71 except IOError:
71 except IOError:
72 print "The file %s can't be opened" %(filename)
72 print "The file %s can't be opened" %(filename)
73 return 0
73 return 0
74
74
75 sts = basicHeaderObj.read(fp)
75 sts = basicHeaderObj.read(fp)
76 fp.close()
76 fp.close()
77
77
78 if not(sts):
78 if not(sts):
79 print "Skipping the file %s because it has not a valid header" %(filename)
79 print "Skipping the file %s because it has not a valid header" %(filename)
80 return 0
80 return 0
81
81
82 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
82 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
83 return 0
83 return 0
84
84
85 return 1
85 return 1
86
86
87 def isTimeInRange(thisTime, startTime, endTime):
87 def isTimeInRange(thisTime, startTime, endTime):
88
88
89 if endTime >= startTime:
89 if endTime >= startTime:
90 if (thisTime < startTime) or (thisTime > endTime):
90 if (thisTime < startTime) or (thisTime > endTime):
91 return 0
91 return 0
92
92
93 return 1
93 return 1
94 else:
94 else:
95 if (thisTime < startTime) and (thisTime > endTime):
95 if (thisTime < startTime) and (thisTime > endTime):
96 return 0
96 return 0
97
97
98 return 1
98 return 1
99
99
100 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
100 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
101 """
101 """
102 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
102 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
103
103
104 Inputs:
104 Inputs:
105 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
105 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
106
106
107 startDate : fecha inicial del rango seleccionado en formato datetime.date
107 startDate : fecha inicial del rango seleccionado en formato datetime.date
108
108
109 endDate : fecha final del rango seleccionado en formato datetime.date
109 endDate : fecha final del rango seleccionado en formato datetime.date
110
110
111 startTime : tiempo inicial del rango seleccionado en formato datetime.time
111 startTime : tiempo inicial del rango seleccionado en formato datetime.time
112
112
113 endTime : tiempo final del rango seleccionado en formato datetime.time
113 endTime : tiempo final del rango seleccionado en formato datetime.time
114
114
115 Return:
115 Return:
116 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
116 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
117 fecha especificado, de lo contrario retorna False.
117 fecha especificado, de lo contrario retorna False.
118
118
119 Excepciones:
119 Excepciones:
120 Si el archivo no existe o no puede ser abierto
120 Si el archivo no existe o no puede ser abierto
121 Si la cabecera no puede ser leida.
121 Si la cabecera no puede ser leida.
122
122
123 """
123 """
124
124
125
125
126 try:
126 try:
127 fp = open(filename,'rb')
127 fp = open(filename,'rb')
128 except IOError:
128 except IOError:
129 print "The file %s can't be opened" %(filename)
129 print "The file %s can't be opened" %(filename)
130 return None
130 return None
131
131
132 firstBasicHeaderObj = BasicHeader(LOCALTIME)
132 firstBasicHeaderObj = BasicHeader(LOCALTIME)
133 systemHeaderObj = SystemHeader()
133 systemHeaderObj = SystemHeader()
134 radarControllerHeaderObj = RadarControllerHeader()
134 radarControllerHeaderObj = RadarControllerHeader()
135 processingHeaderObj = ProcessingHeader()
135 processingHeaderObj = ProcessingHeader()
136
136
137 lastBasicHeaderObj = BasicHeader(LOCALTIME)
137 lastBasicHeaderObj = BasicHeader(LOCALTIME)
138
138
139 sts = firstBasicHeaderObj.read(fp)
139 sts = firstBasicHeaderObj.read(fp)
140
140
141 if not(sts):
141 if not(sts):
142 print "[Reading] Skipping the file %s because it has not a valid header" %(filename)
142 print "[Reading] Skipping the file %s because it has not a valid header" %(filename)
143 return None
143 return None
144
144
145 if not systemHeaderObj.read(fp):
145 if not systemHeaderObj.read(fp):
146 return None
146 return None
147
147
148 if not radarControllerHeaderObj.read(fp):
148 if not radarControllerHeaderObj.read(fp):
149 return None
149 return None
150
150
151 if not processingHeaderObj.read(fp):
151 if not processingHeaderObj.read(fp):
152 return None
152 return None
153
153
154 filesize = os.path.getsize(filename)
154 filesize = os.path.getsize(filename)
155
155
156 offset = processingHeaderObj.blockSize + 24 #header size
156 offset = processingHeaderObj.blockSize + 24 #header size
157
157
158 if filesize <= offset:
158 if filesize <= offset:
159 print "[Reading] %s: This file has not enough data" %filename
159 print "[Reading] %s: This file has not enough data" %filename
160 return None
160 return None
161
161
162 fp.seek(-offset, 2)
162 fp.seek(-offset, 2)
163
163
164 sts = lastBasicHeaderObj.read(fp)
164 sts = lastBasicHeaderObj.read(fp)
165
165
166 fp.close()
166 fp.close()
167
167
168 thisDatetime = lastBasicHeaderObj.datatime
168 thisDatetime = lastBasicHeaderObj.datatime
169 thisTime_last_block = thisDatetime.time()
169 thisTime_last_block = thisDatetime.time()
170
170
171 thisDatetime = firstBasicHeaderObj.datatime
171 thisDatetime = firstBasicHeaderObj.datatime
172 thisDate = thisDatetime.date()
172 thisDate = thisDatetime.date()
173 thisTime_first_block = thisDatetime.time()
173 thisTime_first_block = thisDatetime.time()
174
174
175 #General case
175 #General case
176 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
176 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
177 #-----------o----------------------------o-----------
177 #-----------o----------------------------o-----------
178 # startTime endTime
178 # startTime endTime
179
179
180 if endTime >= startTime:
180 if endTime >= startTime:
181 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
181 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
182 return None
182 return None
183
183
184 return thisDatetime
184 return thisDatetime
185
185
186 #If endTime < startTime then endTime belongs to the next day
186 #If endTime < startTime then endTime belongs to the next day
187
187
188
188
189 #<<<<<<<<<<<o o>>>>>>>>>>>
189 #<<<<<<<<<<<o o>>>>>>>>>>>
190 #-----------o----------------------------o-----------
190 #-----------o----------------------------o-----------
191 # endTime startTime
191 # endTime startTime
192
192
193 if (thisDate == startDate) and (thisTime_last_block < startTime):
193 if (thisDate == startDate) and (thisTime_last_block < startTime):
194 return None
194 return None
195
195
196 if (thisDate == endDate) and (thisTime_first_block > endTime):
196 if (thisDate == endDate) and (thisTime_first_block > endTime):
197 return None
197 return None
198
198
199 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
199 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
200 return None
200 return None
201
201
202 return thisDatetime
202 return thisDatetime
203
203
204 def isFolderInDateRange(folder, startDate=None, endDate=None):
204 def isFolderInDateRange(folder, startDate=None, endDate=None):
205 """
205 """
206 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
206 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
207
207
208 Inputs:
208 Inputs:
209 folder : nombre completo del directorio.
209 folder : nombre completo del directorio.
210 Su formato deberia ser "/path_root/?YYYYDDD"
210 Su formato deberia ser "/path_root/?YYYYDDD"
211
211
212 siendo:
212 siendo:
213 YYYY : Anio (ejemplo 2015)
213 YYYY : Anio (ejemplo 2015)
214 DDD : Dia del anio (ejemplo 305)
214 DDD : Dia del anio (ejemplo 305)
215
215
216 startDate : fecha inicial del rango seleccionado en formato datetime.date
216 startDate : fecha inicial del rango seleccionado en formato datetime.date
217
217
218 endDate : fecha final del rango seleccionado en formato datetime.date
218 endDate : fecha final del rango seleccionado en formato datetime.date
219
219
220 Return:
220 Return:
221 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
221 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
222 fecha especificado, de lo contrario retorna False.
222 fecha especificado, de lo contrario retorna False.
223 Excepciones:
223 Excepciones:
224 Si el directorio no tiene el formato adecuado
224 Si el directorio no tiene el formato adecuado
225 """
225 """
226
226
227 basename = os.path.basename(folder)
227 basename = os.path.basename(folder)
228
228
229 if not isRadarFolder(basename):
229 if not isRadarFolder(basename):
230 print "The folder %s has not the rigth format" %folder
230 print "The folder %s has not the rigth format" %folder
231 return 0
231 return 0
232
232
233 if startDate and endDate:
233 if startDate and endDate:
234 thisDate = getDateFromRadarFolder(basename)
234 thisDate = getDateFromRadarFolder(basename)
235
235
236 if thisDate < startDate:
236 if thisDate < startDate:
237 return 0
237 return 0
238
238
239 if thisDate > endDate:
239 if thisDate > endDate:
240 return 0
240 return 0
241
241
242 return 1
242 return 1
243
243
244 def isFileInDateRange(filename, startDate=None, endDate=None):
244 def isFileInDateRange(filename, startDate=None, endDate=None):
245 """
245 """
246 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
246 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
247
247
248 Inputs:
248 Inputs:
249 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
249 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
250
250
251 Su formato deberia ser "?YYYYDDDsss"
251 Su formato deberia ser "?YYYYDDDsss"
252
252
253 siendo:
253 siendo:
254 YYYY : Anio (ejemplo 2015)
254 YYYY : Anio (ejemplo 2015)
255 DDD : Dia del anio (ejemplo 305)
255 DDD : Dia del anio (ejemplo 305)
256 sss : set
256 sss : set
257
257
258 startDate : fecha inicial del rango seleccionado en formato datetime.date
258 startDate : fecha inicial del rango seleccionado en formato datetime.date
259
259
260 endDate : fecha final del rango seleccionado en formato datetime.date
260 endDate : fecha final del rango seleccionado en formato datetime.date
261
261
262 Return:
262 Return:
263 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
263 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
264 fecha especificado, de lo contrario retorna False.
264 fecha especificado, de lo contrario retorna False.
265 Excepciones:
265 Excepciones:
266 Si el archivo no tiene el formato adecuado
266 Si el archivo no tiene el formato adecuado
267 """
267 """
268
268
269 basename = os.path.basename(filename)
269 basename = os.path.basename(filename)
270
270
271 if not isRadarFile(basename):
271 if not isRadarFile(basename):
272 print "The filename %s has not the rigth format" %filename
272 print "The filename %s has not the rigth format" %filename
273 return 0
273 return 0
274
274
275 if startDate and endDate:
275 if startDate and endDate:
276 thisDate = getDateFromRadarFile(basename)
276 thisDate = getDateFromRadarFile(basename)
277
277
278 if thisDate < startDate:
278 if thisDate < startDate:
279 return 0
279 return 0
280
280
281 if thisDate > endDate:
281 if thisDate > endDate:
282 return 0
282 return 0
283
283
284 return 1
284 return 1
285
285
286 def getFileFromSet(path, ext, set):
286 def getFileFromSet(path, ext, set):
287 validFilelist = []
287 validFilelist = []
288 fileList = os.listdir(path)
288 fileList = os.listdir(path)
289
289
290 # 0 1234 567 89A BCDE
290 # 0 1234 567 89A BCDE
291 # H YYYY DDD SSS .ext
291 # H YYYY DDD SSS .ext
292
292
293 for thisFile in fileList:
293 for thisFile in fileList:
294 try:
294 try:
295 year = int(thisFile[1:5])
295 year = int(thisFile[1:5])
296 doy = int(thisFile[5:8])
296 doy = int(thisFile[5:8])
297 except:
297 except:
298 continue
298 continue
299
299
300 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
300 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
301 continue
301 continue
302
302
303 validFilelist.append(thisFile)
303 validFilelist.append(thisFile)
304
304
305 myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set))
305 myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set))
306
306
307 if len(myfile)!= 0:
307 if len(myfile)!= 0:
308 return myfile[0]
308 return myfile[0]
309 else:
309 else:
310 filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower())
310 filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower())
311 print 'the filename %s does not exist'%filename
311 print 'the filename %s does not exist'%filename
312 print '...going to the last file: '
312 print '...going to the last file: '
313
313
314 if validFilelist:
314 if validFilelist:
315 validFilelist = sorted( validFilelist, key=str.lower )
315 validFilelist = sorted( validFilelist, key=str.lower )
316 return validFilelist[-1]
316 return validFilelist[-1]
317
317
318 return None
318 return None
319
319
320 def getlastFileFromPath(path, ext):
320 def getlastFileFromPath(path, ext):
321 """
321 """
322 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
322 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
323 al final de la depuracion devuelve el ultimo file de la lista que quedo.
323 al final de la depuracion devuelve el ultimo file de la lista que quedo.
324
324
325 Input:
325 Input:
326 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
326 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
327 ext : extension de los files contenidos en una carpeta
327 ext : extension de los files contenidos en una carpeta
328
328
329 Return:
329 Return:
330 El ultimo file de una determinada carpeta, no se considera el path.
330 El ultimo file de una determinada carpeta, no se considera el path.
331 """
331 """
332 validFilelist = []
332 validFilelist = []
333 fileList = os.listdir(path)
333 fileList = os.listdir(path)
334
334
335 # 0 1234 567 89A BCDE
335 # 0 1234 567 89A BCDE
336 # H YYYY DDD SSS .ext
336 # H YYYY DDD SSS .ext
337
337
338 for thisFile in fileList:
338 for thisFile in fileList:
339
339
340 year = thisFile[1:5]
340 year = thisFile[1:5]
341 if not isNumber(year):
341 if not isNumber(year):
342 continue
342 continue
343
343
344 doy = thisFile[5:8]
344 doy = thisFile[5:8]
345 if not isNumber(doy):
345 if not isNumber(doy):
346 continue
346 continue
347
347
348 year = int(year)
348 year = int(year)
349 doy = int(doy)
349 doy = int(doy)
350
350
351 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
351 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
352 continue
352 continue
353
353
354 validFilelist.append(thisFile)
354 validFilelist.append(thisFile)
355
355
356 if validFilelist:
356 if validFilelist:
357 validFilelist = sorted( validFilelist, key=str.lower )
357 validFilelist = sorted( validFilelist, key=str.lower )
358 return validFilelist[-1]
358 return validFilelist[-1]
359
359
360 return None
360 return None
361
361
362 def checkForRealPath(path, foldercounter, year, doy, set, ext):
362 def checkForRealPath(path, foldercounter, year, doy, set, ext):
363 """
363 """
364 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
364 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
365 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
365 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
366 el path exacto de un determinado file.
366 el path exacto de un determinado file.
367
367
368 Example :
368 Example :
369 nombre correcto del file es .../.../D2009307/P2009307367.ext
369 nombre correcto del file es .../.../D2009307/P2009307367.ext
370
370
371 Entonces la funcion prueba con las siguientes combinaciones
371 Entonces la funcion prueba con las siguientes combinaciones
372 .../.../y2009307367.ext
372 .../.../y2009307367.ext
373 .../.../Y2009307367.ext
373 .../.../Y2009307367.ext
374 .../.../x2009307/y2009307367.ext
374 .../.../x2009307/y2009307367.ext
375 .../.../x2009307/Y2009307367.ext
375 .../.../x2009307/Y2009307367.ext
376 .../.../X2009307/y2009307367.ext
376 .../.../X2009307/y2009307367.ext
377 .../.../X2009307/Y2009307367.ext
377 .../.../X2009307/Y2009307367.ext
378 siendo para este caso, la ultima combinacion de letras, identica al file buscado
378 siendo para este caso, la ultima combinacion de letras, identica al file buscado
379
379
380 Return:
380 Return:
381 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
381 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
382 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
382 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
383 para el filename
383 para el filename
384 """
384 """
385 fullfilename = None
385 fullfilename = None
386 find_flag = False
386 find_flag = False
387 filename = None
387 filename = None
388
388
389 prefixDirList = [None,'d','D']
389 prefixDirList = [None,'d','D']
390 if ext.lower() == ".r": #voltage
390 if ext.lower() == ".r": #voltage
391 prefixFileList = ['d','D']
391 prefixFileList = ['d','D']
392 elif ext.lower() == ".pdata": #spectra
392 elif ext.lower() == ".pdata": #spectra
393 prefixFileList = ['p','P']
393 prefixFileList = ['p','P']
394 else:
394 else:
395 return None, filename
395 return None, filename
396
396
397 #barrido por las combinaciones posibles
397 #barrido por las combinaciones posibles
398 for prefixDir in prefixDirList:
398 for prefixDir in prefixDirList:
399 thispath = path
399 thispath = path
400 if prefixDir != None:
400 if prefixDir != None:
401 #formo el nombre del directorio xYYYYDDD (x=d o x=D)
401 #formo el nombre del directorio xYYYYDDD (x=d o x=D)
402 if foldercounter == 0:
402 if foldercounter == 0:
403 thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy ))
403 thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy ))
404 else:
404 else:
405 thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter))
405 thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter))
406 for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D"
406 for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D"
407 filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
407 filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
408 fullfilename = os.path.join( thispath, filename ) #formo el path completo
408 fullfilename = os.path.join( thispath, filename ) #formo el path completo
409
409
410 if os.path.exists( fullfilename ): #verifico que exista
410 if os.path.exists( fullfilename ): #verifico que exista
411 find_flag = True
411 find_flag = True
412 break
412 break
413 if find_flag:
413 if find_flag:
414 break
414 break
415
415
416 if not(find_flag):
416 if not(find_flag):
417 return None, filename
417 return None, filename
418
418
419 return fullfilename, filename
419 return fullfilename, filename
420
420
421 def isRadarFolder(folder):
421 def isRadarFolder(folder):
422 try:
422 try:
423 year = int(folder[1:5])
423 year = int(folder[1:5])
424 doy = int(folder[5:8])
424 doy = int(folder[5:8])
425 except:
425 except:
426 return 0
426 return 0
427
427
428 return 1
428 return 1
429
429
430 def isRadarFile(file):
430 def isRadarFile(file):
431 try:
431 try:
432 year = int(file[1:5])
432 year = int(file[1:5])
433 doy = int(file[5:8])
433 doy = int(file[5:8])
434 set = int(file[8:11])
434 set = int(file[8:11])
435 except:
435 except:
436 return 0
436 return 0
437
437
438 return 1
438 return 1
439
439
440 def getDateFromRadarFile(file):
440 def getDateFromRadarFile(file):
441 try:
441 try:
442 year = int(file[1:5])
442 year = int(file[1:5])
443 doy = int(file[5:8])
443 doy = int(file[5:8])
444 set = int(file[8:11])
444 set = int(file[8:11])
445 except:
445 except:
446 return None
446 return None
447
447
448 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
448 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
449 return thisDate
449 return thisDate
450
450
451 def getDateFromRadarFolder(folder):
451 def getDateFromRadarFolder(folder):
452 try:
452 try:
453 year = int(folder[1:5])
453 year = int(folder[1:5])
454 doy = int(folder[5:8])
454 doy = int(folder[5:8])
455 except:
455 except:
456 return None
456 return None
457
457
458 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
458 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
459 return thisDate
459 return thisDate
460
460
461 class JRODataIO:
461 class JRODataIO:
462
462
463 c = 3E8
463 c = 3E8
464
464
465 isConfig = False
465 isConfig = False
466
466
467 basicHeaderObj = None
467 basicHeaderObj = None
468
468
469 systemHeaderObj = None
469 systemHeaderObj = None
470
470
471 radarControllerHeaderObj = None
471 radarControllerHeaderObj = None
472
472
473 processingHeaderObj = None
473 processingHeaderObj = None
474
474
475 dtype = None
475 dtype = None
476
476
477 pathList = []
477 pathList = []
478
478
479 filenameList = []
479 filenameList = []
480
480
481 filename = None
481 filename = None
482
482
483 ext = None
483 ext = None
484
484
485 flagIsNewFile = 1
485 flagIsNewFile = 1
486
486
487 flagDiscontinuousBlock = 0
487 flagDiscontinuousBlock = 0
488
488
489 flagIsNewBlock = 0
489 flagIsNewBlock = 0
490
490
491 fp = None
491 fp = None
492
492
493 firstHeaderSize = 0
493 firstHeaderSize = 0
494
494
495 basicHeaderSize = 24
495 basicHeaderSize = 24
496
496
497 versionFile = 1103
497 versionFile = 1103
498
498
499 fileSize = None
499 fileSize = None
500
500
501 # ippSeconds = None
501 # ippSeconds = None
502
502
503 fileSizeByHeader = None
503 fileSizeByHeader = None
504
504
505 fileIndex = None
505 fileIndex = None
506
506
507 profileIndex = None
507 profileIndex = None
508
508
509 blockIndex = None
509 blockIndex = None
510
510
511 nTotalBlocks = None
511 nTotalBlocks = None
512
512
513 maxTimeStep = 30
513 maxTimeStep = 30
514
514
515 lastUTTime = None
515 lastUTTime = None
516
516
517 datablock = None
517 datablock = None
518
518
519 dataOut = None
519 dataOut = None
520
520
521 blocksize = None
521 blocksize = None
522
522
523 getByBlock = False
523 getByBlock = False
524
524
525 def __init__(self):
525 def __init__(self):
526
526
527 raise NotImplementedError
527 raise NotImplementedError
528
528
529 def run(self):
529 def run(self):
530
530
531 raise NotImplementedError
531 raise NotImplementedError
532
532
533 def getDtypeWidth(self):
533 def getDtypeWidth(self):
534
534
535 dtype_index = get_dtype_index(self.dtype)
535 dtype_index = get_dtype_index(self.dtype)
536 dtype_width = get_dtype_width(dtype_index)
536 dtype_width = get_dtype_width(dtype_index)
537
537
538 return dtype_width
538 return dtype_width
539
539
540 def getAllowedArgs(self):
540 def getAllowedArgs(self):
541 return inspect.getargspec(self.run).args
541 return inspect.getargspec(self.run).args
542
542
543 class JRODataReader(JRODataIO):
543 class JRODataReader(JRODataIO):
544
544
545
545
546 online = 0
546 online = 0
547
547
548 realtime = 0
548 realtime = 0
549
549
550 nReadBlocks = 0
550 nReadBlocks = 0
551
551
552 delay = 10 #number of seconds waiting a new file
552 delay = 10 #number of seconds waiting a new file
553
553
554 nTries = 3 #quantity tries
554 nTries = 3 #quantity tries
555
555
556 nFiles = 3 #number of files for searching
556 nFiles = 3 #number of files for searching
557
557
558 path = None
558 path = None
559
559
560 foldercounter = 0
560 foldercounter = 0
561
561
562 flagNoMoreFiles = 0
562 flagNoMoreFiles = 0
563
563
564 datetimeList = []
564 datetimeList = []
565
565
566 __isFirstTimeOnline = 1
566 __isFirstTimeOnline = 1
567
567
568 __printInfo = True
568 __printInfo = True
569
569
570 profileIndex = None
570 profileIndex = None
571
571
572 nTxs = 1
572 nTxs = 1
573
573
574 txIndex = None
574 txIndex = None
575
575
576 #Added--------------------
576 #Added--------------------
577
577
578 selBlocksize = None
578 selBlocksize = None
579
579
580 selBlocktime = None
580 selBlocktime = None
581
581
582
582
583 def __init__(self):
583 def __init__(self):
584
584
585 """
585 """
586 This class is used to find data files
586 This class is used to find data files
587
587
588 Example:
588 Example:
589 reader = JRODataReader()
589 reader = JRODataReader()
590 fileList = reader.findDataFiles()
590 fileList = reader.findDataFiles()
591
591
592 """
592 """
593 pass
593 pass
594
594
595
595
596 def createObjByDefault(self):
596 def createObjByDefault(self):
597 """
597 """
598
598
599 """
599 """
600 raise NotImplementedError
600 raise NotImplementedError
601
601
602 def getBlockDimension(self):
602 def getBlockDimension(self):
603
603
604 raise NotImplementedError
604 raise NotImplementedError
605
605
606 def __searchFilesOffLine(self,
606 def __searchFilesOffLine(self,
607 path,
607 path,
608 startDate=None,
608 startDate=None,
609 endDate=None,
609 endDate=None,
610 startTime=datetime.time(0,0,0),
610 startTime=datetime.time(0,0,0),
611 endTime=datetime.time(23,59,59),
611 endTime=datetime.time(23,59,59),
612 set=None,
612 set=None,
613 expLabel='',
613 expLabel='',
614 ext='.r',
614 ext='.r',
615 queue=None,
615 queue=None,
616 cursor=None,
616 cursor=None,
617 skip=None,
617 skip=None,
618 walk=True):
618 walk=True):
619
619
620 self.filenameList = []
620 self.filenameList = []
621 self.datetimeList = []
621 self.datetimeList = []
622
622
623 pathList = []
623 pathList = []
624
624
625 dateList, pathList = self.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
625 dateList, pathList = self.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
626
626
627 if dateList == []:
627 if dateList == []:
628 # print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
628 # print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
629 return None, None
629 return None, None
630
630
631 if len(dateList) > 1:
631 if len(dateList) > 1:
632 print "[Reading] Data found for date range [%s - %s]: total days = %d" %(startDate, endDate, len(dateList))
632 print "[Reading] Data found for date range [%s - %s]: total days = %d" %(startDate, endDate, len(dateList))
633 else:
633 else:
634 print "[Reading] Data found for date range [%s - %s]: date = %s" %(startDate, endDate, dateList[0])
634 print "[Reading] Data found for date range [%s - %s]: date = %s" %(startDate, endDate, dateList[0])
635
635
636 filenameList = []
636 filenameList = []
637 datetimeList = []
637 datetimeList = []
638
638
639 for thisPath in pathList:
639 for thisPath in pathList:
640 # thisPath = pathList[pathDict[file]]
640 # thisPath = pathList[pathDict[file]]
641
641
642 fileList = glob.glob1(thisPath, "*%s" %ext)
642 fileList = glob.glob1(thisPath, "*%s" %ext)
643 fileList.sort()
643 fileList.sort()
644
644
645 skippedFileList = []
645 skippedFileList = []
646
646
647 if cursor is not None and skip is not None:
647 if cursor is not None and skip is not None:
648 # if cursor*skip > len(fileList):
648 # if cursor*skip > len(fileList):
649 if skip == 0:
649 if skip == 0:
650 if queue is not None:
650 if queue is not None:
651 queue.put(len(fileList))
651 queue.put(len(fileList))
652 skippedFileList = []
652 skippedFileList = []
653 else:
653 else:
654 skippedFileList = fileList[cursor*skip: cursor*skip + skip]
654 skippedFileList = fileList[cursor*skip: cursor*skip + skip]
655
655
656 else:
656 else:
657 skippedFileList = fileList
657 skippedFileList = fileList
658
658
659 for file in skippedFileList:
659 for file in skippedFileList:
660
660
661 filename = os.path.join(thisPath,file)
661 filename = os.path.join(thisPath,file)
662
662
663 if not isFileInDateRange(filename, startDate, endDate):
663 if not isFileInDateRange(filename, startDate, endDate):
664 continue
664 continue
665
665
666 thisDatetime = isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
666 thisDatetime = isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
667
667
668 if not(thisDatetime):
668 if not(thisDatetime):
669 continue
669 continue
670
670
671 filenameList.append(filename)
671 filenameList.append(filename)
672 datetimeList.append(thisDatetime)
672 datetimeList.append(thisDatetime)
673
673
674 if not(filenameList):
674 if not(filenameList):
675 print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" %(startTime, endTime, ext, path)
675 print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" %(startTime, endTime, ext, path)
676 return None, None
676 return None, None
677
677
678 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
678 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
679 print
679 print
680
680
681 for i in range(len(filenameList)):
681 for i in range(len(filenameList)):
682 print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
682 print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
683
683
684 self.filenameList = filenameList
684 self.filenameList = filenameList
685 self.datetimeList = datetimeList
685 self.datetimeList = datetimeList
686
686
687 return pathList, filenameList
687 return pathList, filenameList
688
688
689 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
689 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
690
690
691 """
691 """
692 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
692 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
693 devuelve el archivo encontrado ademas de otros datos.
693 devuelve el archivo encontrado ademas de otros datos.
694
694
695 Input:
695 Input:
696 path : carpeta donde estan contenidos los files que contiene data
696 path : carpeta donde estan contenidos los files que contiene data
697
697
698 expLabel : Nombre del subexperimento (subfolder)
698 expLabel : Nombre del subexperimento (subfolder)
699
699
700 ext : extension de los files
700 ext : extension de los files
701
701
702 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
702 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
703
703
704 Return:
704 Return:
705 directory : eL directorio donde esta el file encontrado
705 directory : eL directorio donde esta el file encontrado
706 filename : el ultimo file de una determinada carpeta
706 filename : el ultimo file de una determinada carpeta
707 year : el anho
707 year : el anho
708 doy : el numero de dia del anho
708 doy : el numero de dia del anho
709 set : el set del archivo
709 set : el set del archivo
710
710
711
711
712 """
712 """
713 if not os.path.isdir(path):
713 if not os.path.isdir(path):
714 return None, None, None, None, None, None
714 return None, None, None, None, None, None
715
715
716 dirList = []
716 dirList = []
717
717
718 if not walk:
718 if not walk:
719 fullpath = path
719 fullpath = path
720 foldercounter = 0
720 foldercounter = 0
721 else:
721 else:
722 #Filtra solo los directorios
722 #Filtra solo los directorios
723 for thisPath in os.listdir(path):
723 for thisPath in os.listdir(path):
724 if not os.path.isdir(os.path.join(path,thisPath)):
724 if not os.path.isdir(os.path.join(path,thisPath)):
725 continue
725 continue
726 if not isRadarFolder(thisPath):
726 if not isRadarFolder(thisPath):
727 continue
727 continue
728
728
729 dirList.append(thisPath)
729 dirList.append(thisPath)
730
730
731 if not(dirList):
731 if not(dirList):
732 return None, None, None, None, None, None
732 return None, None, None, None, None, None
733
733
734 dirList = sorted( dirList, key=str.lower )
734 dirList = sorted( dirList, key=str.lower )
735
735
736 doypath = dirList[-1]
736 doypath = dirList[-1]
737 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
737 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
738 fullpath = os.path.join(path, doypath, expLabel)
738 fullpath = os.path.join(path, doypath, expLabel)
739
739
740
740
741 print "[Reading] %s folder was found: " %(fullpath )
741 print "[Reading] %s folder was found: " %(fullpath )
742
742
743 if set == None:
743 if set == None:
744 filename = getlastFileFromPath(fullpath, ext)
744 filename = getlastFileFromPath(fullpath, ext)
745 else:
745 else:
746 filename = getFileFromSet(fullpath, ext, set)
746 filename = getFileFromSet(fullpath, ext, set)
747
747
748 if not(filename):
748 if not(filename):
749 return None, None, None, None, None, None
749 return None, None, None, None, None, None
750
750
751 print "[Reading] %s file was found" %(filename)
751 print "[Reading] %s file was found" %(filename)
752
752
753 if not(self.__verifyFile(os.path.join(fullpath, filename))):
753 if not(self.__verifyFile(os.path.join(fullpath, filename))):
754 return None, None, None, None, None, None
754 return None, None, None, None, None, None
755
755
756 year = int( filename[1:5] )
756 year = int( filename[1:5] )
757 doy = int( filename[5:8] )
757 doy = int( filename[5:8] )
758 set = int( filename[8:11] )
758 set = int( filename[8:11] )
759
759
760 return fullpath, foldercounter, filename, year, doy, set
760 return fullpath, foldercounter, filename, year, doy, set
761
761
762 def __setNextFileOffline(self):
762 def __setNextFileOffline(self):
763
763
764 idFile = self.fileIndex
764 idFile = self.fileIndex
765
765
766 while (True):
766 while (True):
767 idFile += 1
767 idFile += 1
768 if not(idFile < len(self.filenameList)):
768 if not(idFile < len(self.filenameList)):
769 self.flagNoMoreFiles = 1
769 self.flagNoMoreFiles = 1
770 # print "[Reading] No more Files"
770 # print "[Reading] No more Files"
771 return 0
771 return 0
772
772
773 filename = self.filenameList[idFile]
773 filename = self.filenameList[idFile]
774
774
775 if not(self.__verifyFile(filename)):
775 if not(self.__verifyFile(filename)):
776 continue
776 continue
777
777
778 fileSize = os.path.getsize(filename)
778 fileSize = os.path.getsize(filename)
779 fp = open(filename,'rb')
779 fp = open(filename,'rb')
780 break
780 break
781
781
782 self.flagIsNewFile = 1
782 self.flagIsNewFile = 1
783 self.fileIndex = idFile
783 self.fileIndex = idFile
784 self.filename = filename
784 self.filename = filename
785 self.fileSize = fileSize
785 self.fileSize = fileSize
786 self.fp = fp
786 self.fp = fp
787
787
788 # print "[Reading] Setting the file: %s"%self.filename
788 # print "[Reading] Setting the file: %s"%self.filename
789
789
790 return 1
790 return 1
791
791
792 def __setNextFileOnline(self):
792 def __setNextFileOnline(self):
793 """
793 """
794 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
794 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
795 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
795 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
796 siguientes.
796 siguientes.
797
797
798 Affected:
798 Affected:
799 self.flagIsNewFile
799 self.flagIsNewFile
800 self.filename
800 self.filename
801 self.fileSize
801 self.fileSize
802 self.fp
802 self.fp
803 self.set
803 self.set
804 self.flagNoMoreFiles
804 self.flagNoMoreFiles
805
805
806 Return:
806 Return:
807 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
807 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
808 1 : si el file fue abierto con exito y esta listo a ser leido
808 1 : si el file fue abierto con exito y esta listo a ser leido
809
809
810 Excepciones:
810 Excepciones:
811 Si un determinado file no puede ser abierto
811 Si un determinado file no puede ser abierto
812 """
812 """
813 nFiles = 0
813 nFiles = 0
814 fileOk_flag = False
814 fileOk_flag = False
815 firstTime_flag = True
815 firstTime_flag = True
816
816
817 self.set += 1
817 self.set += 1
818
818
819 if self.set > 999:
819 if self.set > 999:
820 self.set = 0
820 self.set = 0
821 self.foldercounter += 1
821 self.foldercounter += 1
822
822
823 #busca el 1er file disponible
823 #busca el 1er file disponible
824 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
824 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
825 if fullfilename:
825 if fullfilename:
826 if self.__verifyFile(fullfilename, False):
826 if self.__verifyFile(fullfilename, False):
827 fileOk_flag = True
827 fileOk_flag = True
828
828
829 #si no encuentra un file entonces espera y vuelve a buscar
829 #si no encuentra un file entonces espera y vuelve a buscar
830 if not(fileOk_flag):
830 if not(fileOk_flag):
831 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
831 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
832
832
833 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
833 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
834 tries = self.nTries
834 tries = self.nTries
835 else:
835 else:
836 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
836 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
837
837
838 for nTries in range( tries ):
838 for nTries in range( tries ):
839 if firstTime_flag:
839 if firstTime_flag:
840 print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
840 print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
841 sleep( self.delay )
841 sleep( self.delay )
842 else:
842 else:
843 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
843 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
844
844
845 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
845 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
846 if fullfilename:
846 if fullfilename:
847 if self.__verifyFile(fullfilename):
847 if self.__verifyFile(fullfilename):
848 fileOk_flag = True
848 fileOk_flag = True
849 break
849 break
850
850
851 if fileOk_flag:
851 if fileOk_flag:
852 break
852 break
853
853
854 firstTime_flag = False
854 firstTime_flag = False
855
855
856 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
856 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
857 self.set += 1
857 self.set += 1
858
858
859 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
859 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
860 self.set = 0
860 self.set = 0
861 self.doy += 1
861 self.doy += 1
862 self.foldercounter = 0
862 self.foldercounter = 0
863
863
864 if fileOk_flag:
864 if fileOk_flag:
865 self.fileSize = os.path.getsize( fullfilename )
865 self.fileSize = os.path.getsize( fullfilename )
866 self.filename = fullfilename
866 self.filename = fullfilename
867 self.flagIsNewFile = 1
867 self.flagIsNewFile = 1
868 if self.fp != None: self.fp.close()
868 if self.fp != None: self.fp.close()
869 self.fp = open(fullfilename, 'rb')
869 self.fp = open(fullfilename, 'rb')
870 self.flagNoMoreFiles = 0
870 self.flagNoMoreFiles = 0
871 # print '[Reading] Setting the file: %s' % fullfilename
871 # print '[Reading] Setting the file: %s' % fullfilename
872 else:
872 else:
873 self.fileSize = 0
873 self.fileSize = 0
874 self.filename = None
874 self.filename = None
875 self.flagIsNewFile = 0
875 self.flagIsNewFile = 0
876 self.fp = None
876 self.fp = None
877 self.flagNoMoreFiles = 1
877 self.flagNoMoreFiles = 1
878 # print '[Reading] No more files to read'
878 # print '[Reading] No more files to read'
879
879
880 return fileOk_flag
880 return fileOk_flag
881
881
882 def setNextFile(self):
882 def setNextFile(self):
883 if self.fp != None:
883 if self.fp != None:
884 self.fp.close()
884 self.fp.close()
885
885
886 if self.online:
886 if self.online:
887 newFile = self.__setNextFileOnline()
887 newFile = self.__setNextFileOnline()
888 else:
888 else:
889 newFile = self.__setNextFileOffline()
889 newFile = self.__setNextFileOffline()
890
890
891 if not(newFile):
891 if not(newFile):
892 print '[Reading] No more files to read'
892 print '[Reading] No more files to read'
893 return 0
893 return 0
894
894
895 if self.verbose:
895 if self.verbose:
896 print '[Reading] Setting the file: %s' % self.filename
896 print '[Reading] Setting the file: %s' % self.filename
897
897
898 self.__readFirstHeader()
898 self.__readFirstHeader()
899 self.nReadBlocks = 0
899 self.nReadBlocks = 0
900 return 1
900 return 1
901
901
902 def __waitNewBlock(self):
902 def __waitNewBlock(self):
903 """
903 """
904 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
904 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
905
905
906 Si el modo de lectura es OffLine siempre retorn 0
906 Si el modo de lectura es OffLine siempre retorn 0
907 """
907 """
908 if not self.online:
908 if not self.online:
909 return 0
909 return 0
910
910
911 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
911 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
912 return 0
912 return 0
913
913
914 currentPointer = self.fp.tell()
914 currentPointer = self.fp.tell()
915
915
916 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
916 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
917
917
918 for nTries in range( self.nTries ):
918 for nTries in range( self.nTries ):
919
919
920 self.fp.close()
920 self.fp.close()
921 self.fp = open( self.filename, 'rb' )
921 self.fp = open( self.filename, 'rb' )
922 self.fp.seek( currentPointer )
922 self.fp.seek( currentPointer )
923
923
924 self.fileSize = os.path.getsize( self.filename )
924 self.fileSize = os.path.getsize( self.filename )
925 currentSize = self.fileSize - currentPointer
925 currentSize = self.fileSize - currentPointer
926
926
927 if ( currentSize >= neededSize ):
927 if ( currentSize >= neededSize ):
928 self.basicHeaderObj.read(self.fp)
928 self.basicHeaderObj.read(self.fp)
929 return 1
929 return 1
930
930
931 if self.fileSize == self.fileSizeByHeader:
931 if self.fileSize == self.fileSizeByHeader:
932 # self.flagEoF = True
932 # self.flagEoF = True
933 return 0
933 return 0
934
934
935 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
935 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
936 sleep( self.delay )
936 sleep( self.delay )
937
937
938
938
939 return 0
939 return 0
940
940
941 def waitDataBlock(self,pointer_location):
941 def waitDataBlock(self,pointer_location):
942
942
943 currentPointer = pointer_location
943 currentPointer = pointer_location
944
944
945 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
945 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
946
946
947 for nTries in range( self.nTries ):
947 for nTries in range( self.nTries ):
948 self.fp.close()
948 self.fp.close()
949 self.fp = open( self.filename, 'rb' )
949 self.fp = open( self.filename, 'rb' )
950 self.fp.seek( currentPointer )
950 self.fp.seek( currentPointer )
951
951
952 self.fileSize = os.path.getsize( self.filename )
952 self.fileSize = os.path.getsize( self.filename )
953 currentSize = self.fileSize - currentPointer
953 currentSize = self.fileSize - currentPointer
954
954
955 if ( currentSize >= neededSize ):
955 if ( currentSize >= neededSize ):
956 return 1
956 return 1
957
957
958 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
958 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
959 sleep( self.delay )
959 sleep( self.delay )
960
960
961 return 0
961 return 0
962
962
963 def __jumpToLastBlock(self):
963 def __jumpToLastBlock(self):
964
964
965 if not(self.__isFirstTimeOnline):
965 if not(self.__isFirstTimeOnline):
966 return
966 return
967
967
968 csize = self.fileSize - self.fp.tell()
968 csize = self.fileSize - self.fp.tell()
969 blocksize = self.processingHeaderObj.blockSize
969 blocksize = self.processingHeaderObj.blockSize
970
970
971 #salta el primer bloque de datos
971 #salta el primer bloque de datos
972 if csize > self.processingHeaderObj.blockSize:
972 if csize > self.processingHeaderObj.blockSize:
973 self.fp.seek(self.fp.tell() + blocksize)
973 self.fp.seek(self.fp.tell() + blocksize)
974 else:
974 else:
975 return
975 return
976
976
977 csize = self.fileSize - self.fp.tell()
977 csize = self.fileSize - self.fp.tell()
978 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
978 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
979 while True:
979 while True:
980
980
981 if self.fp.tell()<self.fileSize:
981 if self.fp.tell()<self.fileSize:
982 self.fp.seek(self.fp.tell() + neededsize)
982 self.fp.seek(self.fp.tell() + neededsize)
983 else:
983 else:
984 self.fp.seek(self.fp.tell() - neededsize)
984 self.fp.seek(self.fp.tell() - neededsize)
985 break
985 break
986
986
987 # csize = self.fileSize - self.fp.tell()
987 # csize = self.fileSize - self.fp.tell()
988 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
988 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
989 # factor = int(csize/neededsize)
989 # factor = int(csize/neededsize)
990 # if factor > 0:
990 # if factor > 0:
991 # self.fp.seek(self.fp.tell() + factor*neededsize)
991 # self.fp.seek(self.fp.tell() + factor*neededsize)
992
992
993 self.flagIsNewFile = 0
993 self.flagIsNewFile = 0
994 self.__isFirstTimeOnline = 0
994 self.__isFirstTimeOnline = 0
995
995
996 def __setNewBlock(self):
996 def __setNewBlock(self):
997 #if self.server is None:
997 #if self.server is None:
998 if self.fp == None:
998 if self.fp == None:
999 return 0
999 return 0
1000
1000
1001 # if self.online:
1001 # if self.online:
1002 # self.__jumpToLastBlock()
1002 # self.__jumpToLastBlock()
1003
1003
1004 if self.flagIsNewFile:
1004 if self.flagIsNewFile:
1005 self.lastUTTime = self.basicHeaderObj.utc
1005 self.lastUTTime = self.basicHeaderObj.utc
1006 return 1
1006 return 1
1007
1007
1008 if self.realtime:
1008 if self.realtime:
1009 self.flagDiscontinuousBlock = 1
1009 self.flagDiscontinuousBlock = 1
1010 if not(self.setNextFile()):
1010 if not(self.setNextFile()):
1011 return 0
1011 return 0
1012 else:
1012 else:
1013 return 1
1013 return 1
1014 #if self.server is None:
1014 #if self.server is None:
1015 currentSize = self.fileSize - self.fp.tell()
1015 currentSize = self.fileSize - self.fp.tell()
1016 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1016 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1017 if (currentSize >= neededSize):
1017 if (currentSize >= neededSize):
1018 self.basicHeaderObj.read(self.fp)
1018 self.basicHeaderObj.read(self.fp)
1019 self.lastUTTime = self.basicHeaderObj.utc
1019 self.lastUTTime = self.basicHeaderObj.utc
1020 return 1
1020 return 1
1021 # else:
1021 # else:
1022 # self.basicHeaderObj.read(self.zHeader)
1022 # self.basicHeaderObj.read(self.zHeader)
1023 # self.lastUTTime = self.basicHeaderObj.utc
1023 # self.lastUTTime = self.basicHeaderObj.utc
1024 # return 1
1024 # return 1
1025 if self.__waitNewBlock():
1025 if self.__waitNewBlock():
1026 self.lastUTTime = self.basicHeaderObj.utc
1026 self.lastUTTime = self.basicHeaderObj.utc
1027 return 1
1027 return 1
1028 #if self.server is None:
1028 #if self.server is None:
1029 if not(self.setNextFile()):
1029 if not(self.setNextFile()):
1030 return 0
1030 return 0
1031
1031
1032 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
1032 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
1033 self.lastUTTime = self.basicHeaderObj.utc
1033 self.lastUTTime = self.basicHeaderObj.utc
1034
1034
1035 self.flagDiscontinuousBlock = 0
1035 self.flagDiscontinuousBlock = 0
1036
1036
1037 if deltaTime > self.maxTimeStep:
1037 if deltaTime > self.maxTimeStep:
1038 self.flagDiscontinuousBlock = 1
1038 self.flagDiscontinuousBlock = 1
1039
1039
1040 return 1
1040 return 1
1041
1041
1042 def readNextBlock(self):
1042 def readNextBlock(self):
1043
1043
1044 #Skip block out of startTime and endTime
1044 #Skip block out of startTime and endTime
1045 while True:
1045 while True:
1046 if not(self.__setNewBlock()):
1046 if not(self.__setNewBlock()):
1047 print 'returning'
1047 print 'returning'
1048 return 0
1048 return 0
1049
1049
1050 if not(self.readBlock()):
1050 if not(self.readBlock()):
1051 return 0
1051 return 0
1052
1052
1053 self.getBasicHeader()
1053 self.getBasicHeader()
1054
1054
1055 if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime):
1055 if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime):
1056
1056
1057 print "[Reading] Block No. %d/%d -> %s [Skipping]" %(self.nReadBlocks,
1057 print "[Reading] Block No. %d/%d -> %s [Skipping]" %(self.nReadBlocks,
1058 self.processingHeaderObj.dataBlocksPerFile,
1058 self.processingHeaderObj.dataBlocksPerFile,
1059 self.dataOut.datatime.ctime())
1059 self.dataOut.datatime.ctime())
1060 continue
1060 continue
1061
1061
1062 break
1062 break
1063
1063
1064 if self.verbose:
1064 if self.verbose:
1065 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1065 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1066 self.processingHeaderObj.dataBlocksPerFile,
1066 self.processingHeaderObj.dataBlocksPerFile,
1067 self.dataOut.datatime.ctime())
1067 self.dataOut.datatime.ctime())
1068 return 1
1068 return 1
1069
1069
1070 def __readFirstHeader(self):
1070 def __readFirstHeader(self):
1071
1071
1072 self.basicHeaderObj.read(self.fp)
1072 self.basicHeaderObj.read(self.fp)
1073 self.systemHeaderObj.read(self.fp)
1073 self.systemHeaderObj.read(self.fp)
1074 self.radarControllerHeaderObj.read(self.fp)
1074 self.radarControllerHeaderObj.read(self.fp)
1075 self.processingHeaderObj.read(self.fp)
1075 self.processingHeaderObj.read(self.fp)
1076
1076
1077 self.firstHeaderSize = self.basicHeaderObj.size
1077 self.firstHeaderSize = self.basicHeaderObj.size
1078
1078
1079 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
1079 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
1080 if datatype == 0:
1080 if datatype == 0:
1081 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
1081 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
1082 elif datatype == 1:
1082 elif datatype == 1:
1083 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
1083 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
1084 elif datatype == 2:
1084 elif datatype == 2:
1085 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
1085 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
1086 elif datatype == 3:
1086 elif datatype == 3:
1087 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
1087 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
1088 elif datatype == 4:
1088 elif datatype == 4:
1089 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
1089 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
1090 elif datatype == 5:
1090 elif datatype == 5:
1091 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
1091 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
1092 else:
1092 else:
1093 raise ValueError, 'Data type was not defined'
1093 raise ValueError, 'Data type was not defined'
1094
1094
1095 self.dtype = datatype_str
1095 self.dtype = datatype_str
1096 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1096 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1097 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
1097 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
1098 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1098 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1099 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1099 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1100 self.getBlockDimension()
1100 self.getBlockDimension()
1101
1101
1102 def __verifyFile(self, filename, msgFlag=True):
1102 def __verifyFile(self, filename, msgFlag=True):
1103
1103
1104 msg = None
1104 msg = None
1105
1105
1106 try:
1106 try:
1107 fp = open(filename, 'rb')
1107 fp = open(filename, 'rb')
1108 except IOError:
1108 except IOError:
1109
1109
1110 if msgFlag:
1110 if msgFlag:
1111 print "[Reading] File %s can't be opened" % (filename)
1111 print "[Reading] File %s can't be opened" % (filename)
1112
1112
1113 return False
1113 return False
1114
1114
1115 currentPosition = fp.tell()
1115 currentPosition = fp.tell()
1116 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1116 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1117
1117
1118 if neededSize == 0:
1118 if neededSize == 0:
1119 basicHeaderObj = BasicHeader(LOCALTIME)
1119 basicHeaderObj = BasicHeader(LOCALTIME)
1120 systemHeaderObj = SystemHeader()
1120 systemHeaderObj = SystemHeader()
1121 radarControllerHeaderObj = RadarControllerHeader()
1121 radarControllerHeaderObj = RadarControllerHeader()
1122 processingHeaderObj = ProcessingHeader()
1122 processingHeaderObj = ProcessingHeader()
1123
1123
1124 if not( basicHeaderObj.read(fp) ):
1124 if not( basicHeaderObj.read(fp) ):
1125 fp.close()
1125 fp.close()
1126 return False
1126 return False
1127
1127
1128 if not( systemHeaderObj.read(fp) ):
1128 if not( systemHeaderObj.read(fp) ):
1129 fp.close()
1129 fp.close()
1130 return False
1130 return False
1131
1131
1132 if not( radarControllerHeaderObj.read(fp) ):
1132 if not( radarControllerHeaderObj.read(fp) ):
1133 fp.close()
1133 fp.close()
1134 return False
1134 return False
1135
1135
1136 if not( processingHeaderObj.read(fp) ):
1136 if not( processingHeaderObj.read(fp) ):
1137 fp.close()
1137 fp.close()
1138 return False
1138 return False
1139
1139
1140 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1140 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1141 else:
1141 else:
1142 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
1142 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
1143
1143
1144 fp.close()
1144 fp.close()
1145
1145
1146 fileSize = os.path.getsize(filename)
1146 fileSize = os.path.getsize(filename)
1147 currentSize = fileSize - currentPosition
1147 currentSize = fileSize - currentPosition
1148
1148
1149 if currentSize < neededSize:
1149 if currentSize < neededSize:
1150 if msgFlag and (msg != None):
1150 if msgFlag and (msg != None):
1151 print msg
1151 print msg
1152 return False
1152 return False
1153
1153
1154 return True
1154 return True
1155
1155
1156 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1156 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1157
1157
1158 path_empty = True
1158 path_empty = True
1159
1159
1160 dateList = []
1160 dateList = []
1161 pathList = []
1161 pathList = []
1162
1162
1163 multi_path = path.split(',')
1163 multi_path = path.split(',')
1164
1164
1165 if not walk:
1165 if not walk:
1166
1166
1167 for single_path in multi_path:
1167 for single_path in multi_path:
1168
1168
1169 if not os.path.isdir(single_path):
1169 if not os.path.isdir(single_path):
1170 continue
1170 continue
1171
1171
1172 fileList = glob.glob1(single_path, "*"+ext)
1172 fileList = glob.glob1(single_path, "*"+ext)
1173
1173
1174 if not fileList:
1174 if not fileList:
1175 continue
1175 continue
1176
1176
1177 path_empty = False
1177 path_empty = False
1178
1178
1179 fileList.sort()
1179 fileList.sort()
1180
1180
1181 for thisFile in fileList:
1181 for thisFile in fileList:
1182
1182
1183 if not os.path.isfile(os.path.join(single_path, thisFile)):
1183 if not os.path.isfile(os.path.join(single_path, thisFile)):
1184 continue
1184 continue
1185
1185
1186 if not isRadarFile(thisFile):
1186 if not isRadarFile(thisFile):
1187 continue
1187 continue
1188
1188
1189 if not isFileInDateRange(thisFile, startDate, endDate):
1189 if not isFileInDateRange(thisFile, startDate, endDate):
1190 continue
1190 continue
1191
1191
1192 thisDate = getDateFromRadarFile(thisFile)
1192 thisDate = getDateFromRadarFile(thisFile)
1193
1193
1194 if thisDate in dateList:
1194 if thisDate in dateList:
1195 continue
1195 continue
1196
1196
1197 dateList.append(thisDate)
1197 dateList.append(thisDate)
1198 pathList.append(single_path)
1198 pathList.append(single_path)
1199
1199
1200 else:
1200 else:
1201 for single_path in multi_path:
1201 for single_path in multi_path:
1202
1202
1203 if not os.path.isdir(single_path):
1203 if not os.path.isdir(single_path):
1204 continue
1204 continue
1205
1205
1206 dirList = []
1206 dirList = []
1207
1207
1208 for thisPath in os.listdir(single_path):
1208 for thisPath in os.listdir(single_path):
1209
1209
1210 if not os.path.isdir(os.path.join(single_path,thisPath)):
1210 if not os.path.isdir(os.path.join(single_path,thisPath)):
1211 continue
1211 continue
1212
1212
1213 if not isRadarFolder(thisPath):
1213 if not isRadarFolder(thisPath):
1214 continue
1214 continue
1215
1215
1216 if not isFolderInDateRange(thisPath, startDate, endDate):
1216 if not isFolderInDateRange(thisPath, startDate, endDate):
1217 continue
1217 continue
1218
1218
1219 dirList.append(thisPath)
1219 dirList.append(thisPath)
1220
1220
1221 if not dirList:
1221 if not dirList:
1222 continue
1222 continue
1223
1223
1224 dirList.sort()
1224 dirList.sort()
1225
1225
1226 for thisDir in dirList:
1226 for thisDir in dirList:
1227
1227
1228 datapath = os.path.join(single_path, thisDir, expLabel)
1228 datapath = os.path.join(single_path, thisDir, expLabel)
1229 fileList = glob.glob1(datapath, "*"+ext)
1229 fileList = glob.glob1(datapath, "*"+ext)
1230
1230
1231 if not fileList:
1231 if not fileList:
1232 continue
1232 continue
1233
1233
1234 path_empty = False
1234 path_empty = False
1235
1235
1236 thisDate = getDateFromRadarFolder(thisDir)
1236 thisDate = getDateFromRadarFolder(thisDir)
1237
1237
1238 pathList.append(datapath)
1238 pathList.append(datapath)
1239 dateList.append(thisDate)
1239 dateList.append(thisDate)
1240
1240
1241 dateList.sort()
1241 dateList.sort()
1242
1242
1243 if walk:
1243 if walk:
1244 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1244 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1245 else:
1245 else:
1246 pattern_path = multi_path[0]
1246 pattern_path = multi_path[0]
1247
1247
1248 if path_empty:
1248 if path_empty:
1249 print "[Reading] No *%s files in %s for %s to %s" %(ext, pattern_path, startDate, endDate)
1249 print "[Reading] No *%s files in %s for %s to %s" %(ext, pattern_path, startDate, endDate)
1250 else:
1250 else:
1251 if not dateList:
1251 if not dateList:
1252 print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
1252 print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
1253
1253
1254 if include_path:
1254 if include_path:
1255 return dateList, pathList
1255 return dateList, pathList
1256
1256
1257 return dateList
1257 return dateList
1258
1258
1259 def setup(self,
1259 def setup(self,
1260 path=None,
1260 path=None,
1261 startDate=None,
1261 startDate=None,
1262 endDate=None,
1262 endDate=None,
1263 startTime=datetime.time(0,0,0),
1263 startTime=datetime.time(0,0,0),
1264 endTime=datetime.time(23,59,59),
1264 endTime=datetime.time(23,59,59),
1265 set=None,
1265 set=None,
1266 expLabel = "",
1266 expLabel = "",
1267 ext = None,
1267 ext = None,
1268 online = False,
1268 online = False,
1269 delay = 60,
1269 delay = 60,
1270 walk = True,
1270 walk = True,
1271 getblock = False,
1271 getblock = False,
1272 nTxs = 1,
1272 nTxs = 1,
1273 realtime=False,
1273 realtime=False,
1274 blocksize=None,
1274 blocksize=None,
1275 blocktime=None,
1275 blocktime=None,
1276 queue=None,
1276 queue=None,
1277 skip=None,
1277 skip=None,
1278 cursor=None,
1278 cursor=None,
1279 warnings=True,
1279 warnings=True,
1280 verbose=True,
1280 verbose=True,
1281 server=None):
1281 server=None):
1282 if server is not None:
1282 if server is not None:
1283 if 'tcp://' in server:
1283 if 'tcp://' in server:
1284 address = server
1284 address = server
1285 else:
1285 else:
1286 address = 'ipc:///tmp/%s' % server
1286 address = 'ipc:///tmp/%s' % server
1287 self.server = address
1287 self.server = address
1288 self.context = zmq.Context()
1288 self.context = zmq.Context()
1289 self.receiver = self.context.socket(zmq.PULL)
1289 self.receiver = self.context.socket(zmq.PULL)
1290 self.receiver.connect(self.server)
1290 self.receiver.connect(self.server)
1291 time.sleep(0.5)
1291 time.sleep(0.5)
1292 print '[Starting] ReceiverData from {}'.format(self.server)
1292 print '[Starting] ReceiverData from {}'.format(self.server)
1293 else:
1293 else:
1294 self.server = None
1294 self.server = None
1295 if path == None:
1295 if path == None:
1296 raise ValueError, "[Reading] The path is not valid"
1296 raise ValueError, "[Reading] The path is not valid"
1297
1297
1298 if ext == None:
1298 if ext == None:
1299 ext = self.ext
1299 ext = self.ext
1300
1300
1301 if online:
1301 if online:
1302 print "[Reading] Searching files in online mode..."
1302 print "[Reading] Searching files in online mode..."
1303
1303
1304 for nTries in range( self.nTries ):
1304 for nTries in range( self.nTries ):
1305 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1305 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1306
1306
1307 if fullpath:
1307 if fullpath:
1308 break
1308 break
1309
1309
1310 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
1310 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
1311 sleep( self.delay )
1311 sleep( self.delay )
1312
1312
1313 if not(fullpath):
1313 if not(fullpath):
1314 print "[Reading] There 'isn't any valid file in %s" % path
1314 print "[Reading] There 'isn't any valid file in %s" % path
1315 return
1315 return
1316
1316
1317 self.year = year
1317 self.year = year
1318 self.doy = doy
1318 self.doy = doy
1319 self.set = set - 1
1319 self.set = set - 1
1320 self.path = path
1320 self.path = path
1321 self.foldercounter = foldercounter
1321 self.foldercounter = foldercounter
1322 last_set = None
1322 last_set = None
1323 else:
1323 else:
1324 print "[Reading] Searching files in offline mode ..."
1324 print "[Reading] Searching files in offline mode ..."
1325 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1325 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1326 startTime=startTime, endTime=endTime,
1326 startTime=startTime, endTime=endTime,
1327 set=set, expLabel=expLabel, ext=ext,
1327 set=set, expLabel=expLabel, ext=ext,
1328 walk=walk, cursor=cursor,
1328 walk=walk, cursor=cursor,
1329 skip=skip, queue=queue)
1329 skip=skip, queue=queue)
1330
1330
1331 if not(pathList):
1331 if not(pathList):
1332 # print "[Reading] No *%s files in %s (%s - %s)"%(ext, path,
1332 # print "[Reading] No *%s files in %s (%s - %s)"%(ext, path,
1333 # datetime.datetime.combine(startDate,startTime).ctime(),
1333 # datetime.datetime.combine(startDate,startTime).ctime(),
1334 # datetime.datetime.combine(endDate,endTime).ctime())
1334 # datetime.datetime.combine(endDate,endTime).ctime())
1335
1335
1336 # sys.exit(-1)
1336 # sys.exit(-1)
1337
1337
1338 self.fileIndex = -1
1338 self.fileIndex = -1
1339 self.pathList = []
1339 self.pathList = []
1340 self.filenameList = []
1340 self.filenameList = []
1341 return
1341 return
1342
1342
1343 self.fileIndex = -1
1343 self.fileIndex = -1
1344 self.pathList = pathList
1344 self.pathList = pathList
1345 self.filenameList = filenameList
1345 self.filenameList = filenameList
1346 file_name = os.path.basename(filenameList[-1])
1346 file_name = os.path.basename(filenameList[-1])
1347 basename, ext = os.path.splitext(file_name)
1347 basename, ext = os.path.splitext(file_name)
1348 last_set = int(basename[-3:])
1348 last_set = int(basename[-3:])
1349
1349
1350 self.online = online
1350 self.online = online
1351 self.realtime = realtime
1351 self.realtime = realtime
1352 self.delay = delay
1352 self.delay = delay
1353 ext = ext.lower()
1353 ext = ext.lower()
1354 self.ext = ext
1354 self.ext = ext
1355 self.getByBlock = getblock
1355 self.getByBlock = getblock
1356 self.nTxs = nTxs
1356 self.nTxs = nTxs
1357 self.startTime = startTime
1357 self.startTime = startTime
1358 self.endTime = endTime
1358 self.endTime = endTime
1359
1359
1360 #Added-----------------
1360 #Added-----------------
1361 self.selBlocksize = blocksize
1361 self.selBlocksize = blocksize
1362 self.selBlocktime = blocktime
1362 self.selBlocktime = blocktime
1363
1363
1364 # Verbose-----------
1364 # Verbose-----------
1365 self.verbose = verbose
1365 self.verbose = verbose
1366 self.warnings = warnings
1366 self.warnings = warnings
1367
1367
1368 if not(self.setNextFile()):
1368 if not(self.setNextFile()):
1369 if (startDate!=None) and (endDate!=None):
1369 if (startDate!=None) and (endDate!=None):
1370 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1370 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1371 elif startDate != None:
1371 elif startDate != None:
1372 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1372 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1373 else:
1373 else:
1374 print "[Reading] No files"
1374 print "[Reading] No files"
1375
1375
1376 self.fileIndex = -1
1376 self.fileIndex = -1
1377 self.pathList = []
1377 self.pathList = []
1378 self.filenameList = []
1378 self.filenameList = []
1379 return
1379 return
1380
1380
1381 # self.getBasicHeader()
1381 # self.getBasicHeader()
1382
1382
1383 if last_set != None:
1383 if last_set != None:
1384 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1384 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1385 return
1385 return
1386
1386
1387 def getBasicHeader(self):
1387 def getBasicHeader(self):
1388
1388
1389 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1389 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1390
1390
1391 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1391 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1392
1392
1393 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1393 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1394
1394
1395 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1395 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1396
1396
1397 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1397 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1398
1398
1399 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1399 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1400
1400
1401 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1401 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1402
1402
1403 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1403 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1404
1404
1405
1405
1406 def getFirstHeader(self):
1406 def getFirstHeader(self):
1407
1407
1408 raise NotImplementedError
1408 raise NotImplementedError
1409
1409
1410 def getData(self):
1410 def getData(self):
1411
1411
1412 raise NotImplementedError
1412 raise NotImplementedError
1413
1413
1414 def hasNotDataInBuffer(self):
1414 def hasNotDataInBuffer(self):
1415
1415
1416 raise NotImplementedError
1416 raise NotImplementedError
1417
1417
1418 def readBlock(self):
1418 def readBlock(self):
1419
1419
1420 raise NotImplementedError
1420 raise NotImplementedError
1421
1421
1422 def isEndProcess(self):
1422 def isEndProcess(self):
1423
1423
1424 return self.flagNoMoreFiles
1424 return self.flagNoMoreFiles
1425
1425
1426 def printReadBlocks(self):
1426 def printReadBlocks(self):
1427
1427
1428 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1428 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1429
1429
1430 def printTotalBlocks(self):
1430 def printTotalBlocks(self):
1431
1431
1432 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1432 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1433
1433
1434 def printNumberOfBlock(self):
1434 def printNumberOfBlock(self):
1435 'SPAM!'
1435
1436
1436 if self.flagIsNewBlock:
1437 # if self.flagIsNewBlock:
1437 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1438 # print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1438 self.processingHeaderObj.dataBlocksPerFile,
1439 # self.processingHeaderObj.dataBlocksPerFile,
1439 self.dataOut.datatime.ctime())
1440 # self.dataOut.datatime.ctime())
1440
1441
1441 def printInfo(self):
1442 def printInfo(self):
1442
1443
1443 if self.__printInfo == False:
1444 if self.__printInfo == False:
1444 return
1445 return
1445
1446
1446 self.basicHeaderObj.printInfo()
1447 self.basicHeaderObj.printInfo()
1447 self.systemHeaderObj.printInfo()
1448 self.systemHeaderObj.printInfo()
1448 self.radarControllerHeaderObj.printInfo()
1449 self.radarControllerHeaderObj.printInfo()
1449 self.processingHeaderObj.printInfo()
1450 self.processingHeaderObj.printInfo()
1450
1451
1451 self.__printInfo = False
1452 self.__printInfo = False
1452
1453
1453
1454
1454 def run(self,
1455 def run(self,
1455 path=None,
1456 path=None,
1456 startDate=None,
1457 startDate=None,
1457 endDate=None,
1458 endDate=None,
1458 startTime=datetime.time(0,0,0),
1459 startTime=datetime.time(0,0,0),
1459 endTime=datetime.time(23,59,59),
1460 endTime=datetime.time(23,59,59),
1460 set=None,
1461 set=None,
1461 expLabel = "",
1462 expLabel = "",
1462 ext = None,
1463 ext = None,
1463 online = False,
1464 online = False,
1464 delay = 60,
1465 delay = 60,
1465 walk = True,
1466 walk = True,
1466 getblock = False,
1467 getblock = False,
1467 nTxs = 1,
1468 nTxs = 1,
1468 realtime=False,
1469 realtime=False,
1469 blocksize=None,
1470 blocksize=None,
1470 blocktime=None,
1471 blocktime=None,
1471 queue=None,
1472 queue=None,
1472 skip=None,
1473 skip=None,
1473 cursor=None,
1474 cursor=None,
1474 warnings=True,
1475 warnings=True,
1475 server=None,
1476 server=None,
1476 verbose=True, **kwargs):
1477 verbose=True, **kwargs):
1477
1478
1478 if not(self.isConfig):
1479 if not(self.isConfig):
1479 # self.dataOut = dataOut
1480 # self.dataOut = dataOut
1480 self.setup( path=path,
1481 self.setup( path=path,
1481 startDate=startDate,
1482 startDate=startDate,
1482 endDate=endDate,
1483 endDate=endDate,
1483 startTime=startTime,
1484 startTime=startTime,
1484 endTime=endTime,
1485 endTime=endTime,
1485 set=set,
1486 set=set,
1486 expLabel=expLabel,
1487 expLabel=expLabel,
1487 ext=ext,
1488 ext=ext,
1488 online=online,
1489 online=online,
1489 delay=delay,
1490 delay=delay,
1490 walk=walk,
1491 walk=walk,
1491 getblock=getblock,
1492 getblock=getblock,
1492 nTxs=nTxs,
1493 nTxs=nTxs,
1493 realtime=realtime,
1494 realtime=realtime,
1494 blocksize=blocksize,
1495 blocksize=blocksize,
1495 blocktime=blocktime,
1496 blocktime=blocktime,
1496 queue=queue,
1497 queue=queue,
1497 skip=skip,
1498 skip=skip,
1498 cursor=cursor,
1499 cursor=cursor,
1499 warnings=warnings,
1500 warnings=warnings,
1500 server=server,
1501 server=server,
1501 verbose=verbose)
1502 verbose=verbose)
1502 self.isConfig = True
1503 self.isConfig = True
1503 if server is None:
1504 if server is None:
1504 self.getData()
1505 self.getData()
1505 else:
1506 else:
1506 self.getFromServer()
1507 self.getFromServer()
1507
1508
1508 class JRODataWriter(JRODataIO):
1509 class JRODataWriter(JRODataIO):
1509
1510
1510 """
1511 """
1511 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1512 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1512 de los datos siempre se realiza por bloques.
1513 de los datos siempre se realiza por bloques.
1513 """
1514 """
1514
1515
1515 blockIndex = 0
1516 blockIndex = 0
1516
1517
1517 path = None
1518 path = None
1518
1519
1519 setFile = None
1520 setFile = None
1520
1521
1521 profilesPerBlock = None
1522 profilesPerBlock = None
1522
1523
1523 blocksPerFile = None
1524 blocksPerFile = None
1524
1525
1525 nWriteBlocks = 0
1526 nWriteBlocks = 0
1526
1527
1527 fileDate = None
1528 fileDate = None
1528
1529
1529 def __init__(self, dataOut=None):
1530 def __init__(self, dataOut=None):
1530 raise NotImplementedError
1531 raise NotImplementedError
1531
1532
1532
1533
1533 def hasAllDataInBuffer(self):
1534 def hasAllDataInBuffer(self):
1534 raise NotImplementedError
1535 raise NotImplementedError
1535
1536
1536
1537
1537 def setBlockDimension(self):
1538 def setBlockDimension(self):
1538 raise NotImplementedError
1539 raise NotImplementedError
1539
1540
1540
1541
1541 def writeBlock(self):
1542 def writeBlock(self):
1542 raise NotImplementedError
1543 raise NotImplementedError
1543
1544
1544
1545
1545 def putData(self):
1546 def putData(self):
1546 raise NotImplementedError
1547 raise NotImplementedError
1547
1548
1548
1549
1549 def getProcessFlags(self):
1550 def getProcessFlags(self):
1550
1551
1551 processFlags = 0
1552 processFlags = 0
1552
1553
1553 dtype_index = get_dtype_index(self.dtype)
1554 dtype_index = get_dtype_index(self.dtype)
1554 procflag_dtype = get_procflag_dtype(dtype_index)
1555 procflag_dtype = get_procflag_dtype(dtype_index)
1555
1556
1556 processFlags += procflag_dtype
1557 processFlags += procflag_dtype
1557
1558
1558 if self.dataOut.flagDecodeData:
1559 if self.dataOut.flagDecodeData:
1559 processFlags += PROCFLAG.DECODE_DATA
1560 processFlags += PROCFLAG.DECODE_DATA
1560
1561
1561 if self.dataOut.flagDeflipData:
1562 if self.dataOut.flagDeflipData:
1562 processFlags += PROCFLAG.DEFLIP_DATA
1563 processFlags += PROCFLAG.DEFLIP_DATA
1563
1564
1564 if self.dataOut.code is not None:
1565 if self.dataOut.code is not None:
1565 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1566 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1566
1567
1567 if self.dataOut.nCohInt > 1:
1568 if self.dataOut.nCohInt > 1:
1568 processFlags += PROCFLAG.COHERENT_INTEGRATION
1569 processFlags += PROCFLAG.COHERENT_INTEGRATION
1569
1570
1570 if self.dataOut.type == "Spectra":
1571 if self.dataOut.type == "Spectra":
1571 if self.dataOut.nIncohInt > 1:
1572 if self.dataOut.nIncohInt > 1:
1572 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1573 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1573
1574
1574 if self.dataOut.data_dc is not None:
1575 if self.dataOut.data_dc is not None:
1575 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1576 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1576
1577
1577 if self.dataOut.flagShiftFFT:
1578 if self.dataOut.flagShiftFFT:
1578 processFlags += PROCFLAG.SHIFT_FFT_DATA
1579 processFlags += PROCFLAG.SHIFT_FFT_DATA
1579
1580
1580 return processFlags
1581 return processFlags
1581
1582
1582 def setBasicHeader(self):
1583 def setBasicHeader(self):
1583
1584
1584 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1585 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1585 self.basicHeaderObj.version = self.versionFile
1586 self.basicHeaderObj.version = self.versionFile
1586 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1587 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1587
1588
1588 utc = numpy.floor(self.dataOut.utctime)
1589 utc = numpy.floor(self.dataOut.utctime)
1589 milisecond = (self.dataOut.utctime - utc)* 1000.0
1590 milisecond = (self.dataOut.utctime - utc)* 1000.0
1590
1591
1591 self.basicHeaderObj.utc = utc
1592 self.basicHeaderObj.utc = utc
1592 self.basicHeaderObj.miliSecond = milisecond
1593 self.basicHeaderObj.miliSecond = milisecond
1593 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1594 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1594 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1595 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1595 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1596 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1596
1597
1597 def setFirstHeader(self):
1598 def setFirstHeader(self):
1598 """
1599 """
1599 Obtiene una copia del First Header
1600 Obtiene una copia del First Header
1600
1601
1601 Affected:
1602 Affected:
1602
1603
1603 self.basicHeaderObj
1604 self.basicHeaderObj
1604 self.systemHeaderObj
1605 self.systemHeaderObj
1605 self.radarControllerHeaderObj
1606 self.radarControllerHeaderObj
1606 self.processingHeaderObj self.
1607 self.processingHeaderObj self.
1607
1608
1608 Return:
1609 Return:
1609 None
1610 None
1610 """
1611 """
1611
1612
1612 raise NotImplementedError
1613 raise NotImplementedError
1613
1614
1614 def __writeFirstHeader(self):
1615 def __writeFirstHeader(self):
1615 """
1616 """
1616 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1617 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1617
1618
1618 Affected:
1619 Affected:
1619 __dataType
1620 __dataType
1620
1621
1621 Return:
1622 Return:
1622 None
1623 None
1623 """
1624 """
1624
1625
1625 # CALCULAR PARAMETROS
1626 # CALCULAR PARAMETROS
1626
1627
1627 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1628 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1628 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1629 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1629
1630
1630 self.basicHeaderObj.write(self.fp)
1631 self.basicHeaderObj.write(self.fp)
1631 self.systemHeaderObj.write(self.fp)
1632 self.systemHeaderObj.write(self.fp)
1632 self.radarControllerHeaderObj.write(self.fp)
1633 self.radarControllerHeaderObj.write(self.fp)
1633 self.processingHeaderObj.write(self.fp)
1634 self.processingHeaderObj.write(self.fp)
1634
1635
1635 def __setNewBlock(self):
1636 def __setNewBlock(self):
1636 """
1637 """
1637 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1638 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1638
1639
1639 Return:
1640 Return:
1640 0 : si no pudo escribir nada
1641 0 : si no pudo escribir nada
1641 1 : Si escribio el Basic el First Header
1642 1 : Si escribio el Basic el First Header
1642 """
1643 """
1643 if self.fp == None:
1644 if self.fp == None:
1644 self.setNextFile()
1645 self.setNextFile()
1645
1646
1646 if self.flagIsNewFile:
1647 if self.flagIsNewFile:
1647 return 1
1648 return 1
1648
1649
1649 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1650 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1650 self.basicHeaderObj.write(self.fp)
1651 self.basicHeaderObj.write(self.fp)
1651 return 1
1652 return 1
1652
1653
1653 if not( self.setNextFile() ):
1654 if not( self.setNextFile() ):
1654 return 0
1655 return 0
1655
1656
1656 return 1
1657 return 1
1657
1658
1658
1659
1659 def writeNextBlock(self):
1660 def writeNextBlock(self):
1660 """
1661 """
1661 Selecciona el bloque siguiente de datos y los escribe en un file
1662 Selecciona el bloque siguiente de datos y los escribe en un file
1662
1663
1663 Return:
1664 Return:
1664 0 : Si no hizo pudo escribir el bloque de datos
1665 0 : Si no hizo pudo escribir el bloque de datos
1665 1 : Si no pudo escribir el bloque de datos
1666 1 : Si no pudo escribir el bloque de datos
1666 """
1667 """
1667 if not( self.__setNewBlock() ):
1668 if not( self.__setNewBlock() ):
1668 return 0
1669 return 0
1669
1670
1670 self.writeBlock()
1671 self.writeBlock()
1671
1672
1672 print "[Writing] Block No. %d/%d" %(self.blockIndex,
1673 print "[Writing] Block No. %d/%d" %(self.blockIndex,
1673 self.processingHeaderObj.dataBlocksPerFile)
1674 self.processingHeaderObj.dataBlocksPerFile)
1674
1675
1675 return 1
1676 return 1
1676
1677
1677 def setNextFile(self):
1678 def setNextFile(self):
1678 """
1679 """
1679 Determina el siguiente file que sera escrito
1680 Determina el siguiente file que sera escrito
1680
1681
1681 Affected:
1682 Affected:
1682 self.filename
1683 self.filename
1683 self.subfolder
1684 self.subfolder
1684 self.fp
1685 self.fp
1685 self.setFile
1686 self.setFile
1686 self.flagIsNewFile
1687 self.flagIsNewFile
1687
1688
1688 Return:
1689 Return:
1689 0 : Si el archivo no puede ser escrito
1690 0 : Si el archivo no puede ser escrito
1690 1 : Si el archivo esta listo para ser escrito
1691 1 : Si el archivo esta listo para ser escrito
1691 """
1692 """
1692 ext = self.ext
1693 ext = self.ext
1693 path = self.path
1694 path = self.path
1694
1695
1695 if self.fp != None:
1696 if self.fp != None:
1696 self.fp.close()
1697 self.fp.close()
1697
1698
1698 timeTuple = time.localtime( self.dataOut.utctime)
1699 timeTuple = time.localtime( self.dataOut.utctime)
1699 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1700 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1700
1701
1701 fullpath = os.path.join( path, subfolder )
1702 fullpath = os.path.join( path, subfolder )
1702 setFile = self.setFile
1703 setFile = self.setFile
1703
1704
1704 if not( os.path.exists(fullpath) ):
1705 if not( os.path.exists(fullpath) ):
1705 os.mkdir(fullpath)
1706 os.mkdir(fullpath)
1706 setFile = -1 #inicializo mi contador de seteo
1707 setFile = -1 #inicializo mi contador de seteo
1707 else:
1708 else:
1708 filesList = os.listdir( fullpath )
1709 filesList = os.listdir( fullpath )
1709 if len( filesList ) > 0:
1710 if len( filesList ) > 0:
1710 filesList = sorted( filesList, key=str.lower )
1711 filesList = sorted( filesList, key=str.lower )
1711 filen = filesList[-1]
1712 filen = filesList[-1]
1712 # el filename debera tener el siguiente formato
1713 # el filename debera tener el siguiente formato
1713 # 0 1234 567 89A BCDE (hex)
1714 # 0 1234 567 89A BCDE (hex)
1714 # x YYYY DDD SSS .ext
1715 # x YYYY DDD SSS .ext
1715 if isNumber( filen[8:11] ):
1716 if isNumber( filen[8:11] ):
1716 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1717 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1717 else:
1718 else:
1718 setFile = -1
1719 setFile = -1
1719 else:
1720 else:
1720 setFile = -1 #inicializo mi contador de seteo
1721 setFile = -1 #inicializo mi contador de seteo
1721
1722
1722 setFile += 1
1723 setFile += 1
1723
1724
1724 #If this is a new day it resets some values
1725 #If this is a new day it resets some values
1725 if self.dataOut.datatime.date() > self.fileDate:
1726 if self.dataOut.datatime.date() > self.fileDate:
1726 setFile = 0
1727 setFile = 0
1727 self.nTotalBlocks = 0
1728 self.nTotalBlocks = 0
1728
1729
1729 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext )
1730 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext )
1730
1731
1731 filename = os.path.join( path, subfolder, filen )
1732 filename = os.path.join( path, subfolder, filen )
1732
1733
1733 fp = open( filename,'wb' )
1734 fp = open( filename,'wb' )
1734
1735
1735 self.blockIndex = 0
1736 self.blockIndex = 0
1736
1737
1737 #guardando atributos
1738 #guardando atributos
1738 self.filename = filename
1739 self.filename = filename
1739 self.subfolder = subfolder
1740 self.subfolder = subfolder
1740 self.fp = fp
1741 self.fp = fp
1741 self.setFile = setFile
1742 self.setFile = setFile
1742 self.flagIsNewFile = 1
1743 self.flagIsNewFile = 1
1743 self.fileDate = self.dataOut.datatime.date()
1744 self.fileDate = self.dataOut.datatime.date()
1744
1745
1745 self.setFirstHeader()
1746 self.setFirstHeader()
1746
1747
1747 print '[Writing] Opening file: %s'%self.filename
1748 print '[Writing] Opening file: %s'%self.filename
1748
1749
1749 self.__writeFirstHeader()
1750 self.__writeFirstHeader()
1750
1751
1751 return 1
1752 return 1
1752
1753
1753 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1754 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1754 """
1755 """
1755 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1756 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1756
1757
1757 Inputs:
1758 Inputs:
1758 path : directory where data will be saved
1759 path : directory where data will be saved
1759 profilesPerBlock : number of profiles per block
1760 profilesPerBlock : number of profiles per block
1760 set : initial file set
1761 set : initial file set
1761 datatype : An integer number that defines data type:
1762 datatype : An integer number that defines data type:
1762 0 : int8 (1 byte)
1763 0 : int8 (1 byte)
1763 1 : int16 (2 bytes)
1764 1 : int16 (2 bytes)
1764 2 : int32 (4 bytes)
1765 2 : int32 (4 bytes)
1765 3 : int64 (8 bytes)
1766 3 : int64 (8 bytes)
1766 4 : float32 (4 bytes)
1767 4 : float32 (4 bytes)
1767 5 : double64 (8 bytes)
1768 5 : double64 (8 bytes)
1768
1769
1769 Return:
1770 Return:
1770 0 : Si no realizo un buen seteo
1771 0 : Si no realizo un buen seteo
1771 1 : Si realizo un buen seteo
1772 1 : Si realizo un buen seteo
1772 """
1773 """
1773
1774
1774 if ext == None:
1775 if ext == None:
1775 ext = self.ext
1776 ext = self.ext
1776
1777
1777 self.ext = ext.lower()
1778 self.ext = ext.lower()
1778
1779
1779 self.path = path
1780 self.path = path
1780
1781
1781 if set is None:
1782 if set is None:
1782 self.setFile = -1
1783 self.setFile = -1
1783 else:
1784 else:
1784 self.setFile = set - 1
1785 self.setFile = set - 1
1785
1786
1786 self.blocksPerFile = blocksPerFile
1787 self.blocksPerFile = blocksPerFile
1787
1788
1788 self.profilesPerBlock = profilesPerBlock
1789 self.profilesPerBlock = profilesPerBlock
1789
1790
1790 self.dataOut = dataOut
1791 self.dataOut = dataOut
1791 self.fileDate = self.dataOut.datatime.date()
1792 self.fileDate = self.dataOut.datatime.date()
1792 #By default
1793 #By default
1793 self.dtype = self.dataOut.dtype
1794 self.dtype = self.dataOut.dtype
1794
1795
1795 if datatype is not None:
1796 if datatype is not None:
1796 self.dtype = get_numpy_dtype(datatype)
1797 self.dtype = get_numpy_dtype(datatype)
1797
1798
1798 if not(self.setNextFile()):
1799 if not(self.setNextFile()):
1799 print "[Writing] There isn't a next file"
1800 print "[Writing] There isn't a next file"
1800 return 0
1801 return 0
1801
1802
1802 self.setBlockDimension()
1803 self.setBlockDimension()
1803
1804
1804 return 1
1805 return 1
1805
1806
1806 def run(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1807 def run(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1807
1808
1808 if not(self.isConfig):
1809 if not(self.isConfig):
1809
1810
1810 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock, set=set, ext=ext, datatype=datatype, **kwargs)
1811 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock, set=set, ext=ext, datatype=datatype, **kwargs)
1811 self.isConfig = True
1812 self.isConfig = True
1812
1813
1813 self.putData()
1814 self.putData()
@@ -1,1105 +1,1105
1 import numpy
1 import numpy
2 import time
2 import time
3 import os
3 import os
4 import h5py
4 import h5py
5 import re
5 import re
6 import datetime
6 import datetime
7
7
8 from schainpy.model.data.jrodata import *
8 from schainpy.model.data.jrodata import *
9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
10 # from jroIO_base import *
10 # from jroIO_base import *
11 from schainpy.model.io.jroIO_base import *
11 from schainpy.model.io.jroIO_base import *
12 import schainpy
12 import schainpy
13
13
14
14
15 class ParamReader(ProcessingUnit):
15 class ParamReader(ProcessingUnit):
16 '''
16 '''
17 Reads HDF5 format files
17 Reads HDF5 format files
18
18
19 path
19 path
20
20
21 startDate
21 startDate
22
22
23 endDate
23 endDate
24
24
25 startTime
25 startTime
26
26
27 endTime
27 endTime
28 '''
28 '''
29
29
30 ext = ".hdf5"
30 ext = ".hdf5"
31
31
32 optchar = "D"
32 optchar = "D"
33
33
34 timezone = None
34 timezone = None
35
35
36 startTime = None
36 startTime = None
37
37
38 endTime = None
38 endTime = None
39
39
40 fileIndex = None
40 fileIndex = None
41
41
42 utcList = None #To select data in the utctime list
42 utcList = None #To select data in the utctime list
43
43
44 blockList = None #List to blocks to be read from the file
44 blockList = None #List to blocks to be read from the file
45
45
46 blocksPerFile = None #Number of blocks to be read
46 blocksPerFile = None #Number of blocks to be read
47
47
48 blockIndex = None
48 blockIndex = None
49
49
50 path = None
50 path = None
51
51
52 #List of Files
52 #List of Files
53
53
54 filenameList = None
54 filenameList = None
55
55
56 datetimeList = None
56 datetimeList = None
57
57
58 #Hdf5 File
58 #Hdf5 File
59
59
60 listMetaname = None
60 listMetaname = None
61
61
62 listMeta = None
62 listMeta = None
63
63
64 listDataname = None
64 listDataname = None
65
65
66 listData = None
66 listData = None
67
67
68 listShapes = None
68 listShapes = None
69
69
70 fp = None
70 fp = None
71
71
72 #dataOut reconstruction
72 #dataOut reconstruction
73
73
74 dataOut = None
74 dataOut = None
75
75
76
76
77 def __init__(self, **kwargs):
77 def __init__(self, **kwargs):
78 ProcessingUnit.__init__(self, **kwargs)
78 ProcessingUnit.__init__(self, **kwargs)
79 self.dataOut = Parameters()
79 self.dataOut = Parameters()
80 return
80 return
81
81
82 def setup(self, **kwargs):
82 def setup(self, **kwargs):
83
83
84 path = kwargs['path']
84 path = kwargs['path']
85 startDate = kwargs['startDate']
85 startDate = kwargs['startDate']
86 endDate = kwargs['endDate']
86 endDate = kwargs['endDate']
87 startTime = kwargs['startTime']
87 startTime = kwargs['startTime']
88 endTime = kwargs['endTime']
88 endTime = kwargs['endTime']
89 walk = kwargs['walk']
89 walk = kwargs['walk']
90 if kwargs.has_key('ext'):
90 if kwargs.has_key('ext'):
91 ext = kwargs['ext']
91 ext = kwargs['ext']
92 else:
92 else:
93 ext = '.hdf5'
93 ext = '.hdf5'
94 if kwargs.has_key('timezone'):
94 if kwargs.has_key('timezone'):
95 self.timezone = kwargs['timezone']
95 self.timezone = kwargs['timezone']
96 else:
96 else:
97 self.timezone = 'lt'
97 self.timezone = 'lt'
98
98
99 print "[Reading] Searching files in offline mode ..."
99 print "[Reading] Searching files in offline mode ..."
100 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
100 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
101 startTime=startTime, endTime=endTime,
101 startTime=startTime, endTime=endTime,
102 ext=ext, walk=walk)
102 ext=ext, walk=walk)
103
103
104 if not(filenameList):
104 if not(filenameList):
105 print "There is no files into the folder: %s"%(path)
105 print "There is no files into the folder: %s"%(path)
106 sys.exit(-1)
106 sys.exit(-1)
107
107
108 self.fileIndex = -1
108 self.fileIndex = -1
109 self.startTime = startTime
109 self.startTime = startTime
110 self.endTime = endTime
110 self.endTime = endTime
111
111
112 self.__readMetadata()
112 self.__readMetadata()
113
113
114 self.__setNextFileOffline()
114 self.__setNextFileOffline()
115
115
116 return
116 return
117
117
118 def __searchFilesOffLine(self,
118 def __searchFilesOffLine(self,
119 path,
119 path,
120 startDate=None,
120 startDate=None,
121 endDate=None,
121 endDate=None,
122 startTime=datetime.time(0,0,0),
122 startTime=datetime.time(0,0,0),
123 endTime=datetime.time(23,59,59),
123 endTime=datetime.time(23,59,59),
124 ext='.hdf5',
124 ext='.hdf5',
125 walk=True):
125 walk=True):
126
126
127 expLabel = ''
127 expLabel = ''
128 self.filenameList = []
128 self.filenameList = []
129 self.datetimeList = []
129 self.datetimeList = []
130
130
131 pathList = []
131 pathList = []
132
132
133 JRODataObj = JRODataReader()
133 JRODataObj = JRODataReader()
134 dateList, pathList = JRODataObj.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
134 dateList, pathList = JRODataObj.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
135
135
136 if dateList == []:
136 if dateList == []:
137 print "[Reading] No *%s files in %s from %s to %s)"%(ext, path,
137 print "[Reading] No *%s files in %s from %s to %s)"%(ext, path,
138 datetime.datetime.combine(startDate,startTime).ctime(),
138 datetime.datetime.combine(startDate,startTime).ctime(),
139 datetime.datetime.combine(endDate,endTime).ctime())
139 datetime.datetime.combine(endDate,endTime).ctime())
140
140
141 return None, None
141 return None, None
142
142
143 if len(dateList) > 1:
143 if len(dateList) > 1:
144 print "[Reading] %d days were found in date range: %s - %s" %(len(dateList), startDate, endDate)
144 print "[Reading] %d days were found in date range: %s - %s" %(len(dateList), startDate, endDate)
145 else:
145 else:
146 print "[Reading] data was found for the date %s" %(dateList[0])
146 print "[Reading] data was found for the date %s" %(dateList[0])
147
147
148 filenameList = []
148 filenameList = []
149 datetimeList = []
149 datetimeList = []
150
150
151 #----------------------------------------------------------------------------------
151 #----------------------------------------------------------------------------------
152
152
153 for thisPath in pathList:
153 for thisPath in pathList:
154 # thisPath = pathList[pathDict[file]]
154 # thisPath = pathList[pathDict[file]]
155
155
156 fileList = glob.glob1(thisPath, "*%s" %ext)
156 fileList = glob.glob1(thisPath, "*%s" %ext)
157 fileList.sort()
157 fileList.sort()
158
158
159 for file in fileList:
159 for file in fileList:
160
160
161 filename = os.path.join(thisPath,file)
161 filename = os.path.join(thisPath,file)
162
162
163 if not isFileInDateRange(filename, startDate, endDate):
163 if not isFileInDateRange(filename, startDate, endDate):
164 continue
164 continue
165
165
166 thisDatetime = self.__isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
166 thisDatetime = self.__isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
167
167
168 if not(thisDatetime):
168 if not(thisDatetime):
169 continue
169 continue
170
170
171 filenameList.append(filename)
171 filenameList.append(filename)
172 datetimeList.append(thisDatetime)
172 datetimeList.append(thisDatetime)
173
173
174 if not(filenameList):
174 if not(filenameList):
175 print "[Reading] Any file was found int time range %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
175 print "[Reading] Any file was found int time range %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
176 return None, None
176 return None, None
177
177
178 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
178 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
179 print
179 print
180
180
181 for i in range(len(filenameList)):
181 # for i in range(len(filenameList)):
182 print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
182 # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
183
183
184 self.filenameList = filenameList
184 self.filenameList = filenameList
185 self.datetimeList = datetimeList
185 self.datetimeList = datetimeList
186
186
187 return pathList, filenameList
187 return pathList, filenameList
188
188
189 def __isFileInTimeRange(self,filename, startDate, endDate, startTime, endTime):
189 def __isFileInTimeRange(self,filename, startDate, endDate, startTime, endTime):
190
190
191 """
191 """
192 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
192 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
193
193
194 Inputs:
194 Inputs:
195 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
195 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
196
196
197 startDate : fecha inicial del rango seleccionado en formato datetime.date
197 startDate : fecha inicial del rango seleccionado en formato datetime.date
198
198
199 endDate : fecha final del rango seleccionado en formato datetime.date
199 endDate : fecha final del rango seleccionado en formato datetime.date
200
200
201 startTime : tiempo inicial del rango seleccionado en formato datetime.time
201 startTime : tiempo inicial del rango seleccionado en formato datetime.time
202
202
203 endTime : tiempo final del rango seleccionado en formato datetime.time
203 endTime : tiempo final del rango seleccionado en formato datetime.time
204
204
205 Return:
205 Return:
206 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
206 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
207 fecha especificado, de lo contrario retorna False.
207 fecha especificado, de lo contrario retorna False.
208
208
209 Excepciones:
209 Excepciones:
210 Si el archivo no existe o no puede ser abierto
210 Si el archivo no existe o no puede ser abierto
211 Si la cabecera no puede ser leida.
211 Si la cabecera no puede ser leida.
212
212
213 """
213 """
214
214
215 try:
215 try:
216 fp = h5py.File(filename,'r')
216 fp = h5py.File(filename,'r')
217 grp1 = fp['Data']
217 grp1 = fp['Data']
218
218
219 except IOError:
219 except IOError:
220 traceback.print_exc()
220 traceback.print_exc()
221 raise IOError, "The file %s can't be opened" %(filename)
221 raise IOError, "The file %s can't be opened" %(filename)
222 #chino rata
222 #chino rata
223 #In case has utctime attribute
223 #In case has utctime attribute
224 grp2 = grp1['utctime']
224 grp2 = grp1['utctime']
225 # thisUtcTime = grp2.value[0] - 5*3600 #To convert to local time
225 # thisUtcTime = grp2.value[0] - 5*3600 #To convert to local time
226 thisUtcTime = grp2.value[0]
226 thisUtcTime = grp2.value[0]
227
227
228 fp.close()
228 fp.close()
229
229
230 if self.timezone == 'lt':
230 if self.timezone == 'lt':
231 thisUtcTime -= 5*3600
231 thisUtcTime -= 5*3600
232
232
233 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
233 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
234 # thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0])
234 # thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0])
235 thisDate = thisDatetime.date()
235 thisDate = thisDatetime.date()
236 thisTime = thisDatetime.time()
236 thisTime = thisDatetime.time()
237
237
238 startUtcTime = (datetime.datetime.combine(thisDate,startTime)- datetime.datetime(1970, 1, 1)).total_seconds()
238 startUtcTime = (datetime.datetime.combine(thisDate,startTime)- datetime.datetime(1970, 1, 1)).total_seconds()
239 endUtcTime = (datetime.datetime.combine(thisDate,endTime)- datetime.datetime(1970, 1, 1)).total_seconds()
239 endUtcTime = (datetime.datetime.combine(thisDate,endTime)- datetime.datetime(1970, 1, 1)).total_seconds()
240
240
241 #General case
241 #General case
242 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
242 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
243 #-----------o----------------------------o-----------
243 #-----------o----------------------------o-----------
244 # startTime endTime
244 # startTime endTime
245
245
246 if endTime >= startTime:
246 if endTime >= startTime:
247 thisUtcLog = numpy.logical_and(thisUtcTime > startUtcTime, thisUtcTime < endUtcTime)
247 thisUtcLog = numpy.logical_and(thisUtcTime > startUtcTime, thisUtcTime < endUtcTime)
248 if numpy.any(thisUtcLog): #If there is one block between the hours mentioned
248 if numpy.any(thisUtcLog): #If there is one block between the hours mentioned
249 return thisDatetime
249 return thisDatetime
250 return None
250 return None
251
251
252 #If endTime < startTime then endTime belongs to the next day
252 #If endTime < startTime then endTime belongs to the next day
253 #<<<<<<<<<<<o o>>>>>>>>>>>
253 #<<<<<<<<<<<o o>>>>>>>>>>>
254 #-----------o----------------------------o-----------
254 #-----------o----------------------------o-----------
255 # endTime startTime
255 # endTime startTime
256
256
257 if (thisDate == startDate) and numpy.all(thisUtcTime < startUtcTime):
257 if (thisDate == startDate) and numpy.all(thisUtcTime < startUtcTime):
258 return None
258 return None
259
259
260 if (thisDate == endDate) and numpy.all(thisUtcTime > endUtcTime):
260 if (thisDate == endDate) and numpy.all(thisUtcTime > endUtcTime):
261 return None
261 return None
262
262
263 if numpy.all(thisUtcTime < startUtcTime) and numpy.all(thisUtcTime > endUtcTime):
263 if numpy.all(thisUtcTime < startUtcTime) and numpy.all(thisUtcTime > endUtcTime):
264 return None
264 return None
265
265
266 return thisDatetime
266 return thisDatetime
267
267
268 def __setNextFileOffline(self):
268 def __setNextFileOffline(self):
269
269
270 self.fileIndex += 1
270 self.fileIndex += 1
271 idFile = self.fileIndex
271 idFile = self.fileIndex
272
272
273 if not(idFile < len(self.filenameList)):
273 if not(idFile < len(self.filenameList)):
274 print "No more Files"
274 print "No more Files"
275 return 0
275 return 0
276
276
277 filename = self.filenameList[idFile]
277 filename = self.filenameList[idFile]
278
278
279 filePointer = h5py.File(filename,'r')
279 filePointer = h5py.File(filename,'r')
280
280
281 self.filename = filename
281 self.filename = filename
282
282
283 self.fp = filePointer
283 self.fp = filePointer
284
284
285 print "Setting the file: %s"%self.filename
285 print "Setting the file: %s"%self.filename
286
286
287 # self.__readMetadata()
287 # self.__readMetadata()
288 self.__setBlockList()
288 self.__setBlockList()
289 self.__readData()
289 self.__readData()
290 # self.nRecords = self.fp['Data'].attrs['blocksPerFile']
290 # self.nRecords = self.fp['Data'].attrs['blocksPerFile']
291 # self.nRecords = self.fp['Data'].attrs['nRecords']
291 # self.nRecords = self.fp['Data'].attrs['nRecords']
292 self.blockIndex = 0
292 self.blockIndex = 0
293 return 1
293 return 1
294
294
295 def __setBlockList(self):
295 def __setBlockList(self):
296 '''
296 '''
297 Selects the data within the times defined
297 Selects the data within the times defined
298
298
299 self.fp
299 self.fp
300 self.startTime
300 self.startTime
301 self.endTime
301 self.endTime
302
302
303 self.blockList
303 self.blockList
304 self.blocksPerFile
304 self.blocksPerFile
305
305
306 '''
306 '''
307 fp = self.fp
307 fp = self.fp
308 startTime = self.startTime
308 startTime = self.startTime
309 endTime = self.endTime
309 endTime = self.endTime
310
310
311 grp = fp['Data']
311 grp = fp['Data']
312 thisUtcTime = grp['utctime'].value.astype(numpy.float)[0]
312 thisUtcTime = grp['utctime'].value.astype(numpy.float)[0]
313
313
314 #ERROOOOR
314 #ERROOOOR
315 if self.timezone == 'lt':
315 if self.timezone == 'lt':
316 thisUtcTime -= 5*3600
316 thisUtcTime -= 5*3600
317
317
318 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
318 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
319
319
320 thisDate = thisDatetime.date()
320 thisDate = thisDatetime.date()
321 thisTime = thisDatetime.time()
321 thisTime = thisDatetime.time()
322
322
323 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
323 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
324 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
324 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
325
325
326 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
326 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
327
327
328 self.blockList = ind
328 self.blockList = ind
329 self.blocksPerFile = len(ind)
329 self.blocksPerFile = len(ind)
330
330
331 return
331 return
332
332
333 def __readMetadata(self):
333 def __readMetadata(self):
334 '''
334 '''
335 Reads Metadata
335 Reads Metadata
336
336
337 self.pathMeta
337 self.pathMeta
338
338
339 self.listShapes
339 self.listShapes
340 self.listMetaname
340 self.listMetaname
341 self.listMeta
341 self.listMeta
342
342
343 '''
343 '''
344
344
345 # grp = self.fp['Data']
345 # grp = self.fp['Data']
346 # pathMeta = os.path.join(self.path, grp.attrs['metadata'])
346 # pathMeta = os.path.join(self.path, grp.attrs['metadata'])
347 #
347 #
348 # if pathMeta == self.pathMeta:
348 # if pathMeta == self.pathMeta:
349 # return
349 # return
350 # else:
350 # else:
351 # self.pathMeta = pathMeta
351 # self.pathMeta = pathMeta
352 #
352 #
353 # filePointer = h5py.File(self.pathMeta,'r')
353 # filePointer = h5py.File(self.pathMeta,'r')
354 # groupPointer = filePointer['Metadata']
354 # groupPointer = filePointer['Metadata']
355
355
356 filename = self.filenameList[0]
356 filename = self.filenameList[0]
357
357
358 fp = h5py.File(filename,'r')
358 fp = h5py.File(filename,'r')
359
359
360 gp = fp['Metadata']
360 gp = fp['Metadata']
361
361
362 listMetaname = []
362 listMetaname = []
363 listMetadata = []
363 listMetadata = []
364 for item in gp.items():
364 for item in gp.items():
365 name = item[0]
365 name = item[0]
366
366
367 if name=='array dimensions':
367 if name=='array dimensions':
368 table = gp[name][:]
368 table = gp[name][:]
369 listShapes = {}
369 listShapes = {}
370 for shapes in table:
370 for shapes in table:
371 listShapes[shapes[0]] = numpy.array([shapes[1],shapes[2],shapes[3],shapes[4],shapes[5]])
371 listShapes[shapes[0]] = numpy.array([shapes[1],shapes[2],shapes[3],shapes[4],shapes[5]])
372 else:
372 else:
373 data = gp[name].value
373 data = gp[name].value
374 listMetaname.append(name)
374 listMetaname.append(name)
375 listMetadata.append(data)
375 listMetadata.append(data)
376
376
377 # if name=='type':
377 # if name=='type':
378 # self.__initDataOut(data)
378 # self.__initDataOut(data)
379
379
380 self.listShapes = listShapes
380 self.listShapes = listShapes
381 self.listMetaname = listMetaname
381 self.listMetaname = listMetaname
382 self.listMeta = listMetadata
382 self.listMeta = listMetadata
383
383
384 fp.close()
384 fp.close()
385 return
385 return
386
386
387 def __readData(self):
387 def __readData(self):
388 grp = self.fp['Data']
388 grp = self.fp['Data']
389 listdataname = []
389 listdataname = []
390 listdata = []
390 listdata = []
391
391
392 for item in grp.items():
392 for item in grp.items():
393 name = item[0]
393 name = item[0]
394 listdataname.append(name)
394 listdataname.append(name)
395
395
396 array = self.__setDataArray(grp[name],self.listShapes[name])
396 array = self.__setDataArray(grp[name],self.listShapes[name])
397 listdata.append(array)
397 listdata.append(array)
398
398
399 self.listDataname = listdataname
399 self.listDataname = listdataname
400 self.listData = listdata
400 self.listData = listdata
401 return
401 return
402
402
403 def __setDataArray(self, dataset, shapes):
403 def __setDataArray(self, dataset, shapes):
404
404
405 nDims = shapes[0]
405 nDims = shapes[0]
406
406
407 nDim2 = shapes[1] #Dimension 0
407 nDim2 = shapes[1] #Dimension 0
408
408
409 nDim1 = shapes[2] #Dimension 1, number of Points or Parameters
409 nDim1 = shapes[2] #Dimension 1, number of Points or Parameters
410
410
411 nDim0 = shapes[3] #Dimension 2, number of samples or ranges
411 nDim0 = shapes[3] #Dimension 2, number of samples or ranges
412
412
413 mode = shapes[4] #Mode of storing
413 mode = shapes[4] #Mode of storing
414
414
415 blockList = self.blockList
415 blockList = self.blockList
416
416
417 blocksPerFile = self.blocksPerFile
417 blocksPerFile = self.blocksPerFile
418
418
419 #Depending on what mode the data was stored
419 #Depending on what mode the data was stored
420 if mode == 0: #Divided in channels
420 if mode == 0: #Divided in channels
421 arrayData = dataset.value.astype(numpy.float)[0][blockList]
421 arrayData = dataset.value.astype(numpy.float)[0][blockList]
422 if mode == 1: #Divided in parameter
422 if mode == 1: #Divided in parameter
423 strds = 'table'
423 strds = 'table'
424 nDatas = nDim1
424 nDatas = nDim1
425 newShapes = (blocksPerFile,nDim2,nDim0)
425 newShapes = (blocksPerFile,nDim2,nDim0)
426 elif mode==2: #Concatenated in a table
426 elif mode==2: #Concatenated in a table
427 strds = 'table0'
427 strds = 'table0'
428 arrayData = dataset[strds].value
428 arrayData = dataset[strds].value
429 #Selecting part of the dataset
429 #Selecting part of the dataset
430 utctime = arrayData[:,0]
430 utctime = arrayData[:,0]
431 u, indices = numpy.unique(utctime, return_index=True)
431 u, indices = numpy.unique(utctime, return_index=True)
432
432
433 if blockList.size != indices.size:
433 if blockList.size != indices.size:
434 indMin = indices[blockList[0]]
434 indMin = indices[blockList[0]]
435 if blockList[1] + 1 >= indices.size:
435 if blockList[1] + 1 >= indices.size:
436 arrayData = arrayData[indMin:,:]
436 arrayData = arrayData[indMin:,:]
437 else:
437 else:
438 indMax = indices[blockList[1] + 1]
438 indMax = indices[blockList[1] + 1]
439 arrayData = arrayData[indMin:indMax,:]
439 arrayData = arrayData[indMin:indMax,:]
440 return arrayData
440 return arrayData
441
441
442 # One dimension
442 # One dimension
443 if nDims == 0:
443 if nDims == 0:
444 arrayData = dataset.value.astype(numpy.float)[0][blockList]
444 arrayData = dataset.value.astype(numpy.float)[0][blockList]
445
445
446 # Two dimensions
446 # Two dimensions
447 elif nDims == 2:
447 elif nDims == 2:
448 arrayData = numpy.zeros((blocksPerFile,nDim1,nDim0))
448 arrayData = numpy.zeros((blocksPerFile,nDim1,nDim0))
449 newShapes = (blocksPerFile,nDim0)
449 newShapes = (blocksPerFile,nDim0)
450 nDatas = nDim1
450 nDatas = nDim1
451
451
452 for i in range(nDatas):
452 for i in range(nDatas):
453 data = dataset[strds + str(i)].value
453 data = dataset[strds + str(i)].value
454 arrayData[:,i,:] = data[blockList,:]
454 arrayData[:,i,:] = data[blockList,:]
455
455
456 # Three dimensions
456 # Three dimensions
457 else:
457 else:
458 arrayData = numpy.zeros((blocksPerFile,nDim2,nDim1,nDim0))
458 arrayData = numpy.zeros((blocksPerFile,nDim2,nDim1,nDim0))
459 for i in range(nDatas):
459 for i in range(nDatas):
460
460
461 data = dataset[strds + str(i)].value
461 data = dataset[strds + str(i)].value
462
462
463 for b in range(blockList.size):
463 for b in range(blockList.size):
464 arrayData[b,:,i,:] = data[:,:,blockList[b]]
464 arrayData[b,:,i,:] = data[:,:,blockList[b]]
465
465
466 return arrayData
466 return arrayData
467
467
468 def __setDataOut(self):
468 def __setDataOut(self):
469 listMeta = self.listMeta
469 listMeta = self.listMeta
470 listMetaname = self.listMetaname
470 listMetaname = self.listMetaname
471 listDataname = self.listDataname
471 listDataname = self.listDataname
472 listData = self.listData
472 listData = self.listData
473 listShapes = self.listShapes
473 listShapes = self.listShapes
474
474
475 blockIndex = self.blockIndex
475 blockIndex = self.blockIndex
476 # blockList = self.blockList
476 # blockList = self.blockList
477
477
478 for i in range(len(listMeta)):
478 for i in range(len(listMeta)):
479 setattr(self.dataOut,listMetaname[i],listMeta[i])
479 setattr(self.dataOut,listMetaname[i],listMeta[i])
480
480
481 for j in range(len(listData)):
481 for j in range(len(listData)):
482 nShapes = listShapes[listDataname[j]][0]
482 nShapes = listShapes[listDataname[j]][0]
483 mode = listShapes[listDataname[j]][4]
483 mode = listShapes[listDataname[j]][4]
484 if nShapes == 1:
484 if nShapes == 1:
485 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
485 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
486 elif nShapes > 1:
486 elif nShapes > 1:
487 setattr(self.dataOut,listDataname[j],listData[j][blockIndex,:])
487 setattr(self.dataOut,listDataname[j],listData[j][blockIndex,:])
488 elif mode==0:
488 elif mode==0:
489 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
489 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
490 #Mode Meteors
490 #Mode Meteors
491 elif mode ==2:
491 elif mode ==2:
492 selectedData = self.__selectDataMode2(listData[j], blockIndex)
492 selectedData = self.__selectDataMode2(listData[j], blockIndex)
493 setattr(self.dataOut, listDataname[j], selectedData)
493 setattr(self.dataOut, listDataname[j], selectedData)
494 return
494 return
495
495
496 def __selectDataMode2(self, data, blockIndex):
496 def __selectDataMode2(self, data, blockIndex):
497 utctime = data[:,0]
497 utctime = data[:,0]
498 aux, indices = numpy.unique(utctime, return_inverse=True)
498 aux, indices = numpy.unique(utctime, return_inverse=True)
499 selInd = numpy.where(indices == blockIndex)[0]
499 selInd = numpy.where(indices == blockIndex)[0]
500 selData = data[selInd,:]
500 selData = data[selInd,:]
501
501
502 return selData
502 return selData
503
503
504 def getData(self):
504 def getData(self):
505
505
506 # if self.flagNoMoreFiles:
506 # if self.flagNoMoreFiles:
507 # self.dataOut.flagNoData = True
507 # self.dataOut.flagNoData = True
508 # print 'Process finished'
508 # print 'Process finished'
509 # return 0
509 # return 0
510 #
510 #
511 if self.blockIndex==self.blocksPerFile:
511 if self.blockIndex==self.blocksPerFile:
512 if not( self.__setNextFileOffline() ):
512 if not( self.__setNextFileOffline() ):
513 self.dataOut.flagNoData = True
513 self.dataOut.flagNoData = True
514 return 0
514 return 0
515
515
516 # if self.datablock == None: # setear esta condicion cuando no hayan datos por leers
516 # if self.datablock == None: # setear esta condicion cuando no hayan datos por leers
517 # self.dataOut.flagNoData = True
517 # self.dataOut.flagNoData = True
518 # return 0
518 # return 0
519 # self.__readData()
519 # self.__readData()
520 self.__setDataOut()
520 self.__setDataOut()
521 self.dataOut.flagNoData = False
521 self.dataOut.flagNoData = False
522
522
523 self.blockIndex += 1
523 self.blockIndex += 1
524
524
525 return
525 return
526
526
527 def run(self, **kwargs):
527 def run(self, **kwargs):
528
528
529 if not(self.isConfig):
529 if not(self.isConfig):
530 self.setup(**kwargs)
530 self.setup(**kwargs)
531 # self.setObjProperties()
531 # self.setObjProperties()
532 self.isConfig = True
532 self.isConfig = True
533
533
534 self.getData()
534 self.getData()
535
535
536 return
536 return
537
537
538 class ParamWriter(Operation):
538 class ParamWriter(Operation):
539 '''
539 '''
540 HDF5 Writer, stores parameters data in HDF5 format files
540 HDF5 Writer, stores parameters data in HDF5 format files
541
541
542 path: path where the files will be stored
542 path: path where the files will be stored
543
543
544 blocksPerFile: number of blocks that will be saved in per HDF5 format file
544 blocksPerFile: number of blocks that will be saved in per HDF5 format file
545
545
546 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
546 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
547
547
548 metadataList: list of attributes that will be stored as metadata
548 metadataList: list of attributes that will be stored as metadata
549
549
550 dataList: list of attributes that will be stores as data
550 dataList: list of attributes that will be stores as data
551
551
552 '''
552 '''
553
553
554
554
555 ext = ".hdf5"
555 ext = ".hdf5"
556
556
557 optchar = "D"
557 optchar = "D"
558
558
559 metaoptchar = "M"
559 metaoptchar = "M"
560
560
561 metaFile = None
561 metaFile = None
562
562
563 filename = None
563 filename = None
564
564
565 path = None
565 path = None
566
566
567 setFile = None
567 setFile = None
568
568
569 fp = None
569 fp = None
570
570
571 grp = None
571 grp = None
572
572
573 ds = None
573 ds = None
574
574
575 firsttime = True
575 firsttime = True
576
576
577 #Configurations
577 #Configurations
578
578
579 blocksPerFile = None
579 blocksPerFile = None
580
580
581 blockIndex = None
581 blockIndex = None
582
582
583 dataOut = None
583 dataOut = None
584
584
585 #Data Arrays
585 #Data Arrays
586
586
587 dataList = None
587 dataList = None
588
588
589 metadataList = None
589 metadataList = None
590
590
591 # arrayDim = None
591 # arrayDim = None
592
592
593 dsList = None #List of dictionaries with dataset properties
593 dsList = None #List of dictionaries with dataset properties
594
594
595 tableDim = None
595 tableDim = None
596
596
597 # dtype = [('arrayName', 'S20'),('nChannels', 'i'), ('nPoints', 'i'), ('nSamples', 'i'),('mode', 'b')]
597 # dtype = [('arrayName', 'S20'),('nChannels', 'i'), ('nPoints', 'i'), ('nSamples', 'i'),('mode', 'b')]
598
598
599 dtype = [('arrayName', 'S20'),('nDimensions', 'i'), ('dim2', 'i'), ('dim1', 'i'),('dim0', 'i'),('mode', 'b')]
599 dtype = [('arrayName', 'S20'),('nDimensions', 'i'), ('dim2', 'i'), ('dim1', 'i'),('dim0', 'i'),('mode', 'b')]
600
600
601 currentDay = None
601 currentDay = None
602
602
603 lastTime = None
603 lastTime = None
604
604
605 def __init__(self, **kwargs):
605 def __init__(self, **kwargs):
606 Operation.__init__(self, **kwargs)
606 Operation.__init__(self, **kwargs)
607 self.isConfig = False
607 self.isConfig = False
608 return
608 return
609
609
610 def setup(self, dataOut, **kwargs):
610 def setup(self, dataOut, **kwargs):
611
611
612 self.path = kwargs['path']
612 self.path = kwargs['path']
613 self.setType = kwargs.get('setType', None)
613 self.setType = kwargs.get('setType', None)
614
614
615 if kwargs.has_key('blocksPerFile'):
615 if kwargs.has_key('blocksPerFile'):
616 self.blocksPerFile = kwargs['blocksPerFile']
616 self.blocksPerFile = kwargs['blocksPerFile']
617 else:
617 else:
618 self.blocksPerFile = 10
618 self.blocksPerFile = 10
619
619
620 self.metadataList = kwargs['metadataList']
620 self.metadataList = kwargs['metadataList']
621 self.dataList = kwargs['dataList']
621 self.dataList = kwargs['dataList']
622 self.dataOut = dataOut
622 self.dataOut = dataOut
623
623
624 if kwargs.has_key('mode'):
624 if kwargs.has_key('mode'):
625 mode = kwargs['mode']
625 mode = kwargs['mode']
626
626
627 if type(mode) == int:
627 if type(mode) == int:
628 mode = numpy.zeros(len(self.dataList)) + mode
628 mode = numpy.zeros(len(self.dataList)) + mode
629 else:
629 else:
630 mode = numpy.ones(len(self.dataList))
630 mode = numpy.ones(len(self.dataList))
631
631
632 self.mode = mode
632 self.mode = mode
633
633
634 arrayDim = numpy.zeros((len(self.dataList),5))
634 arrayDim = numpy.zeros((len(self.dataList),5))
635
635
636 #Table dimensions
636 #Table dimensions
637 dtype0 = self.dtype
637 dtype0 = self.dtype
638 tableList = []
638 tableList = []
639
639
640 #Dictionary and list of tables
640 #Dictionary and list of tables
641 dsList = []
641 dsList = []
642
642
643 for i in range(len(self.dataList)):
643 for i in range(len(self.dataList)):
644 dsDict = {}
644 dsDict = {}
645 dataAux = getattr(self.dataOut, self.dataList[i])
645 dataAux = getattr(self.dataOut, self.dataList[i])
646 dsDict['variable'] = self.dataList[i]
646 dsDict['variable'] = self.dataList[i]
647 #--------------------- Conditionals ------------------------
647 #--------------------- Conditionals ------------------------
648 #There is no data
648 #There is no data
649 if dataAux is None:
649 if dataAux is None:
650 return 0
650 return 0
651
651
652 #Not array, just a number
652 #Not array, just a number
653 #Mode 0
653 #Mode 0
654 if type(dataAux)==float or type(dataAux)==int:
654 if type(dataAux)==float or type(dataAux)==int:
655 dsDict['mode'] = 0
655 dsDict['mode'] = 0
656 dsDict['nDim'] = 0
656 dsDict['nDim'] = 0
657 arrayDim[i,0] = 0
657 arrayDim[i,0] = 0
658 dsList.append(dsDict)
658 dsList.append(dsDict)
659
659
660 #Mode 2: meteors
660 #Mode 2: meteors
661 elif mode[i] == 2:
661 elif mode[i] == 2:
662 # dsDict['nDim'] = 0
662 # dsDict['nDim'] = 0
663 dsDict['dsName'] = 'table0'
663 dsDict['dsName'] = 'table0'
664 dsDict['mode'] = 2 # Mode meteors
664 dsDict['mode'] = 2 # Mode meteors
665 dsDict['shape'] = dataAux.shape[-1]
665 dsDict['shape'] = dataAux.shape[-1]
666 dsDict['nDim'] = 0
666 dsDict['nDim'] = 0
667 dsDict['dsNumber'] = 1
667 dsDict['dsNumber'] = 1
668
668
669 arrayDim[i,3] = dataAux.shape[-1]
669 arrayDim[i,3] = dataAux.shape[-1]
670 arrayDim[i,4] = mode[i] #Mode the data was stored
670 arrayDim[i,4] = mode[i] #Mode the data was stored
671
671
672 dsList.append(dsDict)
672 dsList.append(dsDict)
673
673
674 #Mode 1
674 #Mode 1
675 else:
675 else:
676 arrayDim0 = dataAux.shape #Data dimensions
676 arrayDim0 = dataAux.shape #Data dimensions
677 arrayDim[i,0] = len(arrayDim0) #Number of array dimensions
677 arrayDim[i,0] = len(arrayDim0) #Number of array dimensions
678 arrayDim[i,4] = mode[i] #Mode the data was stored
678 arrayDim[i,4] = mode[i] #Mode the data was stored
679
679
680 strtable = 'table'
680 strtable = 'table'
681 dsDict['mode'] = 1 # Mode parameters
681 dsDict['mode'] = 1 # Mode parameters
682
682
683 # Three-dimension arrays
683 # Three-dimension arrays
684 if len(arrayDim0) == 3:
684 if len(arrayDim0) == 3:
685 arrayDim[i,1:-1] = numpy.array(arrayDim0)
685 arrayDim[i,1:-1] = numpy.array(arrayDim0)
686 nTables = int(arrayDim[i,2])
686 nTables = int(arrayDim[i,2])
687 dsDict['dsNumber'] = nTables
687 dsDict['dsNumber'] = nTables
688 dsDict['shape'] = arrayDim[i,2:4]
688 dsDict['shape'] = arrayDim[i,2:4]
689 dsDict['nDim'] = 3
689 dsDict['nDim'] = 3
690
690
691 for j in range(nTables):
691 for j in range(nTables):
692 dsDict = dsDict.copy()
692 dsDict = dsDict.copy()
693 dsDict['dsName'] = strtable + str(j)
693 dsDict['dsName'] = strtable + str(j)
694 dsList.append(dsDict)
694 dsList.append(dsDict)
695
695
696 # Two-dimension arrays
696 # Two-dimension arrays
697 elif len(arrayDim0) == 2:
697 elif len(arrayDim0) == 2:
698 arrayDim[i,2:-1] = numpy.array(arrayDim0)
698 arrayDim[i,2:-1] = numpy.array(arrayDim0)
699 nTables = int(arrayDim[i,2])
699 nTables = int(arrayDim[i,2])
700 dsDict['dsNumber'] = nTables
700 dsDict['dsNumber'] = nTables
701 dsDict['shape'] = arrayDim[i,3]
701 dsDict['shape'] = arrayDim[i,3]
702 dsDict['nDim'] = 2
702 dsDict['nDim'] = 2
703
703
704 for j in range(nTables):
704 for j in range(nTables):
705 dsDict = dsDict.copy()
705 dsDict = dsDict.copy()
706 dsDict['dsName'] = strtable + str(j)
706 dsDict['dsName'] = strtable + str(j)
707 dsList.append(dsDict)
707 dsList.append(dsDict)
708
708
709 # One-dimension arrays
709 # One-dimension arrays
710 elif len(arrayDim0) == 1:
710 elif len(arrayDim0) == 1:
711 arrayDim[i,3] = arrayDim0[0]
711 arrayDim[i,3] = arrayDim0[0]
712 dsDict['shape'] = arrayDim0[0]
712 dsDict['shape'] = arrayDim0[0]
713 dsDict['dsNumber'] = 1
713 dsDict['dsNumber'] = 1
714 dsDict['dsName'] = strtable + str(0)
714 dsDict['dsName'] = strtable + str(0)
715 dsDict['nDim'] = 1
715 dsDict['nDim'] = 1
716 dsList.append(dsDict)
716 dsList.append(dsDict)
717
717
718 table = numpy.array((self.dataList[i],) + tuple(arrayDim[i,:]),dtype = dtype0)
718 table = numpy.array((self.dataList[i],) + tuple(arrayDim[i,:]),dtype = dtype0)
719 tableList.append(table)
719 tableList.append(table)
720
720
721 # self.arrayDim = arrayDim
721 # self.arrayDim = arrayDim
722 self.dsList = dsList
722 self.dsList = dsList
723 self.tableDim = numpy.array(tableList, dtype = dtype0)
723 self.tableDim = numpy.array(tableList, dtype = dtype0)
724 self.blockIndex = 0
724 self.blockIndex = 0
725
725
726 timeTuple = time.localtime(dataOut.utctime)
726 timeTuple = time.localtime(dataOut.utctime)
727 self.currentDay = timeTuple.tm_yday
727 self.currentDay = timeTuple.tm_yday
728 return 1
728 return 1
729
729
730 def putMetadata(self):
730 def putMetadata(self):
731
731
732 fp = self.createMetadataFile()
732 fp = self.createMetadataFile()
733 self.writeMetadata(fp)
733 self.writeMetadata(fp)
734 fp.close()
734 fp.close()
735 return
735 return
736
736
737 def createMetadataFile(self):
737 def createMetadataFile(self):
738 ext = self.ext
738 ext = self.ext
739 path = self.path
739 path = self.path
740 setFile = self.setFile
740 setFile = self.setFile
741
741
742 timeTuple = time.localtime(self.dataOut.utctime)
742 timeTuple = time.localtime(self.dataOut.utctime)
743
743
744 subfolder = ''
744 subfolder = ''
745 fullpath = os.path.join( path, subfolder )
745 fullpath = os.path.join( path, subfolder )
746
746
747 if not( os.path.exists(fullpath) ):
747 if not( os.path.exists(fullpath) ):
748 os.mkdir(fullpath)
748 os.mkdir(fullpath)
749 setFile = -1 #inicializo mi contador de seteo
749 setFile = -1 #inicializo mi contador de seteo
750
750
751 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
751 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
752 fullpath = os.path.join( path, subfolder )
752 fullpath = os.path.join( path, subfolder )
753
753
754 if not( os.path.exists(fullpath) ):
754 if not( os.path.exists(fullpath) ):
755 os.mkdir(fullpath)
755 os.mkdir(fullpath)
756 setFile = -1 #inicializo mi contador de seteo
756 setFile = -1 #inicializo mi contador de seteo
757
757
758 else:
758 else:
759 filesList = os.listdir( fullpath )
759 filesList = os.listdir( fullpath )
760 filesList = sorted( filesList, key=str.lower )
760 filesList = sorted( filesList, key=str.lower )
761 if len( filesList ) > 0:
761 if len( filesList ) > 0:
762 filesList = [k for k in filesList if 'M' in k]
762 filesList = [k for k in filesList if 'M' in k]
763 filen = filesList[-1]
763 filen = filesList[-1]
764 # el filename debera tener el siguiente formato
764 # el filename debera tener el siguiente formato
765 # 0 1234 567 89A BCDE (hex)
765 # 0 1234 567 89A BCDE (hex)
766 # x YYYY DDD SSS .ext
766 # x YYYY DDD SSS .ext
767 if isNumber( filen[8:11] ):
767 if isNumber( filen[8:11] ):
768 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
768 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
769 else:
769 else:
770 setFile = -1
770 setFile = -1
771 else:
771 else:
772 setFile = -1 #inicializo mi contador de seteo
772 setFile = -1 #inicializo mi contador de seteo
773
773
774 if self.setType is None:
774 if self.setType is None:
775 setFile += 1
775 setFile += 1
776 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
776 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
777 timeTuple.tm_year,
777 timeTuple.tm_year,
778 timeTuple.tm_yday,
778 timeTuple.tm_yday,
779 setFile,
779 setFile,
780 ext )
780 ext )
781 else:
781 else:
782 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
782 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
783 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
783 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
784 timeTuple.tm_year,
784 timeTuple.tm_year,
785 timeTuple.tm_yday,
785 timeTuple.tm_yday,
786 setFile,
786 setFile,
787 ext )
787 ext )
788
788
789 filename = os.path.join( path, subfolder, file )
789 filename = os.path.join( path, subfolder, file )
790 self.metaFile = file
790 self.metaFile = file
791 #Setting HDF5 File
791 #Setting HDF5 File
792 fp = h5py.File(filename,'w')
792 fp = h5py.File(filename,'w')
793
793
794 return fp
794 return fp
795
795
796 def writeMetadata(self, fp):
796 def writeMetadata(self, fp):
797
797
798 grp = fp.create_group("Metadata")
798 grp = fp.create_group("Metadata")
799 grp.create_dataset('array dimensions', data = self.tableDim, dtype = self.dtype)
799 grp.create_dataset('array dimensions', data = self.tableDim, dtype = self.dtype)
800
800
801 for i in range(len(self.metadataList)):
801 for i in range(len(self.metadataList)):
802 grp.create_dataset(self.metadataList[i], data=getattr(self.dataOut, self.metadataList[i]))
802 grp.create_dataset(self.metadataList[i], data=getattr(self.dataOut, self.metadataList[i]))
803 return
803 return
804
804
805 def timeFlag(self):
805 def timeFlag(self):
806 currentTime = self.dataOut.utctime
806 currentTime = self.dataOut.utctime
807
807
808 if self.lastTime is None:
808 if self.lastTime is None:
809 self.lastTime = currentTime
809 self.lastTime = currentTime
810
810
811 #Day
811 #Day
812 timeTuple = time.localtime(currentTime)
812 timeTuple = time.localtime(currentTime)
813 dataDay = timeTuple.tm_yday
813 dataDay = timeTuple.tm_yday
814
814
815 #Time
815 #Time
816 timeDiff = currentTime - self.lastTime
816 timeDiff = currentTime - self.lastTime
817
817
818 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
818 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
819 if dataDay != self.currentDay:
819 if dataDay != self.currentDay:
820 self.currentDay = dataDay
820 self.currentDay = dataDay
821 return True
821 return True
822 elif timeDiff > 3*60*60:
822 elif timeDiff > 3*60*60:
823 self.lastTime = currentTime
823 self.lastTime = currentTime
824 return True
824 return True
825 else:
825 else:
826 self.lastTime = currentTime
826 self.lastTime = currentTime
827 return False
827 return False
828
828
829 def setNextFile(self):
829 def setNextFile(self):
830
830
831 ext = self.ext
831 ext = self.ext
832 path = self.path
832 path = self.path
833 setFile = self.setFile
833 setFile = self.setFile
834 mode = self.mode
834 mode = self.mode
835
835
836 timeTuple = time.localtime(self.dataOut.utctime)
836 timeTuple = time.localtime(self.dataOut.utctime)
837 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
837 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
838
838
839 fullpath = os.path.join( path, subfolder )
839 fullpath = os.path.join( path, subfolder )
840
840
841 if os.path.exists(fullpath):
841 if os.path.exists(fullpath):
842 filesList = os.listdir( fullpath )
842 filesList = os.listdir( fullpath )
843 filesList = [k for k in filesList if 'D' in k]
843 filesList = [k for k in filesList if 'D' in k]
844 if len( filesList ) > 0:
844 if len( filesList ) > 0:
845 filesList = sorted( filesList, key=str.lower )
845 filesList = sorted( filesList, key=str.lower )
846 filen = filesList[-1]
846 filen = filesList[-1]
847 # el filename debera tener el siguiente formato
847 # el filename debera tener el siguiente formato
848 # 0 1234 567 89A BCDE (hex)
848 # 0 1234 567 89A BCDE (hex)
849 # x YYYY DDD SSS .ext
849 # x YYYY DDD SSS .ext
850 if isNumber( filen[8:11] ):
850 if isNumber( filen[8:11] ):
851 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
851 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
852 else:
852 else:
853 setFile = -1
853 setFile = -1
854 else:
854 else:
855 setFile = -1 #inicializo mi contador de seteo
855 setFile = -1 #inicializo mi contador de seteo
856 else:
856 else:
857 os.makedirs(fullpath)
857 os.makedirs(fullpath)
858 setFile = -1 #inicializo mi contador de seteo
858 setFile = -1 #inicializo mi contador de seteo
859
859
860 if self.setType is None:
860 if self.setType is None:
861 setFile += 1
861 setFile += 1
862 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
862 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
863 timeTuple.tm_year,
863 timeTuple.tm_year,
864 timeTuple.tm_yday,
864 timeTuple.tm_yday,
865 setFile,
865 setFile,
866 ext )
866 ext )
867 else:
867 else:
868 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
868 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
869 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
869 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
870 timeTuple.tm_year,
870 timeTuple.tm_year,
871 timeTuple.tm_yday,
871 timeTuple.tm_yday,
872 setFile,
872 setFile,
873 ext )
873 ext )
874
874
875 filename = os.path.join( path, subfolder, file )
875 filename = os.path.join( path, subfolder, file )
876
876
877 #Setting HDF5 File
877 #Setting HDF5 File
878 fp = h5py.File(filename,'w')
878 fp = h5py.File(filename,'w')
879 #write metadata
879 #write metadata
880 self.writeMetadata(fp)
880 self.writeMetadata(fp)
881 #Write data
881 #Write data
882 grp = fp.create_group("Data")
882 grp = fp.create_group("Data")
883 # grp.attrs['metadata'] = self.metaFile
883 # grp.attrs['metadata'] = self.metaFile
884
884
885 # grp.attrs['blocksPerFile'] = 0
885 # grp.attrs['blocksPerFile'] = 0
886 ds = []
886 ds = []
887 data = []
887 data = []
888 dsList = self.dsList
888 dsList = self.dsList
889 i = 0
889 i = 0
890 while i < len(dsList):
890 while i < len(dsList):
891 dsInfo = dsList[i]
891 dsInfo = dsList[i]
892 #One-dimension data
892 #One-dimension data
893 if dsInfo['mode'] == 0:
893 if dsInfo['mode'] == 0:
894 # ds0 = grp.create_dataset(self.dataList[i], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype='S20')
894 # ds0 = grp.create_dataset(self.dataList[i], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype='S20')
895 ds0 = grp.create_dataset(dsInfo['variable'], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype=numpy.float64)
895 ds0 = grp.create_dataset(dsInfo['variable'], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype=numpy.float64)
896 ds.append(ds0)
896 ds.append(ds0)
897 data.append([])
897 data.append([])
898 i += 1
898 i += 1
899 continue
899 continue
900 # nDimsForDs.append(nDims[i])
900 # nDimsForDs.append(nDims[i])
901
901
902 elif dsInfo['mode'] == 2:
902 elif dsInfo['mode'] == 2:
903 grp0 = grp.create_group(dsInfo['variable'])
903 grp0 = grp.create_group(dsInfo['variable'])
904 ds0 = grp0.create_dataset(dsInfo['dsName'], (1,dsInfo['shape']), data = numpy.zeros((1,dsInfo['shape'])) , maxshape=(None,dsInfo['shape']), chunks=True)
904 ds0 = grp0.create_dataset(dsInfo['dsName'], (1,dsInfo['shape']), data = numpy.zeros((1,dsInfo['shape'])) , maxshape=(None,dsInfo['shape']), chunks=True)
905 ds.append(ds0)
905 ds.append(ds0)
906 data.append([])
906 data.append([])
907 i += 1
907 i += 1
908 continue
908 continue
909
909
910 elif dsInfo['mode'] == 1:
910 elif dsInfo['mode'] == 1:
911 grp0 = grp.create_group(dsInfo['variable'])
911 grp0 = grp.create_group(dsInfo['variable'])
912
912
913 for j in range(dsInfo['dsNumber']):
913 for j in range(dsInfo['dsNumber']):
914 dsInfo = dsList[i]
914 dsInfo = dsList[i]
915 tableName = dsInfo['dsName']
915 tableName = dsInfo['dsName']
916 shape = int(dsInfo['shape'])
916 shape = int(dsInfo['shape'])
917
917
918 if dsInfo['nDim'] == 3:
918 if dsInfo['nDim'] == 3:
919 ds0 = grp0.create_dataset(tableName, (shape[0],shape[1],1) , data = numpy.zeros((shape[0],shape[1],1)), maxshape = (None,shape[1],None), chunks=True)
919 ds0 = grp0.create_dataset(tableName, (shape[0],shape[1],1) , data = numpy.zeros((shape[0],shape[1],1)), maxshape = (None,shape[1],None), chunks=True)
920 else:
920 else:
921 ds0 = grp0.create_dataset(tableName, (1,shape), data = numpy.zeros((1,shape)) , maxshape=(None,shape), chunks=True)
921 ds0 = grp0.create_dataset(tableName, (1,shape), data = numpy.zeros((1,shape)) , maxshape=(None,shape), chunks=True)
922
922
923 ds.append(ds0)
923 ds.append(ds0)
924 data.append([])
924 data.append([])
925 i += 1
925 i += 1
926 # nDimsForDs.append(nDims[i])
926 # nDimsForDs.append(nDims[i])
927
927
928 fp.flush()
928 fp.flush()
929 fp.close()
929 fp.close()
930
930
931 # self.nDatas = nDatas
931 # self.nDatas = nDatas
932 # self.nDims = nDims
932 # self.nDims = nDims
933 # self.nDimsForDs = nDimsForDs
933 # self.nDimsForDs = nDimsForDs
934 #Saving variables
934 #Saving variables
935 print 'Writing the file: %s'%filename
935 print 'Writing the file: %s'%filename
936 self.filename = filename
936 self.filename = filename
937 # self.fp = fp
937 # self.fp = fp
938 # self.grp = grp
938 # self.grp = grp
939 # self.grp.attrs.modify('nRecords', 1)
939 # self.grp.attrs.modify('nRecords', 1)
940 self.ds = ds
940 self.ds = ds
941 self.data = data
941 self.data = data
942 # self.setFile = setFile
942 # self.setFile = setFile
943 self.firsttime = True
943 self.firsttime = True
944 self.blockIndex = 0
944 self.blockIndex = 0
945 return
945 return
946
946
947 def putData(self):
947 def putData(self):
948
948
949 if self.blockIndex == self.blocksPerFile or self.timeFlag():
949 if self.blockIndex == self.blocksPerFile or self.timeFlag():
950 self.setNextFile()
950 self.setNextFile()
951
951
952 # if not self.firsttime:
952 # if not self.firsttime:
953 self.readBlock()
953 self.readBlock()
954 self.setBlock() #Prepare data to be written
954 self.setBlock() #Prepare data to be written
955 self.writeBlock() #Write data
955 self.writeBlock() #Write data
956
956
957 return
957 return
958
958
959 def readBlock(self):
959 def readBlock(self):
960
960
961 '''
961 '''
962 data Array configured
962 data Array configured
963
963
964
964
965 self.data
965 self.data
966 '''
966 '''
967 dsList = self.dsList
967 dsList = self.dsList
968 ds = self.ds
968 ds = self.ds
969 #Setting HDF5 File
969 #Setting HDF5 File
970 fp = h5py.File(self.filename,'r+')
970 fp = h5py.File(self.filename,'r+')
971 grp = fp["Data"]
971 grp = fp["Data"]
972 ind = 0
972 ind = 0
973
973
974 # grp.attrs['blocksPerFile'] = 0
974 # grp.attrs['blocksPerFile'] = 0
975 while ind < len(dsList):
975 while ind < len(dsList):
976 dsInfo = dsList[ind]
976 dsInfo = dsList[ind]
977
977
978 if dsInfo['mode'] == 0:
978 if dsInfo['mode'] == 0:
979 ds0 = grp[dsInfo['variable']]
979 ds0 = grp[dsInfo['variable']]
980 ds[ind] = ds0
980 ds[ind] = ds0
981 ind += 1
981 ind += 1
982 else:
982 else:
983
983
984 grp0 = grp[dsInfo['variable']]
984 grp0 = grp[dsInfo['variable']]
985
985
986 for j in range(dsInfo['dsNumber']):
986 for j in range(dsInfo['dsNumber']):
987 dsInfo = dsList[ind]
987 dsInfo = dsList[ind]
988 ds0 = grp0[dsInfo['dsName']]
988 ds0 = grp0[dsInfo['dsName']]
989 ds[ind] = ds0
989 ds[ind] = ds0
990 ind += 1
990 ind += 1
991
991
992 self.fp = fp
992 self.fp = fp
993 self.grp = grp
993 self.grp = grp
994 self.ds = ds
994 self.ds = ds
995
995
996 return
996 return
997
997
998 def setBlock(self):
998 def setBlock(self):
999 '''
999 '''
1000 data Array configured
1000 data Array configured
1001
1001
1002
1002
1003 self.data
1003 self.data
1004 '''
1004 '''
1005 #Creating Arrays
1005 #Creating Arrays
1006 dsList = self.dsList
1006 dsList = self.dsList
1007 data = self.data
1007 data = self.data
1008 ind = 0
1008 ind = 0
1009
1009
1010 while ind < len(dsList):
1010 while ind < len(dsList):
1011 dsInfo = dsList[ind]
1011 dsInfo = dsList[ind]
1012 dataAux = getattr(self.dataOut, dsInfo['variable'])
1012 dataAux = getattr(self.dataOut, dsInfo['variable'])
1013
1013
1014 mode = dsInfo['mode']
1014 mode = dsInfo['mode']
1015 nDim = dsInfo['nDim']
1015 nDim = dsInfo['nDim']
1016
1016
1017 if mode == 0 or mode == 2 or nDim == 1:
1017 if mode == 0 or mode == 2 or nDim == 1:
1018 data[ind] = dataAux
1018 data[ind] = dataAux
1019 ind += 1
1019 ind += 1
1020 # elif nDim == 1:
1020 # elif nDim == 1:
1021 # data[ind] = numpy.reshape(dataAux,(numpy.size(dataAux),1))
1021 # data[ind] = numpy.reshape(dataAux,(numpy.size(dataAux),1))
1022 # ind += 1
1022 # ind += 1
1023 elif nDim == 2:
1023 elif nDim == 2:
1024 for j in range(dsInfo['dsNumber']):
1024 for j in range(dsInfo['dsNumber']):
1025 data[ind] = dataAux[j,:]
1025 data[ind] = dataAux[j,:]
1026 ind += 1
1026 ind += 1
1027 elif nDim == 3:
1027 elif nDim == 3:
1028 for j in range(dsInfo['dsNumber']):
1028 for j in range(dsInfo['dsNumber']):
1029 data[ind] = dataAux[:,j,:]
1029 data[ind] = dataAux[:,j,:]
1030 ind += 1
1030 ind += 1
1031
1031
1032 self.data = data
1032 self.data = data
1033 return
1033 return
1034
1034
1035 def writeBlock(self):
1035 def writeBlock(self):
1036 '''
1036 '''
1037 Saves the block in the HDF5 file
1037 Saves the block in the HDF5 file
1038 '''
1038 '''
1039 dsList = self.dsList
1039 dsList = self.dsList
1040
1040
1041 for i in range(len(self.ds)):
1041 for i in range(len(self.ds)):
1042 dsInfo = dsList[i]
1042 dsInfo = dsList[i]
1043 nDim = dsInfo['nDim']
1043 nDim = dsInfo['nDim']
1044 mode = dsInfo['mode']
1044 mode = dsInfo['mode']
1045
1045
1046 # First time
1046 # First time
1047 if self.firsttime:
1047 if self.firsttime:
1048 # self.ds[i].resize(self.data[i].shape)
1048 # self.ds[i].resize(self.data[i].shape)
1049 # self.ds[i][self.blockIndex,:] = self.data[i]
1049 # self.ds[i][self.blockIndex,:] = self.data[i]
1050 if type(self.data[i]) == numpy.ndarray:
1050 if type(self.data[i]) == numpy.ndarray:
1051
1051
1052 if nDim == 3:
1052 if nDim == 3:
1053 self.data[i] = self.data[i].reshape((self.data[i].shape[0],self.data[i].shape[1],1))
1053 self.data[i] = self.data[i].reshape((self.data[i].shape[0],self.data[i].shape[1],1))
1054 self.ds[i].resize(self.data[i].shape)
1054 self.ds[i].resize(self.data[i].shape)
1055 if mode == 2:
1055 if mode == 2:
1056 self.ds[i].resize(self.data[i].shape)
1056 self.ds[i].resize(self.data[i].shape)
1057 self.ds[i][:] = self.data[i]
1057 self.ds[i][:] = self.data[i]
1058 else:
1058 else:
1059
1059
1060 # From second time
1060 # From second time
1061 # Meteors!
1061 # Meteors!
1062 if mode == 2:
1062 if mode == 2:
1063 dataShape = self.data[i].shape
1063 dataShape = self.data[i].shape
1064 dsShape = self.ds[i].shape
1064 dsShape = self.ds[i].shape
1065 self.ds[i].resize((self.ds[i].shape[0] + dataShape[0],self.ds[i].shape[1]))
1065 self.ds[i].resize((self.ds[i].shape[0] + dataShape[0],self.ds[i].shape[1]))
1066 self.ds[i][dsShape[0]:,:] = self.data[i]
1066 self.ds[i][dsShape[0]:,:] = self.data[i]
1067 # No dimension
1067 # No dimension
1068 elif mode == 0:
1068 elif mode == 0:
1069 self.ds[i].resize((self.ds[i].shape[0], self.ds[i].shape[1] + 1))
1069 self.ds[i].resize((self.ds[i].shape[0], self.ds[i].shape[1] + 1))
1070 self.ds[i][0,-1] = self.data[i]
1070 self.ds[i][0,-1] = self.data[i]
1071 # One dimension
1071 # One dimension
1072 elif nDim == 1:
1072 elif nDim == 1:
1073 self.ds[i].resize((self.ds[i].shape[0] + 1, self.ds[i].shape[1]))
1073 self.ds[i].resize((self.ds[i].shape[0] + 1, self.ds[i].shape[1]))
1074 self.ds[i][-1,:] = self.data[i]
1074 self.ds[i][-1,:] = self.data[i]
1075 # Two dimension
1075 # Two dimension
1076 elif nDim == 2:
1076 elif nDim == 2:
1077 self.ds[i].resize((self.ds[i].shape[0] + 1,self.ds[i].shape[1]))
1077 self.ds[i].resize((self.ds[i].shape[0] + 1,self.ds[i].shape[1]))
1078 self.ds[i][self.blockIndex,:] = self.data[i]
1078 self.ds[i][self.blockIndex,:] = self.data[i]
1079 # Three dimensions
1079 # Three dimensions
1080 elif nDim == 3:
1080 elif nDim == 3:
1081 self.ds[i].resize((self.ds[i].shape[0],self.ds[i].shape[1],self.ds[i].shape[2]+1))
1081 self.ds[i].resize((self.ds[i].shape[0],self.ds[i].shape[1],self.ds[i].shape[2]+1))
1082 self.ds[i][:,:,-1] = self.data[i]
1082 self.ds[i][:,:,-1] = self.data[i]
1083
1083
1084 self.firsttime = False
1084 self.firsttime = False
1085 self.blockIndex += 1
1085 self.blockIndex += 1
1086
1086
1087 #Close to save changes
1087 #Close to save changes
1088 self.fp.flush()
1088 self.fp.flush()
1089 self.fp.close()
1089 self.fp.close()
1090 return
1090 return
1091
1091
1092 def run(self, dataOut, **kwargs):
1092 def run(self, dataOut, **kwargs):
1093
1093
1094 if not(self.isConfig):
1094 if not(self.isConfig):
1095 flagdata = self.setup(dataOut, **kwargs)
1095 flagdata = self.setup(dataOut, **kwargs)
1096
1096
1097 if not(flagdata):
1097 if not(flagdata):
1098 return
1098 return
1099
1099
1100 self.isConfig = True
1100 self.isConfig = True
1101 # self.putMetadata()
1101 # self.putMetadata()
1102 self.setNextFile()
1102 self.setNextFile()
1103
1103
1104 self.putData()
1104 self.putData()
1105 return
1105 return
@@ -1,679 +1,707
1 '''
1 '''
2 Created on Jul 2, 2014
2 Created on Jul 2, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import numpy
6 import numpy
7
7
8 from jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
8 from jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
10 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
10 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
11 from schainpy.model.data.jrodata import Spectra
11 from schainpy.model.data.jrodata import Spectra
12
12
13 class SpectraReader(JRODataReader, ProcessingUnit):
13 class SpectraReader(JRODataReader, ProcessingUnit):
14
14 """
15 """
15 Esta clase permite leer datos de espectros desde archivos procesados (.pdata). La lectura
16 Esta clase permite leer datos de espectros desde archivos procesados (.pdata). La lectura
16 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones)
17 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones)
17 son almacenados en tres buffer's para el Self Spectra, el Cross Spectra y el DC Channel.
18 son almacenados en tres buffer's para el Self Spectra, el Cross Spectra y el DC Channel.
18
19
19 paresCanalesIguales * alturas * perfiles (Self Spectra)
20 paresCanalesIguales * alturas * perfiles (Self Spectra)
20 paresCanalesDiferentes * alturas * perfiles (Cross Spectra)
21 paresCanalesDiferentes * alturas * perfiles (Cross Spectra)
21 canales * alturas (DC Channels)
22 canales * alturas (DC Channels)
22
23
24
23 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
25 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
24 RadarControllerHeader y Spectra. Los tres primeros se usan para almacenar informacion de la
26 RadarControllerHeader y Spectra. Los tres primeros se usan para almacenar informacion de la
25 cabecera de datos (metadata), y el cuarto (Spectra) para obtener y almacenar un bloque de
27 cabecera de datos (metadata), y el cuarto (Spectra) para obtener y almacenar un bloque de
26 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
28 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
27
29
28 Example:
30 Example:
29 dpath = "/home/myuser/data"
31 dpath = "/home/myuser/data"
30
32
31 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
33 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
32
34
33 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
35 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
34
36
35 readerObj = SpectraReader()
37 readerObj = SpectraReader()
36
38
37 readerObj.setup(dpath, startTime, endTime)
39 readerObj.setup(dpath, startTime, endTime)
38
40
39 while(True):
41 while(True):
40
42
41 readerObj.getData()
43 readerObj.getData()
42
44
43 print readerObj.data_spc
45 print readerObj.data_spc
44
46
45 print readerObj.data_cspc
47 print readerObj.data_cspc
46
48
47 print readerObj.data_dc
49 print readerObj.data_dc
48
50
49 if readerObj.flagNoMoreFiles:
51 if readerObj.flagNoMoreFiles:
50 break
52 break
51
53
52 """
54 """
53
55
54 pts2read_SelfSpectra = 0
56 pts2read_SelfSpectra = 0
55
57
56 pts2read_CrossSpectra = 0
58 pts2read_CrossSpectra = 0
57
59
58 pts2read_DCchannels = 0
60 pts2read_DCchannels = 0
59
61
60 ext = ".pdata"
62 ext = ".pdata"
61
63
62 optchar = "P"
64 optchar = "P"
63
65
64 dataOut = None
66 dataOut = None
65
67
66 nRdChannels = None
68 nRdChannels = None
67
69
68 nRdPairs = None
70 nRdPairs = None
69
71
70 rdPairList = []
72 rdPairList = []
71
73
72 def __init__(self, **kwargs):
74 def __init__(self, **kwargs):
73 """
75 """
74 Inicializador de la clase SpectraReader para la lectura de datos de espectros.
76 Inicializador de la clase SpectraReader para la lectura de datos de espectros.
75
77
76 Inputs:
78 Inputs:
79
77 dataOut : Objeto de la clase Spectra. Este objeto sera utilizado para
80 dataOut : Objeto de la clase Spectra. Este objeto sera utilizado para
78 almacenar un perfil de datos cada vez que se haga un requerimiento
81 almacenar un perfil de datos cada vez que se haga un requerimiento
79 (getData). El perfil sera obtenido a partir del buffer de datos,
82 (getData). El perfil sera obtenido a partir del buffer de datos,
80 si el buffer esta vacio se hara un nuevo proceso de lectura de un
83 si el buffer esta vacio se hara un nuevo proceso de lectura de un
81 bloque de datos.
84 bloque de datos.
82 Si este parametro no es pasado se creara uno internamente.
85 Si este parametro no es pasado se creara uno internamente.
83
86
84 Affected:
87
88 Affected:
89
85 self.dataOut
90 self.dataOut
86
91
87 Return : None
92 Return : None
88 """
93 """
89
94
95
90 #Eliminar de la base la herencia
96 #Eliminar de la base la herencia
91 ProcessingUnit.__init__(self, **kwargs)
97 ProcessingUnit.__init__(self, **kwargs)
92
98
93 # self.isConfig = False
99 # self.isConfig = False
94
100
95 self.pts2read_SelfSpectra = 0
101 self.pts2read_SelfSpectra = 0
96
102
97 self.pts2read_CrossSpectra = 0
103 self.pts2read_CrossSpectra = 0
98
104
99 self.pts2read_DCchannels = 0
105 self.pts2read_DCchannels = 0
100
106
101 self.datablock = None
107 self.datablock = None
102
108
103 self.utc = None
109 self.utc = None
104
110
105 self.ext = ".pdata"
111 self.ext = ".pdata"
106
112
107 self.optchar = "P"
113 self.optchar = "P"
108
114
109 self.basicHeaderObj = BasicHeader(LOCALTIME)
115 self.basicHeaderObj = BasicHeader(LOCALTIME)
110
116
111 self.systemHeaderObj = SystemHeader()
117 self.systemHeaderObj = SystemHeader()
112
118
113 self.radarControllerHeaderObj = RadarControllerHeader()
119 self.radarControllerHeaderObj = RadarControllerHeader()
114
120
115 self.processingHeaderObj = ProcessingHeader()
121 self.processingHeaderObj = ProcessingHeader()
116
122
117 self.online = 0
123 self.online = 0
118
124
119 self.fp = None
125 self.fp = None
120
126
121 self.idFile = None
127 self.idFile = None
122
128
123 self.dtype = None
129 self.dtype = None
124
130
125 self.fileSizeByHeader = None
131 self.fileSizeByHeader = None
126
132
127 self.filenameList = []
133 self.filenameList = []
128
134
129 self.filename = None
135 self.filename = None
130
136
131 self.fileSize = None
137 self.fileSize = None
132
138
133 self.firstHeaderSize = 0
139 self.firstHeaderSize = 0
134
140
135 self.basicHeaderSize = 24
141 self.basicHeaderSize = 24
136
142
137 self.pathList = []
143 self.pathList = []
138
144
139 self.lastUTTime = 0
145 self.lastUTTime = 0
140
146
141 self.maxTimeStep = 30
147 self.maxTimeStep = 30
142
148
143 self.flagNoMoreFiles = 0
149 self.flagNoMoreFiles = 0
144
150
145 self.set = 0
151 self.set = 0
146
152
147 self.path = None
153 self.path = None
148
154
149 self.delay = 60 #seconds
155 self.delay = 60 #seconds
150
156
151 self.nTries = 3 #quantity tries
157 self.nTries = 3 #quantity tries
152
158
153 self.nFiles = 3 #number of files for searching
159 self.nFiles = 3 #number of files for searching
154
160
155 self.nReadBlocks = 0
161 self.nReadBlocks = 0
156
162
157 self.flagIsNewFile = 1
163 self.flagIsNewFile = 1
158
164
159 self.__isFirstTimeOnline = 1
165 self.__isFirstTimeOnline = 1
160
166
161 # self.ippSeconds = 0
167 # self.ippSeconds = 0
162
168
163 self.flagDiscontinuousBlock = 0
169 self.flagDiscontinuousBlock = 0
164
170
165 self.flagIsNewBlock = 0
171 self.flagIsNewBlock = 0
166
172
167 self.nTotalBlocks = 0
173 self.nTotalBlocks = 0
168
174
169 self.blocksize = 0
175 self.blocksize = 0
170
176
171 self.dataOut = self.createObjByDefault()
177 self.dataOut = self.createObjByDefault()
172
178
173 self.profileIndex = 1 #Always
179 self.profileIndex = 1 #Always
174
180
175
181
176 def createObjByDefault(self):
182 def createObjByDefault(self):
177
183
178 dataObj = Spectra()
184 dataObj = Spectra()
179
185
180 return dataObj
186 return dataObj
181
187
182 def __hasNotDataInBuffer(self):
188 def __hasNotDataInBuffer(self):
183 return 1
189 return 1
184
190
185
191
186 def getBlockDimension(self):
192 def getBlockDimension(self):
187 """
193 """
188 Obtiene la cantidad de puntos a leer por cada bloque de datos
194 Obtiene la cantidad de puntos a leer por cada bloque de datos
189
195
190 Affected:
196 Affected:
191 self.nRdChannels
197 self.nRdChannels
192 self.nRdPairs
198 self.nRdPairs
193 self.pts2read_SelfSpectra
199 self.pts2read_SelfSpectra
194 self.pts2read_CrossSpectra
200 self.pts2read_CrossSpectra
195 self.pts2read_DCchannels
201 self.pts2read_DCchannels
196 self.blocksize
202 self.blocksize
197 self.dataOut.nChannels
203 self.dataOut.nChannels
198 self.dataOut.nPairs
204 self.dataOut.nPairs
199
205
200 Return:
206 Return:
201 None
207 None
202 """
208 """
203 self.nRdChannels = 0
209 self.nRdChannels = 0
204 self.nRdPairs = 0
210 self.nRdPairs = 0
205 self.rdPairList = []
211 self.rdPairList = []
206
212
207 for i in range(0, self.processingHeaderObj.totalSpectra*2, 2):
213 for i in range(0, self.processingHeaderObj.totalSpectra*2, 2):
208 if self.processingHeaderObj.spectraComb[i] == self.processingHeaderObj.spectraComb[i+1]:
214 if self.processingHeaderObj.spectraComb[i] == self.processingHeaderObj.spectraComb[i+1]:
209 self.nRdChannels = self.nRdChannels + 1 #par de canales iguales
215 self.nRdChannels = self.nRdChannels + 1 #par de canales iguales
216
210 else:
217 else:
211 self.nRdPairs = self.nRdPairs + 1 #par de canales diferentes
218 self.nRdPairs = self.nRdPairs + 1 #par de canales diferentes
212 self.rdPairList.append((self.processingHeaderObj.spectraComb[i], self.processingHeaderObj.spectraComb[i+1]))
219 self.rdPairList.append((self.processingHeaderObj.spectraComb[i], self.processingHeaderObj.spectraComb[i+1]))
213
220
214 pts2read = self.processingHeaderObj.nHeights * self.processingHeaderObj.profilesPerBlock
221 pts2read = self.processingHeaderObj.nHeights * self.processingHeaderObj.profilesPerBlock
215
222
216 self.pts2read_SelfSpectra = int(self.nRdChannels * pts2read)
223 self.pts2read_SelfSpectra = int(self.nRdChannels * pts2read)
217 self.blocksize = self.pts2read_SelfSpectra
224 self.blocksize = self.pts2read_SelfSpectra
218
225
219 if self.processingHeaderObj.flag_cspc:
226 if self.processingHeaderObj.flag_cspc:
220 self.pts2read_CrossSpectra = int(self.nRdPairs * pts2read)
227 self.pts2read_CrossSpectra = int(self.nRdPairs * pts2read)
221 self.blocksize += self.pts2read_CrossSpectra
228 self.blocksize += self.pts2read_CrossSpectra
222
229
223 if self.processingHeaderObj.flag_dc:
230 if self.processingHeaderObj.flag_dc:
224 self.pts2read_DCchannels = int(self.systemHeaderObj.nChannels * self.processingHeaderObj.nHeights)
231 self.pts2read_DCchannels = int(self.systemHeaderObj.nChannels * self.processingHeaderObj.nHeights)
225 self.blocksize += self.pts2read_DCchannels
232 self.blocksize += self.pts2read_DCchannels
226
233
227 # self.blocksize = self.pts2read_SelfSpectra + self.pts2read_CrossSpectra + self.pts2read_DCchannels
234 # self.blocksize = self.pts2read_SelfSpectra + self.pts2read_CrossSpectra + self.pts2read_DCchannels
228
235
229
236
230 def readBlock(self):
237 def readBlock(self):
231 """
238 """
232 Lee el bloque de datos desde la posicion actual del puntero del archivo
239 Lee el bloque de datos desde la posicion actual del puntero del archivo
233 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
240 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
234 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
241 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
235 es seteado a 0
242 es seteado a 0
236
243
237 Return: None
244 Return: None
238
245
239 Variables afectadas:
246 Variables afectadas:
247
240
248
241 self.flagIsNewFile
249 self.flagIsNewFile
242 self.flagIsNewBlock
250 self.flagIsNewBlock
243 self.nTotalBlocks
251 self.nTotalBlocks
244 self.data_spc
252 self.data_spc
245 self.data_cspc
253 self.data_cspc
246 self.data_dc
254 self.data_dc
247
255
248 Exceptions:
256 Exceptions:
249 Si un bloque leido no es un bloque valido
257 Si un bloque leido no es un bloque valido
250 """
258 """
259 print ' ======================================================== '
260 print ' '
261 print ' '
262 print self.processingHeaderObj.totalSpectra, 'TotalSpectra', type(self.processingHeaderObj.totalSpectra)
263 print self.processingHeaderObj.spectraComb, 'SpectraComb', type(self.processingHeaderObj.spectraComb)
264 print ' '
265 print ' '
266 print ' ======================================================== '
267
268
251 blockOk_flag = False
269 blockOk_flag = False
252 fpointer = self.fp.tell()
270 fpointer = self.fp.tell()
253
271
254 spc = numpy.fromfile( self.fp, self.dtype[0], self.pts2read_SelfSpectra )
272 spc = numpy.fromfile( self.fp, self.dtype[0], self.pts2read_SelfSpectra )
255 spc = spc.reshape( (self.nRdChannels, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
273 spc = spc.reshape( (self.nRdChannels, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
256
274
257 if self.processingHeaderObj.flag_cspc:
275 if self.processingHeaderObj.flag_cspc:
258 cspc = numpy.fromfile( self.fp, self.dtype, self.pts2read_CrossSpectra )
276 cspc = numpy.fromfile( self.fp, self.dtype, self.pts2read_CrossSpectra )
259 cspc = cspc.reshape( (self.nRdPairs, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
277 cspc = cspc.reshape( (self.nRdPairs, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
260
278
261 if self.processingHeaderObj.flag_dc:
279 if self.processingHeaderObj.flag_dc:
262 dc = numpy.fromfile( self.fp, self.dtype, self.pts2read_DCchannels ) #int(self.processingHeaderObj.nHeights*self.systemHeaderObj.nChannels) )
280 dc = numpy.fromfile( self.fp, self.dtype, self.pts2read_DCchannels ) #int(self.processingHeaderObj.nHeights*self.systemHeaderObj.nChannels) )
263 dc = dc.reshape( (self.systemHeaderObj.nChannels, self.processingHeaderObj.nHeights) ) #transforma a un arreglo 2D
281 dc = dc.reshape( (self.systemHeaderObj.nChannels, self.processingHeaderObj.nHeights) ) #transforma a un arreglo 2D
264
282
265
283
266 if not(self.processingHeaderObj.shif_fft):
284 if not(self.processingHeaderObj.shif_fft):
267 #desplaza a la derecha en el eje 2 determinadas posiciones
285 #desplaza a la derecha en el eje 2 determinadas posiciones
268 shift = int(self.processingHeaderObj.profilesPerBlock/2)
286 shift = int(self.processingHeaderObj.profilesPerBlock/2)
269 spc = numpy.roll( spc, shift , axis=2 )
287 spc = numpy.roll( spc, shift , axis=2 )
270
288
271 if self.processingHeaderObj.flag_cspc:
289 if self.processingHeaderObj.flag_cspc:
272 #desplaza a la derecha en el eje 2 determinadas posiciones
290 #desplaza a la derecha en el eje 2 determinadas posiciones
273 cspc = numpy.roll( cspc, shift, axis=2 )
291 cspc = numpy.roll( cspc, shift, axis=2 )
274
292
275 #Dimensions : nChannels, nProfiles, nSamples
293 #Dimensions : nChannels, nProfiles, nSamples
276 spc = numpy.transpose( spc, (0,2,1) )
294 spc = numpy.transpose( spc, (0,2,1) )
277 self.data_spc = spc
295 self.data_spc = spc
296
297 if self.processingHeaderObj.flag_cspc:
278
298
279 if self.processingHeaderObj.flag_cspc:
280 cspc = numpy.transpose( cspc, (0,2,1) )
299 cspc = numpy.transpose( cspc, (0,2,1) )
281 self.data_cspc = cspc['real'] + cspc['imag']*1j
300 self.data_cspc = cspc['real'] + cspc['imag']*1j
282 else:
301 else:
283 self.data_cspc = None
302 self.data_cspc = None
303
284
304
285 if self.processingHeaderObj.flag_dc:
305 if self.processingHeaderObj.flag_dc:
286 self.data_dc = dc['real'] + dc['imag']*1j
306 self.data_dc = dc['real'] + dc['imag']*1j
287 else:
307 else:
288 self.data_dc = None
308 self.data_dc = None
289
309
290 self.flagIsNewFile = 0
310 self.flagIsNewFile = 0
291 self.flagIsNewBlock = 1
311 self.flagIsNewBlock = 1
292
312
293 self.nTotalBlocks += 1
313 self.nTotalBlocks += 1
294 self.nReadBlocks += 1
314 self.nReadBlocks += 1
295
315
296 return 1
316 return 1
297
317
298 def getFirstHeader(self):
318 def getFirstHeader(self):
299
319
300 self.getBasicHeader()
320 self.getBasicHeader()
301
321
302 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
322 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
303
323
304 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
324 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
305
325
306 # self.dataOut.ippSeconds = self.ippSeconds
326 # self.dataOut.ippSeconds = self.ippSeconds
307
327
308 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt * self.processingHeaderObj.nIncohInt * self.processingHeaderObj.profilesPerBlock
328 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt * self.processingHeaderObj.nIncohInt * self.processingHeaderObj.profilesPerBlock
309
329
310 self.dataOut.dtype = self.dtype
330 self.dataOut.dtype = self.dtype
311
331
312 # self.dataOut.nPairs = self.nPairs
332 # self.dataOut.nPairs = self.nPairs
313
333
314 self.dataOut.pairsList = self.rdPairList
334 self.dataOut.pairsList = self.rdPairList
315
335
316 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
336 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
317
337
318 self.dataOut.nFFTPoints = self.processingHeaderObj.profilesPerBlock
338 self.dataOut.nFFTPoints = self.processingHeaderObj.profilesPerBlock
319
339
320 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
340 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
321
341
322 self.dataOut.nIncohInt = self.processingHeaderObj.nIncohInt
342 self.dataOut.nIncohInt = self.processingHeaderObj.nIncohInt
323
343
324 xf = self.processingHeaderObj.firstHeight + self.processingHeaderObj.nHeights*self.processingHeaderObj.deltaHeight
344 xf = self.processingHeaderObj.firstHeight + self.processingHeaderObj.nHeights*self.processingHeaderObj.deltaHeight
325
345
326 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight)
346 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight)
327
347
328 self.dataOut.channelList = range(self.systemHeaderObj.nChannels)
348 self.dataOut.channelList = range(self.systemHeaderObj.nChannels)
329
349
330 self.dataOut.flagShiftFFT = True #Data is always shifted
350 self.dataOut.flagShiftFFT = True #Data is always shifted
331
351
332 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode #asumo q la data no esta decodificada
352 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode #asumo q la data no esta decodificada
333
353
334 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data esta sin flip
354 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data esta sin flip
335
355
336 def getData(self):
356 def getData(self):
337 """
357 """
338 First method to execute before "RUN" is called.
358 First method to execute before "RUN" is called.
339
359
340 Copia el buffer de lectura a la clase "Spectra",
360 Copia el buffer de lectura a la clase "Spectra",
341 con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de
361 con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de
342 lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock"
362 lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock"
343
363
344 Return:
364 Return:
345 0 : Si no hay mas archivos disponibles
365 0 : Si no hay mas archivos disponibles
346 1 : Si hizo una buena copia del buffer
366 1 : Si hizo una buena copia del buffer
347
367
348 Affected:
368 Affected:
349 self.dataOut
369 self.dataOut
350
370
351 self.flagDiscontinuousBlock
371 self.flagDiscontinuousBlock
352 self.flagIsNewBlock
372 self.flagIsNewBlock
353 """
373 """
354
374
355 if self.flagNoMoreFiles:
375 if self.flagNoMoreFiles:
356 self.dataOut.flagNoData = True
376 self.dataOut.flagNoData = True
357 print 'Process finished'
377 print 'Process finished'
358 return 0
378 return 0
359
379
360 self.flagDiscontinuousBlock = 0
380 self.flagDiscontinuousBlock = 0
361 self.flagIsNewBlock = 0
381 self.flagIsNewBlock = 0
362
382
363 if self.__hasNotDataInBuffer():
383 if self.__hasNotDataInBuffer():
364
384
365 if not( self.readNextBlock() ):
385 if not( self.readNextBlock() ):
366 self.dataOut.flagNoData = True
386 self.dataOut.flagNoData = True
367 return 0
387 return 0
388
368
389
369 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
390 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
370
391
371 if self.data_spc is None:
392 if self.data_spc is None:
372 self.dataOut.flagNoData = True
393 self.dataOut.flagNoData = True
373 return 0
394 return 0
374
395
375 self.getBasicHeader()
396 self.getBasicHeader()
376
397
377 self.getFirstHeader()
398 self.getFirstHeader()
378
399
379 self.dataOut.data_spc = self.data_spc
400 self.dataOut.data_spc = self.data_spc
380
401
381 self.dataOut.data_cspc = self.data_cspc
402 self.dataOut.data_cspc = self.data_cspc
382
403
383 self.dataOut.data_dc = self.data_dc
404 self.dataOut.data_dc = self.data_dc
384
405
385 self.dataOut.flagNoData = False
406 self.dataOut.flagNoData = False
386
407
387 self.dataOut.realtime = self.online
408 self.dataOut.realtime = self.online
388
409
389 return self.dataOut.data_spc
410 return self.dataOut.data_spc
390
411
391 class SpectraWriter(JRODataWriter, Operation):
412 class SpectraWriter(JRODataWriter, Operation):
392
413
393 """
414 """
394 Esta clase permite escribir datos de espectros a archivos procesados (.pdata). La escritura
415 Esta clase permite escribir datos de espectros a archivos procesados (.pdata). La escritura
395 de los datos siempre se realiza por bloques.
416 de los datos siempre se realiza por bloques.
396 """
417 """
397
418
398 ext = ".pdata"
419 ext = ".pdata"
399
420
400 optchar = "P"
421 optchar = "P"
401
422
402 shape_spc_Buffer = None
423 shape_spc_Buffer = None
403
424
404 shape_cspc_Buffer = None
425 shape_cspc_Buffer = None
405
426
406 shape_dc_Buffer = None
427 shape_dc_Buffer = None
407
428
408 data_spc = None
429 data_spc = None
409
430
410 data_cspc = None
431 data_cspc = None
411
432
412 data_dc = None
433 data_dc = None
413
434
414 # dataOut = None
435 # dataOut = None
415
436
416 def __init__(self, **kwargs):
437 def __init__(self):
417 """
438 """
418 Inicializador de la clase SpectraWriter para la escritura de datos de espectros.
439 Inicializador de la clase SpectraWriter para la escritura de datos de espectros.
440
441 Affected:
419
442
420 Affected:
421 self.dataOut
443 self.dataOut
422 self.basicHeaderObj
444 self.basicHeaderObj
423 self.systemHeaderObj
445 self.systemHeaderObj
424 self.radarControllerHeaderObj
446 self.radarControllerHeaderObj
425 self.processingHeaderObj
447 self.processingHeaderObj
426
448
427 Return: None
449 Return: None
428 """
450 """
429
451
430 Operation.__init__(self, **kwargs)
452 Operation.__init__(self)
431
453
432 self.isConfig = False
454 self.isConfig = False
433
455
434 self.nTotalBlocks = 0
456 self.nTotalBlocks = 0
435
457
436 self.data_spc = None
458 self.data_spc = None
437
459
438 self.data_cspc = None
460 self.data_cspc = None
461
439
462
440 self.data_dc = None
463 self.data_dc = None
441
464
442 self.fp = None
465 self.fp = None
443
466
444 self.flagIsNewFile = 1
467 self.flagIsNewFile = 1
445
468
446 self.nTotalBlocks = 0
469 self.nTotalBlocks = 0
447
470
448 self.flagIsNewBlock = 0
471 self.flagIsNewBlock = 0
449
472
450 self.setFile = None
473 self.setFile = None
451
474
452 self.dtype = None
475 self.dtype = None
453
476
454 self.path = None
477 self.path = None
455
478
456 self.noMoreFiles = 0
479 self.noMoreFiles = 0
457
480
458 self.filename = None
481 self.filename = None
459
482
460 self.basicHeaderObj = BasicHeader(LOCALTIME)
483 self.basicHeaderObj = BasicHeader(LOCALTIME)
461
484
462 self.systemHeaderObj = SystemHeader()
485 self.systemHeaderObj = SystemHeader()
463
486
464 self.radarControllerHeaderObj = RadarControllerHeader()
487 self.radarControllerHeaderObj = RadarControllerHeader()
465
488
466 self.processingHeaderObj = ProcessingHeader()
489 self.processingHeaderObj = ProcessingHeader()
467
490
468
491
469 def hasAllDataInBuffer(self):
492 def hasAllDataInBuffer(self):
470 return 1
493 return 1
471
494
495
472
496
473 def setBlockDimension(self):
497 def setBlockDimension(self):
474 """
498 """
475 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
499 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
476
500
477 Affected:
501 Affected:
478 self.shape_spc_Buffer
502 self.shape_spc_Buffer
479 self.shape_cspc_Buffer
503 self.shape_cspc_Buffer
480 self.shape_dc_Buffer
504 self.shape_dc_Buffer
481
505
482 Return: None
506 Return: None
483 """
507 """
484 self.shape_spc_Buffer = (self.dataOut.nChannels,
508 self.shape_spc_Buffer = (self.dataOut.nChannels,
485 self.processingHeaderObj.nHeights,
509 self.processingHeaderObj.nHeights,
486 self.processingHeaderObj.profilesPerBlock)
510 self.processingHeaderObj.profilesPerBlock)
487
511
488 self.shape_cspc_Buffer = (self.dataOut.nPairs,
512 self.shape_cspc_Buffer = (self.dataOut.nPairs,
489 self.processingHeaderObj.nHeights,
513 self.processingHeaderObj.nHeights,
490 self.processingHeaderObj.profilesPerBlock)
514 self.processingHeaderObj.profilesPerBlock)
491
515
492 self.shape_dc_Buffer = (self.dataOut.nChannels,
516 self.shape_dc_Buffer = (self.dataOut.nChannels,
493 self.processingHeaderObj.nHeights)
517 self.processingHeaderObj.nHeights)
494
518
495
519
496 def writeBlock(self):
520 def writeBlock(self):
497 """
521 """
498 Escribe el buffer en el file designado
522 Escribe el buffer en el file designado
523
499
524
500 Affected:
525 Affected:
501 self.data_spc
526 self.data_spc
502 self.data_cspc
527 self.data_cspc
503 self.data_dc
528 self.data_dc
504 self.flagIsNewFile
529 self.flagIsNewFile
505 self.flagIsNewBlock
530 self.flagIsNewBlock
506 self.nTotalBlocks
531 self.nTotalBlocks
507 self.nWriteBlocks
532 self.nWriteBlocks
508
533
509 Return: None
534 Return: None
510 """
535 """
511
536
512 spc = numpy.transpose( self.data_spc, (0,2,1) )
537 spc = numpy.transpose( self.data_spc, (0,2,1) )
513 if not( self.processingHeaderObj.shif_fft ):
538 if not( self.processingHeaderObj.shif_fft ):
514 spc = numpy.roll( spc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
539 spc = numpy.roll( spc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
515 data = spc.reshape((-1))
540 data = spc.reshape((-1))
516 data = data.astype(self.dtype[0])
541 data = data.astype(self.dtype[0])
517 data.tofile(self.fp)
542 data.tofile(self.fp)
518
543
519 if self.data_cspc is not None:
544 if self.data_cspc is not None:
520 data = numpy.zeros( self.shape_cspc_Buffer, self.dtype )
545 data = numpy.zeros( self.shape_cspc_Buffer, self.dtype )
521 cspc = numpy.transpose( self.data_cspc, (0,2,1) )
546 cspc = numpy.transpose( self.data_cspc, (0,2,1) )
522 if not( self.processingHeaderObj.shif_fft ):
547 if not( self.processingHeaderObj.shif_fft ):
523 cspc = numpy.roll( cspc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
548 cspc = numpy.roll( cspc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
524 data['real'] = cspc.real
549 data['real'] = cspc.real
525 data['imag'] = cspc.imag
550 data['imag'] = cspc.imag
526 data = data.reshape((-1))
551 data = data.reshape((-1))
527 data.tofile(self.fp)
552 data.tofile(self.fp)
553
528
554
529 if self.data_dc is not None:
555 if self.data_dc is not None:
530 data = numpy.zeros( self.shape_dc_Buffer, self.dtype )
556 data = numpy.zeros( self.shape_dc_Buffer, self.dtype )
531 dc = self.data_dc
557 dc = self.data_dc
532 data['real'] = dc.real
558 data['real'] = dc.real
533 data['imag'] = dc.imag
559 data['imag'] = dc.imag
534 data = data.reshape((-1))
560 data = data.reshape((-1))
535 data.tofile(self.fp)
561 data.tofile(self.fp)
536
562
537 # self.data_spc.fill(0)
563 # self.data_spc.fill(0)
538 #
564 #
539 # if self.data_dc is not None:
565 # if self.data_dc is not None:
540 # self.data_dc.fill(0)
566 # self.data_dc.fill(0)
541 #
567 #
542 # if self.data_cspc is not None:
568 # if self.data_cspc is not None:
543 # self.data_cspc.fill(0)
569 # self.data_cspc.fill(0)
570
544
571
545 self.flagIsNewFile = 0
572 self.flagIsNewFile = 0
546 self.flagIsNewBlock = 1
573 self.flagIsNewBlock = 1
547 self.nTotalBlocks += 1
574 self.nTotalBlocks += 1
548 self.nWriteBlocks += 1
575 self.nWriteBlocks += 1
549 self.blockIndex += 1
576 self.blockIndex += 1
550
577
551 # print "[Writing] Block = %d04" %self.blockIndex
578 # print "[Writing] Block = %d04" %self.blockIndex
552
579
553 def putData(self):
580 def putData(self):
554 """
581 """
555 Setea un bloque de datos y luego los escribe en un file
582 Setea un bloque de datos y luego los escribe en un file
583
556
584
557 Affected:
585 Affected:
558 self.data_spc
586 self.data_spc
559 self.data_cspc
587 self.data_cspc
560 self.data_dc
588 self.data_dc
561
589
562 Return:
590 Return:
563 0 : Si no hay data o no hay mas files que puedan escribirse
591 0 : Si no hay data o no hay mas files que puedan escribirse
564 1 : Si se escribio la data de un bloque en un file
592 1 : Si se escribio la data de un bloque en un file
565 """
593 """
566
594
567 if self.dataOut.flagNoData:
595 if self.dataOut.flagNoData:
568 return 0
596 return 0
569
597
570 self.flagIsNewBlock = 0
598 self.flagIsNewBlock = 0
571
599
572 if self.dataOut.flagDiscontinuousBlock:
600 if self.dataOut.flagDiscontinuousBlock:
573 self.data_spc.fill(0)
601 self.data_spc.fill(0)
574 if self.dataOut.data_cspc is not None:
602 self.data_cspc.fill(0)
575 self.data_cspc.fill(0)
603 self.data_dc.fill(0)
576 if self.dataOut.data_dc is not None:
577 self.data_dc.fill(0)
578 self.setNextFile()
604 self.setNextFile()
579
605
580 if self.flagIsNewFile == 0:
606 if self.flagIsNewFile == 0:
581 self.setBasicHeader()
607 self.setBasicHeader()
582
608
583 self.data_spc = self.dataOut.data_spc.copy()
609 self.data_spc = self.dataOut.data_spc.copy()
584
610
585 if self.dataOut.data_cspc is not None:
611 if self.dataOut.data_cspc is not None:
586 self.data_cspc = self.dataOut.data_cspc.copy()
612 self.data_cspc = self.dataOut.data_cspc.copy()
587
613
588 if self.dataOut.data_dc is not None:
614 if self.dataOut.data_dc is not None:
589 self.data_dc = self.dataOut.data_dc.copy()
615 self.data_dc = self.dataOut.data_dc.copy()
590
616
591 # #self.processingHeaderObj.dataBlocksPerFile)
617 # #self.processingHeaderObj.dataBlocksPerFile)
592 if self.hasAllDataInBuffer():
618 if self.hasAllDataInBuffer():
593 # self.setFirstHeader()
619 # self.setFirstHeader()
594 self.writeNextBlock()
620 self.writeNextBlock()
595
621
596 return 1
622 return 1
623
597
624
598 def __getBlockSize(self):
625 def __getBlockSize(self):
599 '''
626 '''
600 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Spectra
627 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Spectra
601 '''
628 '''
602
629
603 dtype_width = self.getDtypeWidth()
630 dtype_width = self.getDtypeWidth()
604
631
605 pts2write = self.dataOut.nHeights * self.dataOut.nFFTPoints
632 pts2write = self.dataOut.nHeights * self.dataOut.nFFTPoints
606
633
607 pts2write_SelfSpectra = int(self.dataOut.nChannels * pts2write)
634 pts2write_SelfSpectra = int(self.dataOut.nChannels * pts2write)
608 blocksize = (pts2write_SelfSpectra*dtype_width)
635 blocksize = (pts2write_SelfSpectra*dtype_width)
609
636
610 if self.dataOut.data_cspc is not None:
637 if self.dataOut.data_cspc is not None:
611 pts2write_CrossSpectra = int(self.dataOut.nPairs * pts2write)
638 pts2write_CrossSpectra = int(self.dataOut.nPairs * pts2write)
612 blocksize += (pts2write_CrossSpectra*dtype_width*2)
639 blocksize += (pts2write_CrossSpectra*dtype_width*2)
613
640
614 if self.dataOut.data_dc is not None:
641 if self.dataOut.data_dc is not None:
615 pts2write_DCchannels = int(self.dataOut.nChannels * self.dataOut.nHeights)
642 pts2write_DCchannels = int(self.dataOut.nChannels * self.dataOut.nHeights)
616 blocksize += (pts2write_DCchannels*dtype_width*2)
643 blocksize += (pts2write_DCchannels*dtype_width*2)
617
644
618 # blocksize = blocksize #* datatypeValue * 2 #CORREGIR ESTO
645 # blocksize = blocksize #* datatypeValue * 2 #CORREGIR ESTO
619
646
620 return blocksize
647 return blocksize
621
648
622 def setFirstHeader(self):
649 def setFirstHeader(self):
623
650
624 """
651 """
625 Obtiene una copia del First Header
652 Obtiene una copia del First Header
626
653
627 Affected:
654 Affected:
628 self.systemHeaderObj
655 self.systemHeaderObj
629 self.radarControllerHeaderObj
656 self.radarControllerHeaderObj
630 self.dtype
657 self.dtype
631
658
632 Return:
659 Return:
633 None
660 None
634 """
661 """
635
662
636 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
663 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
637 self.systemHeaderObj.nChannels = self.dataOut.nChannels
664 self.systemHeaderObj.nChannels = self.dataOut.nChannels
638 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
665 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
639
666
640 self.processingHeaderObj.dtype = 1 # Spectra
667 self.processingHeaderObj.dtype = 1 # Spectra
641 self.processingHeaderObj.blockSize = self.__getBlockSize()
668 self.processingHeaderObj.blockSize = self.__getBlockSize()
642 self.processingHeaderObj.profilesPerBlock = self.dataOut.nFFTPoints
669 self.processingHeaderObj.profilesPerBlock = self.dataOut.nFFTPoints
643 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
670 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
644 self.processingHeaderObj.nWindows = 1 #podria ser 1 o self.dataOut.processingHeaderObj.nWindows
671 self.processingHeaderObj.nWindows = 1 #podria ser 1 o self.dataOut.processingHeaderObj.nWindows
645 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt# Se requiere para determinar el valor de timeInterval
672 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt# Se requiere para determinar el valor de timeInterval
646 self.processingHeaderObj.nIncohInt = self.dataOut.nIncohInt
673 self.processingHeaderObj.nIncohInt = self.dataOut.nIncohInt
647 self.processingHeaderObj.totalSpectra = self.dataOut.nPairs + self.dataOut.nChannels
674 self.processingHeaderObj.totalSpectra = self.dataOut.nPairs + self.dataOut.nChannels
648 self.processingHeaderObj.shif_fft = self.dataOut.flagShiftFFT
675 self.processingHeaderObj.shif_fft = self.dataOut.flagShiftFFT
676
649
677
650 if self.processingHeaderObj.totalSpectra > 0:
678 if self.processingHeaderObj.totalSpectra > 0:
651 channelList = []
679 channelList = []
652 for channel in range(self.dataOut.nChannels):
680 for channel in range(self.dataOut.nChannels):
653 channelList.append(channel)
681 channelList.append(channel)
654 channelList.append(channel)
682 channelList.append(channel)
655
683
656 pairsList = []
684 pairsList = []
657 if self.dataOut.nPairs > 0:
685 if self.dataOut.nPairs > 0:
658 for pair in self.dataOut.pairsList:
686 for pair in self.dataOut.pairsList:
659 pairsList.append(pair[0])
687 pairsList.append(pair[0])
660 pairsList.append(pair[1])
688 pairsList.append(pair[1])
661
689
662 spectraComb = channelList + pairsList
690 spectraComb = channelList + pairsList
663 spectraComb = numpy.array(spectraComb, dtype="u1")
691 spectraComb = numpy.array(spectraComb, dtype="u1")
664 self.processingHeaderObj.spectraComb = spectraComb
692 self.processingHeaderObj.spectraComb = spectraComb
665
693
666 if self.dataOut.code is not None:
694 if self.dataOut.code is not None:
667 self.processingHeaderObj.code = self.dataOut.code
695 self.processingHeaderObj.code = self.dataOut.code
668 self.processingHeaderObj.nCode = self.dataOut.nCode
696 self.processingHeaderObj.nCode = self.dataOut.nCode
669 self.processingHeaderObj.nBaud = self.dataOut.nBaud
697 self.processingHeaderObj.nBaud = self.dataOut.nBaud
670
698
671 if self.processingHeaderObj.nWindows != 0:
699 if self.processingHeaderObj.nWindows != 0:
672 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
700 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
673 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
701 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
674 self.processingHeaderObj.nHeights = self.dataOut.nHeights
702 self.processingHeaderObj.nHeights = self.dataOut.nHeights
675 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
703 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
676
704
677 self.processingHeaderObj.processFlags = self.getProcessFlags()
705 self.processingHeaderObj.processFlags = self.getProcessFlags()
678
706
679 self.setBasicHeader()
707 self.setBasicHeader()
@@ -1,737 +1,743
1 '''
1 '''
2 Created on Jul 2, 2014
2 Created on Jul 2, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6
6
7 import numpy
7 import numpy
8
8
9 from jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
9 from jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
10 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
10 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
11 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
11 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
12 from schainpy.model.data.jrodata import Voltage
12 from schainpy.model.data.jrodata import Voltage
13 import zmq
13 import zmq
14 import tempfile
14 import tempfile
15 from StringIO import StringIO
15 from StringIO import StringIO
16 # from _sha import blocksize
16 # from _sha import blocksize
17
17
18 class VoltageReader(JRODataReader, ProcessingUnit):
18 class VoltageReader(JRODataReader, ProcessingUnit):
19 """
19 """
20 Esta clase permite leer datos de voltage desde archivos en formato rawdata (.r). La lectura
20 Esta clase permite leer datos de voltage desde archivos en formato rawdata (.r). La lectura
21 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones:
21 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones:
22 perfiles*alturas*canales) son almacenados en la variable "buffer".
22 perfiles*alturas*canales) son almacenados en la variable "buffer".
23
23
24 perfiles * alturas * canales
24 perfiles * alturas * canales
25
25
26 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
26 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
27 RadarControllerHeader y Voltage. Los tres primeros se usan para almacenar informacion de la
27 RadarControllerHeader y Voltage. Los tres primeros se usan para almacenar informacion de la
28 cabecera de datos (metadata), y el cuarto (Voltage) para obtener y almacenar un perfil de
28 cabecera de datos (metadata), y el cuarto (Voltage) para obtener y almacenar un perfil de
29 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
29 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
30
30
31 Example:
31 Example:
32
32
33 dpath = "/home/myuser/data"
33 dpath = "/home/myuser/data"
34
34
35 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
35 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
36
36
37 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
37 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
38
38
39 readerObj = VoltageReader()
39 readerObj = VoltageReader()
40
40
41 readerObj.setup(dpath, startTime, endTime)
41 readerObj.setup(dpath, startTime, endTime)
42
42
43 while(True):
43 while(True):
44
44
45 #to get one profile
45 #to get one profile
46 profile = readerObj.getData()
46 profile = readerObj.getData()
47
47
48 #print the profile
48 #print the profile
49 print profile
49 print profile
50
50
51 #If you want to see all datablock
51 #If you want to see all datablock
52 print readerObj.datablock
52 print readerObj.datablock
53
53
54 if readerObj.flagNoMoreFiles:
54 if readerObj.flagNoMoreFiles:
55 break
55 break
56
56
57 """
57 """
58
58
59 ext = ".r"
59 ext = ".r"
60
60
61 optchar = "D"
61 optchar = "D"
62 dataOut = None
62 dataOut = None
63
63
64 def __init__(self, **kwargs):
64 def __init__(self, **kwargs):
65 """
65 """
66 Inicializador de la clase VoltageReader para la lectura de datos de voltage.
66 Inicializador de la clase VoltageReader para la lectura de datos de voltage.
67
67
68 Input:
68 Input:
69 dataOut : Objeto de la clase Voltage. Este objeto sera utilizado para
69 dataOut : Objeto de la clase Voltage. Este objeto sera utilizado para
70 almacenar un perfil de datos cada vez que se haga un requerimiento
70 almacenar un perfil de datos cada vez que se haga un requerimiento
71 (getData). El perfil sera obtenido a partir del buffer de datos,
71 (getData). El perfil sera obtenido a partir del buffer de datos,
72 si el buffer esta vacio se hara un nuevo proceso de lectura de un
72 si el buffer esta vacio se hara un nuevo proceso de lectura de un
73 bloque de datos.
73 bloque de datos.
74 Si este parametro no es pasado se creara uno internamente.
74 Si este parametro no es pasado se creara uno internamente.
75
75
76 Variables afectadas:
76 Variables afectadas:
77 self.dataOut
77 self.dataOut
78
78
79 Return:
79 Return:
80 None
80 None
81 """
81 """
82
82
83 ProcessingUnit.__init__(self, **kwargs)
83 ProcessingUnit.__init__(self, **kwargs)
84
84
85 self.isConfig = False
85 self.isConfig = False
86
86
87 self.datablock = None
87 self.datablock = None
88
88
89 self.utc = 0
89 self.utc = 0
90
90
91 self.ext = ".r"
91 self.ext = ".r"
92
92
93 self.optchar = "D"
93 self.optchar = "D"
94
94
95 self.basicHeaderObj = BasicHeader(LOCALTIME)
95 self.basicHeaderObj = BasicHeader(LOCALTIME)
96
96
97 self.systemHeaderObj = SystemHeader()
97 self.systemHeaderObj = SystemHeader()
98
98
99 self.radarControllerHeaderObj = RadarControllerHeader()
99 self.radarControllerHeaderObj = RadarControllerHeader()
100
100
101 self.processingHeaderObj = ProcessingHeader()
101 self.processingHeaderObj = ProcessingHeader()
102
102
103 self.online = 0
103 self.online = 0
104
104
105 self.fp = None
105 self.fp = None
106
106
107 self.idFile = None
107 self.idFile = None
108
108
109 self.dtype = None
109 self.dtype = None
110
110
111 self.fileSizeByHeader = None
111 self.fileSizeByHeader = None
112
112
113 self.filenameList = []
113 self.filenameList = []
114
114
115 self.filename = None
115 self.filename = None
116
116
117 self.fileSize = None
117 self.fileSize = None
118
118
119 self.firstHeaderSize = 0
119 self.firstHeaderSize = 0
120
120
121 self.basicHeaderSize = 24
121 self.basicHeaderSize = 24
122
122
123 self.pathList = []
123 self.pathList = []
124
124
125 self.filenameList = []
125 self.filenameList = []
126
126
127 self.lastUTTime = 0
127 self.lastUTTime = 0
128
128
129 self.maxTimeStep = 30
129 self.maxTimeStep = 30
130
130
131 self.flagNoMoreFiles = 0
131 self.flagNoMoreFiles = 0
132
132
133 self.set = 0
133 self.set = 0
134
134
135 self.path = None
135 self.path = None
136
136
137 self.profileIndex = 2**32-1
137 self.profileIndex = 2**32-1
138
138
139 self.delay = 3 #seconds
139 self.delay = 3 #seconds
140
140
141 self.nTries = 3 #quantity tries
141 self.nTries = 3 #quantity tries
142
142
143 self.nFiles = 3 #number of files for searching
143 self.nFiles = 3 #number of files for searching
144
144
145 self.nReadBlocks = 0
145 self.nReadBlocks = 0
146
146
147 self.flagIsNewFile = 1
147 self.flagIsNewFile = 1
148
148
149 self.__isFirstTimeOnline = 1
149 self.__isFirstTimeOnline = 1
150
150
151 # self.ippSeconds = 0
151 # self.ippSeconds = 0
152
152
153 self.flagDiscontinuousBlock = 0
153 self.flagDiscontinuousBlock = 0
154
154
155 self.flagIsNewBlock = 0
155 self.flagIsNewBlock = 0
156
156
157 self.nTotalBlocks = 0
157 self.nTotalBlocks = 0
158
158
159 self.blocksize = 0
159 self.blocksize = 0
160
160
161 self.dataOut = self.createObjByDefault()
161 self.dataOut = self.createObjByDefault()
162
162
163 self.nTxs = 1
163 self.nTxs = 1
164
164
165 self.txIndex = 0
165 self.txIndex = 0
166
166
167 def createObjByDefault(self):
167 def createObjByDefault(self):
168
168
169 dataObj = Voltage()
169 dataObj = Voltage()
170
170
171 return dataObj
171 return dataObj
172
172
173 def __hasNotDataInBuffer(self):
173 def __hasNotDataInBuffer(self):
174
174
175 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock*self.nTxs:
175 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock*self.nTxs:
176 return 1
176 return 1
177
177
178 return 0
178 return 0
179
179
180
180
181 def getBlockDimension(self):
181 def getBlockDimension(self):
182 """
182 """
183 Obtiene la cantidad de puntos a leer por cada bloque de datos
183 Obtiene la cantidad de puntos a leer por cada bloque de datos
184
184
185 Affected:
185 Affected:
186 self.blocksize
186 self.blocksize
187
187
188 Return:
188 Return:
189 None
189 None
190 """
190 """
191 pts2read = self.processingHeaderObj.profilesPerBlock * self.processingHeaderObj.nHeights * self.systemHeaderObj.nChannels
191 pts2read = self.processingHeaderObj.profilesPerBlock * self.processingHeaderObj.nHeights * self.systemHeaderObj.nChannels
192 self.blocksize = pts2read
192 self.blocksize = pts2read
193
193
194
194
195
195
196 def readBlock(self):
196 def readBlock(self):
197 """
197 """
198 readBlock lee el bloque de datos desde la posicion actual del puntero del archivo
198 readBlock lee el bloque de datos desde la posicion actual del puntero del archivo
199 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
199 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
200 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
200 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
201 es seteado a 0
201 es seteado a 0
202
202
203 Inputs:
203 Inputs:
204 None
204 None
205
205
206 Return:
206 Return:
207 None
207 None
208
208
209 Affected:
209 Affected:
210 self.profileIndex
210 self.profileIndex
211 self.datablock
211 self.datablock
212 self.flagIsNewFile
212 self.flagIsNewFile
213 self.flagIsNewBlock
213 self.flagIsNewBlock
214 self.nTotalBlocks
214 self.nTotalBlocks
215
215
216 Exceptions:
216 Exceptions:
217 Si un bloque leido no es un bloque valido
217 Si un bloque leido no es un bloque valido
218 """
218 """
219
219
220 # if self.server is not None:
220 # if self.server is not None:
221 # self.zBlock = self.receiver.recv()
221 # self.zBlock = self.receiver.recv()
222 # self.zHeader = self.zBlock[:24]
222 # self.zHeader = self.zBlock[:24]
223 # self.zDataBlock = self.zBlock[24:]
223 # self.zDataBlock = self.zBlock[24:]
224 # junk = numpy.fromstring(self.zDataBlock, numpy.dtype([('real','<i4'),('imag','<i4')]))
224 # junk = numpy.fromstring(self.zDataBlock, numpy.dtype([('real','<i4'),('imag','<i4')]))
225 # self.processingHeaderObj.profilesPerBlock = 240
225 # self.processingHeaderObj.profilesPerBlock = 240
226 # self.processingHeaderObj.nHeights = 248
226 # self.processingHeaderObj.nHeights = 248
227 # self.systemHeaderObj.nChannels
227 # self.systemHeaderObj.nChannels
228 # else:
228 # else:
229 current_pointer_location = self.fp.tell()
229 current_pointer_location = self.fp.tell()
230 junk = numpy.fromfile( self.fp, self.dtype, self.blocksize )
230 junk = numpy.fromfile( self.fp, self.dtype, self.blocksize )
231
231
232 try:
232 try:
233 junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) )
233 junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) )
234 except:
234 except:
235 #print "The read block (%3d) has not enough data" %self.nReadBlocks
235 #print "The read block (%3d) has not enough data" %self.nReadBlocks
236
236
237 if self.waitDataBlock(pointer_location=current_pointer_location):
237 if self.waitDataBlock(pointer_location=current_pointer_location):
238 junk = numpy.fromfile( self.fp, self.dtype, self.blocksize )
238 junk = numpy.fromfile( self.fp, self.dtype, self.blocksize )
239 junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) )
239 junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) )
240 # return 0
240 # return 0
241
241
242 #Dimensions : nChannels, nProfiles, nSamples
242 #Dimensions : nChannels, nProfiles, nSamples
243
243
244 junk = numpy.transpose(junk, (2,0,1))
244 junk = numpy.transpose(junk, (2,0,1))
245 self.datablock = junk['real'] + junk['imag']*1j
245 self.datablock = junk['real'] + junk['imag']*1j
246
246
247 self.profileIndex = 0
247 self.profileIndex = 0
248
248
249 self.flagIsNewFile = 0
249 self.flagIsNewFile = 0
250 self.flagIsNewBlock = 1
250 self.flagIsNewBlock = 1
251
251
252 self.nTotalBlocks += 1
252 self.nTotalBlocks += 1
253 self.nReadBlocks += 1
253 self.nReadBlocks += 1
254
254
255 return 1
255 return 1
256
256
257 def getFirstHeader(self):
257 def getFirstHeader(self):
258
258
259 self.getBasicHeader()
259 self.getBasicHeader()
260
260
261 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
261 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
262
262
263 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
263 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
264
264
265 if self.nTxs > 1:
265 if self.nTxs > 1:
266 self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
266 self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
267
267
268 #Time interval and code are propierties of dataOut. Its value depends of radarControllerHeaderObj.
268 #Time interval and code are propierties of dataOut. Its value depends of radarControllerHeaderObj.
269
269
270 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt
270 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt
271 #
271 #
272 # if self.radarControllerHeaderObj.code is not None:
272 # if self.radarControllerHeaderObj.code is not None:
273 #
273 #
274 # self.dataOut.nCode = self.radarControllerHeaderObj.nCode
274 # self.dataOut.nCode = self.radarControllerHeaderObj.nCode
275 #
275 #
276 # self.dataOut.nBaud = self.radarControllerHeaderObj.nBaud
276 # self.dataOut.nBaud = self.radarControllerHeaderObj.nBaud
277 #
277 #
278 # self.dataOut.code = self.radarControllerHeaderObj.code
278 # self.dataOut.code = self.radarControllerHeaderObj.code
279
279
280 self.dataOut.dtype = self.dtype
280 self.dataOut.dtype = self.dtype
281
281
282 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
282 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
283
283
284 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.nHeights) *self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight
284 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.nHeights) *self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight
285
285
286 self.dataOut.channelList = range(self.systemHeaderObj.nChannels)
286 self.dataOut.channelList = range(self.systemHeaderObj.nChannels)
287
287
288 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
288 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
289
289
290 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode #asumo q la data no esta decodificada
290 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode #asumo q la data no esta decodificada
291
291
292 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data no esta sin flip
292 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data no esta sin flip
293
293
294 self.dataOut.flagShiftFFT = self.processingHeaderObj.shif_fft
294 self.dataOut.flagShiftFFT = self.processingHeaderObj.shif_fft
295
295
296 def reshapeData(self):
296 def reshapeData(self):
297
297
298 if self.nTxs < 0:
298 if self.nTxs < 0:
299 return
299 return
300
300
301 if self.nTxs == 1:
301 if self.nTxs == 1:
302 return
302 return
303
303
304 if self.nTxs < 1 and self.processingHeaderObj.profilesPerBlock % (1./self.nTxs) != 0:
304 if self.nTxs < 1 and self.processingHeaderObj.profilesPerBlock % (1./self.nTxs) != 0:
305 raise ValueError, "1./nTxs (=%f), should be a multiple of nProfiles (=%d)" %(1./self.nTxs, self.processingHeaderObj.profilesPerBlock)
305 raise ValueError, "1./nTxs (=%f), should be a multiple of nProfiles (=%d)" %(1./self.nTxs, self.processingHeaderObj.profilesPerBlock)
306
306
307 if self.nTxs > 1 and self.processingHeaderObj.nHeights % self.nTxs != 0:
307 if self.nTxs > 1 and self.processingHeaderObj.nHeights % self.nTxs != 0:
308 raise ValueError, "nTxs (=%d), should be a multiple of nHeights (=%d)" %(self.nTxs, self.processingHeaderObj.nHeights)
308 raise ValueError, "nTxs (=%d), should be a multiple of nHeights (=%d)" %(self.nTxs, self.processingHeaderObj.nHeights)
309
309
310 self.datablock = self.datablock.reshape((self.systemHeaderObj.nChannels, self.processingHeaderObj.profilesPerBlock*self.nTxs, self.processingHeaderObj.nHeights/self.nTxs))
310 self.datablock = self.datablock.reshape((self.systemHeaderObj.nChannels, self.processingHeaderObj.profilesPerBlock*self.nTxs, self.processingHeaderObj.nHeights/self.nTxs))
311
311
312 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
312 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
313 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.nHeights/self.nTxs) *self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight
313 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.nHeights/self.nTxs) *self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight
314 self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
314 self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
315
315
316 return
316 return
317
317
318 def readFirstHeaderFromServer(self):
318 def readFirstHeaderFromServer(self):
319
319
320 self.getFirstHeader()
320 self.getFirstHeader()
321
321
322 self.firstHeaderSize = self.basicHeaderObj.size
322 self.firstHeaderSize = self.basicHeaderObj.size
323
323
324 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
324 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
325 if datatype == 0:
325 if datatype == 0:
326 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
326 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
327 elif datatype == 1:
327 elif datatype == 1:
328 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
328 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
329 elif datatype == 2:
329 elif datatype == 2:
330 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
330 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
331 elif datatype == 3:
331 elif datatype == 3:
332 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
332 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
333 elif datatype == 4:
333 elif datatype == 4:
334 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
334 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
335 elif datatype == 5:
335 elif datatype == 5:
336 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
336 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
337 else:
337 else:
338 raise ValueError, 'Data type was not defined'
338 raise ValueError, 'Data type was not defined'
339
339
340 self.dtype = datatype_str
340 self.dtype = datatype_str
341 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
341 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
342 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
342 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
343 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
343 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
344 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
344 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
345 self.getBlockDimension()
345 self.getBlockDimension()
346
346
347
347
348 def getFromServer(self):
348 def getFromServer(self):
349 self.flagDiscontinuousBlock = 0
349 self.flagDiscontinuousBlock = 0
350 self.profileIndex = 0
350 self.profileIndex = 0
351 self.flagIsNewBlock = 1
351 self.flagIsNewBlock = 1
352 self.dataOut.flagNoData = False
352 self.dataOut.flagNoData = False
353 self.nTotalBlocks += 1
353 self.nTotalBlocks += 1
354 self.nReadBlocks += 1
354 self.nReadBlocks += 1
355 self.blockPointer = 0
355 self.blockPointer = 0
356
356
357 block = self.receiver.recv()
357 block = self.receiver.recv()
358
358
359 self.basicHeaderObj.read(block[self.blockPointer:])
359 self.basicHeaderObj.read(block[self.blockPointer:])
360 self.blockPointer += self.basicHeaderObj.length
360 self.blockPointer += self.basicHeaderObj.length
361 self.systemHeaderObj.read(block[self.blockPointer:])
361 self.systemHeaderObj.read(block[self.blockPointer:])
362 self.blockPointer += self.systemHeaderObj.length
362 self.blockPointer += self.systemHeaderObj.length
363 self.radarControllerHeaderObj.read(block[self.blockPointer:])
363 self.radarControllerHeaderObj.read(block[self.blockPointer:])
364 self.blockPointer += self.radarControllerHeaderObj.length
364 self.blockPointer += self.radarControllerHeaderObj.length
365 self.processingHeaderObj.read(block[self.blockPointer:])
365 self.processingHeaderObj.read(block[self.blockPointer:])
366 self.blockPointer += self.processingHeaderObj.length
366 self.blockPointer += self.processingHeaderObj.length
367 self.readFirstHeaderFromServer()
367 self.readFirstHeaderFromServer()
368
368
369 timestamp = self.basicHeaderObj.get_datatime()
369 timestamp = self.basicHeaderObj.get_datatime()
370 print '[Reading] - Block {} - {}'.format(self.nTotalBlocks, timestamp)
370 print '[Reading] - Block {} - {}'.format(self.nTotalBlocks, timestamp)
371 current_pointer_location = self.blockPointer
371 current_pointer_location = self.blockPointer
372 junk = numpy.fromstring( block[self.blockPointer:], self.dtype, self.blocksize )
372 junk = numpy.fromstring( block[self.blockPointer:], self.dtype, self.blocksize )
373
373
374 try:
374 try:
375 junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) )
375 junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) )
376 except:
376 except:
377 #print "The read block (%3d) has not enough data" %self.nReadBlocks
377 #print "The read block (%3d) has not enough data" %self.nReadBlocks
378 if self.waitDataBlock(pointer_location=current_pointer_location):
378 if self.waitDataBlock(pointer_location=current_pointer_location):
379 junk = numpy.fromstring( block[self.blockPointer:], self.dtype, self.blocksize )
379 junk = numpy.fromstring( block[self.blockPointer:], self.dtype, self.blocksize )
380 junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) )
380 junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) )
381 # return 0
381 # return 0
382
382
383 #Dimensions : nChannels, nProfiles, nSamples
383 #Dimensions : nChannels, nProfiles, nSamples
384
384
385 junk = numpy.transpose(junk, (2,0,1))
385 junk = numpy.transpose(junk, (2,0,1))
386 self.datablock = junk['real'] + junk['imag'] * 1j
386 self.datablock = junk['real'] + junk['imag'] * 1j
387 self.profileIndex = 0
387 self.profileIndex = 0
388 if self.selBlocksize == None: self.selBlocksize = self.dataOut.nProfiles
388 if self.selBlocksize == None: self.selBlocksize = self.dataOut.nProfiles
389 if self.selBlocktime != None:
389 if self.selBlocktime != None:
390 if self.dataOut.nCohInt is not None:
390 if self.dataOut.nCohInt is not None:
391 nCohInt = self.dataOut.nCohInt
391 nCohInt = self.dataOut.nCohInt
392 else:
392 else:
393 nCohInt = 1
393 nCohInt = 1
394 self.selBlocksize = int(self.dataOut.nProfiles*round(self.selBlocktime/(nCohInt*self.dataOut.ippSeconds*self.dataOut.nProfiles)))
394 self.selBlocksize = int(self.dataOut.nProfiles*round(self.selBlocktime/(nCohInt*self.dataOut.ippSeconds*self.dataOut.nProfiles)))
395 self.dataOut.data = self.datablock[:,self.profileIndex:self.profileIndex+self.selBlocksize,:]
395 self.dataOut.data = self.datablock[:,self.profileIndex:self.profileIndex+self.selBlocksize,:]
396 datasize = self.dataOut.data.shape[1]
396 datasize = self.dataOut.data.shape[1]
397 if datasize < self.selBlocksize:
397 if datasize < self.selBlocksize:
398 buffer = numpy.zeros((self.dataOut.data.shape[0], self.selBlocksize, self.dataOut.data.shape[2]), dtype = 'complex')
398 buffer = numpy.zeros((self.dataOut.data.shape[0], self.selBlocksize, self.dataOut.data.shape[2]), dtype = 'complex')
399 buffer[:,:datasize,:] = self.dataOut.data
399 buffer[:,:datasize,:] = self.dataOut.data
400 self.dataOut.data = buffer
400 self.dataOut.data = buffer
401 self.profileIndex = blockIndex
401 self.profileIndex = blockIndex
402
402
403 self.dataOut.flagDataAsBlock = True
403 self.dataOut.flagDataAsBlock = True
404 self.flagIsNewBlock = 1
404 self.flagIsNewBlock = 1
405 self.dataOut.realtime = self.online
405 self.dataOut.realtime = self.online
406
406
407 return self.dataOut.data
407 return self.dataOut.data
408
408
409 def getData(self):
409 def getData(self):
410 """
410 """
411 getData obtiene una unidad de datos del buffer de lectura, un perfil, y la copia al objeto self.dataOut
411 getData obtiene una unidad de datos del buffer de lectura, un perfil, y la copia al objeto self.dataOut
412 del tipo "Voltage" con todos los parametros asociados a este (metadata). cuando no hay datos
412 del tipo "Voltage" con todos los parametros asociados a este (metadata). cuando no hay datos
413 en el buffer de lectura es necesario hacer una nueva lectura de los bloques de datos usando
413 en el buffer de lectura es necesario hacer una nueva lectura de los bloques de datos usando
414 "readNextBlock"
414 "readNextBlock"
415
415
416 Ademas incrementa el contador del buffer "self.profileIndex" en 1.
416 Ademas incrementa el contador del buffer "self.profileIndex" en 1.
417
417
418 Return:
418 Return:
419
419
420 Si el flag self.getByBlock ha sido seteado el bloque completo es copiado a self.dataOut y el self.profileIndex
420 Si el flag self.getByBlock ha sido seteado el bloque completo es copiado a self.dataOut y el self.profileIndex
421 es igual al total de perfiles leidos desde el archivo.
421 es igual al total de perfiles leidos desde el archivo.
422
422
423 Si self.getByBlock == False:
423 Si self.getByBlock == False:
424
424
425 self.dataOut.data = buffer[:, thisProfile, :]
425 self.dataOut.data = buffer[:, thisProfile, :]
426
426
427 shape = [nChannels, nHeis]
427 shape = [nChannels, nHeis]
428
428
429 Si self.getByBlock == True:
429 Si self.getByBlock == True:
430
430
431 self.dataOut.data = buffer[:, :, :]
431 self.dataOut.data = buffer[:, :, :]
432
432
433 shape = [nChannels, nProfiles, nHeis]
433 shape = [nChannels, nProfiles, nHeis]
434
434
435 Variables afectadas:
435 Variables afectadas:
436 self.dataOut
436 self.dataOut
437 self.profileIndex
437 self.profileIndex
438
438
439 Affected:
439 Affected:
440 self.dataOut
440 self.dataOut
441 self.profileIndex
441 self.profileIndex
442 self.flagDiscontinuousBlock
442 self.flagDiscontinuousBlock
443 self.flagIsNewBlock
443 self.flagIsNewBlock
444 """
444 """
445 if self.flagNoMoreFiles:
445 if self.flagNoMoreFiles:
446 self.dataOut.flagNoData = True
446 self.dataOut.flagNoData = True
447 print 'Process finished'
447 print 'Process finished'
448 return 0
448 return 0
449 self.flagDiscontinuousBlock = 0
449 self.flagDiscontinuousBlock = 0
450 self.flagIsNewBlock = 0
450 self.flagIsNewBlock = 0
451 if self.__hasNotDataInBuffer():
451 if self.__hasNotDataInBuffer():
452 if not( self.readNextBlock() ):
452 if not( self.readNextBlock() ):
453 return 0
453 return 0
454
454
455 self.getFirstHeader()
455 self.getFirstHeader()
456
456
457 self.reshapeData()
457 self.reshapeData()
458 if self.datablock is None:
458 if self.datablock is None:
459 self.dataOut.flagNoData = True
459 self.dataOut.flagNoData = True
460 return 0
460 return 0
461
461
462 if not self.getByBlock:
462 if not self.getByBlock:
463
463
464 """
464 """
465 Return profile by profile
465 Return profile by profile
466
466
467 If nTxs > 1 then one profile is divided by nTxs and number of total
467 If nTxs > 1 then one profile is divided by nTxs and number of total
468 blocks is increased by nTxs (nProfiles *= nTxs)
468 blocks is increased by nTxs (nProfiles *= nTxs)
469 """
469 """
470 self.dataOut.flagDataAsBlock = False
470 self.dataOut.flagDataAsBlock = False
471 self.dataOut.data = self.datablock[:,self.profileIndex,:]
471 self.dataOut.data = self.datablock[:,self.profileIndex,:]
472 self.dataOut.profileIndex = self.profileIndex
472 self.dataOut.profileIndex = self.profileIndex
473
473
474 self.profileIndex += 1
474 self.profileIndex += 1
475
475
476 # elif self.selBlocksize==None or self.selBlocksize==self.dataOut.nProfiles:
476 # elif self.selBlocksize==None or self.selBlocksize==self.dataOut.nProfiles:
477 # """
477 # """
478 # Return all block
478 # Return all block
479 # """
479 # """
480 # self.dataOut.flagDataAsBlock = True
480 # self.dataOut.flagDataAsBlock = True
481 # self.dataOut.data = self.datablock
481 # self.dataOut.data = self.datablock
482 # self.dataOut.profileIndex = self.dataOut.nProfiles - 1
482 # self.dataOut.profileIndex = self.dataOut.nProfiles - 1
483 #
483 #
484 # self.profileIndex = self.dataOut.nProfiles
484 # self.profileIndex = self.dataOut.nProfiles
485
485
486 else:
486 else:
487 """
487 """
488 Return a block
488 Return a block
489 """
489 """
490 if self.selBlocksize == None: self.selBlocksize = self.dataOut.nProfiles
490 if self.selBlocksize == None: self.selBlocksize = self.dataOut.nProfiles
491 if self.selBlocktime != None:
491 if self.selBlocktime != None:
492 if self.dataOut.nCohInt is not None:
492 if self.dataOut.nCohInt is not None:
493 nCohInt = self.dataOut.nCohInt
493 nCohInt = self.dataOut.nCohInt
494 else:
494 else:
495 nCohInt = 1
495 nCohInt = 1
496 self.selBlocksize = int(self.dataOut.nProfiles*round(self.selBlocktime/(nCohInt*self.dataOut.ippSeconds*self.dataOut.nProfiles)))
496 self.selBlocksize = int(self.dataOut.nProfiles*round(self.selBlocktime/(nCohInt*self.dataOut.ippSeconds*self.dataOut.nProfiles)))
497
497
498 self.dataOut.data = self.datablock[:,self.profileIndex:self.profileIndex+self.selBlocksize,:]
498 self.dataOut.data = self.datablock[:,self.profileIndex:self.profileIndex+self.selBlocksize,:]
499 self.profileIndex += self.selBlocksize
499 self.profileIndex += self.selBlocksize
500 datasize = self.dataOut.data.shape[1]
500 datasize = self.dataOut.data.shape[1]
501
501
502 if datasize < self.selBlocksize:
502 if datasize < self.selBlocksize:
503 buffer = numpy.zeros((self.dataOut.data.shape[0],self.selBlocksize,self.dataOut.data.shape[2]), dtype = 'complex')
503 buffer = numpy.zeros((self.dataOut.data.shape[0],self.selBlocksize,self.dataOut.data.shape[2]), dtype = 'complex')
504 buffer[:,:datasize,:] = self.dataOut.data
504 buffer[:,:datasize,:] = self.dataOut.data
505
505
506 while datasize < self.selBlocksize: #Not enough profiles to fill the block
506 while datasize < self.selBlocksize: #Not enough profiles to fill the block
507 if not( self.readNextBlock() ):
507 if not( self.readNextBlock() ):
508 return 0
508 return 0
509 self.getFirstHeader()
509 self.getFirstHeader()
510 self.reshapeData()
510 self.reshapeData()
511 if self.datablock is None:
511 if self.datablock is None:
512 self.dataOut.flagNoData = True
512 self.dataOut.flagNoData = True
513 return 0
513 return 0
514 #stack data
514 #stack data
515 blockIndex = self.selBlocksize - datasize
515 blockIndex = self.selBlocksize - datasize
516 datablock1 = self.datablock[:,:blockIndex,:]
516 datablock1 = self.datablock[:,:blockIndex,:]
517
517
518 buffer[:,datasize:datasize+datablock1.shape[1],:] = datablock1
518 buffer[:,datasize:datasize+datablock1.shape[1],:] = datablock1
519 datasize += datablock1.shape[1]
519 datasize += datablock1.shape[1]
520
520
521 self.dataOut.data = buffer
521 self.dataOut.data = buffer
522 self.profileIndex = blockIndex
522 self.profileIndex = blockIndex
523
523
524 self.dataOut.flagDataAsBlock = True
524 self.dataOut.flagDataAsBlock = True
525 self.dataOut.nProfiles = self.dataOut.data.shape[1]
525 self.dataOut.nProfiles = self.dataOut.data.shape[1]
526
526
527 self.dataOut.flagNoData = False
527 self.dataOut.flagNoData = False
528
528
529 self.getBasicHeader()
529 self.getBasicHeader()
530
530
531 #print self.basicHeaderObj.printInfo()
532 #print self.systemHeaderObj.printInfo()
533 #print self.radarControllerHeaderObj.printInfo()
534 #print self.processingHeaderObj.printInfo()
535
531 self.dataOut.realtime = self.online
536 self.dataOut.realtime = self.online
532
537
533 return self.dataOut.data
538 return self.dataOut.data
539
534
540
535 class VoltageWriter(JRODataWriter, Operation):
541 class VoltageWriter(JRODataWriter, Operation):
536 """
542 """
537 Esta clase permite escribir datos de voltajes a archivos procesados (.r). La escritura
543 Esta clase permite escribir datos de voltajes a archivos procesados (.r). La escritura
538 de los datos siempre se realiza por bloques.
544 de los datos siempre se realiza por bloques.
539 """
545 """
540
546
541 ext = ".r"
547 ext = ".r"
542
548
543 optchar = "D"
549 optchar = "D"
544
550
545 shapeBuffer = None
551 shapeBuffer = None
546
552
547
553
548 def __init__(self, **kwargs):
554 def __init__(self, **kwargs):
549 """
555 """
550 Inicializador de la clase VoltageWriter para la escritura de datos de espectros.
556 Inicializador de la clase VoltageWriter para la escritura de datos de espectros.
551
557
552 Affected:
558 Affected:
553 self.dataOut
559 self.dataOut
554
560
555 Return: None
561 Return: None
556 """
562 """
557 Operation.__init__(self, **kwargs)
563 Operation.__init__(self, **kwargs)
558
564
559 self.nTotalBlocks = 0
565 self.nTotalBlocks = 0
560
566
561 self.profileIndex = 0
567 self.profileIndex = 0
562
568
563 self.isConfig = False
569 self.isConfig = False
564
570
565 self.fp = None
571 self.fp = None
566
572
567 self.flagIsNewFile = 1
573 self.flagIsNewFile = 1
568
574
569 self.blockIndex = 0
575 self.blockIndex = 0
570
576
571 self.flagIsNewBlock = 0
577 self.flagIsNewBlock = 0
572
578
573 self.setFile = None
579 self.setFile = None
574
580
575 self.dtype = None
581 self.dtype = None
576
582
577 self.path = None
583 self.path = None
578
584
579 self.filename = None
585 self.filename = None
580
586
581 self.basicHeaderObj = BasicHeader(LOCALTIME)
587 self.basicHeaderObj = BasicHeader(LOCALTIME)
582
588
583 self.systemHeaderObj = SystemHeader()
589 self.systemHeaderObj = SystemHeader()
584
590
585 self.radarControllerHeaderObj = RadarControllerHeader()
591 self.radarControllerHeaderObj = RadarControllerHeader()
586
592
587 self.processingHeaderObj = ProcessingHeader()
593 self.processingHeaderObj = ProcessingHeader()
588
594
589 def hasAllDataInBuffer(self):
595 def hasAllDataInBuffer(self):
590 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock:
596 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock:
591 return 1
597 return 1
592 return 0
598 return 0
593
599
594
600
595 def setBlockDimension(self):
601 def setBlockDimension(self):
596 """
602 """
597 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
603 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
598
604
599 Affected:
605 Affected:
600 self.shape_spc_Buffer
606 self.shape_spc_Buffer
601 self.shape_cspc_Buffer
607 self.shape_cspc_Buffer
602 self.shape_dc_Buffer
608 self.shape_dc_Buffer
603
609
604 Return: None
610 Return: None
605 """
611 """
606 self.shapeBuffer = (self.processingHeaderObj.profilesPerBlock,
612 self.shapeBuffer = (self.processingHeaderObj.profilesPerBlock,
607 self.processingHeaderObj.nHeights,
613 self.processingHeaderObj.nHeights,
608 self.systemHeaderObj.nChannels)
614 self.systemHeaderObj.nChannels)
609
615
610 self.datablock = numpy.zeros((self.systemHeaderObj.nChannels,
616 self.datablock = numpy.zeros((self.systemHeaderObj.nChannels,
611 self.processingHeaderObj.profilesPerBlock,
617 self.processingHeaderObj.profilesPerBlock,
612 self.processingHeaderObj.nHeights),
618 self.processingHeaderObj.nHeights),
613 dtype=numpy.dtype('complex64'))
619 dtype=numpy.dtype('complex64'))
614
620
615 def writeBlock(self):
621 def writeBlock(self):
616 """
622 """
617 Escribe el buffer en el file designado
623 Escribe el buffer en el file designado
618
624
619 Affected:
625 Affected:
620 self.profileIndex
626 self.profileIndex
621 self.flagIsNewFile
627 self.flagIsNewFile
622 self.flagIsNewBlock
628 self.flagIsNewBlock
623 self.nTotalBlocks
629 self.nTotalBlocks
624 self.blockIndex
630 self.blockIndex
625
631
626 Return: None
632 Return: None
627 """
633 """
628 data = numpy.zeros( self.shapeBuffer, self.dtype )
634 data = numpy.zeros( self.shapeBuffer, self.dtype )
629
635
630 junk = numpy.transpose(self.datablock, (1,2,0))
636 junk = numpy.transpose(self.datablock, (1,2,0))
631
637
632 data['real'] = junk.real
638 data['real'] = junk.real
633 data['imag'] = junk.imag
639 data['imag'] = junk.imag
634
640
635 data = data.reshape( (-1) )
641 data = data.reshape( (-1) )
636
642
637 data.tofile( self.fp )
643 data.tofile( self.fp )
638
644
639 self.datablock.fill(0)
645 self.datablock.fill(0)
640
646
641 self.profileIndex = 0
647 self.profileIndex = 0
642 self.flagIsNewFile = 0
648 self.flagIsNewFile = 0
643 self.flagIsNewBlock = 1
649 self.flagIsNewBlock = 1
644
650
645 self.blockIndex += 1
651 self.blockIndex += 1
646 self.nTotalBlocks += 1
652 self.nTotalBlocks += 1
647
653
648 # print "[Writing] Block = %04d" %self.blockIndex
654 # print "[Writing] Block = %04d" %self.blockIndex
649
655
650 def putData(self):
656 def putData(self):
651 """
657 """
652 Setea un bloque de datos y luego los escribe en un file
658 Setea un bloque de datos y luego los escribe en un file
653
659
654 Affected:
660 Affected:
655 self.flagIsNewBlock
661 self.flagIsNewBlock
656 self.profileIndex
662 self.profileIndex
657
663
658 Return:
664 Return:
659 0 : Si no hay data o no hay mas files que puedan escribirse
665 0 : Si no hay data o no hay mas files que puedan escribirse
660 1 : Si se escribio la data de un bloque en un file
666 1 : Si se escribio la data de un bloque en un file
661 """
667 """
662 if self.dataOut.flagNoData:
668 if self.dataOut.flagNoData:
663 return 0
669 return 0
664
670
665 self.flagIsNewBlock = 0
671 self.flagIsNewBlock = 0
666
672
667 if self.dataOut.flagDiscontinuousBlock:
673 if self.dataOut.flagDiscontinuousBlock:
668 self.datablock.fill(0)
674 self.datablock.fill(0)
669 self.profileIndex = 0
675 self.profileIndex = 0
670 self.setNextFile()
676 self.setNextFile()
671
677
672 if self.profileIndex == 0:
678 if self.profileIndex == 0:
673 self.setBasicHeader()
679 self.setBasicHeader()
674
680
675 self.datablock[:,self.profileIndex,:] = self.dataOut.data
681 self.datablock[:,self.profileIndex,:] = self.dataOut.data
676
682
677 self.profileIndex += 1
683 self.profileIndex += 1
678
684
679 if self.hasAllDataInBuffer():
685 if self.hasAllDataInBuffer():
680 #if self.flagIsNewFile:
686 #if self.flagIsNewFile:
681 self.writeNextBlock()
687 self.writeNextBlock()
682 # self.setFirstHeader()
688 # self.setFirstHeader()
683
689
684 return 1
690 return 1
685
691
686 def __getBlockSize(self):
692 def __getBlockSize(self):
687 '''
693 '''
688 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Voltage
694 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Voltage
689 '''
695 '''
690
696
691 dtype_width = self.getDtypeWidth()
697 dtype_width = self.getDtypeWidth()
692
698
693 blocksize = int(self.dataOut.nHeights * self.dataOut.nChannels * self.profilesPerBlock * dtype_width * 2)
699 blocksize = int(self.dataOut.nHeights * self.dataOut.nChannels * self.profilesPerBlock * dtype_width * 2)
694
700
695 return blocksize
701 return blocksize
696
702
697 def setFirstHeader(self):
703 def setFirstHeader(self):
698
704
699 """
705 """
700 Obtiene una copia del First Header
706 Obtiene una copia del First Header
701
707
702 Affected:
708 Affected:
703 self.systemHeaderObj
709 self.systemHeaderObj
704 self.radarControllerHeaderObj
710 self.radarControllerHeaderObj
705 self.dtype
711 self.dtype
706
712
707 Return:
713 Return:
708 None
714 None
709 """
715 """
710
716
711 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
717 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
712 self.systemHeaderObj.nChannels = self.dataOut.nChannels
718 self.systemHeaderObj.nChannels = self.dataOut.nChannels
713 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
719 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
714
720
715 self.processingHeaderObj.dtype = 0 # Voltage
721 self.processingHeaderObj.dtype = 0 # Voltage
716 self.processingHeaderObj.blockSize = self.__getBlockSize()
722 self.processingHeaderObj.blockSize = self.__getBlockSize()
717 self.processingHeaderObj.profilesPerBlock = self.profilesPerBlock
723 self.processingHeaderObj.profilesPerBlock = self.profilesPerBlock
718 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
724 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
719 self.processingHeaderObj.nWindows = 1 #podria ser 1 o self.dataOut.processingHeaderObj.nWindows
725 self.processingHeaderObj.nWindows = 1 #podria ser 1 o self.dataOut.processingHeaderObj.nWindows
720 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt
726 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt
721 self.processingHeaderObj.nIncohInt = 1 # Cuando la data de origen es de tipo Voltage
727 self.processingHeaderObj.nIncohInt = 1 # Cuando la data de origen es de tipo Voltage
722 self.processingHeaderObj.totalSpectra = 0 # Cuando la data de origen es de tipo Voltage
728 self.processingHeaderObj.totalSpectra = 0 # Cuando la data de origen es de tipo Voltage
723
729
724 if self.dataOut.code is not None:
730 if self.dataOut.code is not None:
725 self.processingHeaderObj.code = self.dataOut.code
731 self.processingHeaderObj.code = self.dataOut.code
726 self.processingHeaderObj.nCode = self.dataOut.nCode
732 self.processingHeaderObj.nCode = self.dataOut.nCode
727 self.processingHeaderObj.nBaud = self.dataOut.nBaud
733 self.processingHeaderObj.nBaud = self.dataOut.nBaud
728
734
729 if self.processingHeaderObj.nWindows != 0:
735 if self.processingHeaderObj.nWindows != 0:
730 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
736 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
731 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
737 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
732 self.processingHeaderObj.nHeights = self.dataOut.nHeights
738 self.processingHeaderObj.nHeights = self.dataOut.nHeights
733 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
739 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
734
740
735 self.processingHeaderObj.processFlags = self.getProcessFlags()
741 self.processingHeaderObj.processFlags = self.getProcessFlags()
736
742
737 self.setBasicHeader()
743 self.setBasicHeader()
@@ -1,14 +1,15
1 '''
1 '''
2
2
3 $Author: murco $
3 $Author: murco $
4 $Id: Processor.py 1 2012-11-12 18:56:07Z murco $
4 $Id: Processor.py 1 2012-11-12 18:56:07Z murco $
5 '''
5 '''
6
6
7 from jroproc_voltage import *
7 from jroproc_voltage import *
8 from jroproc_spectra import *
8 from jroproc_spectra import *
9 from jroproc_heispectra import *
9 from jroproc_heispectra import *
10 from jroproc_amisr import *
10 from jroproc_amisr import *
11 from jroproc_correlation import *
11 from jroproc_correlation import *
12 from jroproc_parameters import *
12 from jroproc_parameters import *
13 from jroproc_spectra_lags import *
13 from jroproc_spectra_lags import *
14 from jroproc_spectra_acf import * No newline at end of file
14 from jroproc_spectra_acf import *
15 from bltrproc_parameters import *
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now