##// END OF EJS Templates
Merge pull request #5 from schain madrigal...
jespinoza -
r1072:d25f23afbecb 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
This diff has been collapsed as it changes many lines, (632 lines changed) Show them Hide them
@@ -0,0 +1,632
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 glob
12 import datetime
13
14 import numpy
15 import h5py
16
17 from schainpy.model.io.jroIO_base import JRODataReader
18 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
19 from schainpy.model.data.jrodata import Parameters
20 from schainpy.utils import log
21
22 try:
23 import madrigal.cedar
24 except:
25 log.warning(
26 'You should install "madrigal library" module if you want to read/write Madrigal data'
27 )
28
29 DEF_CATALOG = {
30 'principleInvestigator': 'Marco Milla',
31 'expPurpose': None,
32 'cycleTime': None,
33 'correlativeExp': None,
34 'sciRemarks': None,
35 'instRemarks': None
36 }
37 DEF_HEADER = {
38 'kindatDesc': None,
39 'analyst': 'Jicamarca User',
40 'comments': None,
41 'history': None
42 }
43 MNEMONICS = {
44 10: 'jro',
45 11: 'jbr',
46 840: 'jul',
47 13: 'jas',
48 1000: 'pbr',
49 1001: 'hbr',
50 1002: 'obr',
51 }
52
53 UT1970 = datetime.datetime(1970, 1, 1) - datetime.timedelta(seconds=time.timezone)
54
55 def load_json(obj):
56 '''
57 Parse json as string instead of unicode
58 '''
59
60 if isinstance(obj, str):
61 iterable = json.loads(obj)
62 else:
63 iterable = obj
64
65 if isinstance(iterable, dict):
66 return {str(k): load_json(v) if isinstance(v, dict) else str(v) if isinstance(v, unicode) else v
67 for k, v in iterable.items()}
68 elif isinstance(iterable, (list, tuple)):
69 return [str(v) if isinstance(v, unicode) else v for v in iterable]
70
71 return iterable
72
73
74 class MADReader(JRODataReader, ProcessingUnit):
75
76 def __init__(self, **kwargs):
77
78 ProcessingUnit.__init__(self, **kwargs)
79
80 self.dataOut = Parameters()
81 self.counter_records = 0
82 self.nrecords = None
83 self.flagNoMoreFiles = 0
84 self.isConfig = False
85 self.filename = None
86 self.intervals = set()
87
88 def setup(self,
89 path=None,
90 startDate=None,
91 endDate=None,
92 format=None,
93 startTime=datetime.time(0, 0, 0),
94 endTime=datetime.time(23, 59, 59),
95 **kwargs):
96
97 self.path = path
98 self.startDate = startDate
99 self.endDate = endDate
100 self.startTime = startTime
101 self.endTime = endTime
102 self.datatime = datetime.datetime(1900,1,1)
103 self.oneDDict = load_json(kwargs.get('oneDDict',
104 "{\"GDLATR\":\"lat\", \"GDLONR\":\"lon\"}"))
105 self.twoDDict = load_json(kwargs.get('twoDDict',
106 "{\"GDALT\": \"heightList\"}"))
107 self.ind2DList = load_json(kwargs.get('ind2DList',
108 "[\"GDALT\"]"))
109 if self.path is None:
110 raise ValueError, 'The path is not valid'
111
112 if format is None:
113 raise ValueError, 'The format is not valid choose simple or hdf5'
114 elif format.lower() in ('simple', 'txt'):
115 self.ext = '.txt'
116 elif format.lower() in ('cedar',):
117 self.ext = '.001'
118 else:
119 self.ext = '.hdf5'
120
121 self.search_files(self.path)
122 self.fileId = 0
123
124 if not self.fileList:
125 raise Warning, 'There is no files matching these date in the folder: {}. \n Check startDate and endDate'.format(path)
126
127 self.setNextFile()
128
129 def search_files(self, path):
130 '''
131 Searching for madrigal files in path
132 Creating a list of files to procces included in [startDate,endDate]
133
134 Input:
135 path - Path to find files
136 '''
137
138 log.log('Searching files {} in {} '.format(self.ext, path), 'MADReader')
139 foldercounter = 0
140 fileList0 = glob.glob1(path, '*{}'.format(self.ext))
141 fileList0.sort()
142
143 self.fileList = []
144 self.dateFileList = []
145
146 startDate = self.startDate - datetime.timedelta(1)
147 endDate = self.endDate + datetime.timedelta(1)
148
149 for thisFile in fileList0:
150 year = thisFile[3:7]
151 if not year.isdigit():
152 continue
153
154 month = thisFile[7:9]
155 if not month.isdigit():
156 continue
157
158 day = thisFile[9:11]
159 if not day.isdigit():
160 continue
161
162 year, month, day = int(year), int(month), int(day)
163 dateFile = datetime.date(year, month, day)
164
165 if (startDate > dateFile) or (endDate < dateFile):
166 continue
167
168 self.fileList.append(thisFile)
169 self.dateFileList.append(dateFile)
170
171 return
172
173 def parseHeader(self):
174 '''
175 '''
176
177 self.output = {}
178 self.version = '2'
179 s_parameters = None
180 if self.ext == '.txt':
181 self.parameters = [s.strip().lower() for s in self.fp.readline().strip().split(' ') if s]
182 elif self.ext == '.hdf5':
183 metadata = self.fp['Metadata']
184 data = self.fp['Data']['Array Layout']
185 if 'Independent Spatial Parameters' in metadata:
186 s_parameters = [s[0].lower() for s in metadata['Independent Spatial Parameters']]
187 self.version = '3'
188 one = [s[0].lower() for s in data['1D Parameters']['Data Parameters']]
189 one_d = [1 for s in one]
190 two = [s[0].lower() for s in data['2D Parameters']['Data Parameters']]
191 two_d = [2 for s in two]
192 self.parameters = one + two
193 self.parameters_d = one_d + two_d
194
195 log.success('Parameters found: {}'.format(','.join(self.parameters)),
196 'MADReader')
197 if s_parameters:
198 log.success('Spatial parameters: {}'.format(','.join(s_parameters)),
199 'MADReader')
200
201 for param in self.oneDDict.keys():
202 if param.lower() not in self.parameters:
203 log.warning(
204 'Parameter {} not found will be ignored'.format(
205 param),
206 'MADReader')
207 self.oneDDict.pop(param, None)
208
209 for param, value in self.twoDDict.items():
210 if param.lower() not in self.parameters:
211 log.warning(
212 'Parameter {} not found, it will be ignored'.format(
213 param),
214 'MADReader')
215 self.twoDDict.pop(param, None)
216 continue
217 if isinstance(value, list):
218 if value[0] not in self.output:
219 self.output[value[0]] = []
220 self.output[value[0]].append(None)
221
222 def parseData(self):
223 '''
224 '''
225
226 if self.ext == '.txt':
227 self.data = numpy.genfromtxt(self.fp, missing_values=('missing'))
228 self.nrecords = self.data.shape[0]
229 self.ranges = numpy.unique(self.data[:,self.parameters.index(self.ind2DList[0].lower())])
230 elif self.ext == '.hdf5':
231 self.data = self.fp['Data']['Array Layout']
232 self.nrecords = len(self.data['timestamps'].value)
233 self.ranges = self.data['range'].value
234
235 def setNextFile(self):
236 '''
237 '''
238
239 file_id = self.fileId
240
241 if file_id == len(self.fileList):
242 log.success('No more files', 'MADReader')
243 self.flagNoMoreFiles = 1
244 return 0
245
246 log.success(
247 'Opening: {}'.format(self.fileList[file_id]),
248 'MADReader'
249 )
250
251 filename = os.path.join(self.path, self.fileList[file_id])
252
253 if self.filename is not None:
254 self.fp.close()
255
256 self.filename = filename
257 self.filedate = self.dateFileList[file_id]
258
259 if self.ext=='.hdf5':
260 self.fp = h5py.File(self.filename, 'r')
261 else:
262 self.fp = open(self.filename, 'rb')
263
264 self.parseHeader()
265 self.parseData()
266 self.sizeOfFile = os.path.getsize(self.filename)
267 self.counter_records = 0
268 self.flagIsNewFile = 0
269 self.fileId += 1
270
271 return 1
272
273 def readNextBlock(self):
274
275 while True:
276 self.flagDiscontinuousBlock = 0
277 if self.flagIsNewFile:
278 if not self.setNextFile():
279 return 0
280
281 self.readBlock()
282
283 if (self.datatime < datetime.datetime.combine(self.startDate, self.startTime)) or \
284 (self.datatime > datetime.datetime.combine(self.endDate, self.endTime)):
285 log.warning(
286 'Reading Record No. {}/{} -> {} [Skipping]'.format(
287 self.counter_records,
288 self.nrecords,
289 self.datatime.ctime()),
290 'MADReader')
291 continue
292 break
293
294 log.log(
295 'Reading Record No. {}/{} -> {}'.format(
296 self.counter_records,
297 self.nrecords,
298 self.datatime.ctime()),
299 'MADReader')
300
301 return 1
302
303 def readBlock(self):
304 '''
305 '''
306 dum = []
307 if self.ext == '.txt':
308 dt = self.data[self.counter_records][:6].astype(int)
309 self.datatime = datetime.datetime(dt[0], dt[1], dt[2], dt[3], dt[4], dt[5])
310 while True:
311 dt = self.data[self.counter_records][:6].astype(int)
312 datatime = datetime.datetime(dt[0], dt[1], dt[2], dt[3], dt[4], dt[5])
313 if datatime == self.datatime:
314 dum.append(self.data[self.counter_records])
315 self.counter_records += 1
316 if self.counter_records == self.nrecords:
317 self.flagIsNewFile = True
318 break
319 continue
320 self.intervals.add((datatime-self.datatime).seconds)
321 if datatime.date() > self.datatime.date():
322 self.flagDiscontinuousBlock = 1
323 break
324 elif self.ext == '.hdf5':
325 datatime = datetime.datetime.utcfromtimestamp(
326 self.data['timestamps'][self.counter_records])
327 nHeights = len(self.ranges)
328 for n, param in enumerate(self.parameters):
329 if self.parameters_d[n] == 1:
330 dum.append(numpy.ones(nHeights)*self.data['1D Parameters'][param][self.counter_records])
331 else:
332 if self.version == '2':
333 dum.append(self.data['2D Parameters'][param][self.counter_records])
334 else:
335 tmp = self.data['2D Parameters'][param].value.T
336 dum.append(tmp[self.counter_records])
337 self.intervals.add((datatime-self.datatime).seconds)
338 if datatime.date()>self.datatime.date():
339 self.flagDiscontinuousBlock = 1
340 self.datatime = datatime
341 self.counter_records += 1
342 if self.counter_records == self.nrecords:
343 self.flagIsNewFile = True
344
345 self.buffer = numpy.array(dum)
346 return
347
348 def set_output(self):
349 '''
350 Storing data from buffer to dataOut object
351 '''
352
353 parameters = [None for __ in self.parameters]
354
355 for param, attr in self.oneDDict.items():
356 x = self.parameters.index(param.lower())
357 setattr(self.dataOut, attr, self.buffer[0][x])
358
359 for param, value in self.twoDDict.items():
360 x = self.parameters.index(param.lower())
361 if self.ext == '.txt':
362 y = self.parameters.index(self.ind2DList[0].lower())
363 ranges = self.buffer[:,y]
364 if self.ranges.size == ranges.size:
365 continue
366 index = numpy.where(numpy.in1d(self.ranges, ranges))[0]
367 dummy = numpy.zeros(self.ranges.shape) + numpy.nan
368 dummy[index] = self.buffer[:,x]
369 else:
370 dummy = self.buffer[x]
371
372 if isinstance(value, str):
373 if value not in self.ind2DList:
374 setattr(self.dataOut, value, dummy.reshape(1,-1))
375 elif isinstance(value, list):
376 self.output[value[0]][value[1]] = dummy
377 parameters[value[1]] = param
378
379 for key, value in self.output.items():
380 setattr(self.dataOut, key, numpy.array(value))
381
382 self.dataOut.parameters = [s for s in parameters if s]
383 self.dataOut.heightList = self.ranges
384 self.dataOut.utctime = (self.datatime - UT1970).total_seconds()
385 self.dataOut.utctimeInit = self.dataOut.utctime
386 self.dataOut.paramInterval = min(self.intervals)
387 self.dataOut.useLocalTime = False
388 self.dataOut.flagNoData = False
389 self.dataOut.nrecords = self.nrecords
390 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
391
392 def getData(self):
393 '''
394 Storing data from databuffer to dataOut object
395 '''
396 if self.flagNoMoreFiles:
397 self.dataOut.flagNoData = True
398 log.error('No file left to process', 'MADReader')
399 return 0
400
401 if not self.readNextBlock():
402 self.dataOut.flagNoData = True
403 return 0
404
405 self.set_output()
406
407 return 1
408
409
410 class MADWriter(Operation):
411
412 missing = -32767
413
414 def __init__(self, **kwargs):
415
416 Operation.__init__(self, **kwargs)
417 self.dataOut = Parameters()
418 self.path = None
419 self.fp = None
420
421 def run(self, dataOut, path, oneDDict, ind2DList='[]', twoDDict='{}',
422 metadata='{}', format='cedar', **kwargs):
423 '''
424 Inputs:
425 path - path where files will be created
426 oneDDict - json of one-dimensional parameters in record where keys
427 are Madrigal codes (integers or mnemonics) and values the corresponding
428 dataOut attribute e.g: {
429 'gdlatr': 'lat',
430 'gdlonr': 'lon',
431 'gdlat2':'lat',
432 'glon2':'lon'}
433 ind2DList - list of independent spatial two-dimensional parameters e.g:
434 ['heighList']
435 twoDDict - json of two-dimensional parameters in record where keys
436 are Madrigal codes (integers or mnemonics) and values the corresponding
437 dataOut attribute if multidimensional array specify as tupple
438 ('attr', pos) e.g: {
439 'gdalt': 'heightList',
440 'vn1p2': ('data_output', 0),
441 'vn2p2': ('data_output', 1),
442 'vn3': ('data_output', 2),
443 'snl': ('data_SNR', 'db')
444 }
445 metadata - json of madrigal metadata (kinst, kindat, catalog and header)
446 '''
447 if not self.isConfig:
448 self.setup(path, oneDDict, ind2DList, twoDDict, metadata, format, **kwargs)
449 self.isConfig = True
450
451 self.dataOut = dataOut
452 self.putData()
453 return
454
455 def setup(self, path, oneDDict, ind2DList, twoDDict, metadata, format, **kwargs):
456 '''
457 Configure Operation
458 '''
459
460 self.path = path
461 self.blocks = kwargs.get('blocks', None)
462 self.counter = 0
463 self.oneDDict = load_json(oneDDict)
464 self.twoDDict = load_json(twoDDict)
465 self.ind2DList = load_json(ind2DList)
466 meta = load_json(metadata)
467 self.kinst = meta.get('kinst')
468 self.kindat = meta.get('kindat')
469 self.catalog = meta.get('catalog', DEF_CATALOG)
470 self.header = meta.get('header', DEF_HEADER)
471 if format == 'cedar':
472 self.ext = '.dat'
473 self.extra_args = {}
474 elif format == 'hdf5':
475 self.ext = '.hdf5'
476 self.extra_args = {'ind2DList': self.ind2DList}
477
478 self.keys = [k.lower() for k in self.twoDDict]
479 if 'range' in self.keys:
480 self.keys.remove('range')
481 if 'gdalt' in self.keys:
482 self.keys.remove('gdalt')
483
484 def setFile(self):
485 '''
486 Create new cedar file object
487 '''
488
489 self.mnemonic = MNEMONICS[self.kinst] #TODO get mnemonic from madrigal
490 date = datetime.datetime.fromtimestamp(self.dataOut.utctime)
491
492 filename = '{}{}{}'.format(self.mnemonic,
493 date.strftime('%Y%m%d_%H%M%S'),
494 self.ext)
495
496 self.fullname = os.path.join(self.path, filename)
497
498 if os.path.isfile(self.fullname) :
499 log.warning(
500 'Destination path {} already exists. Previous file deleted.'.format(
501 self.fullname),
502 'MADWriter')
503 os.remove(self.fullname)
504
505 try:
506 log.success(
507 'Creating file: {}'.format(self.fullname),
508 'MADWriter')
509 self.fp = madrigal.cedar.MadrigalCedarFile(self.fullname, True)
510 except ValueError, e:
511 log.error(
512 'Impossible to create a cedar object with "madrigal.cedar.MadrigalCedarFile"',
513 'MADWriter')
514 return
515
516 return 1
517
518 def writeBlock(self):
519 '''
520 Add data records to cedar file taking data from oneDDict and twoDDict
521 attributes.
522 Allowed parameters in: parcodes.tab
523 '''
524
525 startTime = datetime.datetime.fromtimestamp(self.dataOut.utctime)
526 endTime = startTime + datetime.timedelta(seconds=self.dataOut.paramInterval)
527 heights = self.dataOut.heightList
528
529 if self.ext == '.dat':
530 invalid = numpy.isnan(self.dataOut.data_output)
531 self.dataOut.data_output[invalid] = self.missing
532 out = {}
533 for key, value in self.twoDDict.items():
534 key = key.lower()
535 if isinstance(value, str):
536 if 'db' in value.lower():
537 tmp = getattr(self.dataOut, value.replace('_db', ''))
538 SNRavg = numpy.average(tmp, axis=0)
539 tmp = 10*numpy.log10(SNRavg)
540 else:
541 tmp = getattr(self.dataOut, value)
542 out[key] = tmp.flatten()
543 elif isinstance(value, (tuple, list)):
544 attr, x = value
545 data = getattr(self.dataOut, attr)
546 out[key] = data[int(x)]
547
548 a = numpy.array([out[k] for k in self.keys])
549 nrows = numpy.array([numpy.isnan(a[:, x]).all() for x in range(len(heights))])
550 index = numpy.where(nrows == False)[0]
551
552 rec = madrigal.cedar.MadrigalDataRecord(
553 self.kinst,
554 self.kindat,
555 startTime.year,
556 startTime.month,
557 startTime.day,
558 startTime.hour,
559 startTime.minute,
560 startTime.second,
561 startTime.microsecond/10000,
562 endTime.year,
563 endTime.month,
564 endTime.day,
565 endTime.hour,
566 endTime.minute,
567 endTime.second,
568 endTime.microsecond/10000,
569 self.oneDDict.keys(),
570 self.twoDDict.keys(),
571 len(index),
572 **self.extra_args
573 )
574
575 # Setting 1d values
576 for key in self.oneDDict:
577 rec.set1D(key, getattr(self.dataOut, self.oneDDict[key]))
578
579 # Setting 2d values
580 nrec = 0
581 for n in index:
582 for key in out:
583 rec.set2D(key, nrec, out[key][n])
584 nrec += 1
585
586 self.fp.append(rec)
587 if self.ext == '.hdf5' and self.counter % 500 == 0 and self.counter > 0:
588 self.fp.dump()
589 if self.counter % 10 == 0 and self.counter > 0:
590 log.log(
591 'Writing {} records'.format(
592 self.counter),
593 'MADWriter')
594
595 def setHeader(self):
596 '''
597 Create an add catalog and header to cedar file
598 '''
599
600 log.success('Closing file {}'.format(self.fullname), 'MADWriter')
601
602 if self.ext == '.dat':
603 self.fp.write()
604 else:
605 self.fp.dump()
606 self.fp.close()
607
608 header = madrigal.cedar.CatalogHeaderCreator(self.fullname)
609 header.createCatalog(**self.catalog)
610 header.createHeader(**self.header)
611 header.write()
612
613 def putData(self):
614
615 if self.dataOut.flagNoData:
616 return 0
617
618 if self.dataOut.flagDiscontinuousBlock or self.counter == self.blocks:
619 if self.counter > 0:
620 self.setHeader()
621 self.counter = 0
622
623 if self.counter == 0:
624 self.setFile()
625
626 self.writeBlock()
627 self.counter += 1
628
629 def close(self):
630
631 if self.counter > 0:
632 self.setHeader()
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
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,7 +1,7
1 '''
1 '''
2 Created on Feb 7, 2012
2 Created on Feb 7, 2012
3
3
4 @author $Author$
4 @author $Author$
5 @version $Id$
5 @version $Id$
6 '''
6 '''
7 __version__ = "2.3"
7 __version__ = '2.3'
@@ -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,187 +1,187
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 from schainpy.model import *
5 from schainpy.model import *
6 from figure import Figure, isRealtime
6 from figure import Figure, isRealtime
7
7
8 class CorrelationPlot(Figure):
8 class CorrelationPlot(Figure):
9 isConfig = None
9 isConfig = None
10 __nsubplots = None
10 __nsubplots = None
11
11
12 WIDTHPROF = None
12 WIDTHPROF = None
13 HEIGHTPROF = None
13 HEIGHTPROF = None
14 PREFIX = 'corr'
14 PREFIX = 'corr'
15
15
16 def __init__(self, **kwargs):
16 def __init__(self):
17 Figure.__init__(self, **kwargs)
17
18 self.isConfig = False
18 self.isConfig = False
19 self.__nsubplots = 1
19 self.__nsubplots = 1
20
20
21 self.WIDTH = 280
21 self.WIDTH = 280
22 self.HEIGHT = 250
22 self.HEIGHT = 250
23 self.WIDTHPROF = 120
23 self.WIDTHPROF = 120
24 self.HEIGHTPROF = 0
24 self.HEIGHTPROF = 0
25 self.counter_imagwr = 0
25 self.counter_imagwr = 0
26
26
27 self.PLOT_CODE = 1
27 self.PLOT_CODE = 1
28 self.FTP_WEI = None
28 self.FTP_WEI = None
29 self.EXP_CODE = None
29 self.EXP_CODE = None
30 self.SUB_EXP_CODE = None
30 self.SUB_EXP_CODE = None
31 self.PLOT_POS = None
31 self.PLOT_POS = None
32
32
33 def getSubplots(self):
33 def getSubplots(self):
34
34
35 ncol = int(numpy.sqrt(self.nplots)+0.9)
35 ncol = int(numpy.sqrt(self.nplots)+0.9)
36 nrow = int(self.nplots*1./ncol + 0.9)
36 nrow = int(self.nplots*1./ncol + 0.9)
37
37
38 return nrow, ncol
38 return nrow, ncol
39
39
40 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
40 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
41
41
42 showprofile = False
42 showprofile = False
43 self.__showprofile = showprofile
43 self.__showprofile = showprofile
44 self.nplots = nplots
44 self.nplots = nplots
45
45
46 ncolspan = 1
46 ncolspan = 1
47 colspan = 1
47 colspan = 1
48 if showprofile:
48 if showprofile:
49 ncolspan = 3
49 ncolspan = 3
50 colspan = 2
50 colspan = 2
51 self.__nsubplots = 2
51 self.__nsubplots = 2
52
52
53 self.createFigure(id = id,
53 self.createFigure(id = id,
54 wintitle = wintitle,
54 wintitle = wintitle,
55 widthplot = self.WIDTH + self.WIDTHPROF,
55 widthplot = self.WIDTH + self.WIDTHPROF,
56 heightplot = self.HEIGHT + self.HEIGHTPROF,
56 heightplot = self.HEIGHT + self.HEIGHTPROF,
57 show=show)
57 show=show)
58
58
59 nrow, ncol = self.getSubplots()
59 nrow, ncol = self.getSubplots()
60
60
61 counter = 0
61 counter = 0
62 for y in range(nrow):
62 for y in range(nrow):
63 for x in range(ncol):
63 for x in range(ncol):
64
64
65 if counter >= self.nplots:
65 if counter >= self.nplots:
66 break
66 break
67
67
68 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
68 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
69
69
70 if showprofile:
70 if showprofile:
71 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
71 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
72
72
73 counter += 1
73 counter += 1
74
74
75 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
75 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
76 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
76 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
77 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
77 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
78 server=None, folder=None, username=None, password=None,
78 server=None, folder=None, username=None, password=None,
79 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
79 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
80
80
81 """
81 """
82
82
83 Input:
83 Input:
84 dataOut :
84 dataOut :
85 id :
85 id :
86 wintitle :
86 wintitle :
87 channelList :
87 channelList :
88 showProfile :
88 showProfile :
89 xmin : None,
89 xmin : None,
90 xmax : None,
90 xmax : None,
91 ymin : None,
91 ymin : None,
92 ymax : None,
92 ymax : None,
93 zmin : None,
93 zmin : None,
94 zmax : None
94 zmax : None
95 """
95 """
96
96
97 if dataOut.flagNoData:
97 if dataOut.flagNoData:
98 return None
98 return None
99
99
100 if realtime:
100 if realtime:
101 if not(isRealtime(utcdatatime = dataOut.utctime)):
101 if not(isRealtime(utcdatatime = dataOut.utctime)):
102 print 'Skipping this plot function'
102 print 'Skipping this plot function'
103 return
103 return
104
104
105 if channelList == None:
105 if channelList == None:
106 channelIndexList = dataOut.channelIndexList
106 channelIndexList = dataOut.channelIndexList
107 else:
107 else:
108 channelIndexList = []
108 channelIndexList = []
109 for channel in channelList:
109 for channel in channelList:
110 if channel not in dataOut.channelList:
110 if channel not in dataOut.channelList:
111 raise ValueError, "Channel %d is not in dataOut.channelList"
111 raise ValueError, "Channel %d is not in dataOut.channelList"
112 channelIndexList.append(dataOut.channelList.index(channel))
112 channelIndexList.append(dataOut.channelList.index(channel))
113
113
114 factor = dataOut.normFactor
114 factor = dataOut.normFactor
115 lenfactor = factor.shape[1]
115 lenfactor = factor.shape[1]
116 x = dataOut.getLagTRange(1)
116 x = dataOut.getLagTRange(1)
117 y = dataOut.getHeiRange()
117 y = dataOut.getHeiRange()
118
118
119 z = copy.copy(dataOut.data_corr[:,:,0,:])
119 z = copy.copy(dataOut.data_corr[:,:,0,:])
120 for i in range(dataOut.data_corr.shape[0]):
120 for i in range(dataOut.data_corr.shape[0]):
121 z[i,:,:] = z[i,:,:]/factor[i,:]
121 z[i,:,:] = z[i,:,:]/factor[i,:]
122 zdB = numpy.abs(z)
122 zdB = numpy.abs(z)
123
123
124 avg = numpy.average(z, axis=1)
124 avg = numpy.average(z, axis=1)
125 # avg = numpy.nanmean(z, axis=1)
125 # avg = numpy.nanmean(z, axis=1)
126 # noise = dataOut.noise/factor
126 # noise = dataOut.noise/factor
127
127
128 #thisDatetime = dataOut.datatime
128 #thisDatetime = dataOut.datatime
129 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
129 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
130 title = wintitle + " Correlation"
130 title = wintitle + " Correlation"
131 xlabel = "Lag T (s)"
131 xlabel = "Lag T (s)"
132 ylabel = "Range (Km)"
132 ylabel = "Range (Km)"
133
133
134 if not self.isConfig:
134 if not self.isConfig:
135
135
136 nplots = dataOut.data_corr.shape[0]
136 nplots = dataOut.data_corr.shape[0]
137
137
138 self.setup(id=id,
138 self.setup(id=id,
139 nplots=nplots,
139 nplots=nplots,
140 wintitle=wintitle,
140 wintitle=wintitle,
141 showprofile=showprofile,
141 showprofile=showprofile,
142 show=show)
142 show=show)
143
143
144 if xmin == None: xmin = numpy.nanmin(x)
144 if xmin == None: xmin = numpy.nanmin(x)
145 if xmax == None: xmax = numpy.nanmax(x)
145 if xmax == None: xmax = numpy.nanmax(x)
146 if ymin == None: ymin = numpy.nanmin(y)
146 if ymin == None: ymin = numpy.nanmin(y)
147 if ymax == None: ymax = numpy.nanmax(y)
147 if ymax == None: ymax = numpy.nanmax(y)
148 if zmin == None: zmin = 0
148 if zmin == None: zmin = 0
149 if zmax == None: zmax = 1
149 if zmax == None: zmax = 1
150
150
151 self.FTP_WEI = ftp_wei
151 self.FTP_WEI = ftp_wei
152 self.EXP_CODE = exp_code
152 self.EXP_CODE = exp_code
153 self.SUB_EXP_CODE = sub_exp_code
153 self.SUB_EXP_CODE = sub_exp_code
154 self.PLOT_POS = plot_pos
154 self.PLOT_POS = plot_pos
155
155
156 self.isConfig = True
156 self.isConfig = True
157
157
158 self.setWinTitle(title)
158 self.setWinTitle(title)
159
159
160 for i in range(self.nplots):
160 for i in range(self.nplots):
161 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
161 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
162 title = "Channel %d and %d: : %s" %(dataOut.pairsList[i][0],dataOut.pairsList[i][1] , str_datetime)
162 title = "Channel %d and %d: : %s" %(dataOut.pairsList[i][0],dataOut.pairsList[i][1] , str_datetime)
163 axes = self.axesList[i*self.__nsubplots]
163 axes = self.axesList[i*self.__nsubplots]
164 axes.pcolor(x, y, zdB[i,:,:],
164 axes.pcolor(x, y, zdB[i,:,:],
165 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
165 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
166 xlabel=xlabel, ylabel=ylabel, title=title,
166 xlabel=xlabel, ylabel=ylabel, title=title,
167 ticksize=9, cblabel='')
167 ticksize=9, cblabel='')
168
168
169 # if self.__showprofile:
169 # if self.__showprofile:
170 # axes = self.axesList[i*self.__nsubplots +1]
170 # axes = self.axesList[i*self.__nsubplots +1]
171 # axes.pline(avgdB[i], y,
171 # axes.pline(avgdB[i], y,
172 # xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
172 # xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
173 # xlabel='dB', ylabel='', title='',
173 # xlabel='dB', ylabel='', title='',
174 # ytick_visible=False,
174 # ytick_visible=False,
175 # grid='x')
175 # grid='x')
176 #
176 #
177 # noiseline = numpy.repeat(noisedB[i], len(y))
177 # noiseline = numpy.repeat(noisedB[i], len(y))
178 # axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
178 # axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
179
179
180 self.draw()
180 self.draw()
181
181
182 self.save(figpath=figpath,
182 self.save(figpath=figpath,
183 figfile=figfile,
183 figfile=figfile,
184 save=save,
184 save=save,
185 ftp=ftp,
185 ftp=ftp,
186 wr_period=wr_period,
186 wr_period=wr_period,
187 thisDatetime=thisDatetime)
187 thisDatetime=thisDatetime)
@@ -1,782 +1,819
1
1
2 import os
2 import os
3 import time
3 import time
4 import glob
4 import glob
5 import datetime
5 import datetime
6 from multiprocessing import Process
6 from multiprocessing import Process
7
7
8 import zmq
8 import zmq
9 import numpy
9 import numpy
10 import matplotlib
10 import matplotlib
11 import matplotlib.pyplot as plt
11 import matplotlib.pyplot as plt
12 from mpl_toolkits.axes_grid1 import make_axes_locatable
12 from mpl_toolkits.axes_grid1 import make_axes_locatable
13 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
13 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
14
14
15 from schainpy.model.proc.jroproc_base import Operation
15 from schainpy.model.proc.jroproc_base import Operation
16 from schainpy.utils import log
16 from schainpy.utils import log
17
17
18 func = lambda x, pos: ('%s') %(datetime.datetime.fromtimestamp(x).strftime('%H:%M'))
18 jet_values = matplotlib.pyplot.get_cmap("jet", 100)(numpy.arange(100))[10:90]
19 blu_values = matplotlib.pyplot.get_cmap("seismic_r", 20)(numpy.arange(20))[10:15]
20 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list("jro", numpy.vstack((blu_values, jet_values)))
21 matplotlib.pyplot.register_cmap(cmap=ncmap)
19
22
20 d1970 = datetime.datetime(1970, 1, 1)
23 func = lambda x, pos: '{}'.format(datetime.datetime.fromtimestamp(x).strftime('%H:%M'))
21
24
25 UT1970 = datetime.datetime(1970, 1, 1) - datetime.timedelta(seconds=time.timezone)
26
27 CMAPS = [plt.get_cmap(s) for s in ('jro', 'jet', 'RdBu_r', 'seismic')]
22
28
23 class PlotData(Operation, Process):
29 class PlotData(Operation, Process):
24 '''
30 '''
25 Base class for Schain plotting operations
31 Base class for Schain plotting operations
26 '''
32 '''
27
33
28 CODE = 'Figure'
34 CODE = 'Figure'
29 colormap = 'jro'
35 colormap = 'jro'
30 bgcolor = 'white'
36 bgcolor = 'white'
31 CONFLATE = False
37 CONFLATE = False
32 __MAXNUMX = 80
38 __MAXNUMX = 80
33 __missing = 1E30
39 __missing = 1E30
34
40
35 def __init__(self, **kwargs):
41 def __init__(self, **kwargs):
36
42
37 Operation.__init__(self, plot=True, **kwargs)
43 Operation.__init__(self, plot=True, **kwargs)
38 Process.__init__(self)
44 Process.__init__(self)
39 self.kwargs['code'] = self.CODE
45 self.kwargs['code'] = self.CODE
40 self.mp = False
46 self.mp = False
41 self.data = None
47 self.data = None
42 self.isConfig = False
48 self.isConfig = False
43 self.figures = []
49 self.figures = []
44 self.axes = []
50 self.axes = []
45 self.cb_axes = []
51 self.cb_axes = []
46 self.localtime = kwargs.pop('localtime', True)
52 self.localtime = kwargs.pop('localtime', True)
47 self.show = kwargs.get('show', True)
53 self.show = kwargs.get('show', True)
48 self.save = kwargs.get('save', False)
54 self.save = kwargs.get('save', False)
49 self.colormap = kwargs.get('colormap', self.colormap)
55 self.colormap = kwargs.get('colormap', self.colormap)
50 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
56 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
51 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
57 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
52 self.colormaps = kwargs.get('colormaps', None)
58 self.colormaps = kwargs.get('colormaps', None)
53 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
59 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
54 self.showprofile = kwargs.get('showprofile', False)
60 self.showprofile = kwargs.get('showprofile', False)
55 self.title = kwargs.get('wintitle', self.CODE.upper())
61 self.title = kwargs.get('wintitle', self.CODE.upper())
56 self.cb_label = kwargs.get('cb_label', None)
62 self.cb_label = kwargs.get('cb_label', None)
57 self.cb_labels = kwargs.get('cb_labels', None)
63 self.cb_labels = kwargs.get('cb_labels', None)
58 self.xaxis = kwargs.get('xaxis', 'frequency')
64 self.xaxis = kwargs.get('xaxis', 'frequency')
59 self.zmin = kwargs.get('zmin', None)
65 self.zmin = kwargs.get('zmin', None)
60 self.zmax = kwargs.get('zmax', None)
66 self.zmax = kwargs.get('zmax', None)
61 self.zlimits = kwargs.get('zlimits', None)
67 self.zlimits = kwargs.get('zlimits', None)
62 self.xmin = kwargs.get('xmin', None)
68 self.xmin = kwargs.get('xmin', None)
63 if self.xmin is not None:
64 self.xmin += 5
65 self.xmax = kwargs.get('xmax', None)
69 self.xmax = kwargs.get('xmax', None)
66 self.xrange = kwargs.get('xrange', 24)
70 self.xrange = kwargs.get('xrange', 24)
67 self.ymin = kwargs.get('ymin', None)
71 self.ymin = kwargs.get('ymin', None)
68 self.ymax = kwargs.get('ymax', None)
72 self.ymax = kwargs.get('ymax', None)
69 self.xlabel = kwargs.get('xlabel', None)
73 self.xlabel = kwargs.get('xlabel', None)
70 self.__MAXNUMY = kwargs.get('decimation', 100)
74 self.__MAXNUMY = kwargs.get('decimation', 100)
71 self.showSNR = kwargs.get('showSNR', False)
75 self.showSNR = kwargs.get('showSNR', False)
72 self.oneFigure = kwargs.get('oneFigure', True)
76 self.oneFigure = kwargs.get('oneFigure', True)
73 self.width = kwargs.get('width', None)
77 self.width = kwargs.get('width', None)
74 self.height = kwargs.get('height', None)
78 self.height = kwargs.get('height', None)
75 self.colorbar = kwargs.get('colorbar', True)
79 self.colorbar = kwargs.get('colorbar', True)
76 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
80 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
77 self.titles = ['' for __ in range(16)]
81 self.titles = ['' for __ in range(16)]
78
82
79 def __setup(self):
83 def __setup(self):
80 '''
84 '''
81 Common setup for all figures, here figures and axes are created
85 Common setup for all figures, here figures and axes are created
82 '''
86 '''
83
87
84 self.setup()
88 self.setup()
85
89
90 self.time_label = 'LT' if self.localtime else 'UTC'
91
86 if self.width is None:
92 if self.width is None:
87 self.width = 8
93 self.width = 8
88
94
89 self.figures = []
95 self.figures = []
90 self.axes = []
96 self.axes = []
91 self.cb_axes = []
97 self.cb_axes = []
92 self.pf_axes = []
98 self.pf_axes = []
93 self.cmaps = []
99 self.cmaps = []
94
100
95 size = '15%' if self.ncols==1 else '30%'
101 size = '15%' if self.ncols==1 else '30%'
96 pad = '4%' if self.ncols==1 else '8%'
102 pad = '4%' if self.ncols==1 else '8%'
97
103
98 if self.oneFigure:
104 if self.oneFigure:
99 if self.height is None:
105 if self.height is None:
100 self.height = 1.4*self.nrows + 1
106 self.height = 1.4*self.nrows + 1
101 fig = plt.figure(figsize=(self.width, self.height),
107 fig = plt.figure(figsize=(self.width, self.height),
102 edgecolor='k',
108 edgecolor='k',
103 facecolor='w')
109 facecolor='w')
104 self.figures.append(fig)
110 self.figures.append(fig)
105 for n in range(self.nplots):
111 for n in range(self.nplots):
106 ax = fig.add_subplot(self.nrows, self.ncols, n+1)
112 ax = fig.add_subplot(self.nrows, self.ncols, n+1)
107 ax.tick_params(labelsize=8)
113 ax.tick_params(labelsize=8)
108 ax.firsttime = True
114 ax.firsttime = True
115 ax.index = 0
109 self.axes.append(ax)
116 self.axes.append(ax)
110 if self.showprofile:
117 if self.showprofile:
111 cax = self.__add_axes(ax, size=size, pad=pad)
118 cax = self.__add_axes(ax, size=size, pad=pad)
112 cax.tick_params(labelsize=8)
119 cax.tick_params(labelsize=8)
113 self.pf_axes.append(cax)
120 self.pf_axes.append(cax)
114 else:
121 else:
115 if self.height is None:
122 if self.height is None:
116 self.height = 3
123 self.height = 3
117 for n in range(self.nplots):
124 for n in range(self.nplots):
118 fig = plt.figure(figsize=(self.width, self.height),
125 fig = plt.figure(figsize=(self.width, self.height),
119 edgecolor='k',
126 edgecolor='k',
120 facecolor='w')
127 facecolor='w')
121 ax = fig.add_subplot(1, 1, 1)
128 ax = fig.add_subplot(1, 1, 1)
122 ax.tick_params(labelsize=8)
129 ax.tick_params(labelsize=8)
123 ax.firsttime = True
130 ax.firsttime = True
131 ax.index = 0
124 self.figures.append(fig)
132 self.figures.append(fig)
125 self.axes.append(ax)
133 self.axes.append(ax)
126 if self.showprofile:
134 if self.showprofile:
127 cax = self.__add_axes(ax, size=size, pad=pad)
135 cax = self.__add_axes(ax, size=size, pad=pad)
128 cax.tick_params(labelsize=8)
136 cax.tick_params(labelsize=8)
129 self.pf_axes.append(cax)
137 self.pf_axes.append(cax)
130
138
131 for n in range(self.nrows):
139 for n in range(self.nrows):
132 if self.colormaps is not None:
140 if self.colormaps is not None:
133 cmap = plt.get_cmap(self.colormaps[n])
141 cmap = plt.get_cmap(self.colormaps[n])
134 else:
142 else:
135 cmap = plt.get_cmap(self.colormap)
143 cmap = plt.get_cmap(self.colormap)
136 cmap.set_bad(self.bgcolor, 1.)
144 cmap.set_bad(self.bgcolor, 1.)
137 self.cmaps.append(cmap)
145 self.cmaps.append(cmap)
138
146
147 for fig in self.figures:
148 fig.canvas.mpl_connect('key_press_event', self.event_key_press)
149
150 def event_key_press(self, event):
151 '''
152 '''
153
154 for ax in self.axes:
155 if ax == event.inaxes:
156 if event.key == 'down':
157 ax.index += 1
158 elif event.key == 'up':
159 ax.index -= 1
160 if ax.index < 0:
161 ax.index = len(CMAPS) - 1
162 elif ax.index == len(CMAPS):
163 ax.index = 0
164 cmap = CMAPS[ax.index]
165 ax.cbar.set_cmap(cmap)
166 ax.cbar.draw_all()
167 ax.plt.set_cmap(cmap)
168 ax.cbar.patch.figure.canvas.draw()
169
139 def __add_axes(self, ax, size='30%', pad='8%'):
170 def __add_axes(self, ax, size='30%', pad='8%'):
140 '''
171 '''
141 Add new axes to the given figure
172 Add new axes to the given figure
142 '''
173 '''
143 divider = make_axes_locatable(ax)
174 divider = make_axes_locatable(ax)
144 nax = divider.new_horizontal(size=size, pad=pad)
175 nax = divider.new_horizontal(size=size, pad=pad)
145 ax.figure.add_axes(nax)
176 ax.figure.add_axes(nax)
146 return nax
177 return nax
147
178
179 self.setup()
148
180
149 def setup(self):
181 def setup(self):
150 '''
182 '''
151 This method should be implemented in the child class, the following
183 This method should be implemented in the child class, the following
152 attributes should be set:
184 attributes should be set:
153
185
154 self.nrows: number of rows
186 self.nrows: number of rows
155 self.ncols: number of cols
187 self.ncols: number of cols
156 self.nplots: number of plots (channels or pairs)
188 self.nplots: number of plots (channels or pairs)
157 self.ylabel: label for Y axes
189 self.ylabel: label for Y axes
158 self.titles: list of axes title
190 self.titles: list of axes title
159
191
160 '''
192 '''
161 raise(NotImplementedError, 'Implement this method in child class')
193 raise(NotImplementedError, 'Implement this method in child class')
162
194
163 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
195 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
164 '''
196 '''
165 Create a masked array for missing data
197 Create a masked array for missing data
166 '''
198 '''
167 if x_buffer.shape[0] < 2:
199 if x_buffer.shape[0] < 2:
168 return x_buffer, y_buffer, z_buffer
200 return x_buffer, y_buffer, z_buffer
169
201
170 deltas = x_buffer[1:] - x_buffer[0:-1]
202 deltas = x_buffer[1:] - x_buffer[0:-1]
171 x_median = numpy.median(deltas)
203 x_median = numpy.median(deltas)
172
204
173 index = numpy.where(deltas > 5*x_median)
205 index = numpy.where(deltas > 5*x_median)
174
206
175 if len(index[0]) != 0:
207 if len(index[0]) != 0:
176 z_buffer[::, index[0], ::] = self.__missing
208 z_buffer[::, index[0], ::] = self.__missing
177 z_buffer = numpy.ma.masked_inside(z_buffer,
209 z_buffer = numpy.ma.masked_inside(z_buffer,
178 0.99*self.__missing,
210 0.99*self.__missing,
179 1.01*self.__missing)
211 1.01*self.__missing)
180
212
181 return x_buffer, y_buffer, z_buffer
213 return x_buffer, y_buffer, z_buffer
182
214
183 def decimate(self):
215 def decimate(self):
184
216
185 # dx = int(len(self.x)/self.__MAXNUMX) + 1
217 # dx = int(len(self.x)/self.__MAXNUMX) + 1
186 dy = int(len(self.y)/self.__MAXNUMY) + 1
218 dy = int(len(self.y)/self.__MAXNUMY) + 1
187
219
188 # x = self.x[::dx]
220 # x = self.x[::dx]
189 x = self.x
221 x = self.x
190 y = self.y[::dy]
222 y = self.y[::dy]
191 z = self.z[::, ::, ::dy]
223 z = self.z[::, ::, ::dy]
192
224
193 return x, y, z
225 return x, y, z
194
226
195 def format(self):
227 def format(self):
196 '''
228 '''
197 Set min and max values, labels, ticks and titles
229 Set min and max values, labels, ticks and titles
198 '''
230 '''
199
231
200 if self.xmin is None:
232 if self.xmin is None:
201 xmin = self.min_time
233 xmin = self.min_time
202 else:
234 else:
203 if self.xaxis is 'time':
235 if self.xaxis is 'time':
204 dt = datetime.datetime.fromtimestamp(self.min_time)
236 dt = datetime.datetime.fromtimestamp(self.min_time)
205 xmin = (datetime.datetime.combine(dt.date(),
237 xmin = (datetime.datetime.combine(dt.date(),
206 datetime.time(int(self.xmin), 0, 0))-d1970).total_seconds()
238 datetime.time(int(self.xmin), 0, 0))-UT1970).total_seconds()
207 else:
239 else:
208 xmin = self.xmin
240 xmin = self.xmin
209
241
210 if self.xmax is None:
242 if self.xmax is None:
211 xmax = xmin+self.xrange*60*60
243 xmax = xmin+self.xrange*60*60
212 else:
244 else:
213 if self.xaxis is 'time':
245 if self.xaxis is 'time':
214 dt = datetime.datetime.fromtimestamp(self.min_time)
246 dt = datetime.datetime.fromtimestamp(self.min_time)
215 xmax = (datetime.datetime.combine(dt.date(),
247 xmax = (datetime.datetime.combine(dt.date(),
216 datetime.time(int(self.xmax), 0, 0))-d1970).total_seconds()
248 datetime.time(int(self.xmax), 0, 0))-UT1970).total_seconds()
217 else:
249 else:
218 xmax = self.xmax
250 xmax = self.xmax
219
251
220 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
252 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
221 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
253 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
222
254
223 ystep = 200 if ymax>= 800 else 100 if ymax>=400 else 50 if ymax>=200 else 20
255 ystep = 200 if ymax>= 800 else 100 if ymax>=400 else 50 if ymax>=200 else 20
224
256
225 for n, ax in enumerate(self.axes):
257 for n, ax in enumerate(self.axes):
226 if ax.firsttime:
258 if ax.firsttime:
227 ax.set_facecolor(self.bgcolor)
259 ax.set_facecolor(self.bgcolor)
228 ax.yaxis.set_major_locator(MultipleLocator(ystep))
260 ax.yaxis.set_major_locator(MultipleLocator(ystep))
229 if self.xaxis is 'time':
261 if self.xaxis is 'time':
230 ax.xaxis.set_major_formatter(FuncFormatter(func))
262 ax.xaxis.set_major_formatter(FuncFormatter(func))
231 ax.xaxis.set_major_locator(LinearLocator(9))
263 ax.xaxis.set_major_locator(LinearLocator(9))
232 if self.xlabel is not None:
264 if self.xlabel is not None:
233 ax.set_xlabel(self.xlabel)
265 ax.set_xlabel(self.xlabel)
234 ax.set_ylabel(self.ylabel)
266 ax.set_ylabel(self.ylabel)
235 ax.firsttime = False
267 ax.firsttime = False
236 if self.showprofile:
268 if self.showprofile:
237 self.pf_axes[n].set_ylim(ymin, ymax)
269 self.pf_axes[n].set_ylim(ymin, ymax)
238 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
270 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
239 self.pf_axes[n].set_xlabel('dB')
271 self.pf_axes[n].set_xlabel('dB')
240 self.pf_axes[n].grid(b=True, axis='x')
272 self.pf_axes[n].grid(b=True, axis='x')
241 [tick.set_visible(False) for tick in self.pf_axes[n].get_yticklabels()]
273 [tick.set_visible(False) for tick in self.pf_axes[n].get_yticklabels()]
242 if self.colorbar:
274 if self.colorbar:
243 cb = plt.colorbar(ax.plt, ax=ax, pad=0.02)
275 ax.cbar = plt.colorbar(ax.plt, ax=ax, pad=0.02, aspect=10)
244 cb.ax.tick_params(labelsize=8)
276 ax.cbar.ax.tick_params(labelsize=8)
245 if self.cb_label:
277 if self.cb_label:
246 cb.set_label(self.cb_label, size=8)
278 ax.cbar.set_label(self.cb_label, size=8)
247 elif self.cb_labels:
279 elif self.cb_labels:
248 cb.set_label(self.cb_labels[n], size=8)
280 ax.cbar.set_label(self.cb_labels[n], size=8)
249
281
250 ax.set_title('{} - {} UTC'.format(
282 ax.set_title('{} - {} {}'.format(
251 self.titles[n],
283 self.titles[n],
252 datetime.datetime.fromtimestamp(self.max_time).strftime('%H:%M:%S')),
284 datetime.datetime.fromtimestamp(self.max_time).strftime('%H:%M:%S'),
285 self.time_label),
253 size=8)
286 size=8)
254 ax.set_xlim(xmin, xmax)
287 ax.set_xlim(xmin, xmax)
255 ax.set_ylim(ymin, ymax)
288 ax.set_ylim(ymin, ymax)
256
257
289
258 def __plot(self):
290 def __plot(self):
259 '''
291 '''
260 '''
292 '''
261 log.success('Plotting', self.name)
293 log.success('Plotting', self.name)
262
294
263 self.plot()
295 self.plot()
264 self.format()
296 self.format()
265
297
266 for n, fig in enumerate(self.figures):
298 for n, fig in enumerate(self.figures):
267 if self.nrows == 0 or self.nplots == 0:
299 if self.nrows == 0 or self.nplots == 0:
268 log.warning('No data', self.name)
300 log.warning('No data', self.name)
269 continue
301 continue
270 if self.show:
302 if self.show:
271 fig.show()
303 fig.show()
272
304
273 fig.tight_layout()
305 fig.tight_layout()
274 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
306 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
275 datetime.datetime.fromtimestamp(self.max_time).strftime('%Y/%m/%d')))
307 datetime.datetime.fromtimestamp(self.max_time).strftime('%Y/%m/%d')))
276 # fig.canvas.draw()
308 # fig.canvas.draw()
277
309
278 if self.save and self.data.ended:
310 if self.save and self.data.ended:
279 channels = range(self.nrows)
311 channels = range(self.nrows)
280 if self.oneFigure:
312 if self.oneFigure:
281 label = ''
313 label = ''
282 else:
314 else:
283 label = '_{}'.format(channels[n])
315 label = '_{}'.format(channels[n])
284 figname = os.path.join(
316 figname = os.path.join(
285 self.save,
317 self.save,
286 '{}{}_{}.png'.format(
318 '{}{}_{}.png'.format(
287 self.CODE,
319 self.CODE,
288 label,
320 label,
289 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')
321 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')
290 )
322 )
291 )
323 )
292 print 'Saving figure: {}'.format(figname)
324 print 'Saving figure: {}'.format(figname)
293 fig.savefig(figname)
325 fig.savefig(figname)
294
326
295 def plot(self):
327 def plot(self):
296 '''
328 '''
297 '''
329 '''
298 raise(NotImplementedError, 'Implement this method in child class')
330 raise(NotImplementedError, 'Implement this method in child class')
299
331
300 def run(self):
332 def run(self):
301
333
302 log.success('Starting', self.name)
334 log.success('Starting', self.name)
303
335
304 context = zmq.Context()
336 context = zmq.Context()
305 receiver = context.socket(zmq.SUB)
337 receiver = context.socket(zmq.SUB)
306 receiver.setsockopt(zmq.SUBSCRIBE, '')
338 receiver.setsockopt(zmq.SUBSCRIBE, '')
307 receiver.setsockopt(zmq.CONFLATE, self.CONFLATE)
339 receiver.setsockopt(zmq.CONFLATE, self.CONFLATE)
308
340
309 if 'server' in self.kwargs['parent']:
341 if 'server' in self.kwargs['parent']:
310 receiver.connect('ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
342 receiver.connect('ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
311 else:
343 else:
312 receiver.connect("ipc:///tmp/zmq.plots")
344 receiver.connect("ipc:///tmp/zmq.plots")
313
345
314 while True:
346 while True:
315 try:
347 try:
316 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
348 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
317
349
318 self.min_time = self.data.times[0]
350 if self.localtime:
319 self.max_time = self.data.times[-1]
351 self.times = self.data.times - time.timezone
352 else:
353 self.times = self.data.times
354
355 self.min_time = self.times[0]
356 self.max_time = self.times[-1]
320
357
321 if self.isConfig is False:
358 if self.isConfig is False:
322 self.__setup()
359 self.__setup()
323 self.isConfig = True
360 self.isConfig = True
324
361
325 self.__plot()
362 self.__plot()
326
363
327 except zmq.Again as e:
364 except zmq.Again as e:
328 log.log('Waiting for data...')
365 log.log('Waiting for data...')
329 if self.data:
366 if self.data:
330 plt.pause(self.data.throttle)
367 plt.pause(self.data.throttle)
331 else:
368 else:
332 time.sleep(2)
369 time.sleep(2)
333
370
334 def close(self):
371 def close(self):
335 if self.data:
372 if self.data:
336 self.__plot()
373 self.__plot()
337
374
338
339 class PlotSpectraData(PlotData):
375 class PlotSpectraData(PlotData):
340 '''
376 '''
341 Plot for Spectra data
377 Plot for Spectra data
342 '''
378 '''
343
379
344 CODE = 'spc'
380 CODE = 'spc'
345 colormap = 'jro'
381 colormap = 'jro'
346
382
347 def setup(self):
383 def setup(self):
348 self.nplots = len(self.data.channels)
384 self.nplots = len(self.data.channels)
349 self.ncols = int(numpy.sqrt(self.nplots)+ 0.9)
385 self.ncols = int(numpy.sqrt(self.nplots)+ 0.9)
350 self.nrows = int((1.0*self.nplots/self.ncols) + 0.9)
386 self.nrows = int((1.0*self.nplots/self.ncols) + 0.9)
351 self.width = 3.4*self.ncols
387 self.width = 3.4*self.ncols
352 self.height = 3*self.nrows
388 self.height = 3*self.nrows
353 self.cb_label = 'dB'
389 self.cb_label = 'dB'
354 if self.showprofile:
390 if self.showprofile:
355 self.width += 0.8*self.ncols
391 self.width += 0.8*self.ncols
356
392
357 self.ylabel = 'Range [Km]'
393 self.ylabel = 'Range [Km]'
358
394
359 def plot(self):
395 def plot(self):
360 if self.xaxis == "frequency":
396 if self.xaxis == "frequency":
361 x = self.data.xrange[0]
397 x = self.data.xrange[0]
362 self.xlabel = "Frequency (kHz)"
398 self.xlabel = "Frequency (kHz)"
363 elif self.xaxis == "time":
399 elif self.xaxis == "time":
364 x = self.data.xrange[1]
400 x = self.data.xrange[1]
365 self.xlabel = "Time (ms)"
401 self.xlabel = "Time (ms)"
366 else:
402 else:
367 x = self.data.xrange[2]
403 x = self.data.xrange[2]
368 self.xlabel = "Velocity (m/s)"
404 self.xlabel = "Velocity (m/s)"
369
405
370 if self.CODE == 'spc_mean':
406 if self.CODE == 'spc_mean':
371 x = self.data.xrange[2]
407 x = self.data.xrange[2]
372 self.xlabel = "Velocity (m/s)"
408 self.xlabel = "Velocity (m/s)"
373
409
374 self.titles = []
410 self.titles = []
375
411
376 y = self.data.heights
412 y = self.data.heights
377 self.y = y
413 self.y = y
378 z = self.data['spc']
414 z = self.data['spc']
379
415
380 for n, ax in enumerate(self.axes):
416 for n, ax in enumerate(self.axes):
381 noise = self.data['noise'][n][-1]
417 noise = self.data['noise'][n][-1]
382 if self.CODE == 'spc_mean':
418 if self.CODE == 'spc_mean':
383 mean = self.data['mean'][n][-1]
419 mean = self.data['mean'][n][-1]
384 if ax.firsttime:
420 if ax.firsttime:
385 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
421 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
386 self.xmin = self.xmin if self.xmin else -self.xmax
422 self.xmin = self.xmin if self.xmin else -self.xmax
387 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
423 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
388 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
424 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
389 ax.plt = ax.pcolormesh(x, y, z[n].T,
425 ax.plt = ax.pcolormesh(x, y, z[n].T,
390 vmin=self.zmin,
426 vmin=self.zmin,
391 vmax=self.zmax,
427 vmax=self.zmax,
392 cmap=plt.get_cmap(self.colormap)
428 cmap=plt.get_cmap(self.colormap)
393 )
429 )
394
430
395 if self.showprofile:
431 if self.showprofile:
396 ax.plt_profile= self.pf_axes[n].plot(self.data['rti'][n][-1], y)[0]
432 ax.plt_profile= self.pf_axes[n].plot(self.data['rti'][n][-1], y)[0]
397 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
433 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
398 color="k", linestyle="dashed", lw=1)[0]
434 color="k", linestyle="dashed", lw=1)[0]
399 if self.CODE == 'spc_mean':
435 if self.CODE == 'spc_mean':
400 ax.plt_mean = ax.plot(mean, y, color='k')[0]
436 ax.plt_mean = ax.plot(mean, y, color='k')[0]
401 else:
437 else:
402 ax.plt.set_array(z[n].T.ravel())
438 ax.plt.set_array(z[n].T.ravel())
403 if self.showprofile:
439 if self.showprofile:
404 ax.plt_profile.set_data(self.data['rti'][n][-1], y)
440 ax.plt_profile.set_data(self.data['rti'][n][-1], y)
405 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
441 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
406 if self.CODE == 'spc_mean':
442 if self.CODE == 'spc_mean':
407 ax.plt_mean.set_data(mean, y)
443 ax.plt_mean.set_data(mean, y)
408
444
409 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
445 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
410 self.saveTime = self.max_time
446 self.saveTime = self.max_time
411
447
412
448
413 class PlotCrossSpectraData(PlotData):
449 class PlotCrossSpectraData(PlotData):
414
450
415 CODE = 'cspc'
451 CODE = 'cspc'
416 zmin_coh = None
452 zmin_coh = None
417 zmax_coh = None
453 zmax_coh = None
418 zmin_phase = None
454 zmin_phase = None
419 zmax_phase = None
455 zmax_phase = None
420
456
421 def setup(self):
457 def setup(self):
422
458
423 self.ncols = 4
459 self.ncols = 4
424 self.nrows = len(self.data.pairs)
460 self.nrows = len(self.data.pairs)
425 self.nplots = self.nrows*4
461 self.nplots = self.nrows*4
426 self.width = 3.4*self.ncols
462 self.width = 3.4*self.ncols
427 self.height = 3*self.nrows
463 self.height = 3*self.nrows
428 self.ylabel = 'Range [Km]'
464 self.ylabel = 'Range [Km]'
429 self.showprofile = False
465 self.showprofile = False
430
466
431 def plot(self):
467 def plot(self):
432
468
433 if self.xaxis == "frequency":
469 if self.xaxis == "frequency":
434 x = self.data.xrange[0]
470 x = self.data.xrange[0]
435 self.xlabel = "Frequency (kHz)"
471 self.xlabel = "Frequency (kHz)"
436 elif self.xaxis == "time":
472 elif self.xaxis == "time":
437 x = self.data.xrange[1]
473 x = self.data.xrange[1]
438 self.xlabel = "Time (ms)"
474 self.xlabel = "Time (ms)"
439 else:
475 else:
440 x = self.data.xrange[2]
476 x = self.data.xrange[2]
441 self.xlabel = "Velocity (m/s)"
477 self.xlabel = "Velocity (m/s)"
442
478
443 self.titles = []
479 self.titles = []
444
480
445 y = self.data.heights
481 y = self.data.heights
446 self.y = y
482 self.y = y
447 spc = self.data['spc']
483 spc = self.data['spc']
448 cspc = self.data['cspc']
484 cspc = self.data['cspc']
449
485
450 for n in range(self.nrows):
486 for n in range(self.nrows):
451 noise = self.data['noise'][n][-1]
487 noise = self.data['noise'][n][-1]
452 pair = self.data.pairs[n]
488 pair = self.data.pairs[n]
453 ax = self.axes[4*n]
489 ax = self.axes[4*n]
454 ax3 = self.axes[4*n+3]
490 ax3 = self.axes[4*n+3]
455 if ax.firsttime:
491 if ax.firsttime:
456 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
492 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
457 self.xmin = self.xmin if self.xmin else -self.xmax
493 self.xmin = self.xmin if self.xmin else -self.xmax
458 self.zmin = self.zmin if self.zmin else numpy.nanmin(spc)
494 self.zmin = self.zmin if self.zmin else numpy.nanmin(spc)
459 self.zmax = self.zmax if self.zmax else numpy.nanmax(spc)
495 self.zmax = self.zmax if self.zmax else numpy.nanmax(spc)
460 ax.plt = ax.pcolormesh(x, y, spc[pair[0]].T,
496 ax.plt = ax.pcolormesh(x, y, spc[pair[0]].T,
461 vmin=self.zmin,
497 vmin=self.zmin,
462 vmax=self.zmax,
498 vmax=self.zmax,
463 cmap=plt.get_cmap(self.colormap)
499 cmap=plt.get_cmap(self.colormap)
464 )
500 )
465 else:
501 else:
466 ax.plt.set_array(spc[pair[0]].T.ravel())
502 ax.plt.set_array(spc[pair[0]].T.ravel())
467 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
503 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
468
504
469 ax = self.axes[4*n+1]
505 ax = self.axes[4*n+1]
470 if ax.firsttime:
506 if ax.firsttime:
471 ax.plt = ax.pcolormesh(x, y, spc[pair[1]].T,
507 ax.plt = ax.pcolormesh(x, y, spc[pair[1]].T,
472 vmin=self.zmin,
508 vmin=self.zmin,
473 vmax=self.zmax,
509 vmax=self.zmax,
474 cmap=plt.get_cmap(self.colormap)
510 cmap=plt.get_cmap(self.colormap)
475 )
511 )
476 else:
512 else:
477 ax.plt.set_array(spc[pair[1]].T.ravel())
513 ax.plt.set_array(spc[pair[1]].T.ravel())
478 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
514 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
479
515
480 out = cspc[n]/numpy.sqrt(spc[pair[0]]*spc[pair[1]])
516 out = cspc[n]/numpy.sqrt(spc[pair[0]]*spc[pair[1]])
481 coh = numpy.abs(out)
517 coh = numpy.abs(out)
482 phase = numpy.arctan2(out.imag, out.real)*180/numpy.pi
518 phase = numpy.arctan2(out.imag, out.real)*180/numpy.pi
483
519
484 ax = self.axes[4*n+2]
520 ax = self.axes[4*n+2]
485 if ax.firsttime:
521 if ax.firsttime:
486 ax.plt = ax.pcolormesh(x, y, coh.T,
522 ax.plt = ax.pcolormesh(x, y, coh.T,
487 vmin=0,
523 vmin=0,
488 vmax=1,
524 vmax=1,
489 cmap=plt.get_cmap(self.colormap_coh)
525 cmap=plt.get_cmap(self.colormap_coh)
490 )
526 )
491 else:
527 else:
492 ax.plt.set_array(coh.T.ravel())
528 ax.plt.set_array(coh.T.ravel())
493 self.titles.append('Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
529 self.titles.append('Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
494
530
495 ax = self.axes[4*n+3]
531 ax = self.axes[4*n+3]
496 if ax.firsttime:
532 if ax.firsttime:
497 ax.plt = ax.pcolormesh(x, y, phase.T,
533 ax.plt = ax.pcolormesh(x, y, phase.T,
498 vmin=-180,
534 vmin=-180,
499 vmax=180,
535 vmax=180,
500 cmap=plt.get_cmap(self.colormap_phase)
536 cmap=plt.get_cmap(self.colormap_phase)
501 )
537 )
502 else:
538 else:
503 ax.plt.set_array(phase.T.ravel())
539 ax.plt.set_array(phase.T.ravel())
504 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
540 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
505
541
506 self.saveTime = self.max_time
542 self.saveTime = self.max_time
507
543
508
544
509 class PlotSpectraMeanData(PlotSpectraData):
545 class PlotSpectraMeanData(PlotSpectraData):
510 '''
546 '''
511 Plot for Spectra and Mean
547 Plot for Spectra and Mean
512 '''
548 '''
513 CODE = 'spc_mean'
549 CODE = 'spc_mean'
514 colormap = 'jro'
550 colormap = 'jro'
515
551
516
552
517 class PlotRTIData(PlotData):
553 class PlotRTIData(PlotData):
518 '''
554 '''
519 Plot for RTI data
555 Plot for RTI data
520 '''
556 '''
521
557
522 CODE = 'rti'
558 CODE = 'rti'
523 colormap = 'jro'
559 colormap = 'jro'
524
560
525 def setup(self):
561 def setup(self):
526 self.xaxis = 'time'
562 self.xaxis = 'time'
527 self.ncols = 1
563 self.ncols = 1
528 self.nrows = len(self.data.channels)
564 self.nrows = len(self.data.channels)
529 self.nplots = len(self.data.channels)
565 self.nplots = len(self.data.channels)
530 self.ylabel = 'Range [Km]'
566 self.ylabel = 'Range [Km]'
531 self.cb_label = 'dB'
567 self.cb_label = 'dB'
532 self.titles = ['{} Channel {}'.format(self.CODE.upper(), x) for x in range(self.nrows)]
568 self.titles = ['{} Channel {}'.format(self.CODE.upper(), x) for x in range(self.nrows)]
533
569
534 def plot(self):
570 def plot(self):
535 self.x = self.data.times
571 self.x = self.times
536 self.y = self.data.heights
572 self.y = self.data.heights
537 self.z = self.data[self.CODE]
573 self.z = self.data[self.CODE]
538 self.z = numpy.ma.masked_invalid(self.z)
574 self.z = numpy.ma.masked_invalid(self.z)
539
575
540 for n, ax in enumerate(self.axes):
576 for n, ax in enumerate(self.axes):
541 x, y, z = self.fill_gaps(*self.decimate())
577 x, y, z = self.fill_gaps(*self.decimate())
542 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
578 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
543 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
579 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
544 if ax.firsttime:
580 if ax.firsttime:
545 ax.plt = ax.pcolormesh(x, y, z[n].T,
581 ax.plt = ax.pcolormesh(x, y, z[n].T,
546 vmin=self.zmin,
582 vmin=self.zmin,
547 vmax=self.zmax,
583 vmax=self.zmax,
548 cmap=plt.get_cmap(self.colormap)
584 cmap=plt.get_cmap(self.colormap)
549 )
585 )
550 if self.showprofile:
586 if self.showprofile:
551 ax.plot_profile= self.pf_axes[n].plot(self.data['rti'][n][-1], self.y)[0]
587 ax.plot_profile= self.pf_axes[n].plot(self.data['rti'][n][-1], self.y)[0]
552 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y,
588 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y,
553 color="k", linestyle="dashed", lw=1)[0]
589 color="k", linestyle="dashed", lw=1)[0]
554 else:
590 else:
555 ax.collections.remove(ax.collections[0])
591 ax.collections.remove(ax.collections[0])
556 ax.plt = ax.pcolormesh(x, y, z[n].T,
592 ax.plt = ax.pcolormesh(x, y, z[n].T,
557 vmin=self.zmin,
593 vmin=self.zmin,
558 vmax=self.zmax,
594 vmax=self.zmax,
559 cmap=plt.get_cmap(self.colormap)
595 cmap=plt.get_cmap(self.colormap)
560 )
596 )
561 if self.showprofile:
597 if self.showprofile:
562 ax.plot_profile.set_data(self.data['rti'][n][-1], self.y)
598 ax.plot_profile.set_data(self.data['rti'][n][-1], self.y)
563 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y)
599 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y)
564
600
565 self.saveTime = self.min_time
601 self.saveTime = self.min_time
566
602
567
603
568 class PlotCOHData(PlotRTIData):
604 class PlotCOHData(PlotRTIData):
569 '''
605 '''
570 Plot for Coherence data
606 Plot for Coherence data
571 '''
607 '''
572
608
573 CODE = 'coh'
609 CODE = 'coh'
574
610
575 def setup(self):
611 def setup(self):
576 self.xaxis = 'time'
612 self.xaxis = 'time'
577 self.ncols = 1
613 self.ncols = 1
578 self.nrows = len(self.data.pairs)
614 self.nrows = len(self.data.pairs)
579 self.nplots = len(self.data.pairs)
615 self.nplots = len(self.data.pairs)
580 self.ylabel = 'Range [Km]'
616 self.ylabel = 'Range [Km]'
581 if self.CODE == 'coh':
617 if self.CODE == 'coh':
582 self.cb_label = ''
618 self.cb_label = ''
583 self.titles = ['Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
619 self.titles = ['Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
584 else:
620 else:
585 self.cb_label = 'Degrees'
621 self.cb_label = 'Degrees'
586 self.titles = ['Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
622 self.titles = ['Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
587
623
588
624
589 class PlotPHASEData(PlotCOHData):
625 class PlotPHASEData(PlotCOHData):
590 '''
626 '''
591 Plot for Phase map data
627 Plot for Phase map data
592 '''
628 '''
593
629
594 CODE = 'phase'
630 CODE = 'phase'
595 colormap = 'seismic'
631 colormap = 'seismic'
596
632
597
633
598 class PlotNoiseData(PlotData):
634 class PlotNoiseData(PlotData):
599 '''
635 '''
600 Plot for noise
636 Plot for noise
601 '''
637 '''
602
638
603 CODE = 'noise'
639 CODE = 'noise'
604
640
605 def setup(self):
641 def setup(self):
606 self.xaxis = 'time'
642 self.xaxis = 'time'
607 self.ncols = 1
643 self.ncols = 1
608 self.nrows = 1
644 self.nrows = 1
609 self.nplots = 1
645 self.nplots = 1
610 self.ylabel = 'Intensity [dB]'
646 self.ylabel = 'Intensity [dB]'
611 self.titles = ['Noise']
647 self.titles = ['Noise']
612 self.colorbar = False
648 self.colorbar = False
613
649
614 def plot(self):
650 def plot(self):
615
651
616 x = self.data.times
652 x = self.times
617 xmin = self.min_time
653 xmin = self.min_time
618 xmax = xmin+self.xrange*60*60
654 xmax = xmin+self.xrange*60*60
619 Y = self.data[self.CODE]
655 Y = self.data[self.CODE]
620
656
621 if self.axes[0].firsttime:
657 if self.axes[0].firsttime:
622 for ch in self.data.channels:
658 for ch in self.data.channels:
623 y = Y[ch]
659 y = Y[ch]
624 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
660 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
625 plt.legend()
661 plt.legend()
626 else:
662 else:
627 for ch in self.data.channels:
663 for ch in self.data.channels:
628 y = Y[ch]
664 y = Y[ch]
629 self.axes[0].lines[ch].set_data(x, y)
665 self.axes[0].lines[ch].set_data(x, y)
630
666
631 self.ymin = numpy.nanmin(Y) - 5
667 self.ymin = numpy.nanmin(Y) - 5
632 self.ymax = numpy.nanmax(Y) + 5
668 self.ymax = numpy.nanmax(Y) + 5
633 self.saveTime = self.min_time
669 self.saveTime = self.min_time
634
670
635
671
636 class PlotSNRData(PlotRTIData):
672 class PlotSNRData(PlotRTIData):
637 '''
673 '''
638 Plot for SNR Data
674 Plot for SNR Data
639 '''
675 '''
640
676
641 CODE = 'snr'
677 CODE = 'snr'
642 colormap = 'jet'
678 colormap = 'jet'
643
679
644
680
645 class PlotDOPData(PlotRTIData):
681 class PlotDOPData(PlotRTIData):
646 '''
682 '''
647 Plot for DOPPLER Data
683 Plot for DOPPLER Data
648 '''
684 '''
649
685
650 CODE = 'dop'
686 CODE = 'dop'
651 colormap = 'jet'
687 colormap = 'jet'
652
688
653
689
654 class PlotSkyMapData(PlotData):
690 class PlotSkyMapData(PlotData):
655 '''
691 '''
656 Plot for meteors detection data
692 Plot for meteors detection data
657 '''
693 '''
658
694
659 CODE = 'met'
695 CODE = 'met'
660
696
661 def setup(self):
697 def setup(self):
662
698
663 self.ncols = 1
699 self.ncols = 1
664 self.nrows = 1
700 self.nrows = 1
665 self.width = 7.2
701 self.width = 7.2
666 self.height = 7.2
702 self.height = 7.2
667
703
668 self.xlabel = 'Zonal Zenith Angle (deg)'
704 self.xlabel = 'Zonal Zenith Angle (deg)'
669 self.ylabel = 'Meridional Zenith Angle (deg)'
705 self.ylabel = 'Meridional Zenith Angle (deg)'
670
706
671 if self.figure is None:
707 if self.figure is None:
672 self.figure = plt.figure(figsize=(self.width, self.height),
708 self.figure = plt.figure(figsize=(self.width, self.height),
673 edgecolor='k',
709 edgecolor='k',
674 facecolor='w')
710 facecolor='w')
675 else:
711 else:
676 self.figure.clf()
712 self.figure.clf()
677
713
678 self.ax = plt.subplot2grid((self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
714 self.ax = plt.subplot2grid((self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
679 self.ax.firsttime = True
715 self.ax.firsttime = True
680
716
681
717
682 def plot(self):
718 def plot(self):
683
719
684 arrayParameters = numpy.concatenate([self.data['param'][t] for t in self.data.times])
720 arrayParameters = numpy.concatenate([self.data['param'][t] for t in self.times])
685 error = arrayParameters[:,-1]
721 error = arrayParameters[:,-1]
686 indValid = numpy.where(error == 0)[0]
722 indValid = numpy.where(error == 0)[0]
687 finalMeteor = arrayParameters[indValid,:]
723 finalMeteor = arrayParameters[indValid,:]
688 finalAzimuth = finalMeteor[:,3]
724 finalAzimuth = finalMeteor[:,3]
689 finalZenith = finalMeteor[:,4]
725 finalZenith = finalMeteor[:,4]
690
726
691 x = finalAzimuth*numpy.pi/180
727 x = finalAzimuth*numpy.pi/180
692 y = finalZenith
728 y = finalZenith
693
729
694 if self.ax.firsttime:
730 if self.ax.firsttime:
695 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
731 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
696 self.ax.set_ylim(0,90)
732 self.ax.set_ylim(0,90)
697 self.ax.set_yticks(numpy.arange(0,90,20))
733 self.ax.set_yticks(numpy.arange(0,90,20))
698 self.ax.set_xlabel(self.xlabel)
734 self.ax.set_xlabel(self.xlabel)
699 self.ax.set_ylabel(self.ylabel)
735 self.ax.set_ylabel(self.ylabel)
700 self.ax.yaxis.labelpad = 40
736 self.ax.yaxis.labelpad = 40
701 self.ax.firsttime = False
737 self.ax.firsttime = False
702 else:
738 else:
703 self.ax.plot.set_data(x, y)
739 self.ax.plot.set_data(x, y)
704
740
705
741
706 dt1 = datetime.datetime.fromtimestamp(self.min_time).strftime('%y/%m/%d %H:%M:%S')
742 dt1 = datetime.datetime.fromtimestamp(self.min_time).strftime('%y/%m/%d %H:%M:%S')
707 dt2 = datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')
743 dt2 = datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')
708 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
744 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
709 dt2,
745 dt2,
710 len(x))
746 len(x))
711 self.ax.set_title(title, size=8)
747 self.ax.set_title(title, size=8)
712
748
713 self.saveTime = self.max_time
749 self.saveTime = self.max_time
714
750
715 class PlotParamData(PlotRTIData):
751 class PlotParamData(PlotRTIData):
716 '''
752 '''
717 Plot for data_param object
753 Plot for data_param object
718 '''
754 '''
719
755
720 CODE = 'param'
756 CODE = 'param'
721 colormap = 'seismic'
757 colormap = 'seismic'
722
758
723 def setup(self):
759 def setup(self):
724 self.xaxis = 'time'
760 self.xaxis = 'time'
725 self.ncols = 1
761 self.ncols = 1
726 self.nrows = self.data.shape(self.CODE)[0]
762 self.nrows = self.data.shape(self.CODE)[0]
727 self.nplots = self.nrows
763 self.nplots = self.nrows
728 if self.showSNR:
764 if self.showSNR:
729 self.nrows += 1
765 self.nrows += 1
766 self.nplots += 1
730
767
731 self.ylabel = 'Height [Km]'
768 self.ylabel = 'Height [Km]'
732 self.titles = self.data.parameters \
769 self.titles = self.data.parameters \
733 if self.data.parameters else ['Param {}'.format(x) for x in xrange(self.nrows)]
770 if self.data.parameters else ['Param {}'.format(x) for x in xrange(self.nrows)]
734 if self.showSNR:
771 if self.showSNR:
735 self.titles.append('SNR')
772 self.titles.append('SNR')
736
773
737 def plot(self):
774 def plot(self):
738 self.data.normalize_heights()
775 self.data.normalize_heights()
739 self.x = self.data.times
776 self.x = self.times
740 self.y = self.data.heights
777 self.y = self.data.heights
741 if self.showSNR:
778 if self.showSNR:
742 self.z = numpy.concatenate(
779 self.z = numpy.concatenate(
743 (self.data[self.CODE], self.data['snr'])
780 (self.data[self.CODE], self.data['snr'])
744 )
781 )
745 else:
782 else:
746 self.z = self.data[self.CODE]
783 self.z = self.data[self.CODE]
747
784
748 self.z = numpy.ma.masked_invalid(self.z)
785 self.z = numpy.ma.masked_invalid(self.z)
749
786
750 for n, ax in enumerate(self.axes):
787 for n, ax in enumerate(self.axes):
751
788
752 x, y, z = self.fill_gaps(*self.decimate())
789 x, y, z = self.fill_gaps(*self.decimate())
753
790
754 if ax.firsttime:
791 if ax.firsttime:
755 if self.zlimits is not None:
792 if self.zlimits is not None:
756 self.zmin, self.zmax = self.zlimits[n]
793 self.zmin, self.zmax = self.zlimits[n]
757 self.zmax = self.zmax if self.zmax is not None else numpy.nanmax(abs(self.z[:-1, :]))
794 self.zmax = self.zmax if self.zmax is not None else numpy.nanmax(abs(self.z[:-1, :]))
758 self.zmin = self.zmin if self.zmin is not None else -self.zmax
795 self.zmin = self.zmin if self.zmin is not None else -self.zmax
759 ax.plt = ax.pcolormesh(x, y, z[n, :, :].T*self.factors[n],
796 ax.plt = ax.pcolormesh(x, y, z[n, :, :].T*self.factors[n],
760 vmin=self.zmin,
797 vmin=self.zmin,
761 vmax=self.zmax,
798 vmax=self.zmax,
762 cmap=self.cmaps[n]
799 cmap=self.cmaps[n]
763 )
800 )
764 else:
801 else:
765 if self.zlimits is not None:
802 if self.zlimits is not None:
766 self.zmin, self.zmax = self.zlimits[n]
803 self.zmin, self.zmax = self.zlimits[n]
767 ax.collections.remove(ax.collections[0])
804 ax.collections.remove(ax.collections[0])
768 ax.plt = ax.pcolormesh(x, y, z[n, :, :].T*self.factors[n],
805 ax.plt = ax.pcolormesh(x, y, z[n, :, :].T*self.factors[n],
769 vmin=self.zmin,
806 vmin=self.zmin,
770 vmax=self.zmax,
807 vmax=self.zmax,
771 cmap=self.cmaps[n]
808 cmap=self.cmaps[n]
772 )
809 )
773
810
774 self.saveTime = self.min_time
811 self.saveTime = self.min_time
775
812
776 class PlotOuputData(PlotParamData):
813 class PlotOuputData(PlotParamData):
777 '''
814 '''
778 Plot data_output object
815 Plot data_output object
779 '''
816 '''
780
817
781 CODE = 'output'
818 CODE = 'output'
782 colormap = 'seismic' No newline at end of file
819 colormap = 'seismic'
@@ -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,2151
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 def __init__(self, **kwargs):
228 def __init__(self, **kwargs):
18 Figure.__init__(self, **kwargs)
229 Figure.__init__(self, **kwargs)
19 self.isConfig = False
230 self.isConfig = False
20 self.__nsubplots = 1
231 self.__nsubplots = 1
21
232
22 self.WIDTH = 280
233 self.WIDTH = 280
23 self.HEIGHT = 250
234 self.HEIGHT = 250
24 self.WIDTHPROF = 120
235 self.WIDTHPROF = 120
25 self.HEIGHTPROF = 0
236 self.HEIGHTPROF = 0
26 self.counter_imagwr = 0
237 self.counter_imagwr = 0
27
238
28 self.PLOT_CODE = MOMENTS_CODE
239 self.PLOT_CODE = MOMENTS_CODE
29
240
30 self.FTP_WEI = None
241 self.FTP_WEI = None
31 self.EXP_CODE = None
242 self.EXP_CODE = None
32 self.SUB_EXP_CODE = None
243 self.SUB_EXP_CODE = None
33 self.PLOT_POS = None
244 self.PLOT_POS = None
34
245
35 def getSubplots(self):
246 def getSubplots(self):
36
247
37 ncol = int(numpy.sqrt(self.nplots)+0.9)
248 ncol = int(numpy.sqrt(self.nplots)+0.9)
38 nrow = int(self.nplots*1./ncol + 0.9)
249 nrow = int(self.nplots*1./ncol + 0.9)
39
250
40 return nrow, ncol
251 return nrow, ncol
41
252
42 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
253 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
43
254
44 self.__showprofile = showprofile
255 self.__showprofile = showprofile
45 self.nplots = nplots
256 self.nplots = nplots
46
257
47 ncolspan = 1
258 ncolspan = 1
48 colspan = 1
259 colspan = 1
49 if showprofile:
260 if showprofile:
50 ncolspan = 3
261 ncolspan = 3
51 colspan = 2
262 colspan = 2
52 self.__nsubplots = 2
263 self.__nsubplots = 2
53
264
54 self.createFigure(id = id,
265 self.createFigure(id = id,
55 wintitle = wintitle,
266 wintitle = wintitle,
56 widthplot = self.WIDTH + self.WIDTHPROF,
267 widthplot = self.WIDTH + self.WIDTHPROF,
57 heightplot = self.HEIGHT + self.HEIGHTPROF,
268 heightplot = self.HEIGHT + self.HEIGHTPROF,
58 show=show)
269 show=show)
59
270
60 nrow, ncol = self.getSubplots()
271 nrow, ncol = self.getSubplots()
61
272
62 counter = 0
273 counter = 0
63 for y in range(nrow):
274 for y in range(nrow):
64 for x in range(ncol):
275 for x in range(ncol):
65
276
66 if counter >= self.nplots:
277 if counter >= self.nplots:
67 break
278 break
68
279
69 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
280 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
70
281
71 if showprofile:
282 if showprofile:
72 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
283 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
73
284
74 counter += 1
285 counter += 1
75
286
76 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
287 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
77 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
288 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,
289 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
79 server=None, folder=None, username=None, password=None,
290 server=None, folder=None, username=None, password=None,
80 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
291 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
81
292
82 """
293 """
83
294
84 Input:
295 Input:
85 dataOut :
296 dataOut :
86 id :
297 id :
87 wintitle :
298 wintitle :
88 channelList :
299 channelList :
89 showProfile :
300 showProfile :
90 xmin : None,
301 xmin : None,
91 xmax : None,
302 xmax : None,
92 ymin : None,
303 ymin : None,
93 ymax : None,
304 ymax : None,
94 zmin : None,
305 zmin : None,
95 zmax : None
306 zmax : None
96 """
307 """
97
308
98 if dataOut.flagNoData:
309 if dataOut.flagNoData:
99 return None
310 return None
100
311
101 if realtime:
312 if realtime:
102 if not(isRealtime(utcdatatime = dataOut.utctime)):
313 if not(isRealtime(utcdatatime = dataOut.utctime)):
103 print 'Skipping this plot function'
314 print 'Skipping this plot function'
104 return
315 return
105
316
106 if channelList == None:
317 if channelList == None:
107 channelIndexList = dataOut.channelIndexList
318 channelIndexList = dataOut.channelIndexList
108 else:
319 else:
109 channelIndexList = []
320 channelIndexList = []
110 for channel in channelList:
321 for channel in channelList:
111 if channel not in dataOut.channelList:
322 if channel not in dataOut.channelList:
112 raise ValueError, "Channel %d is not in dataOut.channelList"
323 raise ValueError, "Channel %d is not in dataOut.channelList"
113 channelIndexList.append(dataOut.channelList.index(channel))
324 channelIndexList.append(dataOut.channelList.index(channel))
114
325
115 factor = dataOut.normFactor
326 factor = dataOut.normFactor
116 x = dataOut.abscissaList
327 x = dataOut.abscissaList
117 y = dataOut.heightList
328 y = dataOut.heightList
118
329
119 z = dataOut.data_pre[channelIndexList,:,:]/factor
330 z = dataOut.data_pre[channelIndexList,:,:]/factor
120 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
331 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
121 avg = numpy.average(z, axis=1)
332 avg = numpy.average(z, axis=1)
122 noise = dataOut.noise/factor
333 noise = dataOut.noise/factor
123
334
124 zdB = 10*numpy.log10(z)
335 zdB = 10*numpy.log10(z)
125 avgdB = 10*numpy.log10(avg)
336 avgdB = 10*numpy.log10(avg)
126 noisedB = 10*numpy.log10(noise)
337 noisedB = 10*numpy.log10(noise)
127
338
128 #thisDatetime = dataOut.datatime
339 #thisDatetime = dataOut.datatime
129 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
340 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
130 title = wintitle + " Parameters"
341 title = wintitle + " Parameters"
131 xlabel = "Velocity (m/s)"
342 xlabel = "Velocity (m/s)"
132 ylabel = "Range (Km)"
343 ylabel = "Range (Km)"
133
344
134 update_figfile = False
345 update_figfile = False
135
346
136 if not self.isConfig:
347 if not self.isConfig:
137
348
138 nplots = len(channelIndexList)
349 nplots = len(channelIndexList)
139
350
140 self.setup(id=id,
351 self.setup(id=id,
141 nplots=nplots,
352 nplots=nplots,
142 wintitle=wintitle,
353 wintitle=wintitle,
143 showprofile=showprofile,
354 showprofile=showprofile,
144 show=show)
355 show=show)
145
356
146 if xmin == None: xmin = numpy.nanmin(x)
357 if xmin == None: xmin = numpy.nanmin(x)
147 if xmax == None: xmax = numpy.nanmax(x)
358 if xmax == None: xmax = numpy.nanmax(x)
148 if ymin == None: ymin = numpy.nanmin(y)
359 if ymin == None: ymin = numpy.nanmin(y)
149 if ymax == None: ymax = numpy.nanmax(y)
360 if ymax == None: ymax = numpy.nanmax(y)
150 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
361 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
151 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
362 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
152
363
153 self.FTP_WEI = ftp_wei
364 self.FTP_WEI = ftp_wei
154 self.EXP_CODE = exp_code
365 self.EXP_CODE = exp_code
155 self.SUB_EXP_CODE = sub_exp_code
366 self.SUB_EXP_CODE = sub_exp_code
156 self.PLOT_POS = plot_pos
367 self.PLOT_POS = plot_pos
157
368
158 self.isConfig = True
369 self.isConfig = True
159 update_figfile = True
370 update_figfile = True
160
371
161 self.setWinTitle(title)
372 self.setWinTitle(title)
162
373
163 for i in range(self.nplots):
374 for i in range(self.nplots):
164 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
375 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
165 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
376 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
166 axes = self.axesList[i*self.__nsubplots]
377 axes = self.axesList[i*self.__nsubplots]
167 axes.pcolor(x, y, zdB[i,:,:],
378 axes.pcolor(x, y, zdB[i,:,:],
168 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
379 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
169 xlabel=xlabel, ylabel=ylabel, title=title,
380 xlabel=xlabel, ylabel=ylabel, title=title,
170 ticksize=9, cblabel='')
381 ticksize=9, cblabel='')
171 #Mean Line
382 #Mean Line
172 mean = dataOut.data_param[i, 1, :]
383 mean = dataOut.data_param[i, 1, :]
173 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
384 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
174
385
175 if self.__showprofile:
386 if self.__showprofile:
176 axes = self.axesList[i*self.__nsubplots +1]
387 axes = self.axesList[i*self.__nsubplots +1]
177 axes.pline(avgdB[i], y,
388 axes.pline(avgdB[i], y,
178 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
389 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
179 xlabel='dB', ylabel='', title='',
390 xlabel='dB', ylabel='', title='',
180 ytick_visible=False,
391 ytick_visible=False,
181 grid='x')
392 grid='x')
182
393
183 noiseline = numpy.repeat(noisedB[i], len(y))
394 noiseline = numpy.repeat(noisedB[i], len(y))
184 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
395 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
185
396
186 self.draw()
397 self.draw()
187
398
188 self.save(figpath=figpath,
399 self.save(figpath=figpath,
189 figfile=figfile,
400 figfile=figfile,
190 save=save,
401 save=save,
191 ftp=ftp,
402 ftp=ftp,
192 wr_period=wr_period,
403 wr_period=wr_period,
193 thisDatetime=thisDatetime)
404 thisDatetime=thisDatetime)
194
405
195
406
196
407
197 class SkyMapPlot(Figure):
408 class SkyMapPlot(Figure):
198
409
199 __isConfig = None
410 __isConfig = None
200 __nsubplots = None
411 __nsubplots = None
201
412
202 WIDTHPROF = None
413 WIDTHPROF = None
203 HEIGHTPROF = None
414 HEIGHTPROF = None
204 PREFIX = 'mmap'
415 PREFIX = 'mmap'
205
416
206 def __init__(self, **kwargs):
417 def __init__(self, **kwargs):
207 Figure.__init__(self, **kwargs)
418 Figure.__init__(self, **kwargs)
208 self.isConfig = False
419 self.isConfig = False
209 self.__nsubplots = 1
420 self.__nsubplots = 1
210
421
211 # self.WIDTH = 280
422 # self.WIDTH = 280
212 # self.HEIGHT = 250
423 # self.HEIGHT = 250
213 self.WIDTH = 600
424 self.WIDTH = 600
214 self.HEIGHT = 600
425 self.HEIGHT = 600
215 self.WIDTHPROF = 120
426 self.WIDTHPROF = 120
216 self.HEIGHTPROF = 0
427 self.HEIGHTPROF = 0
217 self.counter_imagwr = 0
428 self.counter_imagwr = 0
218
429
219 self.PLOT_CODE = MSKYMAP_CODE
430 self.PLOT_CODE = MSKYMAP_CODE
220
431
221 self.FTP_WEI = None
432 self.FTP_WEI = None
222 self.EXP_CODE = None
433 self.EXP_CODE = None
223 self.SUB_EXP_CODE = None
434 self.SUB_EXP_CODE = None
224 self.PLOT_POS = None
435 self.PLOT_POS = None
225
436
226 def getSubplots(self):
437 def getSubplots(self):
227
438
228 ncol = int(numpy.sqrt(self.nplots)+0.9)
439 ncol = int(numpy.sqrt(self.nplots)+0.9)
229 nrow = int(self.nplots*1./ncol + 0.9)
440 nrow = int(self.nplots*1./ncol + 0.9)
230
441
231 return nrow, ncol
442 return nrow, ncol
232
443
233 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
444 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
234
445
235 self.__showprofile = showprofile
446 self.__showprofile = showprofile
236 self.nplots = nplots
447 self.nplots = nplots
237
448
238 ncolspan = 1
449 ncolspan = 1
239 colspan = 1
450 colspan = 1
240
451
241 self.createFigure(id = id,
452 self.createFigure(id = id,
242 wintitle = wintitle,
453 wintitle = wintitle,
243 widthplot = self.WIDTH, #+ self.WIDTHPROF,
454 widthplot = self.WIDTH, #+ self.WIDTHPROF,
244 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
455 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
245 show=show)
456 show=show)
246
457
247 nrow, ncol = 1,1
458 nrow, ncol = 1,1
248 counter = 0
459 counter = 0
249 x = 0
460 x = 0
250 y = 0
461 y = 0
251 self.addAxes(1, 1, 0, 0, 1, 1, True)
462 self.addAxes(1, 1, 0, 0, 1, 1, True)
252
463
253 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
464 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
254 tmin=0, tmax=24, timerange=None,
465 tmin=0, tmax=24, timerange=None,
255 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
466 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
256 server=None, folder=None, username=None, password=None,
467 server=None, folder=None, username=None, password=None,
257 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
468 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
258
469
259 """
470 """
260
471
261 Input:
472 Input:
262 dataOut :
473 dataOut :
263 id :
474 id :
264 wintitle :
475 wintitle :
265 channelList :
476 channelList :
266 showProfile :
477 showProfile :
267 xmin : None,
478 xmin : None,
268 xmax : None,
479 xmax : None,
269 ymin : None,
480 ymin : None,
270 ymax : None,
481 ymax : None,
271 zmin : None,
482 zmin : None,
272 zmax : None
483 zmax : None
273 """
484 """
274
485
275 arrayParameters = dataOut.data_param
486 arrayParameters = dataOut.data_param
276 error = arrayParameters[:,-1]
487 error = arrayParameters[:,-1]
277 indValid = numpy.where(error == 0)[0]
488 indValid = numpy.where(error == 0)[0]
278 finalMeteor = arrayParameters[indValid,:]
489 finalMeteor = arrayParameters[indValid,:]
279 finalAzimuth = finalMeteor[:,3]
490 finalAzimuth = finalMeteor[:,3]
280 finalZenith = finalMeteor[:,4]
491 finalZenith = finalMeteor[:,4]
281
492
282 x = finalAzimuth*numpy.pi/180
493 x = finalAzimuth*numpy.pi/180
283 y = finalZenith
494 y = finalZenith
284 x1 = [dataOut.ltctime, dataOut.ltctime]
495 x1 = [dataOut.ltctime, dataOut.ltctime]
285
496
286 #thisDatetime = dataOut.datatime
497 #thisDatetime = dataOut.datatime
287 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
498 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
288 title = wintitle + " Parameters"
499 title = wintitle + " Parameters"
289 xlabel = "Zonal Zenith Angle (deg) "
500 xlabel = "Zonal Zenith Angle (deg) "
290 ylabel = "Meridional Zenith Angle (deg)"
501 ylabel = "Meridional Zenith Angle (deg)"
291 update_figfile = False
502 update_figfile = False
292
503
293 if not self.isConfig:
504 if not self.isConfig:
294
505
295 nplots = 1
506 nplots = 1
296
507
297 self.setup(id=id,
508 self.setup(id=id,
298 nplots=nplots,
509 nplots=nplots,
299 wintitle=wintitle,
510 wintitle=wintitle,
300 showprofile=showprofile,
511 showprofile=showprofile,
301 show=show)
512 show=show)
302
513
303 if self.xmin is None and self.xmax is None:
514 if self.xmin is None and self.xmax is None:
304 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
515 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
305
516
306 if timerange != None:
517 if timerange != None:
307 self.timerange = timerange
518 self.timerange = timerange
308 else:
519 else:
309 self.timerange = self.xmax - self.xmin
520 self.timerange = self.xmax - self.xmin
310
521
311 self.FTP_WEI = ftp_wei
522 self.FTP_WEI = ftp_wei
312 self.EXP_CODE = exp_code
523 self.EXP_CODE = exp_code
313 self.SUB_EXP_CODE = sub_exp_code
524 self.SUB_EXP_CODE = sub_exp_code
314 self.PLOT_POS = plot_pos
525 self.PLOT_POS = plot_pos
315 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
526 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
316 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
527 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
317 self.isConfig = True
528 self.isConfig = True
318 update_figfile = True
529 update_figfile = True
319
530
320 self.setWinTitle(title)
531 self.setWinTitle(title)
321
532
322 i = 0
533 i = 0
323 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
534 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
324
535
325 axes = self.axesList[i*self.__nsubplots]
536 axes = self.axesList[i*self.__nsubplots]
326 nevents = axes.x_buffer.shape[0] + x.shape[0]
537 nevents = axes.x_buffer.shape[0] + x.shape[0]
327 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
538 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
328 axes.polar(x, y,
539 axes.polar(x, y,
329 title=title, xlabel=xlabel, ylabel=ylabel,
540 title=title, xlabel=xlabel, ylabel=ylabel,
330 ticksize=9, cblabel='')
541 ticksize=9, cblabel='')
331
542
332 self.draw()
543 self.draw()
333
544
334 self.save(figpath=figpath,
545 self.save(figpath=figpath,
335 figfile=figfile,
546 figfile=figfile,
336 save=save,
547 save=save,
337 ftp=ftp,
548 ftp=ftp,
338 wr_period=wr_period,
549 wr_period=wr_period,
339 thisDatetime=thisDatetime,
550 thisDatetime=thisDatetime,
340 update_figfile=update_figfile)
551 update_figfile=update_figfile)
341
552
342 if dataOut.ltctime >= self.xmax:
553 if dataOut.ltctime >= self.xmax:
343 self.isConfigmagwr = wr_period
554 self.isConfigmagwr = wr_period
344 self.isConfig = False
555 self.isConfig = False
345 update_figfile = True
556 update_figfile = True
346 axes.__firsttime = True
557 axes.__firsttime = True
347 self.xmin += self.timerange
558 self.xmin += self.timerange
348 self.xmax += self.timerange
559 self.xmax += self.timerange
349
560
350
561
351
562
352
563
353 class WindProfilerPlot(Figure):
564 class WindProfilerPlot(Figure):
354
565
355 __isConfig = None
566 __isConfig = None
356 __nsubplots = None
567 __nsubplots = None
357
568
358 WIDTHPROF = None
569 WIDTHPROF = None
359 HEIGHTPROF = None
570 HEIGHTPROF = None
360 PREFIX = 'wind'
571 PREFIX = 'wind'
361
572
362 def __init__(self, **kwargs):
573 def __init__(self, **kwargs):
363 Figure.__init__(self, **kwargs)
574 Figure.__init__(self, **kwargs)
364 self.timerange = None
575 self.timerange = None
365 self.isConfig = False
576 self.isConfig = False
366 self.__nsubplots = 1
577 self.__nsubplots = 1
367
578
368 self.WIDTH = 800
579 self.WIDTH = 800
369 self.HEIGHT = 300
580 self.HEIGHT = 300
370 self.WIDTHPROF = 120
581 self.WIDTHPROF = 120
371 self.HEIGHTPROF = 0
582 self.HEIGHTPROF = 0
372 self.counter_imagwr = 0
583 self.counter_imagwr = 0
373
584
374 self.PLOT_CODE = WIND_CODE
585 self.PLOT_CODE = WIND_CODE
375
586
376 self.FTP_WEI = None
587 self.FTP_WEI = None
377 self.EXP_CODE = None
588 self.EXP_CODE = None
378 self.SUB_EXP_CODE = None
589 self.SUB_EXP_CODE = None
379 self.PLOT_POS = None
590 self.PLOT_POS = None
380 self.tmin = None
591 self.tmin = None
381 self.tmax = None
592 self.tmax = None
382
593
383 self.xmin = None
594 self.xmin = None
384 self.xmax = None
595 self.xmax = None
385
596
386 self.figfile = None
597 self.figfile = None
387
598
388 def getSubplots(self):
599 def getSubplots(self):
389
600
390 ncol = 1
601 ncol = 1
391 nrow = self.nplots
602 nrow = self.nplots
392
603
393 return nrow, ncol
604 return nrow, ncol
394
605
395 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
606 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
396
607
397 self.__showprofile = showprofile
608 self.__showprofile = showprofile
398 self.nplots = nplots
609 self.nplots = nplots
399
610
400 ncolspan = 1
611 ncolspan = 1
401 colspan = 1
612 colspan = 1
402
613
403 self.createFigure(id = id,
614 self.createFigure(id = id,
404 wintitle = wintitle,
615 wintitle = wintitle,
405 widthplot = self.WIDTH + self.WIDTHPROF,
616 widthplot = self.WIDTH + self.WIDTHPROF,
406 heightplot = self.HEIGHT + self.HEIGHTPROF,
617 heightplot = self.HEIGHT + self.HEIGHTPROF,
407 show=show)
618 show=show)
408
619
409 nrow, ncol = self.getSubplots()
620 nrow, ncol = self.getSubplots()
410
621
411 counter = 0
622 counter = 0
412 for y in range(nrow):
623 for y in range(nrow):
413 if counter >= self.nplots:
624 if counter >= self.nplots:
414 break
625 break
415
626
416 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
627 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
417 counter += 1
628 counter += 1
418
629
419 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
630 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
420 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
631 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
421 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
632 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
422 timerange=None, SNRthresh = None,
633 timerange=None, SNRthresh = None,
423 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
634 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
424 server=None, folder=None, username=None, password=None,
635 server=None, folder=None, username=None, password=None,
425 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
636 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
426 """
637 """
427
638
428 Input:
639 Input:
429 dataOut :
640 dataOut :
430 id :
641 id :
431 wintitle :
642 wintitle :
432 channelList :
643 channelList :
433 showProfile :
644 showProfile :
434 xmin : None,
645 xmin : None,
435 xmax : None,
646 xmax : None,
436 ymin : None,
647 ymin : None,
437 ymax : None,
648 ymax : None,
438 zmin : None,
649 zmin : None,
439 zmax : None
650 zmax : None
440 """
651 """
441
652
442 # if timerange is not None:
653 # if timerange is not None:
443 # self.timerange = timerange
654 # self.timerange = timerange
444 #
655 #
445 # tmin = None
656 # tmin = None
446 # tmax = None
657 # tmax = None
447
658
448
659 x = dataOut.getTimeRange1(dataOut.paramInterval)
449 x = dataOut.getTimeRange1(dataOut.outputInterval)
660 y = dataOut.heightList
450 y = dataOut.heightList
661 z = dataOut.data_output.copy()
451 z = dataOut.data_output.copy()
452 nplots = z.shape[0] #Number of wind dimensions estimated
662 nplots = z.shape[0] #Number of wind dimensions estimated
453 nplotsw = nplots
663 nplotsw = nplots
454
664
455
665
456 #If there is a SNR function defined
666 #If there is a SNR function defined
457 if dataOut.data_SNR is not None:
667 if dataOut.data_SNR is not None:
458 nplots += 1
668 nplots += 1
459 SNR = dataOut.data_SNR
669 SNR = dataOut.data_SNR
460 SNRavg = numpy.average(SNR, axis=0)
670 SNRavg = numpy.average(SNR, axis=0)
461
671
462 SNRdB = 10*numpy.log10(SNR)
672 SNRdB = 10*numpy.log10(SNR)
463 SNRavgdB = 10*numpy.log10(SNRavg)
673 SNRavgdB = 10*numpy.log10(SNRavg)
464
674
465 if SNRthresh == None: SNRthresh = -5.0
675 if SNRthresh == None: SNRthresh = -5.0
466 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
676 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
467
677
468 for i in range(nplotsw):
678 for i in range(nplotsw):
469 z[i,ind] = numpy.nan
679 z[i,ind] = numpy.nan
470
680
471 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
681 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
472 #thisDatetime = datetime.datetime.now()
682 #thisDatetime = datetime.datetime.now()
473 title = wintitle + "Wind"
683 title = wintitle + "Wind"
474 xlabel = ""
684 xlabel = ""
475 ylabel = "Height (km)"
685 ylabel = "Height (km)"
476 update_figfile = False
686 update_figfile = False
477
687
478 if not self.isConfig:
688 if not self.isConfig:
479
689
480 self.setup(id=id,
690 self.setup(id=id,
481 nplots=nplots,
691 nplots=nplots,
482 wintitle=wintitle,
692 wintitle=wintitle,
483 showprofile=showprofile,
693 showprofile=showprofile,
484 show=show)
694 show=show)
485
695
486 if timerange is not None:
696 if timerange is not None:
487 self.timerange = timerange
697 self.timerange = timerange
488
698
489 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
699 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
490
700
491 if ymin == None: ymin = numpy.nanmin(y)
701 if ymin == None: ymin = numpy.nanmin(y)
492 if ymax == None: ymax = numpy.nanmax(y)
702 if ymax == None: ymax = numpy.nanmax(y)
493
703
494 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
704 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
495 #if numpy.isnan(zmax): zmax = 50
705 #if numpy.isnan(zmax): zmax = 50
496 if zmin == None: zmin = -zmax
706 if zmin == None: zmin = -zmax
497
707
498 if nplotsw == 3:
708 if nplotsw == 3:
499 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
709 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
500 if zmin_ver == None: zmin_ver = -zmax_ver
710 if zmin_ver == None: zmin_ver = -zmax_ver
501
711
502 if dataOut.data_SNR is not None:
712 if dataOut.data_SNR is not None:
503 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
713 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
504 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
714 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
505
715
506
716
507 self.FTP_WEI = ftp_wei
717 self.FTP_WEI = ftp_wei
508 self.EXP_CODE = exp_code
718 self.EXP_CODE = exp_code
509 self.SUB_EXP_CODE = sub_exp_code
719 self.SUB_EXP_CODE = sub_exp_code
510 self.PLOT_POS = plot_pos
720 self.PLOT_POS = plot_pos
511
721
512 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
722 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
513 self.isConfig = True
723 self.isConfig = True
514 self.figfile = figfile
724 self.figfile = figfile
515 update_figfile = True
725 update_figfile = True
516
726
517 self.setWinTitle(title)
727 self.setWinTitle(title)
518
728
519 if ((self.xmax - x[1]) < (x[1]-x[0])):
729 if ((self.xmax - x[1]) < (x[1]-x[0])):
520 x[1] = self.xmax
730 x[1] = self.xmax
521
731
522 strWind = ['Zonal', 'Meridional', 'Vertical']
732 strWind = ['Zonal', 'Meridional', 'Vertical']
523 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
733 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
524 zmaxVector = [zmax, zmax, zmax_ver]
734 zmaxVector = [zmax, zmax, zmax_ver]
525 zminVector = [zmin, zmin, zmin_ver]
735 zminVector = [zmin, zmin, zmin_ver]
526 windFactor = [1,1,100]
736 windFactor = [1,1,100]
527
737
528 for i in range(nplotsw):
738 for i in range(nplotsw):
529
739
530 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
740 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
531 axes = self.axesList[i*self.__nsubplots]
741 axes = self.axesList[i*self.__nsubplots]
532
742
533 z1 = z[i,:].reshape((1,-1))*windFactor[i]
743 z1 = z[i,:].reshape((1,-1))*windFactor[i]
534 #z1=numpy.ma.masked_where(z1==0.,z1)
744 #z1=numpy.ma.masked_where(z1==0.,z1)
535
745
536 axes.pcolorbuffer(x, y, z1,
746 axes.pcolorbuffer(x, y, z1,
537 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
747 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
538 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
748 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
539 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
749 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
540
750
541 if dataOut.data_SNR is not None:
751 if dataOut.data_SNR is not None:
542 i += 1
752 i += 1
543 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
753 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
544 axes = self.axesList[i*self.__nsubplots]
754 axes = self.axesList[i*self.__nsubplots]
545 SNRavgdB = SNRavgdB.reshape((1,-1))
755 SNRavgdB = SNRavgdB.reshape((1,-1))
546 axes.pcolorbuffer(x, y, SNRavgdB,
756 axes.pcolorbuffer(x, y, SNRavgdB,
547 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
757 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
548 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
758 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
549 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
759 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
550
760
551 self.draw()
761 self.draw()
552
762
553 self.save(figpath=figpath,
763 self.save(figpath=figpath,
554 figfile=figfile,
764 figfile=figfile,
555 save=save,
765 save=save,
556 ftp=ftp,
766 ftp=ftp,
557 wr_period=wr_period,
767 wr_period=wr_period,
558 thisDatetime=thisDatetime,
768 thisDatetime=thisDatetime,
559 update_figfile=update_figfile)
769 update_figfile=update_figfile)
560
770
561 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
771 if dataOut.ltctime + dataOut.paramInterval >= self.xmax:
562 self.counter_imagwr = wr_period
772 self.counter_imagwr = wr_period
563 self.isConfig = False
773 self.isConfig = False
564 update_figfile = True
774 update_figfile = True
565
775
566
776
567 class ParametersPlot(Figure):
777 class ParametersPlot(Figure):
568
778
569 __isConfig = None
779 __isConfig = None
570 __nsubplots = None
780 __nsubplots = None
571
781
572 WIDTHPROF = None
782 WIDTHPROF = None
573 HEIGHTPROF = None
783 HEIGHTPROF = None
574 PREFIX = 'param'
784 PREFIX = 'param'
575
785
576 nplots = None
786 nplots = None
577 nchan = None
787 nchan = None
578
788
579 def __init__(self, **kwargs):
789 def __init__(self, **kwargs):
580 Figure.__init__(self, **kwargs)
790 Figure.__init__(self, **kwargs)
581 self.timerange = None
791 self.timerange = None
582 self.isConfig = False
792 self.isConfig = False
583 self.__nsubplots = 1
793 self.__nsubplots = 1
584
794
585 self.WIDTH = 800
795 self.WIDTH = 800
586 self.HEIGHT = 180
796 self.HEIGHT = 180
587 self.WIDTHPROF = 120
797 self.WIDTHPROF = 120
588 self.HEIGHTPROF = 0
798 self.HEIGHTPROF = 0
589 self.counter_imagwr = 0
799 self.counter_imagwr = 0
590
800
591 self.PLOT_CODE = RTI_CODE
801 self.PLOT_CODE = RTI_CODE
592
802
593 self.FTP_WEI = None
803 self.FTP_WEI = None
594 self.EXP_CODE = None
804 self.EXP_CODE = None
595 self.SUB_EXP_CODE = None
805 self.SUB_EXP_CODE = None
596 self.PLOT_POS = None
806 self.PLOT_POS = None
597 self.tmin = None
807 self.tmin = None
598 self.tmax = None
808 self.tmax = None
599
809
600 self.xmin = None
810 self.xmin = None
601 self.xmax = None
811 self.xmax = None
602
812
603 self.figfile = None
813 self.figfile = None
604
814
605 def getSubplots(self):
815 def getSubplots(self):
606
816
607 ncol = 1
817 ncol = 1
608 nrow = self.nplots
818 nrow = self.nplots
609
819
610 return nrow, ncol
820 return nrow, ncol
611
821
612 def setup(self, id, nplots, wintitle, show=True):
822 def setup(self, id, nplots, wintitle, show=True):
613
823
614 self.nplots = nplots
824 self.nplots = nplots
615
825
616 ncolspan = 1
826 ncolspan = 1
617 colspan = 1
827 colspan = 1
618
828
619 self.createFigure(id = id,
829 self.createFigure(id = id,
620 wintitle = wintitle,
830 wintitle = wintitle,
621 widthplot = self.WIDTH + self.WIDTHPROF,
831 widthplot = self.WIDTH + self.WIDTHPROF,
622 heightplot = self.HEIGHT + self.HEIGHTPROF,
832 heightplot = self.HEIGHT + self.HEIGHTPROF,
623 show=show)
833 show=show)
624
834
625 nrow, ncol = self.getSubplots()
835 nrow, ncol = self.getSubplots()
626
836
627 counter = 0
837 counter = 0
628 for y in range(nrow):
838 for y in range(nrow):
629 for x in range(ncol):
839 for x in range(ncol):
630
840
631 if counter >= self.nplots:
841 if counter >= self.nplots:
632 break
842 break
633
843
634 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
844 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
635
845
636 counter += 1
846 counter += 1
637
847
638 def run(self, dataOut, id, wintitle="", channelList=None, paramIndex = 0, colormap=True,
848 def run(self, dataOut, id, wintitle="", channelList=None, paramIndex = 0, colormap="jet",
639 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
849 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
640 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
850 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
641 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
851 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
642 server=None, folder=None, username=None, password=None,
852 server=None, folder=None, username=None, password=None,
643 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
853 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, HEIGHT=None):
644 """
854 """
645
855
646 Input:
856 Input:
647 dataOut :
857 dataOut :
648 id :
858 id :
649 wintitle :
859 wintitle :
650 channelList :
860 channelList :
651 showProfile :
861 showProfile :
652 xmin : None,
862 xmin : None,
653 xmax : None,
863 xmax : None,
654 ymin : None,
864 ymin : None,
655 ymax : None,
865 ymax : None,
656 zmin : None,
866 zmin : None,
657 zmax : None
867 zmax : None
658 """
868 """
659
869
660 if colormap:
870 if HEIGHT is not None:
661 colormap="jet"
871 self.HEIGHT = HEIGHT
662 else:
872
663 colormap="RdBu_r"
873
664
665 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
874 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
666 return
875 return
667
876
668 if channelList == None:
877 if channelList == None:
669 channelIndexList = range(dataOut.data_param.shape[0])
878 channelIndexList = range(dataOut.data_param.shape[0])
670 else:
879 else:
671 channelIndexList = []
880 channelIndexList = []
672 for channel in channelList:
881 for channel in channelList:
673 if channel not in dataOut.channelList:
882 if channel not in dataOut.channelList:
674 raise ValueError, "Channel %d is not in dataOut.channelList"
883 raise ValueError, "Channel %d is not in dataOut.channelList"
675 channelIndexList.append(dataOut.channelList.index(channel))
884 channelIndexList.append(dataOut.channelList.index(channel))
676
885
677 x = dataOut.getTimeRange1(dataOut.paramInterval)
886 x = dataOut.getTimeRange1(dataOut.paramInterval)
678 y = dataOut.getHeiRange()
887 y = dataOut.getHeiRange()
679
888
680 if dataOut.data_param.ndim == 3:
889 if dataOut.data_param.ndim == 3:
681 z = dataOut.data_param[channelIndexList,paramIndex,:]
890 z = dataOut.data_param[channelIndexList,paramIndex,:]
682 else:
891 else:
683 z = dataOut.data_param[channelIndexList,:]
892 z = dataOut.data_param[channelIndexList,:]
684
893
685 if showSNR:
894 if showSNR:
686 #SNR data
895 #SNR data
687 SNRarray = dataOut.data_SNR[channelIndexList,:]
896 SNRarray = dataOut.data_SNR[channelIndexList,:]
688 SNRdB = 10*numpy.log10(SNRarray)
897 SNRdB = 10*numpy.log10(SNRarray)
689 ind = numpy.where(SNRdB < SNRthresh)
898 ind = numpy.where(SNRdB < SNRthresh)
690 z[ind] = numpy.nan
899 z[ind] = numpy.nan
691
900
692 thisDatetime = dataOut.datatime
901 thisDatetime = dataOut.datatime
693 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
902 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
694 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
903 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
695 xlabel = ""
904 xlabel = ""
696 ylabel = "Range (Km)"
905 ylabel = "Range (Km)"
697
906
698 update_figfile = False
907 update_figfile = False
699
908
700 if not self.isConfig:
909 if not self.isConfig:
701
910
702 nchan = len(channelIndexList)
911 nchan = len(channelIndexList)
703 self.nchan = nchan
912 self.nchan = nchan
704 self.plotFact = 1
913 self.plotFact = 1
705 nplots = nchan
914 nplots = nchan
706
915
707 if showSNR:
916 if showSNR:
708 nplots = nchan*2
917 nplots = nchan*2
709 self.plotFact = 2
918 self.plotFact = 2
710 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
919 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
711 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
920 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
712
921
713 self.setup(id=id,
922 self.setup(id=id,
714 nplots=nplots,
923 nplots=nplots,
715 wintitle=wintitle,
924 wintitle=wintitle,
716 show=show)
925 show=show)
717
926
718 if timerange != None:
927 if timerange != None:
719 self.timerange = timerange
928 self.timerange = timerange
720
929
721 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
930 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
722
931
723 if ymin == None: ymin = numpy.nanmin(y)
932 if ymin == None: ymin = numpy.nanmin(y)
724 if ymax == None: ymax = numpy.nanmax(y)
933 if ymax == None: ymax = numpy.nanmax(y)
725 if zmin == None: zmin = numpy.nanmin(z)
934 if zmin == None: zmin = numpy.nanmin(z)
726 if zmax == None: zmax = numpy.nanmax(z)
935 if zmax == None: zmax = numpy.nanmax(z)
727
936
728 self.FTP_WEI = ftp_wei
937 self.FTP_WEI = ftp_wei
729 self.EXP_CODE = exp_code
938 self.EXP_CODE = exp_code
730 self.SUB_EXP_CODE = sub_exp_code
939 self.SUB_EXP_CODE = sub_exp_code
731 self.PLOT_POS = plot_pos
940 self.PLOT_POS = plot_pos
732
941
733 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
942 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
734 self.isConfig = True
943 self.isConfig = True
735 self.figfile = figfile
944 self.figfile = figfile
736 update_figfile = True
945 update_figfile = True
737
946
738 self.setWinTitle(title)
947 self.setWinTitle(title)
739
948
740 for i in range(self.nchan):
949 for i in range(self.nchan):
741 index = channelIndexList[i]
950 index = channelIndexList[i]
742 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
951 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
743 axes = self.axesList[i*self.plotFact]
952 axes = self.axesList[i*self.plotFact]
744 z1 = z[i,:].reshape((1,-1))
953 z1 = z[i,:].reshape((1,-1))
745 axes.pcolorbuffer(x, y, z1,
954 axes.pcolorbuffer(x, y, z1,
746 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
955 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
747 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
956 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
748 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
957 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
749
958
750 if showSNR:
959 if showSNR:
751 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
960 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
752 axes = self.axesList[i*self.plotFact + 1]
961 axes = self.axesList[i*self.plotFact + 1]
753 SNRdB1 = SNRdB[i,:].reshape((1,-1))
962 SNRdB1 = SNRdB[i,:].reshape((1,-1))
754 axes.pcolorbuffer(x, y, SNRdB1,
963 axes.pcolorbuffer(x, y, SNRdB1,
755 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
964 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
756 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
965 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
757 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
966 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
758
967
759
968
760 self.draw()
969 self.draw()
761
970
762 if dataOut.ltctime >= self.xmax:
971 if dataOut.ltctime >= self.xmax:
763 self.counter_imagwr = wr_period
972 self.counter_imagwr = wr_period
764 self.isConfig = False
973 self.isConfig = False
765 update_figfile = True
974 update_figfile = True
766
975
767 self.save(figpath=figpath,
976 self.save(figpath=figpath,
768 figfile=figfile,
977 figfile=figfile,
769 save=save,
978 save=save,
770 ftp=ftp,
979 ftp=ftp,
771 wr_period=wr_period,
980 wr_period=wr_period,
772 thisDatetime=thisDatetime,
981 thisDatetime=thisDatetime,
773 update_figfile=update_figfile)
982 update_figfile=update_figfile)
774
983
775
984
776
985
777 class Parameters1Plot(Figure):
986 class Parameters1Plot(Figure):
778
987
779 __isConfig = None
988 __isConfig = None
780 __nsubplots = None
989 __nsubplots = None
781
990
782 WIDTHPROF = None
991 WIDTHPROF = None
783 HEIGHTPROF = None
992 HEIGHTPROF = None
784 PREFIX = 'prm'
993 PREFIX = 'prm'
785
994
786 def __init__(self, **kwargs):
995 def __init__(self, **kwargs):
787 Figure.__init__(self, **kwargs)
996 Figure.__init__(self, **kwargs)
788 self.timerange = 2*60*60
997 self.timerange = 2*60*60
789 self.isConfig = False
998 self.isConfig = False
790 self.__nsubplots = 1
999 self.__nsubplots = 1
791
1000
792 self.WIDTH = 800
1001 self.WIDTH = 800
793 self.HEIGHT = 180
1002 self.HEIGHT = 180
794 self.WIDTHPROF = 120
1003 self.WIDTHPROF = 120
795 self.HEIGHTPROF = 0
1004 self.HEIGHTPROF = 0
796 self.counter_imagwr = 0
1005 self.counter_imagwr = 0
797
1006
798 self.PLOT_CODE = PARMS_CODE
1007 self.PLOT_CODE = PARMS_CODE
799
1008
800 self.FTP_WEI = None
1009 self.FTP_WEI = None
801 self.EXP_CODE = None
1010 self.EXP_CODE = None
802 self.SUB_EXP_CODE = None
1011 self.SUB_EXP_CODE = None
803 self.PLOT_POS = None
1012 self.PLOT_POS = None
804 self.tmin = None
1013 self.tmin = None
805 self.tmax = None
1014 self.tmax = None
806
1015
807 self.xmin = None
1016 self.xmin = None
808 self.xmax = None
1017 self.xmax = None
809
1018
810 self.figfile = None
1019 self.figfile = None
811
1020
812 def getSubplots(self):
1021 def getSubplots(self):
813
1022
814 ncol = 1
1023 ncol = 1
815 nrow = self.nplots
1024 nrow = self.nplots
816
1025
817 return nrow, ncol
1026 return nrow, ncol
818
1027
819 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1028 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
820
1029
821 self.__showprofile = showprofile
1030 self.__showprofile = showprofile
822 self.nplots = nplots
1031 self.nplots = nplots
823
1032
824 ncolspan = 1
1033 ncolspan = 1
825 colspan = 1
1034 colspan = 1
826
1035
827 self.createFigure(id = id,
1036 self.createFigure(id = id,
828 wintitle = wintitle,
1037 wintitle = wintitle,
829 widthplot = self.WIDTH + self.WIDTHPROF,
1038 widthplot = self.WIDTH + self.WIDTHPROF,
830 heightplot = self.HEIGHT + self.HEIGHTPROF,
1039 heightplot = self.HEIGHT + self.HEIGHTPROF,
831 show=show)
1040 show=show)
832
1041
833 nrow, ncol = self.getSubplots()
1042 nrow, ncol = self.getSubplots()
834
1043
835 counter = 0
1044 counter = 0
836 for y in range(nrow):
1045 for y in range(nrow):
837 for x in range(ncol):
1046 for x in range(ncol):
838
1047
839 if counter >= self.nplots:
1048 if counter >= self.nplots:
840 break
1049 break
841
1050
842 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1051 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
843
1052
844 if showprofile:
1053 if showprofile:
845 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1054 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
846
1055
847 counter += 1
1056 counter += 1
848
1057
849 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
1058 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
850 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
1059 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
851 parameterIndex = None, onlyPositive = False,
1060 parameterIndex = None, onlyPositive = False,
852 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
1061 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
853 DOP = True,
1062 DOP = True,
854 zlabel = "", parameterName = "", parameterObject = "data_param",
1063 zlabel = "", parameterName = "", parameterObject = "data_param",
855 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1064 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
856 server=None, folder=None, username=None, password=None,
1065 server=None, folder=None, username=None, password=None,
857 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1066 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
858 #print inspect.getargspec(self.run).args
1067 #print inspect.getargspec(self.run).args
859 """
1068 """
860
1069
861 Input:
1070 Input:
862 dataOut :
1071 dataOut :
863 id :
1072 id :
864 wintitle :
1073 wintitle :
865 channelList :
1074 channelList :
866 showProfile :
1075 showProfile :
867 xmin : None,
1076 xmin : None,
868 xmax : None,
1077 xmax : None,
869 ymin : None,
1078 ymin : None,
870 ymax : None,
1079 ymax : None,
871 zmin : None,
1080 zmin : None,
872 zmax : None
1081 zmax : None
873 """
1082 """
874
1083
875 data_param = getattr(dataOut, parameterObject)
1084 data_param = getattr(dataOut, parameterObject)
876
1085
877 if channelList == None:
1086 if channelList == None:
878 channelIndexList = numpy.arange(data_param.shape[0])
1087 channelIndexList = numpy.arange(data_param.shape[0])
879 else:
1088 else:
880 channelIndexList = numpy.array(channelList)
1089 channelIndexList = numpy.array(channelList)
881
1090
882 nchan = len(channelIndexList) #Number of channels being plotted
1091 nchan = len(channelIndexList) #Number of channels being plotted
883
1092
884 if nchan < 1:
1093 if nchan < 1:
885 return
1094 return
886
1095
887 nGraphsByChannel = 0
1096 nGraphsByChannel = 0
888
1097
889 if SNR:
1098 if SNR:
890 nGraphsByChannel += 1
1099 nGraphsByChannel += 1
891 if DOP:
1100 if DOP:
892 nGraphsByChannel += 1
1101 nGraphsByChannel += 1
893
1102
894 if nGraphsByChannel < 1:
1103 if nGraphsByChannel < 1:
895 return
1104 return
896
1105
897 nplots = nGraphsByChannel*nchan
1106 nplots = nGraphsByChannel*nchan
898
1107
899 if timerange is not None:
1108 if timerange is not None:
900 self.timerange = timerange
1109 self.timerange = timerange
901
1110
902 #tmin = None
1111 #tmin = None
903 #tmax = None
1112 #tmax = None
904 if parameterIndex == None:
1113 if parameterIndex == None:
905 parameterIndex = 1
1114 parameterIndex = 1
906
1115
907 x = dataOut.getTimeRange1(dataOut.paramInterval)
1116 x = dataOut.getTimeRange1(dataOut.paramInterval)
908 y = dataOut.heightList
1117 y = dataOut.heightList
909 z = data_param[channelIndexList,parameterIndex,:].copy()
910
1118
911 zRange = dataOut.abscissaList
1119 if dataOut.data_param.ndim == 3:
912 # nChannels = z.shape[0] #Number of wind dimensions estimated
1120 z = dataOut.data_param[channelIndexList,parameterIndex,:]
913 # thisDatetime = dataOut.datatime
1121 else:
1122 z = dataOut.data_param[channelIndexList,:]
914
1123
915 if dataOut.data_SNR is not None:
1124 if dataOut.data_SNR is not None:
916 SNRarray = dataOut.data_SNR[channelIndexList,:]
1125 if dataOut.data_SNR.ndim == 2:
917 SNRdB = 10*numpy.log10(SNRarray)
1126 SNRavg = numpy.average(dataOut.data_SNR, axis=0)
918 # SNRavgdB = 10*numpy.log10(SNRavg)
1127 else:
919 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
1128 SNRavg = dataOut.data_SNR
920 z[ind] = numpy.nan
1129 SNRdB = 10*numpy.log10(SNRavg)
921
1130
922 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1131 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
923 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
1132 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
924 xlabel = ""
1133 xlabel = ""
925 ylabel = "Range (Km)"
1134 ylabel = "Range (Km)"
926
927 if (SNR and not onlySNR): nplots = 2*nplots
928
1135
929 if onlyPositive:
1136 if onlyPositive:
930 colormap = "jet"
1137 colormap = "jet"
931 zmin = 0
1138 zmin = 0
932 else: colormap = "RdBu_r"
1139 else: colormap = "RdBu_r"
933
1140
934 if not self.isConfig:
1141 if not self.isConfig:
935
1142
936 self.setup(id=id,
1143 self.setup(id=id,
937 nplots=nplots,
1144 nplots=nplots,
938 wintitle=wintitle,
1145 wintitle=wintitle,
939 showprofile=showprofile,
1146 showprofile=showprofile,
940 show=show)
1147 show=show)
941
1148
942 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1149 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
943
1150
944 if ymin == None: ymin = numpy.nanmin(y)
1151 if ymin == None: ymin = numpy.nanmin(y)
945 if ymax == None: ymax = numpy.nanmax(y)
1152 if ymax == None: ymax = numpy.nanmax(y)
946 if zmin == None: zmin = numpy.nanmin(zRange)
1153 if zmin == None: zmin = numpy.nanmin(z)
947 if zmax == None: zmax = numpy.nanmax(zRange)
1154 if zmax == None: zmax = numpy.nanmax(z)
948
1155
949 if SNR:
1156 if SNR:
950 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
1157 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
951 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
1158 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
952
1159
953 self.FTP_WEI = ftp_wei
1160 self.FTP_WEI = ftp_wei
954 self.EXP_CODE = exp_code
1161 self.EXP_CODE = exp_code
955 self.SUB_EXP_CODE = sub_exp_code
1162 self.SUB_EXP_CODE = sub_exp_code
956 self.PLOT_POS = plot_pos
1163 self.PLOT_POS = plot_pos
957
1164
958 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1165 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
959 self.isConfig = True
1166 self.isConfig = True
960 self.figfile = figfile
1167 self.figfile = figfile
961
1168
962 self.setWinTitle(title)
1169 self.setWinTitle(title)
963
1170
964 if ((self.xmax - x[1]) < (x[1]-x[0])):
1171 if ((self.xmax - x[1]) < (x[1]-x[0])):
965 x[1] = self.xmax
1172 x[1] = self.xmax
966
1173
967 for i in range(nchan):
1174 for i in range(nchan):
968
1175
969 if (SNR and not onlySNR): j = 2*i
1176 if (SNR and not onlySNR): j = 2*i
970 else: j = i
1177 else: j = i
971
1178
972 j = nGraphsByChannel*i
1179 j = nGraphsByChannel*i
973
1180
974 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1181 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
975 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
1182 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
976
1183
977 if not onlySNR:
1184 if not onlySNR:
978 axes = self.axesList[j*self.__nsubplots]
1185 axes = self.axesList[j*self.__nsubplots]
979 z1 = z[i,:].reshape((1,-1))
1186 z1 = z[i,:].reshape((1,-1))
980 axes.pcolorbuffer(x, y, z1,
1187 axes.pcolorbuffer(x, y, z1,
981 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
1188 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
982 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
1189 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
983 ticksize=9, cblabel=zlabel, cbsize="1%")
1190 ticksize=9, cblabel=zlabel, cbsize="1%")
984
1191
985 if DOP:
1192 if DOP:
986 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1193 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
987
1194
988 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1195 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
989 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
1196 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
990 axes = self.axesList[j]
1197 axes = self.axesList[j]
991 z1 = z[i,:].reshape((1,-1))
1198 z1 = z[i,:].reshape((1,-1))
992 axes.pcolorbuffer(x, y, z1,
1199 axes.pcolorbuffer(x, y, z1,
993 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
1200 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
994 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
1201 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
995 ticksize=9, cblabel=zlabel, cbsize="1%")
1202 ticksize=9, cblabel=zlabel, cbsize="1%")
996
1203
997 if SNR:
1204 if SNR:
998 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1205 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
999 axes = self.axesList[(j)*self.__nsubplots]
1206 axes = self.axesList[(j)*self.__nsubplots]
1000 if not onlySNR:
1207 if not onlySNR:
1001 axes = self.axesList[(j + 1)*self.__nsubplots]
1208 axes = self.axesList[(j + 1)*self.__nsubplots]
1002
1003 axes = self.axesList[(j + nGraphsByChannel-1)]
1004
1209
1005 z1 = SNRdB[i,:].reshape((1,-1))
1210 axes = self.axesList[(j + nGraphsByChannel-1)]
1006 axes.pcolorbuffer(x, y, z1,
1211 z1 = SNRdB.reshape((1,-1))
1007 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1212 axes.pcolorbuffer(x, y, z1,
1008 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1213 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1009 ticksize=9, cblabel=zlabel, cbsize="1%")
1214 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1215 ticksize=9, cblabel=zlabel, cbsize="1%")
1010
1216
1011
1217
1012
1218
1013 self.draw()
1219 self.draw()
1014
1220
1015 if x[1] >= self.axesList[0].xmax:
1221 if x[1] >= self.axesList[0].xmax:
1016 self.counter_imagwr = wr_period
1222 self.counter_imagwr = wr_period
1017 self.isConfig = False
1223 self.isConfig = False
1018 self.figfile = None
1224 self.figfile = None
1019
1225
1020 self.save(figpath=figpath,
1226 self.save(figpath=figpath,
1021 figfile=figfile,
1227 figfile=figfile,
1022 save=save,
1228 save=save,
1023 ftp=ftp,
1229 ftp=ftp,
1024 wr_period=wr_period,
1230 wr_period=wr_period,
1025 thisDatetime=thisDatetime,
1231 thisDatetime=thisDatetime,
1026 update_figfile=False)
1232 update_figfile=False)
1027
1233
1028 class SpectralFittingPlot(Figure):
1234 class SpectralFittingPlot(Figure):
1029
1235
1030 __isConfig = None
1236 __isConfig = None
1031 __nsubplots = None
1237 __nsubplots = None
1032
1238
1033 WIDTHPROF = None
1239 WIDTHPROF = None
1034 HEIGHTPROF = None
1240 HEIGHTPROF = None
1035 PREFIX = 'prm'
1241 PREFIX = 'prm'
1036
1242
1037
1243
1038 N = None
1244 N = None
1039 ippSeconds = None
1245 ippSeconds = None
1040
1246
1041 def __init__(self, **kwargs):
1247 def __init__(self, **kwargs):
1042 Figure.__init__(self, **kwargs)
1248 Figure.__init__(self, **kwargs)
1043 self.isConfig = False
1249 self.isConfig = False
1044 self.__nsubplots = 1
1250 self.__nsubplots = 1
1045
1251
1046 self.PLOT_CODE = SPECFIT_CODE
1252 self.PLOT_CODE = SPECFIT_CODE
1047
1253
1048 self.WIDTH = 450
1254 self.WIDTH = 450
1049 self.HEIGHT = 250
1255 self.HEIGHT = 250
1050 self.WIDTHPROF = 0
1256 self.WIDTHPROF = 0
1051 self.HEIGHTPROF = 0
1257 self.HEIGHTPROF = 0
1052
1258
1053 def getSubplots(self):
1259 def getSubplots(self):
1054
1260
1055 ncol = int(numpy.sqrt(self.nplots)+0.9)
1261 ncol = int(numpy.sqrt(self.nplots)+0.9)
1056 nrow = int(self.nplots*1./ncol + 0.9)
1262 nrow = int(self.nplots*1./ncol + 0.9)
1057
1263
1058 return nrow, ncol
1264 return nrow, ncol
1059
1265
1060 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1266 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1061
1267
1062 showprofile = False
1268 showprofile = False
1063 self.__showprofile = showprofile
1269 self.__showprofile = showprofile
1064 self.nplots = nplots
1270 self.nplots = nplots
1065
1271
1066 ncolspan = 5
1272 ncolspan = 5
1067 colspan = 4
1273 colspan = 4
1068 if showprofile:
1274 if showprofile:
1069 ncolspan = 5
1275 ncolspan = 5
1070 colspan = 4
1276 colspan = 4
1071 self.__nsubplots = 2
1277 self.__nsubplots = 2
1072
1278
1073 self.createFigure(id = id,
1279 self.createFigure(id = id,
1074 wintitle = wintitle,
1280 wintitle = wintitle,
1075 widthplot = self.WIDTH + self.WIDTHPROF,
1281 widthplot = self.WIDTH + self.WIDTHPROF,
1076 heightplot = self.HEIGHT + self.HEIGHTPROF,
1282 heightplot = self.HEIGHT + self.HEIGHTPROF,
1077 show=show)
1283 show=show)
1078
1284
1079 nrow, ncol = self.getSubplots()
1285 nrow, ncol = self.getSubplots()
1080
1286
1081 counter = 0
1287 counter = 0
1082 for y in range(nrow):
1288 for y in range(nrow):
1083 for x in range(ncol):
1289 for x in range(ncol):
1084
1290
1085 if counter >= self.nplots:
1291 if counter >= self.nplots:
1086 break
1292 break
1087
1293
1088 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1294 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1089
1295
1090 if showprofile:
1296 if showprofile:
1091 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1297 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1092
1298
1093 counter += 1
1299 counter += 1
1094
1300
1095 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1301 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1096 xmin=None, xmax=None, ymin=None, ymax=None,
1302 xmin=None, xmax=None, ymin=None, ymax=None,
1097 save=False, figpath='./', figfile=None, show=True):
1303 save=False, figpath='./', figfile=None, show=True):
1098
1304
1099 """
1305 """
1100
1306
1101 Input:
1307 Input:
1102 dataOut :
1308 dataOut :
1103 id :
1309 id :
1104 wintitle :
1310 wintitle :
1105 channelList :
1311 channelList :
1106 showProfile :
1312 showProfile :
1107 xmin : None,
1313 xmin : None,
1108 xmax : None,
1314 xmax : None,
1109 zmin : None,
1315 zmin : None,
1110 zmax : None
1316 zmax : None
1111 """
1317 """
1112
1318
1113 if cutHeight==None:
1319 if cutHeight==None:
1114 h=270
1320 h=270
1115 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1321 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1116 cutHeight = dataOut.heightList[heightindex]
1322 cutHeight = dataOut.heightList[heightindex]
1117
1323
1118 factor = dataOut.normFactor
1324 factor = dataOut.normFactor
1119 x = dataOut.abscissaList[:-1]
1325 x = dataOut.abscissaList[:-1]
1120 #y = dataOut.getHeiRange()
1326 #y = dataOut.getHeiRange()
1121
1327
1122 z = dataOut.data_pre[:,:,heightindex]/factor
1328 z = dataOut.data_pre[:,:,heightindex]/factor
1123 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1329 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1124 avg = numpy.average(z, axis=1)
1330 avg = numpy.average(z, axis=1)
1125 listChannels = z.shape[0]
1331 listChannels = z.shape[0]
1126
1332
1127 #Reconstruct Function
1333 #Reconstruct Function
1128 if fit==True:
1334 if fit==True:
1129 groupArray = dataOut.groupList
1335 groupArray = dataOut.groupList
1130 listChannels = groupArray.reshape((groupArray.size))
1336 listChannels = groupArray.reshape((groupArray.size))
1131 listChannels.sort()
1337 listChannels.sort()
1132 spcFitLine = numpy.zeros(z.shape)
1338 spcFitLine = numpy.zeros(z.shape)
1133 constants = dataOut.constants
1339 constants = dataOut.constants
1134
1340
1135 nGroups = groupArray.shape[0]
1341 nGroups = groupArray.shape[0]
1136 nChannels = groupArray.shape[1]
1342 nChannels = groupArray.shape[1]
1137 nProfiles = z.shape[1]
1343 nProfiles = z.shape[1]
1138
1344
1139 for f in range(nGroups):
1345 for f in range(nGroups):
1140 groupChann = groupArray[f,:]
1346 groupChann = groupArray[f,:]
1141 p = dataOut.data_param[f,:,heightindex]
1347 p = dataOut.data_param[f,:,heightindex]
1142 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1348 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1143 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1349 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1144 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1350 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1145 spcFitLine[groupChann,:] = fitLineAux
1351 spcFitLine[groupChann,:] = fitLineAux
1146 # spcFitLine = spcFitLine/factor
1352 # spcFitLine = spcFitLine/factor
1147
1353
1148 z = z[listChannels,:]
1354 z = z[listChannels,:]
1149 spcFitLine = spcFitLine[listChannels,:]
1355 spcFitLine = spcFitLine[listChannels,:]
1150 spcFitLinedB = 10*numpy.log10(spcFitLine)
1356 spcFitLinedB = 10*numpy.log10(spcFitLine)
1151
1357
1152 zdB = 10*numpy.log10(z)
1358 zdB = 10*numpy.log10(z)
1153 #thisDatetime = dataOut.datatime
1359 #thisDatetime = dataOut.datatime
1154 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1360 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1155 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1361 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1156 xlabel = "Velocity (m/s)"
1362 xlabel = "Velocity (m/s)"
1157 ylabel = "Spectrum"
1363 ylabel = "Spectrum"
1158
1364
1159 if not self.isConfig:
1365 if not self.isConfig:
1160
1366
1161 nplots = listChannels.size
1367 nplots = listChannels.size
1162
1368
1163 self.setup(id=id,
1369 self.setup(id=id,
1164 nplots=nplots,
1370 nplots=nplots,
1165 wintitle=wintitle,
1371 wintitle=wintitle,
1166 showprofile=showprofile,
1372 showprofile=showprofile,
1167 show=show)
1373 show=show)
1168
1374
1169 if xmin == None: xmin = numpy.nanmin(x)
1375 if xmin == None: xmin = numpy.nanmin(x)
1170 if xmax == None: xmax = numpy.nanmax(x)
1376 if xmax == None: xmax = numpy.nanmax(x)
1171 if ymin == None: ymin = numpy.nanmin(zdB)
1377 if ymin == None: ymin = numpy.nanmin(zdB)
1172 if ymax == None: ymax = numpy.nanmax(zdB)+2
1378 if ymax == None: ymax = numpy.nanmax(zdB)+2
1173
1379
1174 self.isConfig = True
1380 self.isConfig = True
1175
1381
1176 self.setWinTitle(title)
1382 self.setWinTitle(title)
1177 for i in range(self.nplots):
1383 for i in range(self.nplots):
1178 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1384 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1179 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1385 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1180 axes = self.axesList[i*self.__nsubplots]
1386 axes = self.axesList[i*self.__nsubplots]
1181 if fit == False:
1387 if fit == False:
1182 axes.pline(x, zdB[i,:],
1388 axes.pline(x, zdB[i,:],
1183 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1389 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1184 xlabel=xlabel, ylabel=ylabel, title=title
1390 xlabel=xlabel, ylabel=ylabel, title=title
1185 )
1391 )
1186 if fit == True:
1392 if fit == True:
1187 fitline=spcFitLinedB[i,:]
1393 fitline=spcFitLinedB[i,:]
1188 y=numpy.vstack([zdB[i,:],fitline] )
1394 y=numpy.vstack([zdB[i,:],fitline] )
1189 legendlabels=['Data','Fitting']
1395 legendlabels=['Data','Fitting']
1190 axes.pmultilineyaxis(x, y,
1396 axes.pmultilineyaxis(x, y,
1191 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1397 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1192 xlabel=xlabel, ylabel=ylabel, title=title,
1398 xlabel=xlabel, ylabel=ylabel, title=title,
1193 legendlabels=legendlabels, marker=None,
1399 legendlabels=legendlabels, marker=None,
1194 linestyle='solid', grid='both')
1400 linestyle='solid', grid='both')
1195
1401
1196 self.draw()
1402 self.draw()
1197
1403
1198 self.save(figpath=figpath,
1404 self.save(figpath=figpath,
1199 figfile=figfile,
1405 figfile=figfile,
1200 save=save,
1406 save=save,
1201 ftp=ftp,
1407 ftp=ftp,
1202 wr_period=wr_period,
1408 wr_period=wr_period,
1203 thisDatetime=thisDatetime)
1409 thisDatetime=thisDatetime)
1204
1410
1205
1411
1206 class EWDriftsPlot(Figure):
1412 class EWDriftsPlot(Figure):
1207
1413
1208 __isConfig = None
1414 __isConfig = None
1209 __nsubplots = None
1415 __nsubplots = None
1210
1416
1211 WIDTHPROF = None
1417 WIDTHPROF = None
1212 HEIGHTPROF = None
1418 HEIGHTPROF = None
1213 PREFIX = 'drift'
1419 PREFIX = 'drift'
1214
1420
1215 def __init__(self, **kwargs):
1421 def __init__(self, **kwargs):
1216 Figure.__init__(self, **kwargs)
1422 Figure.__init__(self, **kwargs)
1217 self.timerange = 2*60*60
1423 self.timerange = 2*60*60
1218 self.isConfig = False
1424 self.isConfig = False
1219 self.__nsubplots = 1
1425 self.__nsubplots = 1
1220
1426
1221 self.WIDTH = 800
1427 self.WIDTH = 800
1222 self.HEIGHT = 150
1428 self.HEIGHT = 150
1223 self.WIDTHPROF = 120
1429 self.WIDTHPROF = 120
1224 self.HEIGHTPROF = 0
1430 self.HEIGHTPROF = 0
1225 self.counter_imagwr = 0
1431 self.counter_imagwr = 0
1226
1432
1227 self.PLOT_CODE = EWDRIFT_CODE
1433 self.PLOT_CODE = EWDRIFT_CODE
1228
1434
1229 self.FTP_WEI = None
1435 self.FTP_WEI = None
1230 self.EXP_CODE = None
1436 self.EXP_CODE = None
1231 self.SUB_EXP_CODE = None
1437 self.SUB_EXP_CODE = None
1232 self.PLOT_POS = None
1438 self.PLOT_POS = None
1233 self.tmin = None
1439 self.tmin = None
1234 self.tmax = None
1440 self.tmax = None
1235
1441
1236 self.xmin = None
1442 self.xmin = None
1237 self.xmax = None
1443 self.xmax = None
1238
1444
1239 self.figfile = None
1445 self.figfile = None
1240
1446
1241 def getSubplots(self):
1447 def getSubplots(self):
1242
1448
1243 ncol = 1
1449 ncol = 1
1244 nrow = self.nplots
1450 nrow = self.nplots
1245
1451
1246 return nrow, ncol
1452 return nrow, ncol
1247
1453
1248 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1454 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1249
1455
1250 self.__showprofile = showprofile
1456 self.__showprofile = showprofile
1251 self.nplots = nplots
1457 self.nplots = nplots
1252
1458
1253 ncolspan = 1
1459 ncolspan = 1
1254 colspan = 1
1460 colspan = 1
1255
1461
1256 self.createFigure(id = id,
1462 self.createFigure(id = id,
1257 wintitle = wintitle,
1463 wintitle = wintitle,
1258 widthplot = self.WIDTH + self.WIDTHPROF,
1464 widthplot = self.WIDTH + self.WIDTHPROF,
1259 heightplot = self.HEIGHT + self.HEIGHTPROF,
1465 heightplot = self.HEIGHT + self.HEIGHTPROF,
1260 show=show)
1466 show=show)
1261
1467
1262 nrow, ncol = self.getSubplots()
1468 nrow, ncol = self.getSubplots()
1263
1469
1264 counter = 0
1470 counter = 0
1265 for y in range(nrow):
1471 for y in range(nrow):
1266 if counter >= self.nplots:
1472 if counter >= self.nplots:
1267 break
1473 break
1268
1474
1269 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1475 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1270 counter += 1
1476 counter += 1
1271
1477
1272 def run(self, dataOut, id, wintitle="", channelList=None,
1478 def run(self, dataOut, id, wintitle="", channelList=None,
1273 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1479 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1274 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1480 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1275 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1481 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1276 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1482 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1277 server=None, folder=None, username=None, password=None,
1483 server=None, folder=None, username=None, password=None,
1278 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1484 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1279 """
1485 """
1280
1486
1281 Input:
1487 Input:
1282 dataOut :
1488 dataOut :
1283 id :
1489 id :
1284 wintitle :
1490 wintitle :
1285 channelList :
1491 channelList :
1286 showProfile :
1492 showProfile :
1287 xmin : None,
1493 xmin : None,
1288 xmax : None,
1494 xmax : None,
1289 ymin : None,
1495 ymin : None,
1290 ymax : None,
1496 ymax : None,
1291 zmin : None,
1497 zmin : None,
1292 zmax : None
1498 zmax : None
1293 """
1499 """
1294
1500
1295 if timerange is not None:
1501 if timerange is not None:
1296 self.timerange = timerange
1502 self.timerange = timerange
1297
1503
1298 tmin = None
1504 tmin = None
1299 tmax = None
1505 tmax = None
1300
1506
1301 x = dataOut.getTimeRange1(dataOut.outputInterval)
1507 x = dataOut.getTimeRange1(dataOut.outputInterval)
1302 # y = dataOut.heightList
1508 # y = dataOut.heightList
1303 y = dataOut.heightList
1509 y = dataOut.heightList
1304
1510
1305 z = dataOut.data_output
1511 z = dataOut.data_output
1306 nplots = z.shape[0] #Number of wind dimensions estimated
1512 nplots = z.shape[0] #Number of wind dimensions estimated
1307 nplotsw = nplots
1513 nplotsw = nplots
1308
1514
1309 #If there is a SNR function defined
1515 #If there is a SNR function defined
1310 if dataOut.data_SNR is not None:
1516 if dataOut.data_SNR is not None:
1311 nplots += 1
1517 nplots += 1
1312 SNR = dataOut.data_SNR
1518 SNR = dataOut.data_SNR
1313
1519
1314 if SNR_1:
1520 if SNR_1:
1315 SNR += 1
1521 SNR += 1
1316
1522
1317 SNRavg = numpy.average(SNR, axis=0)
1523 SNRavg = numpy.average(SNR, axis=0)
1318
1524
1319 SNRdB = 10*numpy.log10(SNR)
1525 SNRdB = 10*numpy.log10(SNR)
1320 SNRavgdB = 10*numpy.log10(SNRavg)
1526 SNRavgdB = 10*numpy.log10(SNRavg)
1321
1527
1322 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1528 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1323
1529
1324 for i in range(nplotsw):
1530 for i in range(nplotsw):
1325 z[i,ind] = numpy.nan
1531 z[i,ind] = numpy.nan
1326
1532
1327
1533
1328 showprofile = False
1534 showprofile = False
1329 # thisDatetime = dataOut.datatime
1535 # thisDatetime = dataOut.datatime
1330 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1536 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1331 title = wintitle + " EW Drifts"
1537 title = wintitle + " EW Drifts"
1332 xlabel = ""
1538 xlabel = ""
1333 ylabel = "Height (Km)"
1539 ylabel = "Height (Km)"
1334
1540
1335 if not self.isConfig:
1541 if not self.isConfig:
1336
1542
1337 self.setup(id=id,
1543 self.setup(id=id,
1338 nplots=nplots,
1544 nplots=nplots,
1339 wintitle=wintitle,
1545 wintitle=wintitle,
1340 showprofile=showprofile,
1546 showprofile=showprofile,
1341 show=show)
1547 show=show)
1342
1548
1343 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1549 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1344
1550
1345 if ymin == None: ymin = numpy.nanmin(y)
1551 if ymin == None: ymin = numpy.nanmin(y)
1346 if ymax == None: ymax = numpy.nanmax(y)
1552 if ymax == None: ymax = numpy.nanmax(y)
1347
1553
1348 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1554 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1349 if zminZonal == None: zminZonal = -zmaxZonal
1555 if zminZonal == None: zminZonal = -zmaxZonal
1350 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1556 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1351 if zminVertical == None: zminVertical = -zmaxVertical
1557 if zminVertical == None: zminVertical = -zmaxVertical
1352
1558
1353 if dataOut.data_SNR is not None:
1559 if dataOut.data_SNR is not None:
1354 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1560 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1355 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1561 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1356
1562
1357 self.FTP_WEI = ftp_wei
1563 self.FTP_WEI = ftp_wei
1358 self.EXP_CODE = exp_code
1564 self.EXP_CODE = exp_code
1359 self.SUB_EXP_CODE = sub_exp_code
1565 self.SUB_EXP_CODE = sub_exp_code
1360 self.PLOT_POS = plot_pos
1566 self.PLOT_POS = plot_pos
1361
1567
1362 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1568 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1363 self.isConfig = True
1569 self.isConfig = True
1364
1570
1365
1571
1366 self.setWinTitle(title)
1572 self.setWinTitle(title)
1367
1573
1368 if ((self.xmax - x[1]) < (x[1]-x[0])):
1574 if ((self.xmax - x[1]) < (x[1]-x[0])):
1369 x[1] = self.xmax
1575 x[1] = self.xmax
1370
1576
1371 strWind = ['Zonal','Vertical']
1577 strWind = ['Zonal','Vertical']
1372 strCb = 'Velocity (m/s)'
1578 strCb = 'Velocity (m/s)'
1373 zmaxVector = [zmaxZonal, zmaxVertical]
1579 zmaxVector = [zmaxZonal, zmaxVertical]
1374 zminVector = [zminZonal, zminVertical]
1580 zminVector = [zminZonal, zminVertical]
1375
1581
1376 for i in range(nplotsw):
1582 for i in range(nplotsw):
1377
1583
1378 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1584 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1379 axes = self.axesList[i*self.__nsubplots]
1585 axes = self.axesList[i*self.__nsubplots]
1380
1586
1381 z1 = z[i,:].reshape((1,-1))
1587 z1 = z[i,:].reshape((1,-1))
1382
1588
1383 axes.pcolorbuffer(x, y, z1,
1589 axes.pcolorbuffer(x, y, z1,
1384 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1590 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1385 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1591 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1386 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1592 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1387
1593
1388 if dataOut.data_SNR is not None:
1594 if dataOut.data_SNR is not None:
1389 i += 1
1595 i += 1
1390 if SNR_1:
1596 if SNR_1:
1391 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1597 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1392 else:
1598 else:
1393 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1599 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1394 axes = self.axesList[i*self.__nsubplots]
1600 axes = self.axesList[i*self.__nsubplots]
1395 SNRavgdB = SNRavgdB.reshape((1,-1))
1601 SNRavgdB = SNRavgdB.reshape((1,-1))
1396
1602
1397 axes.pcolorbuffer(x, y, SNRavgdB,
1603 axes.pcolorbuffer(x, y, SNRavgdB,
1398 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1604 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1399 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1605 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1400 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1606 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1401
1607
1402 self.draw()
1608 self.draw()
1403
1609
1404 if x[1] >= self.axesList[0].xmax:
1610 if x[1] >= self.axesList[0].xmax:
1405 self.counter_imagwr = wr_period
1611 self.counter_imagwr = wr_period
1406 self.isConfig = False
1612 self.isConfig = False
1407 self.figfile = None
1613 self.figfile = None
1408
1614
1409
1615
1410
1616
1411
1617
1412 class PhasePlot(Figure):
1618 class PhasePlot(Figure):
1413
1619
1414 __isConfig = None
1620 __isConfig = None
1415 __nsubplots = None
1621 __nsubplots = None
1416
1622
1417 PREFIX = 'mphase'
1623 PREFIX = 'mphase'
1418
1624
1419
1625
1420 def __init__(self, **kwargs):
1626 def __init__(self, **kwargs):
1421 Figure.__init__(self, **kwargs)
1627 Figure.__init__(self, **kwargs)
1422 self.timerange = 24*60*60
1628 self.timerange = 24*60*60
1423 self.isConfig = False
1629 self.isConfig = False
1424 self.__nsubplots = 1
1630 self.__nsubplots = 1
1425 self.counter_imagwr = 0
1631 self.counter_imagwr = 0
1426 self.WIDTH = 600
1632 self.WIDTH = 600
1427 self.HEIGHT = 300
1633 self.HEIGHT = 300
1428 self.WIDTHPROF = 120
1634 self.WIDTHPROF = 120
1429 self.HEIGHTPROF = 0
1635 self.HEIGHTPROF = 0
1430 self.xdata = None
1636 self.xdata = None
1431 self.ydata = None
1637 self.ydata = None
1432
1638
1433 self.PLOT_CODE = MPHASE_CODE
1639 self.PLOT_CODE = MPHASE_CODE
1434
1640
1435 self.FTP_WEI = None
1641 self.FTP_WEI = None
1436 self.EXP_CODE = None
1642 self.EXP_CODE = None
1437 self.SUB_EXP_CODE = None
1643 self.SUB_EXP_CODE = None
1438 self.PLOT_POS = None
1644 self.PLOT_POS = None
1439
1645
1440
1646
1441 self.filename_phase = None
1647 self.filename_phase = None
1442
1648
1443 self.figfile = None
1649 self.figfile = None
1444
1650
1445 def getSubplots(self):
1651 def getSubplots(self):
1446
1652
1447 ncol = 1
1653 ncol = 1
1448 nrow = 1
1654 nrow = 1
1449
1655
1450 return nrow, ncol
1656 return nrow, ncol
1451
1657
1452 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1658 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1453
1659
1454 self.__showprofile = showprofile
1660 self.__showprofile = showprofile
1455 self.nplots = nplots
1661 self.nplots = nplots
1456
1662
1457 ncolspan = 7
1663 ncolspan = 7
1458 colspan = 6
1664 colspan = 6
1459 self.__nsubplots = 2
1665 self.__nsubplots = 2
1460
1666
1461 self.createFigure(id = id,
1667 self.createFigure(id = id,
1462 wintitle = wintitle,
1668 wintitle = wintitle,
1463 widthplot = self.WIDTH+self.WIDTHPROF,
1669 widthplot = self.WIDTH+self.WIDTHPROF,
1464 heightplot = self.HEIGHT+self.HEIGHTPROF,
1670 heightplot = self.HEIGHT+self.HEIGHTPROF,
1465 show=show)
1671 show=show)
1466
1672
1467 nrow, ncol = self.getSubplots()
1673 nrow, ncol = self.getSubplots()
1468
1674
1469 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1675 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1470
1676
1471
1677
1472 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1678 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1473 xmin=None, xmax=None, ymin=None, ymax=None,
1679 xmin=None, xmax=None, ymin=None, ymax=None,
1474 timerange=None,
1680 timerange=None,
1475 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1681 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1476 server=None, folder=None, username=None, password=None,
1682 server=None, folder=None, username=None, password=None,
1477 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1683 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1478
1684
1479
1685
1480 tmin = None
1686 tmin = None
1481 tmax = None
1687 tmax = None
1482 x = dataOut.getTimeRange1(dataOut.outputInterval)
1688 x = dataOut.getTimeRange1(dataOut.outputInterval)
1483 y = dataOut.getHeiRange()
1689 y = dataOut.getHeiRange()
1484
1690
1485
1691
1486 #thisDatetime = dataOut.datatime
1692 #thisDatetime = dataOut.datatime
1487 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1693 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1488 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1694 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1489 xlabel = "Local Time"
1695 xlabel = "Local Time"
1490 ylabel = "Phase"
1696 ylabel = "Phase"
1491
1697
1492
1698
1493 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1699 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1494 phase_beacon = dataOut.data_output
1700 phase_beacon = dataOut.data_output
1495 update_figfile = False
1701 update_figfile = False
1496
1702
1497 if not self.isConfig:
1703 if not self.isConfig:
1498
1704
1499 self.nplots = phase_beacon.size
1705 self.nplots = phase_beacon.size
1500
1706
1501 self.setup(id=id,
1707 self.setup(id=id,
1502 nplots=self.nplots,
1708 nplots=self.nplots,
1503 wintitle=wintitle,
1709 wintitle=wintitle,
1504 showprofile=showprofile,
1710 showprofile=showprofile,
1505 show=show)
1711 show=show)
1506
1712
1507 if timerange is not None:
1713 if timerange is not None:
1508 self.timerange = timerange
1714 self.timerange = timerange
1509
1715
1510 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1716 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1511
1717
1512 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1718 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1513 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1719 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1514
1720
1515 self.FTP_WEI = ftp_wei
1721 self.FTP_WEI = ftp_wei
1516 self.EXP_CODE = exp_code
1722 self.EXP_CODE = exp_code
1517 self.SUB_EXP_CODE = sub_exp_code
1723 self.SUB_EXP_CODE = sub_exp_code
1518 self.PLOT_POS = plot_pos
1724 self.PLOT_POS = plot_pos
1519
1725
1520 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1726 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1521 self.isConfig = True
1727 self.isConfig = True
1522 self.figfile = figfile
1728 self.figfile = figfile
1523 self.xdata = numpy.array([])
1729 self.xdata = numpy.array([])
1524 self.ydata = numpy.array([])
1730 self.ydata = numpy.array([])
1525
1731
1526 #open file beacon phase
1732 #open file beacon phase
1527 path = '%s%03d' %(self.PREFIX, self.id)
1733 path = '%s%03d' %(self.PREFIX, self.id)
1528 beacon_file = os.path.join(path,'%s.txt'%self.name)
1734 beacon_file = os.path.join(path,'%s.txt'%self.name)
1529 self.filename_phase = os.path.join(figpath,beacon_file)
1735 self.filename_phase = os.path.join(figpath,beacon_file)
1530 update_figfile = True
1736 update_figfile = True
1531
1737
1532
1738
1533 #store data beacon phase
1739 #store data beacon phase
1534 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1740 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1535
1741
1536 self.setWinTitle(title)
1742 self.setWinTitle(title)
1537
1743
1538
1744
1539 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1745 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1540
1746
1541 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1747 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1542
1748
1543 axes = self.axesList[0]
1749 axes = self.axesList[0]
1544
1750
1545 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1751 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1546
1752
1547 if len(self.ydata)==0:
1753 if len(self.ydata)==0:
1548 self.ydata = phase_beacon.reshape(-1,1)
1754 self.ydata = phase_beacon.reshape(-1,1)
1549 else:
1755 else:
1550 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1756 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1551
1757
1552
1758
1553 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1759 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1554 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1760 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",
1761 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1556 XAxisAsTime=True, grid='both'
1762 XAxisAsTime=True, grid='both'
1557 )
1763 )
1558
1764
1559 self.draw()
1765 self.draw()
1560
1766
1561 self.save(figpath=figpath,
1767 self.save(figpath=figpath,
1562 figfile=figfile,
1768 figfile=figfile,
1563 save=save,
1769 save=save,
1564 ftp=ftp,
1770 ftp=ftp,
1565 wr_period=wr_period,
1771 wr_period=wr_period,
1566 thisDatetime=thisDatetime,
1772 thisDatetime=thisDatetime,
1567 update_figfile=update_figfile)
1773 update_figfile=update_figfile)
1568
1774
1569 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1775 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1570 self.counter_imagwr = wr_period
1776 self.counter_imagwr = wr_period
1571 self.isConfig = False
1777 self.isConfig = False
1572 update_figfile = True
1778 update_figfile = True
1573
1779
1574
1780
1575
1781
1576 class NSMeteorDetection1Plot(Figure):
1782 class NSMeteorDetection1Plot(Figure):
1577
1783
1578 isConfig = None
1784 isConfig = None
1579 __nsubplots = None
1785 __nsubplots = None
1580
1786
1581 WIDTHPROF = None
1787 WIDTHPROF = None
1582 HEIGHTPROF = None
1788 HEIGHTPROF = None
1583 PREFIX = 'nsm'
1789 PREFIX = 'nsm'
1584
1790
1585 zminList = None
1791 zminList = None
1586 zmaxList = None
1792 zmaxList = None
1587 cmapList = None
1793 cmapList = None
1588 titleList = None
1794 titleList = None
1589 nPairs = None
1795 nPairs = None
1590 nChannels = None
1796 nChannels = None
1591 nParam = None
1797 nParam = None
1592
1798
1593 def __init__(self, **kwargs):
1799 def __init__(self, **kwargs):
1594 Figure.__init__(self, **kwargs)
1800 Figure.__init__(self, **kwargs)
1595 self.isConfig = False
1801 self.isConfig = False
1596 self.__nsubplots = 1
1802 self.__nsubplots = 1
1597
1803
1598 self.WIDTH = 750
1804 self.WIDTH = 750
1599 self.HEIGHT = 250
1805 self.HEIGHT = 250
1600 self.WIDTHPROF = 120
1806 self.WIDTHPROF = 120
1601 self.HEIGHTPROF = 0
1807 self.HEIGHTPROF = 0
1602 self.counter_imagwr = 0
1808 self.counter_imagwr = 0
1603
1809
1604 self.PLOT_CODE = SPEC_CODE
1810 self.PLOT_CODE = SPEC_CODE
1605
1811
1606 self.FTP_WEI = None
1812 self.FTP_WEI = None
1607 self.EXP_CODE = None
1813 self.EXP_CODE = None
1608 self.SUB_EXP_CODE = None
1814 self.SUB_EXP_CODE = None
1609 self.PLOT_POS = None
1815 self.PLOT_POS = None
1610
1816
1611 self.__xfilter_ena = False
1817 self.__xfilter_ena = False
1612 self.__yfilter_ena = False
1818 self.__yfilter_ena = False
1613
1819
1614 def getSubplots(self):
1820 def getSubplots(self):
1615
1821
1616 ncol = 3
1822 ncol = 3
1617 nrow = int(numpy.ceil(self.nplots/3.0))
1823 nrow = int(numpy.ceil(self.nplots/3.0))
1618
1824
1619 return nrow, ncol
1825 return nrow, ncol
1620
1826
1621 def setup(self, id, nplots, wintitle, show=True):
1827 def setup(self, id, nplots, wintitle, show=True):
1622
1828
1623 self.nplots = nplots
1829 self.nplots = nplots
1624
1830
1625 ncolspan = 1
1831 ncolspan = 1
1626 colspan = 1
1832 colspan = 1
1627
1833
1628 self.createFigure(id = id,
1834 self.createFigure(id = id,
1629 wintitle = wintitle,
1835 wintitle = wintitle,
1630 widthplot = self.WIDTH + self.WIDTHPROF,
1836 widthplot = self.WIDTH + self.WIDTHPROF,
1631 heightplot = self.HEIGHT + self.HEIGHTPROF,
1837 heightplot = self.HEIGHT + self.HEIGHTPROF,
1632 show=show)
1838 show=show)
1633
1839
1634 nrow, ncol = self.getSubplots()
1840 nrow, ncol = self.getSubplots()
1635
1841
1636 counter = 0
1842 counter = 0
1637 for y in range(nrow):
1843 for y in range(nrow):
1638 for x in range(ncol):
1844 for x in range(ncol):
1639
1845
1640 if counter >= self.nplots:
1846 if counter >= self.nplots:
1641 break
1847 break
1642
1848
1643 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1849 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1644
1850
1645 counter += 1
1851 counter += 1
1646
1852
1647 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1853 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1648 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1854 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1649 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1855 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1650 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1856 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1651 server=None, folder=None, username=None, password=None,
1857 server=None, folder=None, username=None, password=None,
1652 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1858 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1653 xaxis="frequency"):
1859 xaxis="frequency"):
1654
1860
1655 """
1861 """
1656
1862
1657 Input:
1863 Input:
1658 dataOut :
1864 dataOut :
1659 id :
1865 id :
1660 wintitle :
1866 wintitle :
1661 channelList :
1867 channelList :
1662 showProfile :
1868 showProfile :
1663 xmin : None,
1869 xmin : None,
1664 xmax : None,
1870 xmax : None,
1665 ymin : None,
1871 ymin : None,
1666 ymax : None,
1872 ymax : None,
1667 zmin : None,
1873 zmin : None,
1668 zmax : None
1874 zmax : None
1669 """
1875 """
1670 #SEPARAR EN DOS PLOTS
1876 #SEPARAR EN DOS PLOTS
1671 nParam = dataOut.data_param.shape[1] - 3
1877 nParam = dataOut.data_param.shape[1] - 3
1672
1878
1673 utctime = dataOut.data_param[0,0]
1879 utctime = dataOut.data_param[0,0]
1674 tmet = dataOut.data_param[:,1].astype(int)
1880 tmet = dataOut.data_param[:,1].astype(int)
1675 hmet = dataOut.data_param[:,2].astype(int)
1881 hmet = dataOut.data_param[:,2].astype(int)
1676
1882
1677 x = dataOut.abscissaList
1883 x = dataOut.abscissaList
1678 y = dataOut.heightList
1884 y = dataOut.heightList
1679
1885
1680 z = numpy.zeros((nParam, y.size, x.size - 1))
1886 z = numpy.zeros((nParam, y.size, x.size - 1))
1681 z[:,:] = numpy.nan
1887 z[:,:] = numpy.nan
1682 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1888 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1683 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1889 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1684
1890
1685 xlabel = "Time (s)"
1891 xlabel = "Time (s)"
1686 ylabel = "Range (km)"
1892 ylabel = "Range (km)"
1687
1893
1688 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1894 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1689
1895
1690 if not self.isConfig:
1896 if not self.isConfig:
1691
1897
1692 nplots = nParam
1898 nplots = nParam
1693
1899
1694 self.setup(id=id,
1900 self.setup(id=id,
1695 nplots=nplots,
1901 nplots=nplots,
1696 wintitle=wintitle,
1902 wintitle=wintitle,
1697 show=show)
1903 show=show)
1698
1904
1699 if xmin is None: xmin = numpy.nanmin(x)
1905 if xmin is None: xmin = numpy.nanmin(x)
1700 if xmax is None: xmax = numpy.nanmax(x)
1906 if xmax is None: xmax = numpy.nanmax(x)
1701 if ymin is None: ymin = numpy.nanmin(y)
1907 if ymin is None: ymin = numpy.nanmin(y)
1702 if ymax is None: ymax = numpy.nanmax(y)
1908 if ymax is None: ymax = numpy.nanmax(y)
1703 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1909 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1704 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1910 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1705 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1911 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1706 if vmin is None: vmin = -vmax
1912 if vmin is None: vmin = -vmax
1707 if wmin is None: wmin = 0
1913 if wmin is None: wmin = 0
1708 if wmax is None: wmax = 50
1914 if wmax is None: wmax = 50
1709
1915
1710 pairsList = dataOut.groupList
1916 pairsList = dataOut.groupList
1711 self.nPairs = len(dataOut.groupList)
1917 self.nPairs = len(dataOut.groupList)
1712
1918
1713 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1919 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1714 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1920 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1715 titleList = ["SNR","Radial Velocity","Coherence"]
1921 titleList = ["SNR","Radial Velocity","Coherence"]
1716 cmapList = ["jet","RdBu_r","jet"]
1922 cmapList = ["jet","RdBu_r","jet"]
1717
1923
1718 for i in range(self.nPairs):
1924 for i in range(self.nPairs):
1719 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1925 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1720 titleList = titleList + [strAux1]
1926 titleList = titleList + [strAux1]
1721 cmapList = cmapList + ["RdBu_r"]
1927 cmapList = cmapList + ["RdBu_r"]
1722
1928
1723 self.zminList = zminList
1929 self.zminList = zminList
1724 self.zmaxList = zmaxList
1930 self.zmaxList = zmaxList
1725 self.cmapList = cmapList
1931 self.cmapList = cmapList
1726 self.titleList = titleList
1932 self.titleList = titleList
1727
1933
1728 self.FTP_WEI = ftp_wei
1934 self.FTP_WEI = ftp_wei
1729 self.EXP_CODE = exp_code
1935 self.EXP_CODE = exp_code
1730 self.SUB_EXP_CODE = sub_exp_code
1936 self.SUB_EXP_CODE = sub_exp_code
1731 self.PLOT_POS = plot_pos
1937 self.PLOT_POS = plot_pos
1732
1938
1733 self.isConfig = True
1939 self.isConfig = True
1734
1940
1735 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1941 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1736
1942
1737 for i in range(nParam):
1943 for i in range(nParam):
1738 title = self.titleList[i] + ": " +str_datetime
1944 title = self.titleList[i] + ": " +str_datetime
1739 axes = self.axesList[i]
1945 axes = self.axesList[i]
1740 axes.pcolor(x, y, z[i,:].T,
1946 axes.pcolor(x, y, z[i,:].T,
1741 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1947 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='')
1948 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1743 self.draw()
1949 self.draw()
1744
1950
1745 if figfile == None:
1951 if figfile == None:
1746 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1952 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1747 name = str_datetime
1953 name = str_datetime
1748 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1954 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1749 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1955 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1750 figfile = self.getFilename(name)
1956 figfile = self.getFilename(name)
1751
1957
1752 self.save(figpath=figpath,
1958 self.save(figpath=figpath,
1753 figfile=figfile,
1959 figfile=figfile,
1754 save=save,
1960 save=save,
1755 ftp=ftp,
1961 ftp=ftp,
1756 wr_period=wr_period,
1962 wr_period=wr_period,
1757 thisDatetime=thisDatetime)
1963 thisDatetime=thisDatetime)
1758
1964
1759
1965
1760 class NSMeteorDetection2Plot(Figure):
1966 class NSMeteorDetection2Plot(Figure):
1761
1967
1762 isConfig = None
1968 isConfig = None
1763 __nsubplots = None
1969 __nsubplots = None
1764
1970
1765 WIDTHPROF = None
1971 WIDTHPROF = None
1766 HEIGHTPROF = None
1972 HEIGHTPROF = None
1767 PREFIX = 'nsm'
1973 PREFIX = 'nsm'
1768
1974
1769 zminList = None
1975 zminList = None
1770 zmaxList = None
1976 zmaxList = None
1771 cmapList = None
1977 cmapList = None
1772 titleList = None
1978 titleList = None
1773 nPairs = None
1979 nPairs = None
1774 nChannels = None
1980 nChannels = None
1775 nParam = None
1981 nParam = None
1776
1982
1777 def __init__(self, **kwargs):
1983 def __init__(self, **kwargs):
1778 Figure.__init__(self, **kwargs)
1984 Figure.__init__(self, **kwargs)
1779 self.isConfig = False
1985 self.isConfig = False
1780 self.__nsubplots = 1
1986 self.__nsubplots = 1
1781
1987
1782 self.WIDTH = 750
1988 self.WIDTH = 750
1783 self.HEIGHT = 250
1989 self.HEIGHT = 250
1784 self.WIDTHPROF = 120
1990 self.WIDTHPROF = 120
1785 self.HEIGHTPROF = 0
1991 self.HEIGHTPROF = 0
1786 self.counter_imagwr = 0
1992 self.counter_imagwr = 0
1787
1993
1788 self.PLOT_CODE = SPEC_CODE
1994 self.PLOT_CODE = SPEC_CODE
1789
1995
1790 self.FTP_WEI = None
1996 self.FTP_WEI = None
1791 self.EXP_CODE = None
1997 self.EXP_CODE = None
1792 self.SUB_EXP_CODE = None
1998 self.SUB_EXP_CODE = None
1793 self.PLOT_POS = None
1999 self.PLOT_POS = None
1794
2000
1795 self.__xfilter_ena = False
2001 self.__xfilter_ena = False
1796 self.__yfilter_ena = False
2002 self.__yfilter_ena = False
1797
2003
1798 def getSubplots(self):
2004 def getSubplots(self):
1799
2005
1800 ncol = 3
2006 ncol = 3
1801 nrow = int(numpy.ceil(self.nplots/3.0))
2007 nrow = int(numpy.ceil(self.nplots/3.0))
1802
2008
1803 return nrow, ncol
2009 return nrow, ncol
1804
2010
1805 def setup(self, id, nplots, wintitle, show=True):
2011 def setup(self, id, nplots, wintitle, show=True):
1806
2012
1807 self.nplots = nplots
2013 self.nplots = nplots
1808
2014
1809 ncolspan = 1
2015 ncolspan = 1
1810 colspan = 1
2016 colspan = 1
1811
2017
1812 self.createFigure(id = id,
2018 self.createFigure(id = id,
1813 wintitle = wintitle,
2019 wintitle = wintitle,
1814 widthplot = self.WIDTH + self.WIDTHPROF,
2020 widthplot = self.WIDTH + self.WIDTHPROF,
1815 heightplot = self.HEIGHT + self.HEIGHTPROF,
2021 heightplot = self.HEIGHT + self.HEIGHTPROF,
1816 show=show)
2022 show=show)
1817
2023
1818 nrow, ncol = self.getSubplots()
2024 nrow, ncol = self.getSubplots()
1819
2025
1820 counter = 0
2026 counter = 0
1821 for y in range(nrow):
2027 for y in range(nrow):
1822 for x in range(ncol):
2028 for x in range(ncol):
1823
2029
1824 if counter >= self.nplots:
2030 if counter >= self.nplots:
1825 break
2031 break
1826
2032
1827 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
2033 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1828
2034
1829 counter += 1
2035 counter += 1
1830
2036
1831 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
2037 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1832 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
2038 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1833 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
2039 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1834 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
2040 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1835 server=None, folder=None, username=None, password=None,
2041 server=None, folder=None, username=None, password=None,
1836 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
2042 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1837 xaxis="frequency"):
2043 xaxis="frequency"):
1838
2044
1839 """
2045 """
1840
2046
1841 Input:
2047 Input:
1842 dataOut :
2048 dataOut :
1843 id :
2049 id :
1844 wintitle :
2050 wintitle :
1845 channelList :
2051 channelList :
1846 showProfile :
2052 showProfile :
1847 xmin : None,
2053 xmin : None,
1848 xmax : None,
2054 xmax : None,
1849 ymin : None,
2055 ymin : None,
1850 ymax : None,
2056 ymax : None,
1851 zmin : None,
2057 zmin : None,
1852 zmax : None
2058 zmax : None
1853 """
2059 """
1854 #Rebuild matrix
2060 #Rebuild matrix
1855 utctime = dataOut.data_param[0,0]
2061 utctime = dataOut.data_param[0,0]
1856 cmet = dataOut.data_param[:,1].astype(int)
2062 cmet = dataOut.data_param[:,1].astype(int)
1857 tmet = dataOut.data_param[:,2].astype(int)
2063 tmet = dataOut.data_param[:,2].astype(int)
1858 hmet = dataOut.data_param[:,3].astype(int)
2064 hmet = dataOut.data_param[:,3].astype(int)
1859
2065
1860 nParam = 3
2066 nParam = 3
1861 nChan = len(dataOut.groupList)
2067 nChan = len(dataOut.groupList)
1862 x = dataOut.abscissaList
2068 x = dataOut.abscissaList
1863 y = dataOut.heightList
2069 y = dataOut.heightList
1864
2070
1865 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
2071 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
1866 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
2072 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
1867 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
2073 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
1868 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
2074 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
1869
2075
1870 xlabel = "Time (s)"
2076 xlabel = "Time (s)"
1871 ylabel = "Range (km)"
2077 ylabel = "Range (km)"
1872
2078
1873 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
2079 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1874
2080
1875 if not self.isConfig:
2081 if not self.isConfig:
1876
2082
1877 nplots = nParam*nChan
2083 nplots = nParam*nChan
1878
2084
1879 self.setup(id=id,
2085 self.setup(id=id,
1880 nplots=nplots,
2086 nplots=nplots,
1881 wintitle=wintitle,
2087 wintitle=wintitle,
1882 show=show)
2088 show=show)
1883
2089
1884 if xmin is None: xmin = numpy.nanmin(x)
2090 if xmin is None: xmin = numpy.nanmin(x)
1885 if xmax is None: xmax = numpy.nanmax(x)
2091 if xmax is None: xmax = numpy.nanmax(x)
1886 if ymin is None: ymin = numpy.nanmin(y)
2092 if ymin is None: ymin = numpy.nanmin(y)
1887 if ymax is None: ymax = numpy.nanmax(y)
2093 if ymax is None: ymax = numpy.nanmax(y)
1888 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
2094 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1889 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
2095 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1890 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
2096 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1891 if vmin is None: vmin = -vmax
2097 if vmin is None: vmin = -vmax
1892 if wmin is None: wmin = 0
2098 if wmin is None: wmin = 0
1893 if wmax is None: wmax = 50
2099 if wmax is None: wmax = 50
1894
2100
1895 self.nChannels = nChan
2101 self.nChannels = nChan
1896
2102
1897 zminList = []
2103 zminList = []
1898 zmaxList = []
2104 zmaxList = []
1899 titleList = []
2105 titleList = []
1900 cmapList = []
2106 cmapList = []
1901 for i in range(self.nChannels):
2107 for i in range(self.nChannels):
1902 strAux1 = "SNR Channel "+ str(i)
2108 strAux1 = "SNR Channel "+ str(i)
1903 strAux2 = "Radial Velocity Channel "+ str(i)
2109 strAux2 = "Radial Velocity Channel "+ str(i)
1904 strAux3 = "Spectral Width Channel "+ str(i)
2110 strAux3 = "Spectral Width Channel "+ str(i)
1905
2111
1906 titleList = titleList + [strAux1,strAux2,strAux3]
2112 titleList = titleList + [strAux1,strAux2,strAux3]
1907 cmapList = cmapList + ["jet","RdBu_r","jet"]
2113 cmapList = cmapList + ["jet","RdBu_r","jet"]
1908 zminList = zminList + [SNRmin,vmin,wmin]
2114 zminList = zminList + [SNRmin,vmin,wmin]
1909 zmaxList = zmaxList + [SNRmax,vmax,wmax]
2115 zmaxList = zmaxList + [SNRmax,vmax,wmax]
1910
2116
1911 self.zminList = zminList
2117 self.zminList = zminList
1912 self.zmaxList = zmaxList
2118 self.zmaxList = zmaxList
1913 self.cmapList = cmapList
2119 self.cmapList = cmapList
1914 self.titleList = titleList
2120 self.titleList = titleList
1915
2121
1916 self.FTP_WEI = ftp_wei
2122 self.FTP_WEI = ftp_wei
1917 self.EXP_CODE = exp_code
2123 self.EXP_CODE = exp_code
1918 self.SUB_EXP_CODE = sub_exp_code
2124 self.SUB_EXP_CODE = sub_exp_code
1919 self.PLOT_POS = plot_pos
2125 self.PLOT_POS = plot_pos
1920
2126
1921 self.isConfig = True
2127 self.isConfig = True
1922
2128
1923 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
2129 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1924
2130
1925 for i in range(self.nplots):
2131 for i in range(self.nplots):
1926 title = self.titleList[i] + ": " +str_datetime
2132 title = self.titleList[i] + ": " +str_datetime
1927 axes = self.axesList[i]
2133 axes = self.axesList[i]
1928 axes.pcolor(x, y, z[i,:].T,
2134 axes.pcolor(x, y, z[i,:].T,
1929 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
2135 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='')
2136 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1931 self.draw()
2137 self.draw()
1932
2138
1933 if figfile == None:
2139 if figfile == None:
1934 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
2140 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1935 name = str_datetime
2141 name = str_datetime
1936 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
2142 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1937 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
2143 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1938 figfile = self.getFilename(name)
2144 figfile = self.getFilename(name)
1939
2145
1940 self.save(figpath=figpath,
2146 self.save(figpath=figpath,
1941 figfile=figfile,
2147 figfile=figfile,
1942 save=save,
2148 save=save,
1943 ftp=ftp,
2149 ftp=ftp,
1944 wr_period=wr_period,
2150 wr_period=wr_period,
1945 thisDatetime=thisDatetime)
2151 thisDatetime=thisDatetime)
@@ -1,1535 +1,1542
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
13
14 class SpectraPlot(Figure):
14 class SpectraPlot(Figure):
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, **kwargs):
24 Figure.__init__(self, **kwargs)
24 Figure.__init__(self, **kwargs)
25 self.isConfig = False
25 self.isConfig = False
26 self.__nsubplots = 1
26 self.__nsubplots = 1
27
27
28 self.WIDTH = 250
28 self.WIDTH = 250
29 self.HEIGHT = 250
29 self.HEIGHT = 250
30 self.WIDTHPROF = 120
30 self.WIDTHPROF = 120
31 self.HEIGHTPROF = 0
31 self.HEIGHTPROF = 0
32 self.counter_imagwr = 0
32 self.counter_imagwr = 0
33
33
34 self.PLOT_CODE = SPEC_CODE
34 self.PLOT_CODE = SPEC_CODE
35
35
36 self.FTP_WEI = None
36 self.FTP_WEI = None
37 self.EXP_CODE = None
37 self.EXP_CODE = None
38 self.SUB_EXP_CODE = None
38 self.SUB_EXP_CODE = None
39 self.PLOT_POS = None
39 self.PLOT_POS = None
40
40
41 self.__xfilter_ena = False
41 self.__xfilter_ena = False
42 self.__yfilter_ena = False
42 self.__yfilter_ena = False
43
43
44 def getSubplots(self):
44 def getSubplots(self):
45
45
46 ncol = int(numpy.sqrt(self.nplots)+0.9)
46 ncol = int(numpy.sqrt(self.nplots)+0.9)
47 nrow = int(self.nplots*1./ncol + 0.9)
47 nrow = int(self.nplots*1./ncol + 0.9)
48
48
49 return nrow, ncol
49 return nrow, ncol
50
50
51 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
51 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
52
52
53 self.__showprofile = showprofile
53 self.__showprofile = showprofile
54 self.nplots = nplots
54 self.nplots = nplots
55
55
56 ncolspan = 1
56 ncolspan = 1
57 colspan = 1
57 colspan = 1
58 if showprofile:
58 if showprofile:
59 ncolspan = 3
59 ncolspan = 3
60 colspan = 2
60 colspan = 2
61 self.__nsubplots = 2
61 self.__nsubplots = 2
62
62
63 self.createFigure(id = id,
63 self.createFigure(id = id,
64 wintitle = wintitle,
64 wintitle = wintitle,
65 widthplot = self.WIDTH + self.WIDTHPROF,
65 widthplot = self.WIDTH + self.WIDTHPROF,
66 heightplot = self.HEIGHT + self.HEIGHTPROF,
66 heightplot = self.HEIGHT + self.HEIGHTPROF,
67 show=show)
67 show=show)
68
68
69 nrow, ncol = self.getSubplots()
69 nrow, ncol = self.getSubplots()
70
70
71 counter = 0
71 counter = 0
72 for y in range(nrow):
72 for y in range(nrow):
73 for x in range(ncol):
73 for x in range(ncol):
74
74
75 if counter >= self.nplots:
75 if counter >= self.nplots:
76 break
76 break
77
77
78 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
78 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
79
79
80 if showprofile:
80 if showprofile:
81 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
81 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
82
82
83 counter += 1
83 counter += 1
84
84
85 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
85 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
86 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
86 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
87 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
87 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
88 server=None, folder=None, username=None, password=None,
88 server=None, folder=None, username=None, password=None,
89 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
89 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
90 xaxis="velocity", **kwargs):
90 xaxis="frequency", colormap='jet', normFactor=None):
91
91
92 """
92 """
93
93
94 Input:
94 Input:
95 dataOut :
95 dataOut :
96 id :
96 id :
97 wintitle :
97 wintitle :
98 channelList :
98 channelList :
99 showProfile :
99 showProfile :
100 xmin : None,
100 xmin : None,
101 xmax : None,
101 xmax : None,
102 ymin : None,
102 ymin : None,
103 ymax : None,
103 ymax : None,
104 zmin : None,
104 zmin : None,
105 zmax : None
105 zmax : None
106 """
106 """
107
108 colormap = kwargs.get('colormap','jet')
109
110 if realtime:
107 if realtime:
111 if not(isRealtime(utcdatatime = dataOut.utctime)):
108 if not(isRealtime(utcdatatime = dataOut.utctime)):
112 print 'Skipping this plot function'
109 print 'Skipping this plot function'
113 return
110 return
114
111
115 if channelList == None:
112 if channelList == None:
116 channelIndexList = dataOut.channelIndexList
113 channelIndexList = dataOut.channelIndexList
117 else:
114 else:
118 channelIndexList = []
115 channelIndexList = []
119 for channel in channelList:
116 for channel in channelList:
120 if channel not in dataOut.channelList:
117 if channel not in dataOut.channelList:
121 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
118 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
122 channelIndexList.append(dataOut.channelList.index(channel))
119 channelIndexList.append(dataOut.channelList.index(channel))
123
120
124 factor = dataOut.normFactor
121 if normFactor is None:
125
122 factor = dataOut.normFactor
123 else:
124 factor = normFactor
126 if xaxis == "frequency":
125 if xaxis == "frequency":
127 x = dataOut.getFreqRange(1)/1000.
126 x = dataOut.getFreqRange(1)/1000.
128 xlabel = "Frequency (kHz)"
127 xlabel = "Frequency (kHz)"
129
128
130 elif xaxis == "time":
129 elif xaxis == "time":
131 x = dataOut.getAcfRange(1)
130 x = dataOut.getAcfRange(1)
132 xlabel = "Time (ms)"
131 xlabel = "Time (ms)"
133
132
134 else:
133 else:
135 x = dataOut.getVelRange(1)
134 x = dataOut.getVelRange(1)
136 xlabel = "Velocity (m/s)"
135 xlabel = "Velocity (m/s)"
137
136
138 ylabel = "Range (Km)"
137 ylabel = "Range (Km)"
139
138
140 y = dataOut.getHeiRange()
139 y = dataOut.getHeiRange()
141
140
142 z = dataOut.data_spc/factor
141 z = dataOut.data_spc/factor
143 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
142 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
144 zdB = 10*numpy.log10(z)
143 zdB = 10*numpy.log10(z)
145
144
146 avg = numpy.average(z, axis=1)
145 avg = numpy.average(z, axis=1)
147 avgdB = 10*numpy.log10(avg)
146 avgdB = 10*numpy.log10(avg)
148
147
149 noise = dataOut.getNoise()/factor
148 noise = dataOut.getNoise()/factor
150 noisedB = 10*numpy.log10(noise)
149 noisedB = 10*numpy.log10(noise)
151
150
152 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
151 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
153 title = wintitle + " Spectra"
152 title = wintitle + " Spectra"
154 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
153 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
155 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
154 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
156
155
157 if not self.isConfig:
156 if not self.isConfig:
158
157
159 nplots = len(channelIndexList)
158 nplots = len(channelIndexList)
160
159
161 self.setup(id=id,
160 self.setup(id=id,
162 nplots=nplots,
161 nplots=nplots,
163 wintitle=wintitle,
162 wintitle=wintitle,
164 showprofile=showprofile,
163 showprofile=showprofile,
165 show=show)
164 show=show)
166
165
167 if xmin == None: xmin = numpy.nanmin(x)
166 if xmin == None: xmin = numpy.nanmin(x)
168 if xmax == None: xmax = numpy.nanmax(x)
167 if xmax == None: xmax = numpy.nanmax(x)
169 if ymin == None: ymin = numpy.nanmin(y)
168 if ymin == None: ymin = numpy.nanmin(y)
170 if ymax == None: ymax = numpy.nanmax(y)
169 if ymax == None: ymax = numpy.nanmax(y)
171 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
170 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
172 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
171 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
173
172
174 self.FTP_WEI = ftp_wei
173 self.FTP_WEI = ftp_wei
175 self.EXP_CODE = exp_code
174 self.EXP_CODE = exp_code
176 self.SUB_EXP_CODE = sub_exp_code
175 self.SUB_EXP_CODE = sub_exp_code
177 self.PLOT_POS = plot_pos
176 self.PLOT_POS = plot_pos
178
177
179 self.isConfig = True
178 self.isConfig = True
180
179
181 self.setWinTitle(title)
180 self.setWinTitle(title)
182
181
183 for i in range(self.nplots):
182 for i in range(self.nplots):
184 index = channelIndexList[i]
183 index = channelIndexList[i]
185 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
184 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
186 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
185 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
187 if len(dataOut.beam.codeList) != 0:
186 if len(dataOut.beam.codeList) != 0:
188 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)
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)
189
188
190 axes = self.axesList[i*self.__nsubplots]
189 axes = self.axesList[i*self.__nsubplots]
191 axes.pcolor(x, y, zdB[index,:,:],
190 axes.pcolor(x, y, zdB[index,:,:],
192 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
191 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
193 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
192 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
194 ticksize=9, cblabel='')
193 ticksize=9, cblabel='')
195
194
196 if self.__showprofile:
195 if self.__showprofile:
197 axes = self.axesList[i*self.__nsubplots +1]
196 axes = self.axesList[i*self.__nsubplots +1]
198 axes.pline(avgdB[index,:], y,
197 axes.pline(avgdB[index,:], y,
199 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
198 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
200 xlabel='dB', ylabel='', title='',
199 xlabel='dB', ylabel='', title='',
201 ytick_visible=False,
200 ytick_visible=False,
202 grid='x')
201 grid='x')
203
202
204 noiseline = numpy.repeat(noisedB[index], len(y))
203 noiseline = numpy.repeat(noisedB[index], len(y))
205 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
204 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
206
205
207 self.draw()
206 self.draw()
208
207
209 if figfile == None:
208 if figfile == None:
210 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
209 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
211 name = str_datetime
210 name = str_datetime
212 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
211 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
213 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
212 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
214 figfile = self.getFilename(name)
213 figfile = self.getFilename(name)
215
214
216 self.save(figpath=figpath,
215 self.save(figpath=figpath,
217 figfile=figfile,
216 figfile=figfile,
218 save=save,
217 save=save,
219 ftp=ftp,
218 ftp=ftp,
220 wr_period=wr_period,
219 wr_period=wr_period,
221 thisDatetime=thisDatetime)
220 thisDatetime=thisDatetime)
222
221
223 class CrossSpectraPlot(Figure):
222 class CrossSpectraPlot(Figure):
224
223
225 isConfig = None
224 isConfig = None
226 __nsubplots = None
225 __nsubplots = None
227
226
228 WIDTH = None
227 WIDTH = None
229 HEIGHT = None
228 HEIGHT = None
230 WIDTHPROF = None
229 WIDTHPROF = None
231 HEIGHTPROF = None
230 HEIGHTPROF = None
232 PREFIX = 'cspc'
231 PREFIX = 'cspc'
233
232
234 def __init__(self, **kwargs):
233 def __init__(self, **kwargs):
235 Figure.__init__(self, **kwargs)
234 Figure.__init__(self, **kwargs)
236 self.isConfig = False
235 self.isConfig = False
237 self.__nsubplots = 4
236 self.__nsubplots = 4
238 self.counter_imagwr = 0
237 self.counter_imagwr = 0
239 self.WIDTH = 250
238 self.WIDTH = 250
240 self.HEIGHT = 250
239 self.HEIGHT = 250
241 self.WIDTHPROF = 0
240 self.WIDTHPROF = 0
242 self.HEIGHTPROF = 0
241 self.HEIGHTPROF = 0
243
242
244 self.PLOT_CODE = CROSS_CODE
243 self.PLOT_CODE = CROSS_CODE
245 self.FTP_WEI = None
244 self.FTP_WEI = None
246 self.EXP_CODE = None
245 self.EXP_CODE = None
247 self.SUB_EXP_CODE = None
246 self.SUB_EXP_CODE = None
248 self.PLOT_POS = None
247 self.PLOT_POS = None
249
248
250 def getSubplots(self):
249 def getSubplots(self):
251
250
252 ncol = 4
251 ncol = 4
253 nrow = self.nplots
252 nrow = self.nplots
254
253
255 return nrow, ncol
254 return nrow, ncol
256
255
257 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
256 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
258
257
259 self.__showprofile = showprofile
258 self.__showprofile = showprofile
260 self.nplots = nplots
259 self.nplots = nplots
261
260
262 ncolspan = 1
261 ncolspan = 1
263 colspan = 1
262 colspan = 1
264
263
265 self.createFigure(id = id,
264 self.createFigure(id = id,
266 wintitle = wintitle,
265 wintitle = wintitle,
267 widthplot = self.WIDTH + self.WIDTHPROF,
266 widthplot = self.WIDTH + self.WIDTHPROF,
268 heightplot = self.HEIGHT + self.HEIGHTPROF,
267 heightplot = self.HEIGHT + self.HEIGHTPROF,
269 show=True)
268 show=True)
270
269
271 nrow, ncol = self.getSubplots()
270 nrow, ncol = self.getSubplots()
272
271
273 counter = 0
272 counter = 0
274 for y in range(nrow):
273 for y in range(nrow):
275 for x in range(ncol):
274 for x in range(ncol):
276 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
275 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
277
276
278 counter += 1
277 counter += 1
279
278
280 def run(self, dataOut, id, wintitle="", pairsList=None,
279 def run(self, dataOut, id, wintitle="", pairsList=None,
281 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
280 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
282 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
281 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
283 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
282 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
284 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
283 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
285 server=None, folder=None, username=None, password=None,
284 server=None, folder=None, username=None, password=None,
286 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0,
285 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None,
287 xaxis='frequency'):
286 xaxis='frequency'):
288
287
289 """
288 """
290
289
291 Input:
290 Input:
292 dataOut :
291 dataOut :
293 id :
292 id :
294 wintitle :
293 wintitle :
295 channelList :
294 channelList :
296 showProfile :
295 showProfile :
297 xmin : None,
296 xmin : None,
298 xmax : None,
297 xmax : None,
299 ymin : None,
298 ymin : None,
300 ymax : None,
299 ymax : None,
301 zmin : None,
300 zmin : None,
302 zmax : None
301 zmax : None
303 """
302 """
304
303
305 if pairsList == None:
304 if pairsList == None:
306 pairsIndexList = dataOut.pairsIndexList
305 pairsIndexList = dataOut.pairsIndexList
307 else:
306 else:
308 pairsIndexList = []
307 pairsIndexList = []
309 for pair in pairsList:
308 for pair in pairsList:
310 if pair not in dataOut.pairsList:
309 if pair not in dataOut.pairsList:
311 raise ValueError, "Pair %s is not in dataOut.pairsList" %str(pair)
310 raise ValueError, "Pair %s is not in dataOut.pairsList" %str(pair)
312 pairsIndexList.append(dataOut.pairsList.index(pair))
311 pairsIndexList.append(dataOut.pairsList.index(pair))
313
312
314 if not pairsIndexList:
313 if not pairsIndexList:
315 return
314 return
316
315
317 if len(pairsIndexList) > 4:
316 if len(pairsIndexList) > 4:
318 pairsIndexList = pairsIndexList[0:4]
317 pairsIndexList = pairsIndexList[0:4]
319
318
320 factor = dataOut.normFactor
319 if normFactor is None:
320 factor = dataOut.normFactor
321 else:
322 factor = normFactor
321 x = dataOut.getVelRange(1)
323 x = dataOut.getVelRange(1)
322 y = dataOut.getHeiRange()
324 y = dataOut.getHeiRange()
323 z = dataOut.data_spc[:,:,:]/factor
325 z = dataOut.data_spc[:,:,:]/factor
324 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
326 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
325
327
326 noise = dataOut.noise/factor
328 noise = dataOut.noise/factor
327
329
328 zdB = 10*numpy.log10(z)
330 zdB = 10*numpy.log10(z)
329 noisedB = 10*numpy.log10(noise)
331 noisedB = 10*numpy.log10(noise)
330
332
331 if coh_min == None:
333 if coh_min == None:
332 coh_min = 0.0
334 coh_min = 0.0
333 if coh_max == None:
335 if coh_max == None:
334 coh_max = 1.0
336 coh_max = 1.0
335
337
336 if phase_min == None:
338 if phase_min == None:
337 phase_min = -180
339 phase_min = -180
338 if phase_max == None:
340 if phase_max == None:
339 phase_max = 180
341 phase_max = 180
340
342
341 #thisDatetime = dataOut.datatime
343 #thisDatetime = dataOut.datatime
342 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
344 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
343 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
345 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
344 # xlabel = "Velocity (m/s)"
346 # xlabel = "Velocity (m/s)"
345 ylabel = "Range (Km)"
347 ylabel = "Range (Km)"
346
348
347 if xaxis == "frequency":
349 if xaxis == "frequency":
348 x = dataOut.getFreqRange(1)/1000.
350 x = dataOut.getFreqRange(1)/1000.
349 xlabel = "Frequency (kHz)"
351 xlabel = "Frequency (kHz)"
350
352
351 elif xaxis == "time":
353 elif xaxis == "time":
352 x = dataOut.getAcfRange(1)
354 x = dataOut.getAcfRange(1)
353 xlabel = "Time (ms)"
355 xlabel = "Time (ms)"
354
356
355 else:
357 else:
356 x = dataOut.getVelRange(1)
358 x = dataOut.getVelRange(1)
357 xlabel = "Velocity (m/s)"
359 xlabel = "Velocity (m/s)"
358
360
359 if not self.isConfig:
361 if not self.isConfig:
360
362
361 nplots = len(pairsIndexList)
363 nplots = len(pairsIndexList)
362
364
363 self.setup(id=id,
365 self.setup(id=id,
364 nplots=nplots,
366 nplots=nplots,
365 wintitle=wintitle,
367 wintitle=wintitle,
366 showprofile=False,
368 showprofile=False,
367 show=show)
369 show=show)
368
370
369 avg = numpy.abs(numpy.average(z, axis=1))
371 avg = numpy.abs(numpy.average(z, axis=1))
370 avgdB = 10*numpy.log10(avg)
372 avgdB = 10*numpy.log10(avg)
371
373
372 if xmin == None: xmin = numpy.nanmin(x)
374 if xmin == None: xmin = numpy.nanmin(x)
373 if xmax == None: xmax = numpy.nanmax(x)
375 if xmax == None: xmax = numpy.nanmax(x)
374 if ymin == None: ymin = numpy.nanmin(y)
376 if ymin == None: ymin = numpy.nanmin(y)
375 if ymax == None: ymax = numpy.nanmax(y)
377 if ymax == None: ymax = numpy.nanmax(y)
376 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
378 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
377 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
379 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
378
380
379 self.FTP_WEI = ftp_wei
381 self.FTP_WEI = ftp_wei
380 self.EXP_CODE = exp_code
382 self.EXP_CODE = exp_code
381 self.SUB_EXP_CODE = sub_exp_code
383 self.SUB_EXP_CODE = sub_exp_code
382 self.PLOT_POS = plot_pos
384 self.PLOT_POS = plot_pos
383
385
384 self.isConfig = True
386 self.isConfig = True
385
387
386 self.setWinTitle(title)
388 self.setWinTitle(title)
387
389
388 for i in range(self.nplots):
390 for i in range(self.nplots):
389 pair = dataOut.pairsList[pairsIndexList[i]]
391 pair = dataOut.pairsList[pairsIndexList[i]]
390
392
391 chan_index0 = dataOut.channelList.index(pair[0])
393 chan_index0 = dataOut.channelList.index(pair[0])
392 chan_index1 = dataOut.channelList.index(pair[1])
394 chan_index1 = dataOut.channelList.index(pair[1])
393
395
394 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
396 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
395 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
397 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
396 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
398 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
397 axes0 = self.axesList[i*self.__nsubplots]
399 axes0 = self.axesList[i*self.__nsubplots]
398 axes0.pcolor(x, y, zdB,
400 axes0.pcolor(x, y, zdB,
399 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
401 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
400 xlabel=xlabel, ylabel=ylabel, title=title,
402 xlabel=xlabel, ylabel=ylabel, title=title,
401 ticksize=9, colormap=power_cmap, cblabel='')
403 ticksize=9, colormap=power_cmap, cblabel='')
402
404
403 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
405 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
404 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
406 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
405 axes0 = self.axesList[i*self.__nsubplots+1]
407 axes0 = self.axesList[i*self.__nsubplots+1]
406 axes0.pcolor(x, y, zdB,
408 axes0.pcolor(x, y, zdB,
407 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
409 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
408 xlabel=xlabel, ylabel=ylabel, title=title,
410 xlabel=xlabel, ylabel=ylabel, title=title,
409 ticksize=9, colormap=power_cmap, cblabel='')
411 ticksize=9, colormap=power_cmap, cblabel='')
410
412
411 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:])
413 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:])
412 coherence = numpy.abs(coherenceComplex)
414 coherence = numpy.abs(coherenceComplex)
413 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
415 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
414 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
416 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
415
417
416 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
418 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
417 axes0 = self.axesList[i*self.__nsubplots+2]
419 axes0 = self.axesList[i*self.__nsubplots+2]
418 axes0.pcolor(x, y, coherence,
420 axes0.pcolor(x, y, coherence,
419 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
421 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
420 xlabel=xlabel, ylabel=ylabel, title=title,
422 xlabel=xlabel, ylabel=ylabel, title=title,
421 ticksize=9, colormap=coherence_cmap, cblabel='')
423 ticksize=9, colormap=coherence_cmap, cblabel='')
422
424
423 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
425 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
424 axes0 = self.axesList[i*self.__nsubplots+3]
426 axes0 = self.axesList[i*self.__nsubplots+3]
425 axes0.pcolor(x, y, phase,
427 axes0.pcolor(x, y, phase,
426 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
428 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
427 xlabel=xlabel, ylabel=ylabel, title=title,
429 xlabel=xlabel, ylabel=ylabel, title=title,
428 ticksize=9, colormap=phase_cmap, cblabel='')
430 ticksize=9, colormap=phase_cmap, cblabel='')
429
431
430
432
431
433
432 self.draw()
434 self.draw()
433
435
434 self.save(figpath=figpath,
436 self.save(figpath=figpath,
435 figfile=figfile,
437 figfile=figfile,
436 save=save,
438 save=save,
437 ftp=ftp,
439 ftp=ftp,
438 wr_period=wr_period,
440 wr_period=wr_period,
439 thisDatetime=thisDatetime)
441 thisDatetime=thisDatetime)
440
442
441
443
442 class RTIPlot(Figure):
444 class RTIPlot(Figure):
443
445
444 __isConfig = None
446 __isConfig = None
445 __nsubplots = None
447 __nsubplots = None
446
448
447 WIDTHPROF = None
449 WIDTHPROF = None
448 HEIGHTPROF = None
450 HEIGHTPROF = None
449 PREFIX = 'rti'
451 PREFIX = 'rti'
450
452
451 def __init__(self, **kwargs):
453 def __init__(self, **kwargs):
452
454
453 Figure.__init__(self, **kwargs)
455 Figure.__init__(self, **kwargs)
454 self.timerange = None
456 self.timerange = None
455 self.isConfig = False
457 self.isConfig = False
456 self.__nsubplots = 1
458 self.__nsubplots = 1
457
459
458 self.WIDTH = 800
460 self.WIDTH = 800
459 self.HEIGHT = 180
461 self.HEIGHT = 180
460 self.WIDTHPROF = 120
462 self.WIDTHPROF = 120
461 self.HEIGHTPROF = 0
463 self.HEIGHTPROF = 0
462 self.counter_imagwr = 0
464 self.counter_imagwr = 0
463
465
464 self.PLOT_CODE = RTI_CODE
466 self.PLOT_CODE = RTI_CODE
465
467
466 self.FTP_WEI = None
468 self.FTP_WEI = None
467 self.EXP_CODE = None
469 self.EXP_CODE = None
468 self.SUB_EXP_CODE = None
470 self.SUB_EXP_CODE = None
469 self.PLOT_POS = None
471 self.PLOT_POS = None
470 self.tmin = None
472 self.tmin = None
471 self.tmax = None
473 self.tmax = None
472
474
473 self.xmin = None
475 self.xmin = None
474 self.xmax = None
476 self.xmax = None
475
477
476 self.figfile = None
478 self.figfile = None
477
479
478 def getSubplots(self):
480 def getSubplots(self):
479
481
480 ncol = 1
482 ncol = 1
481 nrow = self.nplots
483 nrow = self.nplots
482
484
483 return nrow, ncol
485 return nrow, ncol
484
486
485 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
487 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
486
488
487 self.__showprofile = showprofile
489 self.__showprofile = showprofile
488 self.nplots = nplots
490 self.nplots = nplots
489
491
490 ncolspan = 1
492 ncolspan = 1
491 colspan = 1
493 colspan = 1
492 if showprofile:
494 if showprofile:
493 ncolspan = 7
495 ncolspan = 7
494 colspan = 6
496 colspan = 6
495 self.__nsubplots = 2
497 self.__nsubplots = 2
496
498
497 self.createFigure(id = id,
499 self.createFigure(id = id,
498 wintitle = wintitle,
500 wintitle = wintitle,
499 widthplot = self.WIDTH + self.WIDTHPROF,
501 widthplot = self.WIDTH + self.WIDTHPROF,
500 heightplot = self.HEIGHT + self.HEIGHTPROF,
502 heightplot = self.HEIGHT + self.HEIGHTPROF,
501 show=show)
503 show=show)
502
504
503 nrow, ncol = self.getSubplots()
505 nrow, ncol = self.getSubplots()
504
506
505 counter = 0
507 counter = 0
506 for y in range(nrow):
508 for y in range(nrow):
507 for x in range(ncol):
509 for x in range(ncol):
508
510
509 if counter >= self.nplots:
511 if counter >= self.nplots:
510 break
512 break
511
513
512 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
514 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
513
515
514 if showprofile:
516 if showprofile:
515 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
517 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
516
518
517 counter += 1
519 counter += 1
518
520
519 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
521 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
520 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
522 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
521 timerange=None,
523 timerange=None, colormap='jet',
522 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
524 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
523 server=None, folder=None, username=None, password=None,
525 server=None, folder=None, username=None, password=None,
524 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, **kwargs):
526 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None, HEIGHT=None):
525
527
526 """
528 """
527
529
528 Input:
530 Input:
529 dataOut :
531 dataOut :
530 id :
532 id :
531 wintitle :
533 wintitle :
532 channelList :
534 channelList :
533 showProfile :
535 showProfile :
534 xmin : None,
536 xmin : None,
535 xmax : None,
537 xmax : None,
536 ymin : None,
538 ymin : None,
537 ymax : None,
539 ymax : None,
538 zmin : None,
540 zmin : None,
539 zmax : None
541 zmax : None
540 """
542 """
541
543
542 colormap = kwargs.get('colormap', 'jet')
544 #colormap = kwargs.get('colormap', 'jet')
545 if HEIGHT is not None:
546 self.HEIGHT = HEIGHT
547
543 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
548 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
544 return
549 return
545
550
546 if channelList == None:
551 if channelList == None:
547 channelIndexList = dataOut.channelIndexList
552 channelIndexList = dataOut.channelIndexList
548 else:
553 else:
549 channelIndexList = []
554 channelIndexList = []
550 for channel in channelList:
555 for channel in channelList:
551 if channel not in dataOut.channelList:
556 if channel not in dataOut.channelList:
552 raise ValueError, "Channel %d is not in dataOut.channelList"
557 raise ValueError, "Channel %d is not in dataOut.channelList"
553 channelIndexList.append(dataOut.channelList.index(channel))
558 channelIndexList.append(dataOut.channelList.index(channel))
554
559
555 if hasattr(dataOut, 'normFactor'):
560 if normFactor is None:
556 factor = dataOut.normFactor
561 factor = dataOut.normFactor
557 else:
562 else:
558 factor = 1
563 factor = normFactor
559
564
560 # factor = dataOut.normFactor
565 # factor = dataOut.normFactor
561 x = dataOut.getTimeRange()
566 x = dataOut.getTimeRange()
562 y = dataOut.getHeiRange()
567 y = dataOut.getHeiRange()
563
568
564 # z = dataOut.data_spc/factor
569 z = dataOut.data_spc/factor
565 # z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
570 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
566 # avg = numpy.average(z, axis=1)
571 avg = numpy.average(z, axis=1)
567 # avgdB = 10.*numpy.log10(avg)
572 avgdB = 10.*numpy.log10(avg)
568 avgdB = dataOut.getPower()
573 # avgdB = dataOut.getPower()
574
569
575
570 thisDatetime = dataOut.datatime
576 thisDatetime = dataOut.datatime
571 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
577 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
572 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
578 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
573 xlabel = ""
579 xlabel = ""
574 ylabel = "Range (Km)"
580 ylabel = "Range (Km)"
575
581
576 update_figfile = False
582 update_figfile = False
577
583
578 if dataOut.ltctime >= self.xmax:
584 if dataOut.ltctime >= self.xmax:
579 self.counter_imagwr = wr_period
585 self.counter_imagwr = wr_period
580 self.isConfig = False
586 self.isConfig = False
581 update_figfile = True
587 update_figfile = True
582
588
583 if not self.isConfig:
589 if not self.isConfig:
584
590
585 nplots = len(channelIndexList)
591 nplots = len(channelIndexList)
586
592
587 self.setup(id=id,
593 self.setup(id=id,
588 nplots=nplots,
594 nplots=nplots,
589 wintitle=wintitle,
595 wintitle=wintitle,
590 showprofile=showprofile,
596 showprofile=showprofile,
591 show=show)
597 show=show)
592
598
593 if timerange != None:
599 if timerange != None:
594 self.timerange = timerange
600 self.timerange = timerange
595
601
596 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
602 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
597
603
598 noise = dataOut.noise/factor
604 noise = dataOut.noise/factor
599 noisedB = 10*numpy.log10(noise)
605 noisedB = 10*numpy.log10(noise)
600
606
601 if ymin == None: ymin = numpy.nanmin(y)
607 if ymin == None: ymin = numpy.nanmin(y)
602 if ymax == None: ymax = numpy.nanmax(y)
608 if ymax == None: ymax = numpy.nanmax(y)
603 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
609 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
604 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
610 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
605
611
606 self.FTP_WEI = ftp_wei
612 self.FTP_WEI = ftp_wei
607 self.EXP_CODE = exp_code
613 self.EXP_CODE = exp_code
608 self.SUB_EXP_CODE = sub_exp_code
614 self.SUB_EXP_CODE = sub_exp_code
609 self.PLOT_POS = plot_pos
615 self.PLOT_POS = plot_pos
610
616
611 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
617 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
612 self.isConfig = True
618 self.isConfig = True
613 self.figfile = figfile
619 self.figfile = figfile
614 update_figfile = True
620 update_figfile = True
615
621
616 self.setWinTitle(title)
622 self.setWinTitle(title)
617
623
618 for i in range(self.nplots):
624 for i in range(self.nplots):
619 index = channelIndexList[i]
625 index = channelIndexList[i]
620 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
626 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
621 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
627 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
622 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
628 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
623 axes = self.axesList[i*self.__nsubplots]
629 axes = self.axesList[i*self.__nsubplots]
624 zdB = avgdB[index].reshape((1,-1))
630 zdB = avgdB[index].reshape((1,-1))
625 axes.pcolorbuffer(x, y, zdB,
631 axes.pcolorbuffer(x, y, zdB,
626 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
632 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
627 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
633 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
628 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
634 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
629
635
630 if self.__showprofile:
636 if self.__showprofile:
631 axes = self.axesList[i*self.__nsubplots +1]
637 axes = self.axesList[i*self.__nsubplots +1]
632 axes.pline(avgdB[index], y,
638 axes.pline(avgdB[index], y,
633 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
639 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
634 xlabel='dB', ylabel='', title='',
640 xlabel='dB', ylabel='', title='',
635 ytick_visible=False,
641 ytick_visible=False,
636 grid='x')
642 grid='x')
637
643
638 self.draw()
644 self.draw()
639
645
640 self.save(figpath=figpath,
646 self.save(figpath=figpath,
641 figfile=figfile,
647 figfile=figfile,
642 save=save,
648 save=save,
643 ftp=ftp,
649 ftp=ftp,
644 wr_period=wr_period,
650 wr_period=wr_period,
645 thisDatetime=thisDatetime,
651 thisDatetime=thisDatetime,
646 update_figfile=update_figfile)
652 update_figfile=update_figfile)
647
653
648 class CoherenceMap(Figure):
654 class CoherenceMap(Figure):
649 isConfig = None
655 isConfig = None
650 __nsubplots = None
656 __nsubplots = None
651
657
652 WIDTHPROF = None
658 WIDTHPROF = None
653 HEIGHTPROF = None
659 HEIGHTPROF = None
654 PREFIX = 'cmap'
660 PREFIX = 'cmap'
655
661
656 def __init__(self, **kwargs):
662 def __init__(self, **kwargs):
657 Figure.__init__(self, **kwargs)
663 Figure.__init__(self, **kwargs)
658 self.timerange = 2*60*60
664 self.timerange = 2*60*60
659 self.isConfig = False
665 self.isConfig = False
660 self.__nsubplots = 1
666 self.__nsubplots = 1
661
667
662 self.WIDTH = 800
668 self.WIDTH = 800
663 self.HEIGHT = 180
669 self.HEIGHT = 180
664 self.WIDTHPROF = 120
670 self.WIDTHPROF = 120
665 self.HEIGHTPROF = 0
671 self.HEIGHTPROF = 0
666 self.counter_imagwr = 0
672 self.counter_imagwr = 0
667
673
668 self.PLOT_CODE = COH_CODE
674 self.PLOT_CODE = COH_CODE
669
675
670 self.FTP_WEI = None
676 self.FTP_WEI = None
671 self.EXP_CODE = None
677 self.EXP_CODE = None
672 self.SUB_EXP_CODE = None
678 self.SUB_EXP_CODE = None
673 self.PLOT_POS = None
679 self.PLOT_POS = None
674 self.counter_imagwr = 0
680 self.counter_imagwr = 0
675
681
676 self.xmin = None
682 self.xmin = None
677 self.xmax = None
683 self.xmax = None
678
684
679 def getSubplots(self):
685 def getSubplots(self):
680 ncol = 1
686 ncol = 1
681 nrow = self.nplots*2
687 nrow = self.nplots*2
682
688
683 return nrow, ncol
689 return nrow, ncol
684
690
685 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
691 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
686 self.__showprofile = showprofile
692 self.__showprofile = showprofile
687 self.nplots = nplots
693 self.nplots = nplots
688
694
689 ncolspan = 1
695 ncolspan = 1
690 colspan = 1
696 colspan = 1
691 if showprofile:
697 if showprofile:
692 ncolspan = 7
698 ncolspan = 7
693 colspan = 6
699 colspan = 6
694 self.__nsubplots = 2
700 self.__nsubplots = 2
695
701
696 self.createFigure(id = id,
702 self.createFigure(id = id,
697 wintitle = wintitle,
703 wintitle = wintitle,
698 widthplot = self.WIDTH + self.WIDTHPROF,
704 widthplot = self.WIDTH + self.WIDTHPROF,
699 heightplot = self.HEIGHT + self.HEIGHTPROF,
705 heightplot = self.HEIGHT + self.HEIGHTPROF,
700 show=True)
706 show=True)
701
707
702 nrow, ncol = self.getSubplots()
708 nrow, ncol = self.getSubplots()
703
709
704 for y in range(nrow):
710 for y in range(nrow):
705 for x in range(ncol):
711 for x in range(ncol):
706
712
707 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
713 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
708
714
709 if showprofile:
715 if showprofile:
710 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
716 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
711
717
712 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
718 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
713 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
719 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
714 timerange=None, phase_min=None, phase_max=None,
720 timerange=None, phase_min=None, phase_max=None,
715 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
721 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
716 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
722 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
717 server=None, folder=None, username=None, password=None,
723 server=None, folder=None, username=None, password=None,
718 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
724 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
719
725
720 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
726 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
721 return
727 return
722
728
723 if pairsList == None:
729 if pairsList == None:
724 pairsIndexList = dataOut.pairsIndexList
730 pairsIndexList = dataOut.pairsIndexList
725 else:
731 else:
726 pairsIndexList = []
732 pairsIndexList = []
727 for pair in pairsList:
733 for pair in pairsList:
728 if pair not in dataOut.pairsList:
734 if pair not in dataOut.pairsList:
729 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
735 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
730 pairsIndexList.append(dataOut.pairsList.index(pair))
736 pairsIndexList.append(dataOut.pairsList.index(pair))
731
737
732 if pairsIndexList == []:
738 if pairsIndexList == []:
733 return
739 return
734
740
735 if len(pairsIndexList) > 4:
741 if len(pairsIndexList) > 4:
736 pairsIndexList = pairsIndexList[0:4]
742 pairsIndexList = pairsIndexList[0:4]
737
743
738 if phase_min == None:
744 if phase_min == None:
739 phase_min = -180
745 phase_min = -180
740 if phase_max == None:
746 if phase_max == None:
741 phase_max = 180
747 phase_max = 180
742
748
743 x = dataOut.getTimeRange()
749 x = dataOut.getTimeRange()
744 y = dataOut.getHeiRange()
750 y = dataOut.getHeiRange()
745
751
746 thisDatetime = dataOut.datatime
752 thisDatetime = dataOut.datatime
747
753
748 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
754 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
749 xlabel = ""
755 xlabel = ""
750 ylabel = "Range (Km)"
756 ylabel = "Range (Km)"
751 update_figfile = False
757 update_figfile = False
752
758
753 if not self.isConfig:
759 if not self.isConfig:
754 nplots = len(pairsIndexList)
760 nplots = len(pairsIndexList)
755 self.setup(id=id,
761 self.setup(id=id,
756 nplots=nplots,
762 nplots=nplots,
757 wintitle=wintitle,
763 wintitle=wintitle,
758 showprofile=showprofile,
764 showprofile=showprofile,
759 show=show)
765 show=show)
760
766
761 if timerange != None:
767 if timerange != None:
762 self.timerange = timerange
768 self.timerange = timerange
763
769
764 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
770 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
765
771
766 if ymin == None: ymin = numpy.nanmin(y)
772 if ymin == None: ymin = numpy.nanmin(y)
767 if ymax == None: ymax = numpy.nanmax(y)
773 if ymax == None: ymax = numpy.nanmax(y)
768 if zmin == None: zmin = 0.
774 if zmin == None: zmin = 0.
769 if zmax == None: zmax = 1.
775 if zmax == None: zmax = 1.
770
776
771 self.FTP_WEI = ftp_wei
777 self.FTP_WEI = ftp_wei
772 self.EXP_CODE = exp_code
778 self.EXP_CODE = exp_code
773 self.SUB_EXP_CODE = sub_exp_code
779 self.SUB_EXP_CODE = sub_exp_code
774 self.PLOT_POS = plot_pos
780 self.PLOT_POS = plot_pos
775
781
776 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
782 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
777
783
778 self.isConfig = True
784 self.isConfig = True
779 update_figfile = True
785 update_figfile = True
780
786
781 self.setWinTitle(title)
787 self.setWinTitle(title)
782
788
783 for i in range(self.nplots):
789 for i in range(self.nplots):
784
790
785 pair = dataOut.pairsList[pairsIndexList[i]]
791 pair = dataOut.pairsList[pairsIndexList[i]]
786
792
787 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
793 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
788 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
794 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
789 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
795 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
790
796
791
797
792 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
798 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
793 coherence = numpy.abs(avgcoherenceComplex)
799 coherence = numpy.abs(avgcoherenceComplex)
794
800
795 z = coherence.reshape((1,-1))
801 z = coherence.reshape((1,-1))
796
802
797 counter = 0
803 counter = 0
798
804
799 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
805 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
800 axes = self.axesList[i*self.__nsubplots*2]
806 axes = self.axesList[i*self.__nsubplots*2]
801 axes.pcolorbuffer(x, y, z,
807 axes.pcolorbuffer(x, y, z,
802 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
808 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
803 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
809 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
804 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
810 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
805
811
806 if self.__showprofile:
812 if self.__showprofile:
807 counter += 1
813 counter += 1
808 axes = self.axesList[i*self.__nsubplots*2 + counter]
814 axes = self.axesList[i*self.__nsubplots*2 + counter]
809 axes.pline(coherence, y,
815 axes.pline(coherence, y,
810 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
816 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
811 xlabel='', ylabel='', title='', ticksize=7,
817 xlabel='', ylabel='', title='', ticksize=7,
812 ytick_visible=False, nxticks=5,
818 ytick_visible=False, nxticks=5,
813 grid='x')
819 grid='x')
814
820
815 counter += 1
821 counter += 1
816
822
817 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
823 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
818
824
819 z = phase.reshape((1,-1))
825 z = phase.reshape((1,-1))
820
826
821 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
827 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
822 axes = self.axesList[i*self.__nsubplots*2 + counter]
828 axes = self.axesList[i*self.__nsubplots*2 + counter]
823 axes.pcolorbuffer(x, y, z,
829 axes.pcolorbuffer(x, y, z,
824 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
830 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
825 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
831 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
826 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
832 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
827
833
828 if self.__showprofile:
834 if self.__showprofile:
829 counter += 1
835 counter += 1
830 axes = self.axesList[i*self.__nsubplots*2 + counter]
836 axes = self.axesList[i*self.__nsubplots*2 + counter]
831 axes.pline(phase, y,
837 axes.pline(phase, y,
832 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
838 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
833 xlabel='', ylabel='', title='', ticksize=7,
839 xlabel='', ylabel='', title='', ticksize=7,
834 ytick_visible=False, nxticks=4,
840 ytick_visible=False, nxticks=4,
835 grid='x')
841 grid='x')
836
842
837 self.draw()
843 self.draw()
838
844
839 if dataOut.ltctime >= self.xmax:
845 if dataOut.ltctime >= self.xmax:
840 self.counter_imagwr = wr_period
846 self.counter_imagwr = wr_period
841 self.isConfig = False
847 self.isConfig = False
842 update_figfile = True
848 update_figfile = True
843
849
844 self.save(figpath=figpath,
850 self.save(figpath=figpath,
845 figfile=figfile,
851 figfile=figfile,
846 save=save,
852 save=save,
847 ftp=ftp,
853 ftp=ftp,
848 wr_period=wr_period,
854 wr_period=wr_period,
849 thisDatetime=thisDatetime,
855 thisDatetime=thisDatetime,
850 update_figfile=update_figfile)
856 update_figfile=update_figfile)
851
857
852 class PowerProfilePlot(Figure):
858 class PowerProfilePlot(Figure):
853
859
854 isConfig = None
860 isConfig = None
855 __nsubplots = None
861 __nsubplots = None
856
862
857 WIDTHPROF = None
863 WIDTHPROF = None
858 HEIGHTPROF = None
864 HEIGHTPROF = None
859 PREFIX = 'spcprofile'
865 PREFIX = 'spcprofile'
860
866
861 def __init__(self, **kwargs):
867 def __init__(self, **kwargs):
862 Figure.__init__(self, **kwargs)
868 Figure.__init__(self, **kwargs)
863 self.isConfig = False
869 self.isConfig = False
864 self.__nsubplots = 1
870 self.__nsubplots = 1
865
871
866 self.PLOT_CODE = POWER_CODE
872 self.PLOT_CODE = POWER_CODE
867
873
868 self.WIDTH = 300
874 self.WIDTH = 300
869 self.HEIGHT = 500
875 self.HEIGHT = 500
870 self.counter_imagwr = 0
876 self.counter_imagwr = 0
871
877
872 def getSubplots(self):
878 def getSubplots(self):
873 ncol = 1
879 ncol = 1
874 nrow = 1
880 nrow = 1
875
881
876 return nrow, ncol
882 return nrow, ncol
877
883
878 def setup(self, id, nplots, wintitle, show):
884 def setup(self, id, nplots, wintitle, show):
879
885
880 self.nplots = nplots
886 self.nplots = nplots
881
887
882 ncolspan = 1
888 ncolspan = 1
883 colspan = 1
889 colspan = 1
884
890
885 self.createFigure(id = id,
891 self.createFigure(id = id,
886 wintitle = wintitle,
892 wintitle = wintitle,
887 widthplot = self.WIDTH,
893 widthplot = self.WIDTH,
888 heightplot = self.HEIGHT,
894 heightplot = self.HEIGHT,
889 show=show)
895 show=show)
890
896
891 nrow, ncol = self.getSubplots()
897 nrow, ncol = self.getSubplots()
892
898
893 counter = 0
899 counter = 0
894 for y in range(nrow):
900 for y in range(nrow):
895 for x in range(ncol):
901 for x in range(ncol):
896 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
902 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
897
903
898 def run(self, dataOut, id, wintitle="", channelList=None,
904 def run(self, dataOut, id, wintitle="", channelList=None,
899 xmin=None, xmax=None, ymin=None, ymax=None,
905 xmin=None, xmax=None, ymin=None, ymax=None,
900 save=False, figpath='./', figfile=None, show=True,
906 save=False, figpath='./', figfile=None, show=True,
901 ftp=False, wr_period=1, server=None,
907 ftp=False, wr_period=1, server=None,
902 folder=None, username=None, password=None):
908 folder=None, username=None, password=None):
903
909
904
910
905 if channelList == None:
911 if channelList == None:
906 channelIndexList = dataOut.channelIndexList
912 channelIndexList = dataOut.channelIndexList
907 channelList = dataOut.channelList
913 channelList = dataOut.channelList
908 else:
914 else:
909 channelIndexList = []
915 channelIndexList = []
910 for channel in channelList:
916 for channel in channelList:
911 if channel not in dataOut.channelList:
917 if channel not in dataOut.channelList:
912 raise ValueError, "Channel %d is not in dataOut.channelList"
918 raise ValueError, "Channel %d is not in dataOut.channelList"
913 channelIndexList.append(dataOut.channelList.index(channel))
919 channelIndexList.append(dataOut.channelList.index(channel))
914
920
915 factor = dataOut.normFactor
921 factor = dataOut.normFactor
916
922
917 y = dataOut.getHeiRange()
923 y = dataOut.getHeiRange()
918
924
919 #for voltage
925 #for voltage
920 if dataOut.type == 'Voltage':
926 if dataOut.type == 'Voltage':
921 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
927 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
922 x = x.real
928 x = x.real
923 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
929 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
924
930
925 #for spectra
931 #for spectra
926 if dataOut.type == 'Spectra':
932 if dataOut.type == 'Spectra':
927 x = dataOut.data_spc[channelIndexList,:,:]/factor
933 x = dataOut.data_spc[channelIndexList,:,:]/factor
928 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
934 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
929 x = numpy.average(x, axis=1)
935 x = numpy.average(x, axis=1)
930
936
931
937
932 xdB = 10*numpy.log10(x)
938 xdB = 10*numpy.log10(x)
933
939
934 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
940 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
935 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
941 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
936 xlabel = "dB"
942 xlabel = "dB"
937 ylabel = "Range (Km)"
943 ylabel = "Range (Km)"
938
944
939 if not self.isConfig:
945 if not self.isConfig:
940
946
941 nplots = 1
947 nplots = 1
942
948
943 self.setup(id=id,
949 self.setup(id=id,
944 nplots=nplots,
950 nplots=nplots,
945 wintitle=wintitle,
951 wintitle=wintitle,
946 show=show)
952 show=show)
947
953
948 if ymin == None: ymin = numpy.nanmin(y)
954 if ymin == None: ymin = numpy.nanmin(y)
949 if ymax == None: ymax = numpy.nanmax(y)
955 if ymax == None: ymax = numpy.nanmax(y)
950 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
956 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
951 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
957 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
952
958
953 self.isConfig = True
959 self.isConfig = True
954
960
955 self.setWinTitle(title)
961 self.setWinTitle(title)
956
962
957 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
963 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
958 axes = self.axesList[0]
964 axes = self.axesList[0]
959
965
960 legendlabels = ["channel %d"%x for x in channelList]
966 legendlabels = ["channel %d"%x for x in channelList]
961 axes.pmultiline(xdB, y,
967 axes.pmultiline(xdB, y,
962 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
968 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
963 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
969 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
964 ytick_visible=True, nxticks=5,
970 ytick_visible=True, nxticks=5,
965 grid='x')
971 grid='x')
966
972
967 self.draw()
973 self.draw()
968
974
969 self.save(figpath=figpath,
975 self.save(figpath=figpath,
970 figfile=figfile,
976 figfile=figfile,
971 save=save,
977 save=save,
972 ftp=ftp,
978 ftp=ftp,
973 wr_period=wr_period,
979 wr_period=wr_period,
974 thisDatetime=thisDatetime)
980 thisDatetime=thisDatetime)
975
981
976 class SpectraCutPlot(Figure):
982 class SpectraCutPlot(Figure):
977
983
978 isConfig = None
984 isConfig = None
979 __nsubplots = None
985 __nsubplots = None
980
986
981 WIDTHPROF = None
987 WIDTHPROF = None
982 HEIGHTPROF = None
988 HEIGHTPROF = None
983 PREFIX = 'spc_cut'
989 PREFIX = 'spc_cut'
984
990
985 def __init__(self, **kwargs):
991 def __init__(self, **kwargs):
986 Figure.__init__(self, **kwargs)
992 Figure.__init__(self, **kwargs)
987 self.isConfig = False
993 self.isConfig = False
988 self.__nsubplots = 1
994 self.__nsubplots = 1
989
995
990 self.PLOT_CODE = POWER_CODE
996 self.PLOT_CODE = POWER_CODE
991
997
992 self.WIDTH = 700
998 self.WIDTH = 700
993 self.HEIGHT = 500
999 self.HEIGHT = 500
994 self.counter_imagwr = 0
1000 self.counter_imagwr = 0
995
1001
996 def getSubplots(self):
1002 def getSubplots(self):
997 ncol = 1
1003 ncol = 1
998 nrow = 1
1004 nrow = 1
999
1005
1000 return nrow, ncol
1006 return nrow, ncol
1001
1007
1002 def setup(self, id, nplots, wintitle, show):
1008 def setup(self, id, nplots, wintitle, show):
1003
1009
1004 self.nplots = nplots
1010 self.nplots = nplots
1005
1011
1006 ncolspan = 1
1012 ncolspan = 1
1007 colspan = 1
1013 colspan = 1
1008
1014
1009 self.createFigure(id = id,
1015 self.createFigure(id = id,
1010 wintitle = wintitle,
1016 wintitle = wintitle,
1011 widthplot = self.WIDTH,
1017 widthplot = self.WIDTH,
1012 heightplot = self.HEIGHT,
1018 heightplot = self.HEIGHT,
1013 show=show)
1019 show=show)
1014
1020
1015 nrow, ncol = self.getSubplots()
1021 nrow, ncol = self.getSubplots()
1016
1022
1017 counter = 0
1023 counter = 0
1018 for y in range(nrow):
1024 for y in range(nrow):
1019 for x in range(ncol):
1025 for x in range(ncol):
1020 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1026 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1021
1027
1022 def run(self, dataOut, id, wintitle="", channelList=None,
1028 def run(self, dataOut, id, wintitle="", channelList=None,
1023 xmin=None, xmax=None, ymin=None, ymax=None,
1029 xmin=None, xmax=None, ymin=None, ymax=None,
1024 save=False, figpath='./', figfile=None, show=True,
1030 save=False, figpath='./', figfile=None, show=True,
1025 ftp=False, wr_period=1, server=None,
1031 ftp=False, wr_period=1, server=None,
1026 folder=None, username=None, password=None,
1032 folder=None, username=None, password=None,
1027 xaxis="frequency"):
1033 xaxis="frequency"):
1028
1034
1029
1035
1030 if channelList == None:
1036 if channelList == None:
1031 channelIndexList = dataOut.channelIndexList
1037 channelIndexList = dataOut.channelIndexList
1032 channelList = dataOut.channelList
1038 channelList = dataOut.channelList
1033 else:
1039 else:
1034 channelIndexList = []
1040 channelIndexList = []
1035 for channel in channelList:
1041 for channel in channelList:
1036 if channel not in dataOut.channelList:
1042 if channel not in dataOut.channelList:
1037 raise ValueError, "Channel %d is not in dataOut.channelList"
1043 raise ValueError, "Channel %d is not in dataOut.channelList"
1038 channelIndexList.append(dataOut.channelList.index(channel))
1044 channelIndexList.append(dataOut.channelList.index(channel))
1039
1045
1040 factor = dataOut.normFactor
1046 factor = dataOut.normFactor
1041
1047
1042 y = dataOut.getHeiRange()
1048 y = dataOut.getHeiRange()
1043
1049
1044 z = dataOut.data_spc/factor
1050 z = dataOut.data_spc/factor
1045 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1051 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1046
1052
1047 hei_index = numpy.arange(25)*3 + 20
1053 hei_index = numpy.arange(25)*3 + 20
1048
1054
1049 if xaxis == "frequency":
1055 if xaxis == "frequency":
1050 x = dataOut.getFreqRange()/1000.
1056 x = dataOut.getFreqRange()/1000.
1051 zdB = 10*numpy.log10(z[0,:,hei_index])
1057 zdB = 10*numpy.log10(z[0,:,hei_index])
1052 xlabel = "Frequency (kHz)"
1058 xlabel = "Frequency (kHz)"
1053 ylabel = "Power (dB)"
1059 ylabel = "Power (dB)"
1054
1060
1055 elif xaxis == "time":
1061 elif xaxis == "time":
1056 x = dataOut.getAcfRange()
1062 x = dataOut.getAcfRange()
1057 zdB = z[0,:,hei_index]
1063 zdB = z[0,:,hei_index]
1058 xlabel = "Time (ms)"
1064 xlabel = "Time (ms)"
1059 ylabel = "ACF"
1065 ylabel = "ACF"
1060
1066
1061 else:
1067 else:
1062 x = dataOut.getVelRange()
1068 x = dataOut.getVelRange()
1063 zdB = 10*numpy.log10(z[0,:,hei_index])
1069 zdB = 10*numpy.log10(z[0,:,hei_index])
1064 xlabel = "Velocity (m/s)"
1070 xlabel = "Velocity (m/s)"
1065 ylabel = "Power (dB)"
1071 ylabel = "Power (dB)"
1066
1072
1067 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1073 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1068 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1074 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1069
1075
1070 if not self.isConfig:
1076 if not self.isConfig:
1071
1077
1072 nplots = 1
1078 nplots = 1
1073
1079
1074 self.setup(id=id,
1080 self.setup(id=id,
1075 nplots=nplots,
1081 nplots=nplots,
1076 wintitle=wintitle,
1082 wintitle=wintitle,
1077 show=show)
1083 show=show)
1078
1084
1079 if xmin == None: xmin = numpy.nanmin(x)*0.9
1085 if xmin == None: xmin = numpy.nanmin(x)*0.9
1080 if xmax == None: xmax = numpy.nanmax(x)*1.1
1086 if xmax == None: xmax = numpy.nanmax(x)*1.1
1081 if ymin == None: ymin = numpy.nanmin(zdB)
1087 if ymin == None: ymin = numpy.nanmin(zdB)
1082 if ymax == None: ymax = numpy.nanmax(zdB)
1088 if ymax == None: ymax = numpy.nanmax(zdB)
1083
1089
1084 self.isConfig = True
1090 self.isConfig = True
1085
1091
1086 self.setWinTitle(title)
1092 self.setWinTitle(title)
1087
1093
1088 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1094 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1089 axes = self.axesList[0]
1095 axes = self.axesList[0]
1090
1096
1091 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1097 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1092
1098
1093 axes.pmultilineyaxis( x, zdB,
1099 axes.pmultilineyaxis( x, zdB,
1094 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1100 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1095 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1101 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1096 ytick_visible=True, nxticks=5,
1102 ytick_visible=True, nxticks=5,
1097 grid='x')
1103 grid='x')
1098
1104
1099 self.draw()
1105 self.draw()
1100
1106
1101 self.save(figpath=figpath,
1107 self.save(figpath=figpath,
1102 figfile=figfile,
1108 figfile=figfile,
1103 save=save,
1109 save=save,
1104 ftp=ftp,
1110 ftp=ftp,
1105 wr_period=wr_period,
1111 wr_period=wr_period,
1106 thisDatetime=thisDatetime)
1112 thisDatetime=thisDatetime)
1107
1113
1108 class Noise(Figure):
1114 class Noise(Figure):
1109
1115
1110 isConfig = None
1116 isConfig = None
1111 __nsubplots = None
1117 __nsubplots = None
1112
1118
1113 PREFIX = 'noise'
1119 PREFIX = 'noise'
1114
1120
1121
1115 def __init__(self, **kwargs):
1122 def __init__(self, **kwargs):
1116 Figure.__init__(self, **kwargs)
1123 Figure.__init__(self, **kwargs)
1117 self.timerange = 24*60*60
1124 self.timerange = 24*60*60
1118 self.isConfig = False
1125 self.isConfig = False
1119 self.__nsubplots = 1
1126 self.__nsubplots = 1
1120 self.counter_imagwr = 0
1127 self.counter_imagwr = 0
1121 self.WIDTH = 800
1128 self.WIDTH = 800
1122 self.HEIGHT = 400
1129 self.HEIGHT = 400
1123 self.WIDTHPROF = 120
1130 self.WIDTHPROF = 120
1124 self.HEIGHTPROF = 0
1131 self.HEIGHTPROF = 0
1125 self.xdata = None
1132 self.xdata = None
1126 self.ydata = None
1133 self.ydata = None
1127
1134
1128 self.PLOT_CODE = NOISE_CODE
1135 self.PLOT_CODE = NOISE_CODE
1129
1136
1130 self.FTP_WEI = None
1137 self.FTP_WEI = None
1131 self.EXP_CODE = None
1138 self.EXP_CODE = None
1132 self.SUB_EXP_CODE = None
1139 self.SUB_EXP_CODE = None
1133 self.PLOT_POS = None
1140 self.PLOT_POS = None
1134 self.figfile = None
1141 self.figfile = None
1135
1142
1136 self.xmin = None
1143 self.xmin = None
1137 self.xmax = None
1144 self.xmax = None
1138
1145
1139 def getSubplots(self):
1146 def getSubplots(self):
1140
1147
1141 ncol = 1
1148 ncol = 1
1142 nrow = 1
1149 nrow = 1
1143
1150
1144 return nrow, ncol
1151 return nrow, ncol
1145
1152
1146 def openfile(self, filename):
1153 def openfile(self, filename):
1147 dirname = os.path.dirname(filename)
1154 dirname = os.path.dirname(filename)
1148
1155
1149 if not os.path.exists(dirname):
1156 if not os.path.exists(dirname):
1150 os.mkdir(dirname)
1157 os.mkdir(dirname)
1151
1158
1152 f = open(filename,'w+')
1159 f = open(filename,'w+')
1153 f.write('\n\n')
1160 f.write('\n\n')
1154 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1161 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1155 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1162 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1156 f.close()
1163 f.close()
1157
1164
1158 def save_data(self, filename_phase, data, data_datetime):
1165 def save_data(self, filename_phase, data, data_datetime):
1159
1166
1160 f=open(filename_phase,'a')
1167 f=open(filename_phase,'a')
1161
1168
1162 timetuple_data = data_datetime.timetuple()
1169 timetuple_data = data_datetime.timetuple()
1163 day = str(timetuple_data.tm_mday)
1170 day = str(timetuple_data.tm_mday)
1164 month = str(timetuple_data.tm_mon)
1171 month = str(timetuple_data.tm_mon)
1165 year = str(timetuple_data.tm_year)
1172 year = str(timetuple_data.tm_year)
1166 hour = str(timetuple_data.tm_hour)
1173 hour = str(timetuple_data.tm_hour)
1167 minute = str(timetuple_data.tm_min)
1174 minute = str(timetuple_data.tm_min)
1168 second = str(timetuple_data.tm_sec)
1175 second = str(timetuple_data.tm_sec)
1169
1176
1170 data_msg = ''
1177 data_msg = ''
1171 for i in range(len(data)):
1178 for i in range(len(data)):
1172 data_msg += str(data[i]) + ' '
1179 data_msg += str(data[i]) + ' '
1173
1180
1174 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1181 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1175 f.close()
1182 f.close()
1176
1183
1177
1184
1178 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1185 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1179
1186
1180 self.__showprofile = showprofile
1187 self.__showprofile = showprofile
1181 self.nplots = nplots
1188 self.nplots = nplots
1182
1189
1183 ncolspan = 7
1190 ncolspan = 7
1184 colspan = 6
1191 colspan = 6
1185 self.__nsubplots = 2
1192 self.__nsubplots = 2
1186
1193
1187 self.createFigure(id = id,
1194 self.createFigure(id = id,
1188 wintitle = wintitle,
1195 wintitle = wintitle,
1189 widthplot = self.WIDTH+self.WIDTHPROF,
1196 widthplot = self.WIDTH+self.WIDTHPROF,
1190 heightplot = self.HEIGHT+self.HEIGHTPROF,
1197 heightplot = self.HEIGHT+self.HEIGHTPROF,
1191 show=show)
1198 show=show)
1192
1199
1193 nrow, ncol = self.getSubplots()
1200 nrow, ncol = self.getSubplots()
1194
1201
1195 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1202 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1196
1203
1197
1204
1198 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1205 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1199 xmin=None, xmax=None, ymin=None, ymax=None,
1206 xmin=None, xmax=None, ymin=None, ymax=None,
1200 timerange=None,
1207 timerange=None,
1201 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1208 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1202 server=None, folder=None, username=None, password=None,
1209 server=None, folder=None, username=None, password=None,
1203 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1210 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1204
1211
1205 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1212 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1206 return
1213 return
1207
1214
1208 if channelList == None:
1215 if channelList == None:
1209 channelIndexList = dataOut.channelIndexList
1216 channelIndexList = dataOut.channelIndexList
1210 channelList = dataOut.channelList
1217 channelList = dataOut.channelList
1211 else:
1218 else:
1212 channelIndexList = []
1219 channelIndexList = []
1213 for channel in channelList:
1220 for channel in channelList:
1214 if channel not in dataOut.channelList:
1221 if channel not in dataOut.channelList:
1215 raise ValueError, "Channel %d is not in dataOut.channelList"
1222 raise ValueError, "Channel %d is not in dataOut.channelList"
1216 channelIndexList.append(dataOut.channelList.index(channel))
1223 channelIndexList.append(dataOut.channelList.index(channel))
1217
1224
1218 x = dataOut.getTimeRange()
1225 x = dataOut.getTimeRange()
1219 #y = dataOut.getHeiRange()
1226 #y = dataOut.getHeiRange()
1220 factor = dataOut.normFactor
1227 factor = dataOut.normFactor
1221 noise = dataOut.noise[channelIndexList]/factor
1228 noise = dataOut.noise[channelIndexList]/factor
1222 noisedB = 10*numpy.log10(noise)
1229 noisedB = 10*numpy.log10(noise)
1223
1230
1224 thisDatetime = dataOut.datatime
1231 thisDatetime = dataOut.datatime
1225
1232
1226 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1233 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1227 xlabel = ""
1234 xlabel = ""
1228 ylabel = "Intensity (dB)"
1235 ylabel = "Intensity (dB)"
1229 update_figfile = False
1236 update_figfile = False
1230
1237
1231 if not self.isConfig:
1238 if not self.isConfig:
1232
1239
1233 nplots = 1
1240 nplots = 1
1234
1241
1235 self.setup(id=id,
1242 self.setup(id=id,
1236 nplots=nplots,
1243 nplots=nplots,
1237 wintitle=wintitle,
1244 wintitle=wintitle,
1238 showprofile=showprofile,
1245 showprofile=showprofile,
1239 show=show)
1246 show=show)
1240
1247
1241 if timerange != None:
1248 if timerange != None:
1242 self.timerange = timerange
1249 self.timerange = timerange
1243
1250
1244 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1251 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1245
1252
1246 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1253 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1247 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1254 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1248
1255
1249 self.FTP_WEI = ftp_wei
1256 self.FTP_WEI = ftp_wei
1250 self.EXP_CODE = exp_code
1257 self.EXP_CODE = exp_code
1251 self.SUB_EXP_CODE = sub_exp_code
1258 self.SUB_EXP_CODE = sub_exp_code
1252 self.PLOT_POS = plot_pos
1259 self.PLOT_POS = plot_pos
1253
1260
1254
1261
1255 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1262 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1256 self.isConfig = True
1263 self.isConfig = True
1257 self.figfile = figfile
1264 self.figfile = figfile
1258 self.xdata = numpy.array([])
1265 self.xdata = numpy.array([])
1259 self.ydata = numpy.array([])
1266 self.ydata = numpy.array([])
1260
1267
1261 update_figfile = True
1268 update_figfile = True
1262
1269
1263 #open file beacon phase
1270 #open file beacon phase
1264 path = '%s%03d' %(self.PREFIX, self.id)
1271 path = '%s%03d' %(self.PREFIX, self.id)
1265 noise_file = os.path.join(path,'%s.txt'%self.name)
1272 noise_file = os.path.join(path,'%s.txt'%self.name)
1266 self.filename_noise = os.path.join(figpath,noise_file)
1273 self.filename_noise = os.path.join(figpath,noise_file)
1267
1274
1268 self.setWinTitle(title)
1275 self.setWinTitle(title)
1269
1276
1270 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1277 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1271
1278
1272 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1279 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1273 axes = self.axesList[0]
1280 axes = self.axesList[0]
1274
1281
1275 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1282 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1276
1283
1277 if len(self.ydata)==0:
1284 if len(self.ydata)==0:
1278 self.ydata = noisedB.reshape(-1,1)
1285 self.ydata = noisedB.reshape(-1,1)
1279 else:
1286 else:
1280 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1287 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1281
1288
1282
1289
1283 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1290 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1284 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1291 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1285 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1292 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1286 XAxisAsTime=True, grid='both'
1293 XAxisAsTime=True, grid='both'
1287 )
1294 )
1288
1295
1289 self.draw()
1296 self.draw()
1290
1297
1291 if dataOut.ltctime >= self.xmax:
1298 if dataOut.ltctime >= self.xmax:
1292 self.counter_imagwr = wr_period
1299 self.counter_imagwr = wr_period
1293 self.isConfig = False
1300 self.isConfig = False
1294 update_figfile = True
1301 update_figfile = True
1295
1302
1296 self.save(figpath=figpath,
1303 self.save(figpath=figpath,
1297 figfile=figfile,
1304 figfile=figfile,
1298 save=save,
1305 save=save,
1299 ftp=ftp,
1306 ftp=ftp,
1300 wr_period=wr_period,
1307 wr_period=wr_period,
1301 thisDatetime=thisDatetime,
1308 thisDatetime=thisDatetime,
1302 update_figfile=update_figfile)
1309 update_figfile=update_figfile)
1303
1310
1304 #store data beacon phase
1311 #store data beacon phase
1305 if save:
1312 if save:
1306 self.save_data(self.filename_noise, noisedB, thisDatetime)
1313 self.save_data(self.filename_noise, noisedB, thisDatetime)
1307
1314
1308 class BeaconPhase(Figure):
1315 class BeaconPhase(Figure):
1309
1316
1310 __isConfig = None
1317 __isConfig = None
1311 __nsubplots = None
1318 __nsubplots = None
1312
1319
1313 PREFIX = 'beacon_phase'
1320 PREFIX = 'beacon_phase'
1314
1321
1315 def __init__(self, **kwargs):
1322 def __init__(self, **kwargs):
1316 Figure.__init__(self, **kwargs)
1323 Figure.__init__(self, **kwargs)
1317 self.timerange = 24*60*60
1324 self.timerange = 24*60*60
1318 self.isConfig = False
1325 self.isConfig = False
1319 self.__nsubplots = 1
1326 self.__nsubplots = 1
1320 self.counter_imagwr = 0
1327 self.counter_imagwr = 0
1321 self.WIDTH = 800
1328 self.WIDTH = 800
1322 self.HEIGHT = 400
1329 self.HEIGHT = 400
1323 self.WIDTHPROF = 120
1330 self.WIDTHPROF = 120
1324 self.HEIGHTPROF = 0
1331 self.HEIGHTPROF = 0
1325 self.xdata = None
1332 self.xdata = None
1326 self.ydata = None
1333 self.ydata = None
1327
1334
1328 self.PLOT_CODE = BEACON_CODE
1335 self.PLOT_CODE = BEACON_CODE
1329
1336
1330 self.FTP_WEI = None
1337 self.FTP_WEI = None
1331 self.EXP_CODE = None
1338 self.EXP_CODE = None
1332 self.SUB_EXP_CODE = None
1339 self.SUB_EXP_CODE = None
1333 self.PLOT_POS = None
1340 self.PLOT_POS = None
1334
1341
1335 self.filename_phase = None
1342 self.filename_phase = None
1336
1343
1337 self.figfile = None
1344 self.figfile = None
1338
1345
1339 self.xmin = None
1346 self.xmin = None
1340 self.xmax = None
1347 self.xmax = None
1341
1348
1342 def getSubplots(self):
1349 def getSubplots(self):
1343
1350
1344 ncol = 1
1351 ncol = 1
1345 nrow = 1
1352 nrow = 1
1346
1353
1347 return nrow, ncol
1354 return nrow, ncol
1348
1355
1349 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1356 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1350
1357
1351 self.__showprofile = showprofile
1358 self.__showprofile = showprofile
1352 self.nplots = nplots
1359 self.nplots = nplots
1353
1360
1354 ncolspan = 7
1361 ncolspan = 7
1355 colspan = 6
1362 colspan = 6
1356 self.__nsubplots = 2
1363 self.__nsubplots = 2
1357
1364
1358 self.createFigure(id = id,
1365 self.createFigure(id = id,
1359 wintitle = wintitle,
1366 wintitle = wintitle,
1360 widthplot = self.WIDTH+self.WIDTHPROF,
1367 widthplot = self.WIDTH+self.WIDTHPROF,
1361 heightplot = self.HEIGHT+self.HEIGHTPROF,
1368 heightplot = self.HEIGHT+self.HEIGHTPROF,
1362 show=show)
1369 show=show)
1363
1370
1364 nrow, ncol = self.getSubplots()
1371 nrow, ncol = self.getSubplots()
1365
1372
1366 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1373 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1367
1374
1368 def save_phase(self, filename_phase):
1375 def save_phase(self, filename_phase):
1369 f = open(filename_phase,'w+')
1376 f = open(filename_phase,'w+')
1370 f.write('\n\n')
1377 f.write('\n\n')
1371 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1378 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1372 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1379 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1373 f.close()
1380 f.close()
1374
1381
1375 def save_data(self, filename_phase, data, data_datetime):
1382 def save_data(self, filename_phase, data, data_datetime):
1376 f=open(filename_phase,'a')
1383 f=open(filename_phase,'a')
1377 timetuple_data = data_datetime.timetuple()
1384 timetuple_data = data_datetime.timetuple()
1378 day = str(timetuple_data.tm_mday)
1385 day = str(timetuple_data.tm_mday)
1379 month = str(timetuple_data.tm_mon)
1386 month = str(timetuple_data.tm_mon)
1380 year = str(timetuple_data.tm_year)
1387 year = str(timetuple_data.tm_year)
1381 hour = str(timetuple_data.tm_hour)
1388 hour = str(timetuple_data.tm_hour)
1382 minute = str(timetuple_data.tm_min)
1389 minute = str(timetuple_data.tm_min)
1383 second = str(timetuple_data.tm_sec)
1390 second = str(timetuple_data.tm_sec)
1384 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1391 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1385 f.close()
1392 f.close()
1386
1393
1387
1394
1388 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1395 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1389 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1396 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1390 timerange=None,
1397 timerange=None,
1391 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1398 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1392 server=None, folder=None, username=None, password=None,
1399 server=None, folder=None, username=None, password=None,
1393 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1400 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1394
1401
1395 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1402 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1396 return
1403 return
1397
1404
1398 if pairsList == None:
1405 if pairsList == None:
1399 pairsIndexList = dataOut.pairsIndexList[:10]
1406 pairsIndexList = dataOut.pairsIndexList[:10]
1400 else:
1407 else:
1401 pairsIndexList = []
1408 pairsIndexList = []
1402 for pair in pairsList:
1409 for pair in pairsList:
1403 if pair not in dataOut.pairsList:
1410 if pair not in dataOut.pairsList:
1404 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
1411 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
1405 pairsIndexList.append(dataOut.pairsList.index(pair))
1412 pairsIndexList.append(dataOut.pairsList.index(pair))
1406
1413
1407 if pairsIndexList == []:
1414 if pairsIndexList == []:
1408 return
1415 return
1409
1416
1410 # if len(pairsIndexList) > 4:
1417 # if len(pairsIndexList) > 4:
1411 # pairsIndexList = pairsIndexList[0:4]
1418 # pairsIndexList = pairsIndexList[0:4]
1412
1419
1413 hmin_index = None
1420 hmin_index = None
1414 hmax_index = None
1421 hmax_index = None
1415
1422
1416 if hmin != None and hmax != None:
1423 if hmin != None and hmax != None:
1417 indexes = numpy.arange(dataOut.nHeights)
1424 indexes = numpy.arange(dataOut.nHeights)
1418 hmin_list = indexes[dataOut.heightList >= hmin]
1425 hmin_list = indexes[dataOut.heightList >= hmin]
1419 hmax_list = indexes[dataOut.heightList <= hmax]
1426 hmax_list = indexes[dataOut.heightList <= hmax]
1420
1427
1421 if hmin_list.any():
1428 if hmin_list.any():
1422 hmin_index = hmin_list[0]
1429 hmin_index = hmin_list[0]
1423
1430
1424 if hmax_list.any():
1431 if hmax_list.any():
1425 hmax_index = hmax_list[-1]+1
1432 hmax_index = hmax_list[-1]+1
1426
1433
1427 x = dataOut.getTimeRange()
1434 x = dataOut.getTimeRange()
1428 #y = dataOut.getHeiRange()
1435 #y = dataOut.getHeiRange()
1429
1436
1430
1437
1431 thisDatetime = dataOut.datatime
1438 thisDatetime = dataOut.datatime
1432
1439
1433 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1440 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1434 xlabel = "Local Time"
1441 xlabel = "Local Time"
1435 ylabel = "Phase (degrees)"
1442 ylabel = "Phase (degrees)"
1436
1443
1437 update_figfile = False
1444 update_figfile = False
1438
1445
1439 nplots = len(pairsIndexList)
1446 nplots = len(pairsIndexList)
1440 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1447 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1441 phase_beacon = numpy.zeros(len(pairsIndexList))
1448 phase_beacon = numpy.zeros(len(pairsIndexList))
1442 for i in range(nplots):
1449 for i in range(nplots):
1443 pair = dataOut.pairsList[pairsIndexList[i]]
1450 pair = dataOut.pairsList[pairsIndexList[i]]
1444 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1451 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1445 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1452 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1446 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1453 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1447 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1454 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1448 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1455 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1449
1456
1450 #print "Phase %d%d" %(pair[0], pair[1])
1457 #print "Phase %d%d" %(pair[0], pair[1])
1451 #print phase[dataOut.beacon_heiIndexList]
1458 #print phase[dataOut.beacon_heiIndexList]
1452
1459
1453 if dataOut.beacon_heiIndexList:
1460 if dataOut.beacon_heiIndexList:
1454 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1461 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1455 else:
1462 else:
1456 phase_beacon[i] = numpy.average(phase)
1463 phase_beacon[i] = numpy.average(phase)
1457
1464
1458 if not self.isConfig:
1465 if not self.isConfig:
1459
1466
1460 nplots = len(pairsIndexList)
1467 nplots = len(pairsIndexList)
1461
1468
1462 self.setup(id=id,
1469 self.setup(id=id,
1463 nplots=nplots,
1470 nplots=nplots,
1464 wintitle=wintitle,
1471 wintitle=wintitle,
1465 showprofile=showprofile,
1472 showprofile=showprofile,
1466 show=show)
1473 show=show)
1467
1474
1468 if timerange != None:
1475 if timerange != None:
1469 self.timerange = timerange
1476 self.timerange = timerange
1470
1477
1471 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1478 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1472
1479
1473 if ymin == None: ymin = 0
1480 if ymin == None: ymin = 0
1474 if ymax == None: ymax = 360
1481 if ymax == None: ymax = 360
1475
1482
1476 self.FTP_WEI = ftp_wei
1483 self.FTP_WEI = ftp_wei
1477 self.EXP_CODE = exp_code
1484 self.EXP_CODE = exp_code
1478 self.SUB_EXP_CODE = sub_exp_code
1485 self.SUB_EXP_CODE = sub_exp_code
1479 self.PLOT_POS = plot_pos
1486 self.PLOT_POS = plot_pos
1480
1487
1481 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1488 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1482 self.isConfig = True
1489 self.isConfig = True
1483 self.figfile = figfile
1490 self.figfile = figfile
1484 self.xdata = numpy.array([])
1491 self.xdata = numpy.array([])
1485 self.ydata = numpy.array([])
1492 self.ydata = numpy.array([])
1486
1493
1487 update_figfile = True
1494 update_figfile = True
1488
1495
1489 #open file beacon phase
1496 #open file beacon phase
1490 path = '%s%03d' %(self.PREFIX, self.id)
1497 path = '%s%03d' %(self.PREFIX, self.id)
1491 beacon_file = os.path.join(path,'%s.txt'%self.name)
1498 beacon_file = os.path.join(path,'%s.txt'%self.name)
1492 self.filename_phase = os.path.join(figpath,beacon_file)
1499 self.filename_phase = os.path.join(figpath,beacon_file)
1493 #self.save_phase(self.filename_phase)
1500 #self.save_phase(self.filename_phase)
1494
1501
1495
1502
1496 #store data beacon phase
1503 #store data beacon phase
1497 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1504 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1498
1505
1499 self.setWinTitle(title)
1506 self.setWinTitle(title)
1500
1507
1501
1508
1502 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1509 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1503
1510
1504 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1511 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1505
1512
1506 axes = self.axesList[0]
1513 axes = self.axesList[0]
1507
1514
1508 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1515 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1509
1516
1510 if len(self.ydata)==0:
1517 if len(self.ydata)==0:
1511 self.ydata = phase_beacon.reshape(-1,1)
1518 self.ydata = phase_beacon.reshape(-1,1)
1512 else:
1519 else:
1513 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1520 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1514
1521
1515
1522
1516 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1523 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1517 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1524 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1518 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1525 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1519 XAxisAsTime=True, grid='both'
1526 XAxisAsTime=True, grid='both'
1520 )
1527 )
1521
1528
1522 self.draw()
1529 self.draw()
1523
1530
1524 if dataOut.ltctime >= self.xmax:
1531 if dataOut.ltctime >= self.xmax:
1525 self.counter_imagwr = wr_period
1532 self.counter_imagwr = wr_period
1526 self.isConfig = False
1533 self.isConfig = False
1527 update_figfile = True
1534 update_figfile = True
1528
1535
1529 self.save(figpath=figpath,
1536 self.save(figpath=figpath,
1530 figfile=figfile,
1537 figfile=figfile,
1531 save=save,
1538 save=save,
1532 ftp=ftp,
1539 ftp=ftp,
1533 wr_period=wr_period,
1540 wr_period=wr_period,
1534 thisDatetime=thisDatetime,
1541 thisDatetime=thisDatetime,
1535 update_figfile=update_figfile)
1542 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("GTK3Agg")
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,20
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 *
@@ -1,1794 +1,1807
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 online = 0
545 online = 0
546
546
547 realtime = 0
547 realtime = 0
548
548
549 nReadBlocks = 0
549 nReadBlocks = 0
550
550
551 delay = 10 #number of seconds waiting a new file
551 delay = 10 #number of seconds waiting a new file
552
552
553 nTries = 3 #quantity tries
553 nTries = 3 #quantity tries
554
554
555 nFiles = 3 #number of files for searching
555 nFiles = 3 #number of files for searching
556
556
557 path = None
557 path = None
558
558
559 foldercounter = 0
559 foldercounter = 0
560
560
561 flagNoMoreFiles = 0
561 flagNoMoreFiles = 0
562
562
563 datetimeList = []
563 datetimeList = []
564
564
565 __isFirstTimeOnline = 1
565 __isFirstTimeOnline = 1
566
566
567 __printInfo = True
567 __printInfo = True
568
568
569 profileIndex = None
569 profileIndex = None
570
570
571 nTxs = 1
571 nTxs = 1
572
572
573 txIndex = None
573 txIndex = None
574
574
575 #Added--------------------
575 #Added--------------------
576
576
577 selBlocksize = None
577 selBlocksize = None
578
578
579 selBlocktime = None
579 selBlocktime = None
580
580
581 def __init__(self):
581 def __init__(self):
582
582
583 """
583 """
584 This class is used to find data files
584 This class is used to find data files
585
585
586 Example:
586 Example:
587 reader = JRODataReader()
587 reader = JRODataReader()
588 fileList = reader.findDataFiles()
588 fileList = reader.findDataFiles()
589
589
590 """
590 """
591 pass
591 pass
592
592
593
593
594 def createObjByDefault(self):
594 def createObjByDefault(self):
595 """
595 """
596
596
597 """
597 """
598 raise NotImplementedError
598 raise NotImplementedError
599
599
600 def getBlockDimension(self):
600 def getBlockDimension(self):
601
601
602 raise NotImplementedError
602 raise NotImplementedError
603
603
604 def searchFilesOffLine(self,
604 def searchFilesOffLine(self,
605 path,
605 path,
606 startDate=None,
606 startDate=None,
607 endDate=None,
607 endDate=None,
608 startTime=datetime.time(0,0,0),
608 startTime=datetime.time(0,0,0),
609 endTime=datetime.time(23,59,59),
609 endTime=datetime.time(23,59,59),
610 set=None,
610 set=None,
611 expLabel='',
611 expLabel='',
612 ext='.r',
612 ext='.r',
613 cursor=None,
613 cursor=None,
614 skip=None,
614 skip=None,
615 walk=True):
615 walk=True):
616
616
617 self.filenameList = []
617 self.filenameList = []
618 self.datetimeList = []
618 self.datetimeList = []
619
619
620 pathList = []
620 pathList = []
621
621
622 dateList, pathList = self.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
622 dateList, pathList = self.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
623
623
624 if dateList == []:
624 if dateList == []:
625 return [], []
625 return [], []
626
626
627 if len(dateList) > 1:
627 if len(dateList) > 1:
628 print "[Reading] Data found for date range [%s - %s]: total days = %d" %(startDate, endDate, len(dateList))
628 print "[Reading] Data found for date range [%s - %s]: total days = %d" %(startDate, endDate, len(dateList))
629 else:
629 else:
630 print "[Reading] Data found for date range [%s - %s]: date = %s" %(startDate, endDate, dateList[0])
630 print "[Reading] Data found for date range [%s - %s]: date = %s" %(startDate, endDate, dateList[0])
631
631
632 filenameList = []
632 filenameList = []
633 datetimeList = []
633 datetimeList = []
634
634
635 for thisPath in pathList:
635 for thisPath in pathList:
636
636
637 fileList = glob.glob1(thisPath, "*%s" %ext)
637 fileList = glob.glob1(thisPath, "*%s" %ext)
638 fileList.sort()
638 fileList.sort()
639
639
640 skippedFileList = []
640 skippedFileList = []
641
641
642 if cursor is not None and skip is not None:
642 if cursor is not None and skip is not None:
643
643
644 if skip == 0:
644 if skip == 0:
645 skippedFileList = []
645 skippedFileList = []
646 else:
646 else:
647 skippedFileList = fileList[cursor*skip: cursor*skip + skip]
647 skippedFileList = fileList[cursor*skip: cursor*skip + skip]
648
648
649 else:
649 else:
650 skippedFileList = fileList
650 skippedFileList = fileList
651
651
652 for file in skippedFileList:
652 for file in skippedFileList:
653
653
654 filename = os.path.join(thisPath,file)
654 filename = os.path.join(thisPath,file)
655
655
656 if not isFileInDateRange(filename, startDate, endDate):
656 if not isFileInDateRange(filename, startDate, endDate):
657 continue
657 continue
658
658
659 thisDatetime = isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
659 thisDatetime = isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
660
660
661 if not(thisDatetime):
661 if not(thisDatetime):
662 continue
662 continue
663
663
664 filenameList.append(filename)
664 filenameList.append(filename)
665 datetimeList.append(thisDatetime)
665 datetimeList.append(thisDatetime)
666
666
667 if not(filenameList):
667 if not(filenameList):
668 print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" %(startTime, endTime, ext, path)
668 print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" %(startTime, endTime, ext, path)
669 return [], []
669 return [], []
670
670
671 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
671 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
672 print
672 print
673
673
674 # for i in range(len(filenameList)):
674 # for i in range(len(filenameList)):
675 # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
675 # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
676
676
677 self.filenameList = filenameList
677 self.filenameList = filenameList
678 self.datetimeList = datetimeList
678 self.datetimeList = datetimeList
679
679
680 return pathList, filenameList
680 return pathList, filenameList
681
681
682 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
682 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
683
683
684 """
684 """
685 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
685 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
686 devuelve el archivo encontrado ademas de otros datos.
686 devuelve el archivo encontrado ademas de otros datos.
687
687
688 Input:
688 Input:
689 path : carpeta donde estan contenidos los files que contiene data
689 path : carpeta donde estan contenidos los files que contiene data
690
690
691 expLabel : Nombre del subexperimento (subfolder)
691 expLabel : Nombre del subexperimento (subfolder)
692
692
693 ext : extension de los files
693 ext : extension de los files
694
694
695 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
695 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
696
696
697 Return:
697 Return:
698 directory : eL directorio donde esta el file encontrado
698 directory : eL directorio donde esta el file encontrado
699 filename : el ultimo file de una determinada carpeta
699 filename : el ultimo file de una determinada carpeta
700 year : el anho
700 year : el anho
701 doy : el numero de dia del anho
701 doy : el numero de dia del anho
702 set : el set del archivo
702 set : el set del archivo
703
703
704
704
705 """
705 """
706 if not os.path.isdir(path):
706 if not os.path.isdir(path):
707 return None, None, None, None, None, None
707 return None, None, None, None, None, None
708
708
709 dirList = []
709 dirList = []
710
710
711 if not walk:
711 if not walk:
712 fullpath = path
712 fullpath = path
713 foldercounter = 0
713 foldercounter = 0
714 else:
714 else:
715 #Filtra solo los directorios
715 #Filtra solo los directorios
716 for thisPath in os.listdir(path):
716 for thisPath in os.listdir(path):
717 if not os.path.isdir(os.path.join(path,thisPath)):
717 if not os.path.isdir(os.path.join(path,thisPath)):
718 continue
718 continue
719 if not isRadarFolder(thisPath):
719 if not isRadarFolder(thisPath):
720 continue
720 continue
721
721
722 dirList.append(thisPath)
722 dirList.append(thisPath)
723
723
724 if not(dirList):
724 if not(dirList):
725 return None, None, None, None, None, None
725 return None, None, None, None, None, None
726
726
727 dirList = sorted( dirList, key=str.lower )
727 dirList = sorted( dirList, key=str.lower )
728
728
729 doypath = dirList[-1]
729 doypath = dirList[-1]
730 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
730 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
731 fullpath = os.path.join(path, doypath, expLabel)
731 fullpath = os.path.join(path, doypath, expLabel)
732
732
733
733
734 print "[Reading] %s folder was found: " %(fullpath )
734 print "[Reading] %s folder was found: " %(fullpath )
735
735
736 if set == None:
736 if set == None:
737 filename = getlastFileFromPath(fullpath, ext)
737 filename = getlastFileFromPath(fullpath, ext)
738 else:
738 else:
739 filename = getFileFromSet(fullpath, ext, set)
739 filename = getFileFromSet(fullpath, ext, set)
740
740
741 if not(filename):
741 if not(filename):
742 return None, None, None, None, None, None
742 return None, None, None, None, None, None
743
743
744 print "[Reading] %s file was found" %(filename)
744 print "[Reading] %s file was found" %(filename)
745
745
746 if not(self.__verifyFile(os.path.join(fullpath, filename))):
746 if not(self.__verifyFile(os.path.join(fullpath, filename))):
747 return None, None, None, None, None, None
747 return None, None, None, None, None, None
748
748
749 year = int( filename[1:5] )
749 year = int( filename[1:5] )
750 doy = int( filename[5:8] )
750 doy = int( filename[5:8] )
751 set = int( filename[8:11] )
751 set = int( filename[8:11] )
752
752
753 return fullpath, foldercounter, filename, year, doy, set
753 return fullpath, foldercounter, filename, year, doy, set
754
754
755 def __setNextFileOffline(self):
755 def __setNextFileOffline(self):
756
756
757 idFile = self.fileIndex
757 idFile = self.fileIndex
758
758
759 while (True):
759 while (True):
760 idFile += 1
760 idFile += 1
761 if not(idFile < len(self.filenameList)):
761 if not(idFile < len(self.filenameList)):
762 self.flagNoMoreFiles = 1
762 self.flagNoMoreFiles = 1
763 # print "[Reading] No more Files"
763 # print "[Reading] No more Files"
764 return 0
764 return 0
765
765
766 filename = self.filenameList[idFile]
766 filename = self.filenameList[idFile]
767
767
768 if not(self.__verifyFile(filename)):
768 if not(self.__verifyFile(filename)):
769 continue
769 continue
770
770
771 fileSize = os.path.getsize(filename)
771 fileSize = os.path.getsize(filename)
772 fp = open(filename,'rb')
772 fp = open(filename,'rb')
773 break
773 break
774
774
775 self.flagIsNewFile = 1
775 self.flagIsNewFile = 1
776 self.fileIndex = idFile
776 self.fileIndex = idFile
777 self.filename = filename
777 self.filename = filename
778 self.fileSize = fileSize
778 self.fileSize = fileSize
779 self.fp = fp
779 self.fp = fp
780
780
781 # print "[Reading] Setting the file: %s"%self.filename
781 # print "[Reading] Setting the file: %s"%self.filename
782
782
783 return 1
783 return 1
784
784
785 def __setNextFileOnline(self):
785 def __setNextFileOnline(self):
786 """
786 """
787 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
787 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
788 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
788 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
789 siguientes.
789 siguientes.
790
790
791 Affected:
791 Affected:
792 self.flagIsNewFile
792 self.flagIsNewFile
793 self.filename
793 self.filename
794 self.fileSize
794 self.fileSize
795 self.fp
795 self.fp
796 self.set
796 self.set
797 self.flagNoMoreFiles
797 self.flagNoMoreFiles
798
798
799 Return:
799 Return:
800 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
800 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
801 1 : si el file fue abierto con exito y esta listo a ser leido
801 1 : si el file fue abierto con exito y esta listo a ser leido
802
802
803 Excepciones:
803 Excepciones:
804 Si un determinado file no puede ser abierto
804 Si un determinado file no puede ser abierto
805 """
805 """
806 nFiles = 0
806 nFiles = 0
807 fileOk_flag = False
807 fileOk_flag = False
808 firstTime_flag = True
808 firstTime_flag = True
809
809
810 self.set += 1
810 self.set += 1
811
811
812 if self.set > 999:
812 if self.set > 999:
813 self.set = 0
813 self.set = 0
814 self.foldercounter += 1
814 self.foldercounter += 1
815
815
816 #busca el 1er file disponible
816 #busca el 1er file disponible
817 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
817 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
818 if fullfilename:
818 if fullfilename:
819 if self.__verifyFile(fullfilename, False):
819 if self.__verifyFile(fullfilename, False):
820 fileOk_flag = True
820 fileOk_flag = True
821
821
822 #si no encuentra un file entonces espera y vuelve a buscar
822 #si no encuentra un file entonces espera y vuelve a buscar
823 if not(fileOk_flag):
823 if not(fileOk_flag):
824 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
824 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
825
825
826 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
826 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
827 tries = self.nTries
827 tries = self.nTries
828 else:
828 else:
829 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
829 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
830
830
831 for nTries in range( tries ):
831 for nTries in range( tries ):
832 if firstTime_flag:
832 if firstTime_flag:
833 print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
833 print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
834 sleep( self.delay )
834 sleep( self.delay )
835 else:
835 else:
836 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
836 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
837
837
838 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
838 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
839 if fullfilename:
839 if fullfilename:
840 if self.__verifyFile(fullfilename):
840 if self.__verifyFile(fullfilename):
841 fileOk_flag = True
841 fileOk_flag = True
842 break
842 break
843
843
844 if fileOk_flag:
844 if fileOk_flag:
845 break
845 break
846
846
847 firstTime_flag = False
847 firstTime_flag = False
848
848
849 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
849 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
850 self.set += 1
850 self.set += 1
851
851
852 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
852 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
853 self.set = 0
853 self.set = 0
854 self.doy += 1
854 self.doy += 1
855 self.foldercounter = 0
855 self.foldercounter = 0
856
856
857 if fileOk_flag:
857 if fileOk_flag:
858 self.fileSize = os.path.getsize( fullfilename )
858 self.fileSize = os.path.getsize( fullfilename )
859 self.filename = fullfilename
859 self.filename = fullfilename
860 self.flagIsNewFile = 1
860 self.flagIsNewFile = 1
861 if self.fp != None: self.fp.close()
861 if self.fp != None: self.fp.close()
862 self.fp = open(fullfilename, 'rb')
862 self.fp = open(fullfilename, 'rb')
863 self.flagNoMoreFiles = 0
863 self.flagNoMoreFiles = 0
864 # print '[Reading] Setting the file: %s' % fullfilename
864 # print '[Reading] Setting the file: %s' % fullfilename
865 else:
865 else:
866 self.fileSize = 0
866 self.fileSize = 0
867 self.filename = None
867 self.filename = None
868 self.flagIsNewFile = 0
868 self.flagIsNewFile = 0
869 self.fp = None
869 self.fp = None
870 self.flagNoMoreFiles = 1
870 self.flagNoMoreFiles = 1
871 # print '[Reading] No more files to read'
871 # print '[Reading] No more files to read'
872
872
873 return fileOk_flag
873 return fileOk_flag
874
874
875 def setNextFile(self):
875 def setNextFile(self):
876 if self.fp != None:
876 if self.fp != None:
877 self.fp.close()
877 self.fp.close()
878
878
879 if self.online:
879 if self.online:
880 newFile = self.__setNextFileOnline()
880 newFile = self.__setNextFileOnline()
881 else:
881 else:
882 newFile = self.__setNextFileOffline()
882 newFile = self.__setNextFileOffline()
883
883
884 if not(newFile):
884 if not(newFile):
885 print '[Reading] No more files to read'
885 print '[Reading] No more files to read'
886 return 0
886 return 0
887
887
888 if self.verbose:
888 if self.verbose:
889 print '[Reading] Setting the file: %s' % self.filename
889 print '[Reading] Setting the file: %s' % self.filename
890
890
891 self.__readFirstHeader()
891 self.__readFirstHeader()
892 self.nReadBlocks = 0
892 self.nReadBlocks = 0
893 return 1
893 return 1
894
894
895 def __waitNewBlock(self):
895 def __waitNewBlock(self):
896 """
896 """
897 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
897 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
898
898
899 Si el modo de lectura es OffLine siempre retorn 0
899 Si el modo de lectura es OffLine siempre retorn 0
900 """
900 """
901 if not self.online:
901 if not self.online:
902 return 0
902 return 0
903
903
904 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
904 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
905 return 0
905 return 0
906
906
907 currentPointer = self.fp.tell()
907 currentPointer = self.fp.tell()
908
908
909 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
909 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
910
910
911 for nTries in range( self.nTries ):
911 for nTries in range( self.nTries ):
912
912
913 self.fp.close()
913 self.fp.close()
914 self.fp = open( self.filename, 'rb' )
914 self.fp = open( self.filename, 'rb' )
915 self.fp.seek( currentPointer )
915 self.fp.seek( currentPointer )
916
916
917 self.fileSize = os.path.getsize( self.filename )
917 self.fileSize = os.path.getsize( self.filename )
918 currentSize = self.fileSize - currentPointer
918 currentSize = self.fileSize - currentPointer
919
919
920 if ( currentSize >= neededSize ):
920 if ( currentSize >= neededSize ):
921 self.basicHeaderObj.read(self.fp)
921 self.basicHeaderObj.read(self.fp)
922 return 1
922 return 1
923
923
924 if self.fileSize == self.fileSizeByHeader:
924 if self.fileSize == self.fileSizeByHeader:
925 # self.flagEoF = True
925 # self.flagEoF = True
926 return 0
926 return 0
927
927
928 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
928 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
929 sleep( self.delay )
929 sleep( self.delay )
930
930
931
931
932 return 0
932 return 0
933
933
934 def waitDataBlock(self,pointer_location):
934 def waitDataBlock(self,pointer_location):
935
935
936 currentPointer = pointer_location
936 currentPointer = pointer_location
937
937
938 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
938 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
939
939
940 for nTries in range( self.nTries ):
940 for nTries in range( self.nTries ):
941 self.fp.close()
941 self.fp.close()
942 self.fp = open( self.filename, 'rb' )
942 self.fp = open( self.filename, 'rb' )
943 self.fp.seek( currentPointer )
943 self.fp.seek( currentPointer )
944
944
945 self.fileSize = os.path.getsize( self.filename )
945 self.fileSize = os.path.getsize( self.filename )
946 currentSize = self.fileSize - currentPointer
946 currentSize = self.fileSize - currentPointer
947
947
948 if ( currentSize >= neededSize ):
948 if ( currentSize >= neededSize ):
949 return 1
949 return 1
950
950
951 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
951 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
952 sleep( self.delay )
952 sleep( self.delay )
953
953
954 return 0
954 return 0
955
955
956 def __jumpToLastBlock(self):
956 def __jumpToLastBlock(self):
957
957
958 if not(self.__isFirstTimeOnline):
958 if not(self.__isFirstTimeOnline):
959 return
959 return
960
960
961 csize = self.fileSize - self.fp.tell()
961 csize = self.fileSize - self.fp.tell()
962 blocksize = self.processingHeaderObj.blockSize
962 blocksize = self.processingHeaderObj.blockSize
963
963
964 #salta el primer bloque de datos
964 #salta el primer bloque de datos
965 if csize > self.processingHeaderObj.blockSize:
965 if csize > self.processingHeaderObj.blockSize:
966 self.fp.seek(self.fp.tell() + blocksize)
966 self.fp.seek(self.fp.tell() + blocksize)
967 else:
967 else:
968 return
968 return
969
969
970 csize = self.fileSize - self.fp.tell()
970 csize = self.fileSize - self.fp.tell()
971 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
971 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
972 while True:
972 while True:
973
973
974 if self.fp.tell()<self.fileSize:
974 if self.fp.tell()<self.fileSize:
975 self.fp.seek(self.fp.tell() + neededsize)
975 self.fp.seek(self.fp.tell() + neededsize)
976 else:
976 else:
977 self.fp.seek(self.fp.tell() - neededsize)
977 self.fp.seek(self.fp.tell() - neededsize)
978 break
978 break
979
979
980 # csize = self.fileSize - self.fp.tell()
980 # csize = self.fileSize - self.fp.tell()
981 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
981 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
982 # factor = int(csize/neededsize)
982 # factor = int(csize/neededsize)
983 # if factor > 0:
983 # if factor > 0:
984 # self.fp.seek(self.fp.tell() + factor*neededsize)
984 # self.fp.seek(self.fp.tell() + factor*neededsize)
985
985
986 self.flagIsNewFile = 0
986 self.flagIsNewFile = 0
987 self.__isFirstTimeOnline = 0
987 self.__isFirstTimeOnline = 0
988
988
989 def __setNewBlock(self):
989 def __setNewBlock(self):
990 #if self.server is None:
990 #if self.server is None:
991 if self.fp == None:
991 if self.fp == None:
992 return 0
992 return 0
993
993
994 # if self.online:
994 # if self.online:
995 # self.__jumpToLastBlock()
995 # self.__jumpToLastBlock()
996
996
997 if self.flagIsNewFile:
997 if self.flagIsNewFile:
998 self.lastUTTime = self.basicHeaderObj.utc
998 self.lastUTTime = self.basicHeaderObj.utc
999 return 1
999 return 1
1000
1000
1001 if self.realtime:
1001 if self.realtime:
1002 self.flagDiscontinuousBlock = 1
1002 self.flagDiscontinuousBlock = 1
1003 if not(self.setNextFile()):
1003 if not(self.setNextFile()):
1004 return 0
1004 return 0
1005 else:
1005 else:
1006 return 1
1006 return 1
1007 #if self.server is None:
1007 #if self.server is None:
1008 currentSize = self.fileSize - self.fp.tell()
1008 currentSize = self.fileSize - self.fp.tell()
1009 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1009 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1010 if (currentSize >= neededSize):
1010 if (currentSize >= neededSize):
1011 self.basicHeaderObj.read(self.fp)
1011 self.basicHeaderObj.read(self.fp)
1012 self.lastUTTime = self.basicHeaderObj.utc
1012 self.lastUTTime = self.basicHeaderObj.utc
1013 return 1
1013 return 1
1014 # else:
1014 # else:
1015 # self.basicHeaderObj.read(self.zHeader)
1015 # self.basicHeaderObj.read(self.zHeader)
1016 # self.lastUTTime = self.basicHeaderObj.utc
1016 # self.lastUTTime = self.basicHeaderObj.utc
1017 # return 1
1017 # return 1
1018 if self.__waitNewBlock():
1018 if self.__waitNewBlock():
1019 self.lastUTTime = self.basicHeaderObj.utc
1019 self.lastUTTime = self.basicHeaderObj.utc
1020 return 1
1020 return 1
1021 #if self.server is None:
1021 #if self.server is None:
1022 if not(self.setNextFile()):
1022 if not(self.setNextFile()):
1023 return 0
1023 return 0
1024
1024
1025 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
1025 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
1026 self.lastUTTime = self.basicHeaderObj.utc
1026 self.lastUTTime = self.basicHeaderObj.utc
1027
1027
1028 self.flagDiscontinuousBlock = 0
1028 self.flagDiscontinuousBlock = 0
1029
1029
1030 if deltaTime > self.maxTimeStep:
1030 if deltaTime > self.maxTimeStep:
1031 self.flagDiscontinuousBlock = 1
1031 self.flagDiscontinuousBlock = 1
1032
1032
1033 return 1
1033 return 1
1034
1034
1035 def readNextBlock(self):
1035 def readNextBlock(self):
1036
1036
1037 #Skip block out of startTime and endTime
1037 #Skip block out of startTime and endTime
1038 while True:
1038 while True:
1039 if not(self.__setNewBlock()):
1039 if not(self.__setNewBlock()):
1040 return 0
1040 return 0
1041
1041
1042 if not(self.readBlock()):
1042 if not(self.readBlock()):
1043 return 0
1043 return 0
1044
1044
1045 self.getBasicHeader()
1045 self.getBasicHeader()
1046
1046
1047 if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime):
1047 if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime):
1048
1048
1049 print "[Reading] Block No. %d/%d -> %s [Skipping]" %(self.nReadBlocks,
1049 print "[Reading] Block No. %d/%d -> %s [Skipping]" %(self.nReadBlocks,
1050 self.processingHeaderObj.dataBlocksPerFile,
1050 self.processingHeaderObj.dataBlocksPerFile,
1051 self.dataOut.datatime.ctime())
1051 self.dataOut.datatime.ctime())
1052 continue
1052 continue
1053
1053
1054 break
1054 break
1055
1055
1056 if self.verbose:
1056 if self.verbose:
1057 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1057 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1058 self.processingHeaderObj.dataBlocksPerFile,
1058 self.processingHeaderObj.dataBlocksPerFile,
1059 self.dataOut.datatime.ctime())
1059 self.dataOut.datatime.ctime())
1060 return 1
1060 return 1
1061
1061
1062 def __readFirstHeader(self):
1062 def __readFirstHeader(self):
1063
1063
1064 self.basicHeaderObj.read(self.fp)
1064 self.basicHeaderObj.read(self.fp)
1065 self.systemHeaderObj.read(self.fp)
1065 self.systemHeaderObj.read(self.fp)
1066 self.radarControllerHeaderObj.read(self.fp)
1066 self.radarControllerHeaderObj.read(self.fp)
1067 self.processingHeaderObj.read(self.fp)
1067 self.processingHeaderObj.read(self.fp)
1068
1068
1069 self.firstHeaderSize = self.basicHeaderObj.size
1069 self.firstHeaderSize = self.basicHeaderObj.size
1070
1070
1071 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
1071 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
1072 if datatype == 0:
1072 if datatype == 0:
1073 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
1073 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
1074 elif datatype == 1:
1074 elif datatype == 1:
1075 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
1075 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
1076 elif datatype == 2:
1076 elif datatype == 2:
1077 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
1077 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
1078 elif datatype == 3:
1078 elif datatype == 3:
1079 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
1079 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
1080 elif datatype == 4:
1080 elif datatype == 4:
1081 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
1081 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
1082 elif datatype == 5:
1082 elif datatype == 5:
1083 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
1083 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
1084 else:
1084 else:
1085 raise ValueError, 'Data type was not defined'
1085 raise ValueError, 'Data type was not defined'
1086
1086
1087 self.dtype = datatype_str
1087 self.dtype = datatype_str
1088 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1088 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1089 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
1089 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
1090 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1090 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1091 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1091 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1092 self.getBlockDimension()
1092 self.getBlockDimension()
1093
1093
1094 def __verifyFile(self, filename, msgFlag=True):
1094 def __verifyFile(self, filename, msgFlag=True):
1095
1095
1096 msg = None
1096 msg = None
1097
1097
1098 try:
1098 try:
1099 fp = open(filename, 'rb')
1099 fp = open(filename, 'rb')
1100 except IOError:
1100 except IOError:
1101
1101
1102 if msgFlag:
1102 if msgFlag:
1103 print "[Reading] File %s can't be opened" % (filename)
1103 print "[Reading] File %s can't be opened" % (filename)
1104
1104
1105 return False
1105 return False
1106
1106
1107 currentPosition = fp.tell()
1107 currentPosition = fp.tell()
1108 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1108 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1109
1109
1110 if neededSize == 0:
1110 if neededSize == 0:
1111 basicHeaderObj = BasicHeader(LOCALTIME)
1111 basicHeaderObj = BasicHeader(LOCALTIME)
1112 systemHeaderObj = SystemHeader()
1112 systemHeaderObj = SystemHeader()
1113 radarControllerHeaderObj = RadarControllerHeader()
1113 radarControllerHeaderObj = RadarControllerHeader()
1114 processingHeaderObj = ProcessingHeader()
1114 processingHeaderObj = ProcessingHeader()
1115
1115
1116 if not( basicHeaderObj.read(fp) ):
1116 if not( basicHeaderObj.read(fp) ):
1117 fp.close()
1117 fp.close()
1118 return False
1118 return False
1119
1119
1120 if not( systemHeaderObj.read(fp) ):
1120 if not( systemHeaderObj.read(fp) ):
1121 fp.close()
1121 fp.close()
1122 return False
1122 return False
1123
1123
1124 if not( radarControllerHeaderObj.read(fp) ):
1124 if not( radarControllerHeaderObj.read(fp) ):
1125 fp.close()
1125 fp.close()
1126 return False
1126 return False
1127
1127
1128 if not( processingHeaderObj.read(fp) ):
1128 if not( processingHeaderObj.read(fp) ):
1129 fp.close()
1129 fp.close()
1130 return False
1130 return False
1131
1131
1132 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1132 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1133 else:
1133 else:
1134 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
1134 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
1135
1135
1136 fp.close()
1136 fp.close()
1137
1137
1138 fileSize = os.path.getsize(filename)
1138 fileSize = os.path.getsize(filename)
1139 currentSize = fileSize - currentPosition
1139 currentSize = fileSize - currentPosition
1140
1140
1141 if currentSize < neededSize:
1141 if currentSize < neededSize:
1142 if msgFlag and (msg != None):
1142 if msgFlag and (msg != None):
1143 print msg
1143 print msg
1144 return False
1144 return False
1145
1145
1146 return True
1146 return True
1147
1147
1148 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1148 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1149
1149
1150 path_empty = True
1150 path_empty = True
1151
1151
1152 dateList = []
1152 dateList = []
1153 pathList = []
1153 pathList = []
1154
1154
1155 multi_path = path.split(',')
1155 multi_path = path.split(',')
1156
1156
1157 if not walk:
1157 if not walk:
1158
1158
1159 for single_path in multi_path:
1159 for single_path in multi_path:
1160
1160
1161 if not os.path.isdir(single_path):
1161 if not os.path.isdir(single_path):
1162 continue
1162 continue
1163
1163
1164 fileList = glob.glob1(single_path, "*"+ext)
1164 fileList = glob.glob1(single_path, "*"+ext)
1165
1165
1166 if not fileList:
1166 if not fileList:
1167 continue
1167 continue
1168
1168
1169 path_empty = False
1169 path_empty = False
1170
1170
1171 fileList.sort()
1171 fileList.sort()
1172
1172
1173 for thisFile in fileList:
1173 for thisFile in fileList:
1174
1174
1175 if not os.path.isfile(os.path.join(single_path, thisFile)):
1175 if not os.path.isfile(os.path.join(single_path, thisFile)):
1176 continue
1176 continue
1177
1177
1178 if not isRadarFile(thisFile):
1178 if not isRadarFile(thisFile):
1179 continue
1179 continue
1180
1180
1181 if not isFileInDateRange(thisFile, startDate, endDate):
1181 if not isFileInDateRange(thisFile, startDate, endDate):
1182 continue
1182 continue
1183
1183
1184 thisDate = getDateFromRadarFile(thisFile)
1184 thisDate = getDateFromRadarFile(thisFile)
1185
1185
1186 if thisDate in dateList:
1186 if thisDate in dateList:
1187 continue
1187 continue
1188
1188
1189 dateList.append(thisDate)
1189 dateList.append(thisDate)
1190 pathList.append(single_path)
1190 pathList.append(single_path)
1191
1191
1192 else:
1192 else:
1193 for single_path in multi_path:
1193 for single_path in multi_path:
1194
1194
1195 if not os.path.isdir(single_path):
1195 if not os.path.isdir(single_path):
1196 continue
1196 continue
1197
1197
1198 dirList = []
1198 dirList = []
1199
1199
1200 for thisPath in os.listdir(single_path):
1200 for thisPath in os.listdir(single_path):
1201
1201
1202 if not os.path.isdir(os.path.join(single_path,thisPath)):
1202 if not os.path.isdir(os.path.join(single_path,thisPath)):
1203 continue
1203 continue
1204
1204
1205 if not isRadarFolder(thisPath):
1205 if not isRadarFolder(thisPath):
1206 continue
1206 continue
1207
1207
1208 if not isFolderInDateRange(thisPath, startDate, endDate):
1208 if not isFolderInDateRange(thisPath, startDate, endDate):
1209 continue
1209 continue
1210
1210
1211 dirList.append(thisPath)
1211 dirList.append(thisPath)
1212
1212
1213 if not dirList:
1213 if not dirList:
1214 continue
1214 continue
1215
1215
1216 dirList.sort()
1216 dirList.sort()
1217
1217
1218 for thisDir in dirList:
1218 for thisDir in dirList:
1219
1219
1220 datapath = os.path.join(single_path, thisDir, expLabel)
1220 datapath = os.path.join(single_path, thisDir, expLabel)
1221 fileList = glob.glob1(datapath, "*"+ext)
1221 fileList = glob.glob1(datapath, "*"+ext)
1222
1222
1223 if not fileList:
1223 if not fileList:
1224 continue
1224 continue
1225
1225
1226 path_empty = False
1226 path_empty = False
1227
1227
1228 thisDate = getDateFromRadarFolder(thisDir)
1228 thisDate = getDateFromRadarFolder(thisDir)
1229
1229
1230 pathList.append(datapath)
1230 pathList.append(datapath)
1231 dateList.append(thisDate)
1231 dateList.append(thisDate)
1232
1232
1233 dateList.sort()
1233 dateList.sort()
1234
1234
1235 if walk:
1235 if walk:
1236 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1236 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1237 else:
1237 else:
1238 pattern_path = multi_path[0]
1238 pattern_path = multi_path[0]
1239
1239
1240 if path_empty:
1240 if path_empty:
1241 print "[Reading] No *%s files in %s for %s to %s" %(ext, pattern_path, startDate, endDate)
1241 print "[Reading] No *%s files in %s for %s to %s" %(ext, pattern_path, startDate, endDate)
1242 else:
1242 else:
1243 if not dateList:
1243 if not dateList:
1244 print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
1244 print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
1245
1245
1246 if include_path:
1246 if include_path:
1247 return dateList, pathList
1247 return dateList, pathList
1248
1248
1249 return dateList
1249 return dateList
1250
1250
1251 def setup(self,
1251 def setup(self,
1252 path=None,
1252 path=None,
1253 startDate=None,
1253 startDate=None,
1254 endDate=None,
1254 endDate=None,
1255 startTime=datetime.time(0,0,0),
1255 startTime=datetime.time(0,0,0),
1256 endTime=datetime.time(23,59,59),
1256 endTime=datetime.time(23,59,59),
1257 set=None,
1257 set=None,
1258 expLabel = "",
1258 expLabel = "",
1259 ext = None,
1259 ext = None,
1260 online = False,
1260 online = False,
1261 delay = 60,
1261 delay = 60,
1262 walk = True,
1262 walk = True,
1263 getblock = False,
1263 getblock = False,
1264 nTxs = 1,
1264 nTxs = 1,
1265 realtime=False,
1265 realtime=False,
1266 blocksize=None,
1266 blocksize=None,
1267 blocktime=None,
1267 blocktime=None,
1268 skip=None,
1268 skip=None,
1269 cursor=None,
1269 cursor=None,
1270 warnings=True,
1270 warnings=True,
1271 verbose=True,
1271 verbose=True,
1272 server=None):
1272 server=None,
1273 format=None,
1274 oneDDict=None,
1275 twoDDict=None,
1276 ind2DList=None):
1273 if server is not None:
1277 if server is not None:
1274 if 'tcp://' in server:
1278 if 'tcp://' in server:
1275 address = server
1279 address = server
1276 else:
1280 else:
1277 address = 'ipc:///tmp/%s' % server
1281 address = 'ipc:///tmp/%s' % server
1278 self.server = address
1282 self.server = address
1279 self.context = zmq.Context()
1283 self.context = zmq.Context()
1280 self.receiver = self.context.socket(zmq.PULL)
1284 self.receiver = self.context.socket(zmq.PULL)
1281 self.receiver.connect(self.server)
1285 self.receiver.connect(self.server)
1282 time.sleep(0.5)
1286 time.sleep(0.5)
1283 print '[Starting] ReceiverData from {}'.format(self.server)
1287 print '[Starting] ReceiverData from {}'.format(self.server)
1284 else:
1288 else:
1285 self.server = None
1289 self.server = None
1286 if path == None:
1290 if path == None:
1287 raise ValueError, "[Reading] The path is not valid"
1291 raise ValueError, "[Reading] The path is not valid"
1288
1292
1289 if ext == None:
1293 if ext == None:
1290 ext = self.ext
1294 ext = self.ext
1291
1295
1292 if online:
1296 if online:
1293 print "[Reading] Searching files in online mode..."
1297 print "[Reading] Searching files in online mode..."
1294
1298
1295 for nTries in range( self.nTries ):
1299 for nTries in range( self.nTries ):
1296 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1300 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1297
1301
1298 if fullpath:
1302 if fullpath:
1299 break
1303 break
1300
1304
1301 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
1305 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
1302 sleep( self.delay )
1306 sleep( self.delay )
1303
1307
1304 if not(fullpath):
1308 if not(fullpath):
1305 print "[Reading] There 'isn't any valid file in %s" % path
1309 print "[Reading] There 'isn't any valid file in %s" % path
1306 return
1310 return
1307
1311
1308 self.year = year
1312 self.year = year
1309 self.doy = doy
1313 self.doy = doy
1310 self.set = set - 1
1314 self.set = set - 1
1311 self.path = path
1315 self.path = path
1312 self.foldercounter = foldercounter
1316 self.foldercounter = foldercounter
1313 last_set = None
1317 last_set = None
1314 else:
1318 else:
1315 print "[Reading] Searching files in offline mode ..."
1319 print "[Reading] Searching files in offline mode ..."
1316 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1320 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1317 startTime=startTime, endTime=endTime,
1321 startTime=startTime, endTime=endTime,
1318 set=set, expLabel=expLabel, ext=ext,
1322 set=set, expLabel=expLabel, ext=ext,
1319 walk=walk, cursor=cursor,
1323 walk=walk, cursor=cursor,
1320 skip=skip)
1324 skip=skip)
1321
1325
1322 if not(pathList):
1326 if not(pathList):
1323 self.fileIndex = -1
1327 self.fileIndex = -1
1324 self.pathList = []
1328 self.pathList = []
1325 self.filenameList = []
1329 self.filenameList = []
1326 return
1330 return
1327
1331
1328 self.fileIndex = -1
1332 self.fileIndex = -1
1329 self.pathList = pathList
1333 self.pathList = pathList
1330 self.filenameList = filenameList
1334 self.filenameList = filenameList
1331 file_name = os.path.basename(filenameList[-1])
1335 file_name = os.path.basename(filenameList[-1])
1332 basename, ext = os.path.splitext(file_name)
1336 basename, ext = os.path.splitext(file_name)
1333 last_set = int(basename[-3:])
1337 last_set = int(basename[-3:])
1334
1338
1335 self.online = online
1339 self.online = online
1336 self.realtime = realtime
1340 self.realtime = realtime
1337 self.delay = delay
1341 self.delay = delay
1338 ext = ext.lower()
1342 ext = ext.lower()
1339 self.ext = ext
1343 self.ext = ext
1340 self.getByBlock = getblock
1344 self.getByBlock = getblock
1341 self.nTxs = nTxs
1345 self.nTxs = nTxs
1342 self.startTime = startTime
1346 self.startTime = startTime
1343 self.endTime = endTime
1347 self.endTime = endTime
1344
1348
1345 #Added-----------------
1349 #Added-----------------
1346 self.selBlocksize = blocksize
1350 self.selBlocksize = blocksize
1347 self.selBlocktime = blocktime
1351 self.selBlocktime = blocktime
1348
1352
1349 # Verbose-----------
1353 # Verbose-----------
1350 self.verbose = verbose
1354 self.verbose = verbose
1351 self.warnings = warnings
1355 self.warnings = warnings
1352
1356
1353 if not(self.setNextFile()):
1357 if not(self.setNextFile()):
1354 if (startDate!=None) and (endDate!=None):
1358 if (startDate!=None) and (endDate!=None):
1355 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1359 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1356 elif startDate != None:
1360 elif startDate != None:
1357 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1361 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1358 else:
1362 else:
1359 print "[Reading] No files"
1363 print "[Reading] No files"
1360
1364
1361 self.fileIndex = -1
1365 self.fileIndex = -1
1362 self.pathList = []
1366 self.pathList = []
1363 self.filenameList = []
1367 self.filenameList = []
1364 return
1368 return
1365
1369
1366 # self.getBasicHeader()
1370 # self.getBasicHeader()
1367
1371
1368 if last_set != None:
1372 if last_set != None:
1369 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1373 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1370 return
1374 return
1371
1375
1372 def getBasicHeader(self):
1376 def getBasicHeader(self):
1373
1377
1374 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1378 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1375
1379
1376 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1380 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1377
1381
1378 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1382 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1379
1383
1380 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1384 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1381
1385
1382 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1386 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1383
1387
1384 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1388 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1385
1389
1386 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1390 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1387
1391
1388 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1392 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1389
1393
1390
1394
1391 def getFirstHeader(self):
1395 def getFirstHeader(self):
1392
1396
1393 raise NotImplementedError
1397 raise NotImplementedError
1394
1398
1395 def getData(self):
1399 def getData(self):
1396
1400
1397 raise NotImplementedError
1401 raise NotImplementedError
1398
1402
1399 def hasNotDataInBuffer(self):
1403 def hasNotDataInBuffer(self):
1400
1404
1401 raise NotImplementedError
1405 raise NotImplementedError
1402
1406
1403 def readBlock(self):
1407 def readBlock(self):
1404
1408
1405 raise NotImplementedError
1409 raise NotImplementedError
1406
1410
1407 def isEndProcess(self):
1411 def isEndProcess(self):
1408
1412
1409 return self.flagNoMoreFiles
1413 return self.flagNoMoreFiles
1410
1414
1411 def printReadBlocks(self):
1415 def printReadBlocks(self):
1412
1416
1413 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1417 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1414
1418
1415 def printTotalBlocks(self):
1419 def printTotalBlocks(self):
1416
1420
1417 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1421 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1418
1422
1419 def printNumberOfBlock(self):
1423 def printNumberOfBlock(self):
1424 'SPAM!'
1420
1425
1421 if self.flagIsNewBlock:
1426 # if self.flagIsNewBlock:
1422 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1427 # print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1423 self.processingHeaderObj.dataBlocksPerFile,
1428 # self.processingHeaderObj.dataBlocksPerFile,
1424 self.dataOut.datatime.ctime())
1429 # self.dataOut.datatime.ctime())
1425
1430
1426 def printInfo(self):
1431 def printInfo(self):
1427
1432
1428 if self.__printInfo == False:
1433 if self.__printInfo == False:
1429 return
1434 return
1430
1435
1431 self.basicHeaderObj.printInfo()
1436 self.basicHeaderObj.printInfo()
1432 self.systemHeaderObj.printInfo()
1437 self.systemHeaderObj.printInfo()
1433 self.radarControllerHeaderObj.printInfo()
1438 self.radarControllerHeaderObj.printInfo()
1434 self.processingHeaderObj.printInfo()
1439 self.processingHeaderObj.printInfo()
1435
1440
1436 self.__printInfo = False
1441 self.__printInfo = False
1437
1442
1438 def run(self,
1443 def run(self,
1439 path=None,
1444 path=None,
1440 startDate=None,
1445 startDate=None,
1441 endDate=None,
1446 endDate=None,
1442 startTime=datetime.time(0,0,0),
1447 startTime=datetime.time(0,0,0),
1443 endTime=datetime.time(23,59,59),
1448 endTime=datetime.time(23,59,59),
1444 set=None,
1449 set=None,
1445 expLabel = "",
1450 expLabel = "",
1446 ext = None,
1451 ext = None,
1447 online = False,
1452 online = False,
1448 delay = 60,
1453 delay = 60,
1449 walk = True,
1454 walk = True,
1450 getblock = False,
1455 getblock = False,
1451 nTxs = 1,
1456 nTxs = 1,
1452 realtime=False,
1457 realtime=False,
1453 blocksize=None,
1458 blocksize=None,
1454 blocktime=None,
1459 blocktime=None,
1455 skip=None,
1460 skip=None,
1456 cursor=None,
1461 cursor=None,
1457 warnings=True,
1462 warnings=True,
1458 server=None,
1463 server=None,
1459 verbose=True, **kwargs):
1464 verbose=True,
1465 format=None,
1466 oneDDict=None,
1467 twoDDict=None,
1468 ind2DList=None, **kwargs):
1460
1469
1461 if not(self.isConfig):
1470 if not(self.isConfig):
1462 self.setup(path=path,
1471 self.setup(path=path,
1463 startDate=startDate,
1472 startDate=startDate,
1464 endDate=endDate,
1473 endDate=endDate,
1465 startTime=startTime,
1474 startTime=startTime,
1466 endTime=endTime,
1475 endTime=endTime,
1467 set=set,
1476 set=set,
1468 expLabel=expLabel,
1477 expLabel=expLabel,
1469 ext=ext,
1478 ext=ext,
1470 online=online,
1479 online=online,
1471 delay=delay,
1480 delay=delay,
1472 walk=walk,
1481 walk=walk,
1473 getblock=getblock,
1482 getblock=getblock,
1474 nTxs=nTxs,
1483 nTxs=nTxs,
1475 realtime=realtime,
1484 realtime=realtime,
1476 blocksize=blocksize,
1485 blocksize=blocksize,
1477 blocktime=blocktime,
1486 blocktime=blocktime,
1478 skip=skip,
1487 skip=skip,
1479 cursor=cursor,
1488 cursor=cursor,
1480 warnings=warnings,
1489 warnings=warnings,
1481 server=server,
1490 server=server,
1482 verbose=verbose)
1491 verbose=verbose,
1492 format=format,
1493 oneDDict=oneDDict,
1494 twoDDict=twoDDict,
1495 ind2DList=ind2DList)
1483 self.isConfig = True
1496 self.isConfig = True
1484 if server is None:
1497 if server is None:
1485 self.getData()
1498 self.getData()
1486 else:
1499 else:
1487 self.getFromServer()
1500 self.getFromServer()
1488
1501
1489 class JRODataWriter(JRODataIO):
1502 class JRODataWriter(JRODataIO):
1490
1503
1491 """
1504 """
1492 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1505 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1493 de los datos siempre se realiza por bloques.
1506 de los datos siempre se realiza por bloques.
1494 """
1507 """
1495
1508
1496 blockIndex = 0
1509 blockIndex = 0
1497
1510
1498 path = None
1511 path = None
1499
1512
1500 setFile = None
1513 setFile = None
1501
1514
1502 profilesPerBlock = None
1515 profilesPerBlock = None
1503
1516
1504 blocksPerFile = None
1517 blocksPerFile = None
1505
1518
1506 nWriteBlocks = 0
1519 nWriteBlocks = 0
1507
1520
1508 fileDate = None
1521 fileDate = None
1509
1522
1510 def __init__(self, dataOut=None):
1523 def __init__(self, dataOut=None):
1511 raise NotImplementedError
1524 raise NotImplementedError
1512
1525
1513
1526
1514 def hasAllDataInBuffer(self):
1527 def hasAllDataInBuffer(self):
1515 raise NotImplementedError
1528 raise NotImplementedError
1516
1529
1517
1530
1518 def setBlockDimension(self):
1531 def setBlockDimension(self):
1519 raise NotImplementedError
1532 raise NotImplementedError
1520
1533
1521
1534
1522 def writeBlock(self):
1535 def writeBlock(self):
1523 raise NotImplementedError
1536 raise NotImplementedError
1524
1537
1525
1538
1526 def putData(self):
1539 def putData(self):
1527 raise NotImplementedError
1540 raise NotImplementedError
1528
1541
1529
1542
1530 def getProcessFlags(self):
1543 def getProcessFlags(self):
1531
1544
1532 processFlags = 0
1545 processFlags = 0
1533
1546
1534 dtype_index = get_dtype_index(self.dtype)
1547 dtype_index = get_dtype_index(self.dtype)
1535 procflag_dtype = get_procflag_dtype(dtype_index)
1548 procflag_dtype = get_procflag_dtype(dtype_index)
1536
1549
1537 processFlags += procflag_dtype
1550 processFlags += procflag_dtype
1538
1551
1539 if self.dataOut.flagDecodeData:
1552 if self.dataOut.flagDecodeData:
1540 processFlags += PROCFLAG.DECODE_DATA
1553 processFlags += PROCFLAG.DECODE_DATA
1541
1554
1542 if self.dataOut.flagDeflipData:
1555 if self.dataOut.flagDeflipData:
1543 processFlags += PROCFLAG.DEFLIP_DATA
1556 processFlags += PROCFLAG.DEFLIP_DATA
1544
1557
1545 if self.dataOut.code is not None:
1558 if self.dataOut.code is not None:
1546 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1559 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1547
1560
1548 if self.dataOut.nCohInt > 1:
1561 if self.dataOut.nCohInt > 1:
1549 processFlags += PROCFLAG.COHERENT_INTEGRATION
1562 processFlags += PROCFLAG.COHERENT_INTEGRATION
1550
1563
1551 if self.dataOut.type == "Spectra":
1564 if self.dataOut.type == "Spectra":
1552 if self.dataOut.nIncohInt > 1:
1565 if self.dataOut.nIncohInt > 1:
1553 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1566 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1554
1567
1555 if self.dataOut.data_dc is not None:
1568 if self.dataOut.data_dc is not None:
1556 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1569 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1557
1570
1558 if self.dataOut.flagShiftFFT:
1571 if self.dataOut.flagShiftFFT:
1559 processFlags += PROCFLAG.SHIFT_FFT_DATA
1572 processFlags += PROCFLAG.SHIFT_FFT_DATA
1560
1573
1561 return processFlags
1574 return processFlags
1562
1575
1563 def setBasicHeader(self):
1576 def setBasicHeader(self):
1564
1577
1565 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1578 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1566 self.basicHeaderObj.version = self.versionFile
1579 self.basicHeaderObj.version = self.versionFile
1567 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1580 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1568
1581
1569 utc = numpy.floor(self.dataOut.utctime)
1582 utc = numpy.floor(self.dataOut.utctime)
1570 milisecond = (self.dataOut.utctime - utc)* 1000.0
1583 milisecond = (self.dataOut.utctime - utc)* 1000.0
1571
1584
1572 self.basicHeaderObj.utc = utc
1585 self.basicHeaderObj.utc = utc
1573 self.basicHeaderObj.miliSecond = milisecond
1586 self.basicHeaderObj.miliSecond = milisecond
1574 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1587 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1575 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1588 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1576 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1589 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1577
1590
1578 def setFirstHeader(self):
1591 def setFirstHeader(self):
1579 """
1592 """
1580 Obtiene una copia del First Header
1593 Obtiene una copia del First Header
1581
1594
1582 Affected:
1595 Affected:
1583
1596
1584 self.basicHeaderObj
1597 self.basicHeaderObj
1585 self.systemHeaderObj
1598 self.systemHeaderObj
1586 self.radarControllerHeaderObj
1599 self.radarControllerHeaderObj
1587 self.processingHeaderObj self.
1600 self.processingHeaderObj self.
1588
1601
1589 Return:
1602 Return:
1590 None
1603 None
1591 """
1604 """
1592
1605
1593 raise NotImplementedError
1606 raise NotImplementedError
1594
1607
1595 def __writeFirstHeader(self):
1608 def __writeFirstHeader(self):
1596 """
1609 """
1597 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1610 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1598
1611
1599 Affected:
1612 Affected:
1600 __dataType
1613 __dataType
1601
1614
1602 Return:
1615 Return:
1603 None
1616 None
1604 """
1617 """
1605
1618
1606 # CALCULAR PARAMETROS
1619 # CALCULAR PARAMETROS
1607
1620
1608 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1621 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1609 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1622 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1610
1623
1611 self.basicHeaderObj.write(self.fp)
1624 self.basicHeaderObj.write(self.fp)
1612 self.systemHeaderObj.write(self.fp)
1625 self.systemHeaderObj.write(self.fp)
1613 self.radarControllerHeaderObj.write(self.fp)
1626 self.radarControllerHeaderObj.write(self.fp)
1614 self.processingHeaderObj.write(self.fp)
1627 self.processingHeaderObj.write(self.fp)
1615
1628
1616 def __setNewBlock(self):
1629 def __setNewBlock(self):
1617 """
1630 """
1618 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1631 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1619
1632
1620 Return:
1633 Return:
1621 0 : si no pudo escribir nada
1634 0 : si no pudo escribir nada
1622 1 : Si escribio el Basic el First Header
1635 1 : Si escribio el Basic el First Header
1623 """
1636 """
1624 if self.fp == None:
1637 if self.fp == None:
1625 self.setNextFile()
1638 self.setNextFile()
1626
1639
1627 if self.flagIsNewFile:
1640 if self.flagIsNewFile:
1628 return 1
1641 return 1
1629
1642
1630 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1643 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1631 self.basicHeaderObj.write(self.fp)
1644 self.basicHeaderObj.write(self.fp)
1632 return 1
1645 return 1
1633
1646
1634 if not( self.setNextFile() ):
1647 if not( self.setNextFile() ):
1635 return 0
1648 return 0
1636
1649
1637 return 1
1650 return 1
1638
1651
1639
1652
1640 def writeNextBlock(self):
1653 def writeNextBlock(self):
1641 """
1654 """
1642 Selecciona el bloque siguiente de datos y los escribe en un file
1655 Selecciona el bloque siguiente de datos y los escribe en un file
1643
1656
1644 Return:
1657 Return:
1645 0 : Si no hizo pudo escribir el bloque de datos
1658 0 : Si no hizo pudo escribir el bloque de datos
1646 1 : Si no pudo escribir el bloque de datos
1659 1 : Si no pudo escribir el bloque de datos
1647 """
1660 """
1648 if not( self.__setNewBlock() ):
1661 if not( self.__setNewBlock() ):
1649 return 0
1662 return 0
1650
1663
1651 self.writeBlock()
1664 self.writeBlock()
1652
1665
1653 print "[Writing] Block No. %d/%d" %(self.blockIndex,
1666 print "[Writing] Block No. %d/%d" %(self.blockIndex,
1654 self.processingHeaderObj.dataBlocksPerFile)
1667 self.processingHeaderObj.dataBlocksPerFile)
1655
1668
1656 return 1
1669 return 1
1657
1670
1658 def setNextFile(self):
1671 def setNextFile(self):
1659 """
1672 """
1660 Determina el siguiente file que sera escrito
1673 Determina el siguiente file que sera escrito
1661
1674
1662 Affected:
1675 Affected:
1663 self.filename
1676 self.filename
1664 self.subfolder
1677 self.subfolder
1665 self.fp
1678 self.fp
1666 self.setFile
1679 self.setFile
1667 self.flagIsNewFile
1680 self.flagIsNewFile
1668
1681
1669 Return:
1682 Return:
1670 0 : Si el archivo no puede ser escrito
1683 0 : Si el archivo no puede ser escrito
1671 1 : Si el archivo esta listo para ser escrito
1684 1 : Si el archivo esta listo para ser escrito
1672 """
1685 """
1673 ext = self.ext
1686 ext = self.ext
1674 path = self.path
1687 path = self.path
1675
1688
1676 if self.fp != None:
1689 if self.fp != None:
1677 self.fp.close()
1690 self.fp.close()
1678
1691
1679 timeTuple = time.localtime( self.dataOut.utctime)
1692 timeTuple = time.localtime( self.dataOut.utctime)
1680 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1693 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1681
1694
1682 fullpath = os.path.join( path, subfolder )
1695 fullpath = os.path.join( path, subfolder )
1683 setFile = self.setFile
1696 setFile = self.setFile
1684
1697
1685 if not( os.path.exists(fullpath) ):
1698 if not( os.path.exists(fullpath) ):
1686 os.mkdir(fullpath)
1699 os.mkdir(fullpath)
1687 setFile = -1 #inicializo mi contador de seteo
1700 setFile = -1 #inicializo mi contador de seteo
1688 else:
1701 else:
1689 filesList = os.listdir( fullpath )
1702 filesList = os.listdir( fullpath )
1690 if len( filesList ) > 0:
1703 if len( filesList ) > 0:
1691 filesList = sorted( filesList, key=str.lower )
1704 filesList = sorted( filesList, key=str.lower )
1692 filen = filesList[-1]
1705 filen = filesList[-1]
1693 # el filename debera tener el siguiente formato
1706 # el filename debera tener el siguiente formato
1694 # 0 1234 567 89A BCDE (hex)
1707 # 0 1234 567 89A BCDE (hex)
1695 # x YYYY DDD SSS .ext
1708 # x YYYY DDD SSS .ext
1696 if isNumber( filen[8:11] ):
1709 if isNumber( filen[8:11] ):
1697 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1710 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1698 else:
1711 else:
1699 setFile = -1
1712 setFile = -1
1700 else:
1713 else:
1701 setFile = -1 #inicializo mi contador de seteo
1714 setFile = -1 #inicializo mi contador de seteo
1702
1715
1703 setFile += 1
1716 setFile += 1
1704
1717
1705 #If this is a new day it resets some values
1718 #If this is a new day it resets some values
1706 if self.dataOut.datatime.date() > self.fileDate:
1719 if self.dataOut.datatime.date() > self.fileDate:
1707 setFile = 0
1720 setFile = 0
1708 self.nTotalBlocks = 0
1721 self.nTotalBlocks = 0
1709
1722
1710 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext )
1723 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext )
1711
1724
1712 filename = os.path.join( path, subfolder, filen )
1725 filename = os.path.join( path, subfolder, filen )
1713
1726
1714 fp = open( filename,'wb' )
1727 fp = open( filename,'wb' )
1715
1728
1716 self.blockIndex = 0
1729 self.blockIndex = 0
1717
1730
1718 #guardando atributos
1731 #guardando atributos
1719 self.filename = filename
1732 self.filename = filename
1720 self.subfolder = subfolder
1733 self.subfolder = subfolder
1721 self.fp = fp
1734 self.fp = fp
1722 self.setFile = setFile
1735 self.setFile = setFile
1723 self.flagIsNewFile = 1
1736 self.flagIsNewFile = 1
1724 self.fileDate = self.dataOut.datatime.date()
1737 self.fileDate = self.dataOut.datatime.date()
1725
1738
1726 self.setFirstHeader()
1739 self.setFirstHeader()
1727
1740
1728 print '[Writing] Opening file: %s'%self.filename
1741 print '[Writing] Opening file: %s'%self.filename
1729
1742
1730 self.__writeFirstHeader()
1743 self.__writeFirstHeader()
1731
1744
1732 return 1
1745 return 1
1733
1746
1734 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1747 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1735 """
1748 """
1736 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1749 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1737
1750
1738 Inputs:
1751 Inputs:
1739 path : directory where data will be saved
1752 path : directory where data will be saved
1740 profilesPerBlock : number of profiles per block
1753 profilesPerBlock : number of profiles per block
1741 set : initial file set
1754 set : initial file set
1742 datatype : An integer number that defines data type:
1755 datatype : An integer number that defines data type:
1743 0 : int8 (1 byte)
1756 0 : int8 (1 byte)
1744 1 : int16 (2 bytes)
1757 1 : int16 (2 bytes)
1745 2 : int32 (4 bytes)
1758 2 : int32 (4 bytes)
1746 3 : int64 (8 bytes)
1759 3 : int64 (8 bytes)
1747 4 : float32 (4 bytes)
1760 4 : float32 (4 bytes)
1748 5 : double64 (8 bytes)
1761 5 : double64 (8 bytes)
1749
1762
1750 Return:
1763 Return:
1751 0 : Si no realizo un buen seteo
1764 0 : Si no realizo un buen seteo
1752 1 : Si realizo un buen seteo
1765 1 : Si realizo un buen seteo
1753 """
1766 """
1754
1767
1755 if ext == None:
1768 if ext == None:
1756 ext = self.ext
1769 ext = self.ext
1757
1770
1758 self.ext = ext.lower()
1771 self.ext = ext.lower()
1759
1772
1760 self.path = path
1773 self.path = path
1761
1774
1762 if set is None:
1775 if set is None:
1763 self.setFile = -1
1776 self.setFile = -1
1764 else:
1777 else:
1765 self.setFile = set - 1
1778 self.setFile = set - 1
1766
1779
1767 self.blocksPerFile = blocksPerFile
1780 self.blocksPerFile = blocksPerFile
1768
1781
1769 self.profilesPerBlock = profilesPerBlock
1782 self.profilesPerBlock = profilesPerBlock
1770
1783
1771 self.dataOut = dataOut
1784 self.dataOut = dataOut
1772 self.fileDate = self.dataOut.datatime.date()
1785 self.fileDate = self.dataOut.datatime.date()
1773 #By default
1786 #By default
1774 self.dtype = self.dataOut.dtype
1787 self.dtype = self.dataOut.dtype
1775
1788
1776 if datatype is not None:
1789 if datatype is not None:
1777 self.dtype = get_numpy_dtype(datatype)
1790 self.dtype = get_numpy_dtype(datatype)
1778
1791
1779 if not(self.setNextFile()):
1792 if not(self.setNextFile()):
1780 print "[Writing] There isn't a next file"
1793 print "[Writing] There isn't a next file"
1781 return 0
1794 return 0
1782
1795
1783 self.setBlockDimension()
1796 self.setBlockDimension()
1784
1797
1785 return 1
1798 return 1
1786
1799
1787 def run(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1800 def run(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1788
1801
1789 if not(self.isConfig):
1802 if not(self.isConfig):
1790
1803
1791 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock, set=set, ext=ext, datatype=datatype, **kwargs)
1804 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock, set=set, ext=ext, datatype=datatype, **kwargs)
1792 self.isConfig = True
1805 self.isConfig = True
1793
1806
1794 self.putData()
1807 self.putData()
@@ -1,1095 +1,1095
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, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, **kwargs):
610 def setup(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, **kwargs):
611 self.path = path
611 self.path = path
612 self.blocksPerFile = blocksPerFile
612 self.blocksPerFile = blocksPerFile
613 self.metadataList = metadataList
613 self.metadataList = metadataList
614 self.dataList = dataList
614 self.dataList = dataList
615 self.dataOut = dataOut
615 self.dataOut = dataOut
616 self.mode = mode
616 self.mode = mode
617
617
618 if self.mode is not None:
618 if self.mode is not None:
619 self.mode = numpy.zeros(len(self.dataList)) + mode
619 self.mode = numpy.zeros(len(self.dataList)) + mode
620 else:
620 else:
621 self.mode = numpy.ones(len(self.dataList))
621 self.mode = numpy.ones(len(self.dataList))
622
622
623 arrayDim = numpy.zeros((len(self.dataList),5))
623 arrayDim = numpy.zeros((len(self.dataList),5))
624
624
625 #Table dimensions
625 #Table dimensions
626 dtype0 = self.dtype
626 dtype0 = self.dtype
627 tableList = []
627 tableList = []
628
628
629 #Dictionary and list of tables
629 #Dictionary and list of tables
630 dsList = []
630 dsList = []
631
631
632 for i in range(len(self.dataList)):
632 for i in range(len(self.dataList)):
633 dsDict = {}
633 dsDict = {}
634 dataAux = getattr(self.dataOut, self.dataList[i])
634 dataAux = getattr(self.dataOut, self.dataList[i])
635 dsDict['variable'] = self.dataList[i]
635 dsDict['variable'] = self.dataList[i]
636 #--------------------- Conditionals ------------------------
636 #--------------------- Conditionals ------------------------
637 #There is no data
637 #There is no data
638 if dataAux is None:
638 if dataAux is None:
639 return 0
639 return 0
640
640
641 #Not array, just a number
641 #Not array, just a number
642 #Mode 0
642 #Mode 0
643 if type(dataAux)==float or type(dataAux)==int:
643 if type(dataAux)==float or type(dataAux)==int:
644 dsDict['mode'] = 0
644 dsDict['mode'] = 0
645 dsDict['nDim'] = 0
645 dsDict['nDim'] = 0
646 arrayDim[i,0] = 0
646 arrayDim[i,0] = 0
647 dsList.append(dsDict)
647 dsList.append(dsDict)
648
648
649 #Mode 2: meteors
649 #Mode 2: meteors
650 elif mode[i] == 2:
650 elif mode[i] == 2:
651 # dsDict['nDim'] = 0
651 # dsDict['nDim'] = 0
652 dsDict['dsName'] = 'table0'
652 dsDict['dsName'] = 'table0'
653 dsDict['mode'] = 2 # Mode meteors
653 dsDict['mode'] = 2 # Mode meteors
654 dsDict['shape'] = dataAux.shape[-1]
654 dsDict['shape'] = dataAux.shape[-1]
655 dsDict['nDim'] = 0
655 dsDict['nDim'] = 0
656 dsDict['dsNumber'] = 1
656 dsDict['dsNumber'] = 1
657
657
658 arrayDim[i,3] = dataAux.shape[-1]
658 arrayDim[i,3] = dataAux.shape[-1]
659 arrayDim[i,4] = mode[i] #Mode the data was stored
659 arrayDim[i,4] = mode[i] #Mode the data was stored
660
660
661 dsList.append(dsDict)
661 dsList.append(dsDict)
662
662
663 #Mode 1
663 #Mode 1
664 else:
664 else:
665 arrayDim0 = dataAux.shape #Data dimensions
665 arrayDim0 = dataAux.shape #Data dimensions
666 arrayDim[i,0] = len(arrayDim0) #Number of array dimensions
666 arrayDim[i,0] = len(arrayDim0) #Number of array dimensions
667 arrayDim[i,4] = mode[i] #Mode the data was stored
667 arrayDim[i,4] = mode[i] #Mode the data was stored
668
668
669 strtable = 'table'
669 strtable = 'table'
670 dsDict['mode'] = 1 # Mode parameters
670 dsDict['mode'] = 1 # Mode parameters
671
671
672 # Three-dimension arrays
672 # Three-dimension arrays
673 if len(arrayDim0) == 3:
673 if len(arrayDim0) == 3:
674 arrayDim[i,1:-1] = numpy.array(arrayDim0)
674 arrayDim[i,1:-1] = numpy.array(arrayDim0)
675 nTables = int(arrayDim[i,2])
675 nTables = int(arrayDim[i,2])
676 dsDict['dsNumber'] = nTables
676 dsDict['dsNumber'] = nTables
677 dsDict['shape'] = arrayDim[i,2:4]
677 dsDict['shape'] = arrayDim[i,2:4]
678 dsDict['nDim'] = 3
678 dsDict['nDim'] = 3
679
679
680 for j in range(nTables):
680 for j in range(nTables):
681 dsDict = dsDict.copy()
681 dsDict = dsDict.copy()
682 dsDict['dsName'] = strtable + str(j)
682 dsDict['dsName'] = strtable + str(j)
683 dsList.append(dsDict)
683 dsList.append(dsDict)
684
684
685 # Two-dimension arrays
685 # Two-dimension arrays
686 elif len(arrayDim0) == 2:
686 elif len(arrayDim0) == 2:
687 arrayDim[i,2:-1] = numpy.array(arrayDim0)
687 arrayDim[i,2:-1] = numpy.array(arrayDim0)
688 nTables = int(arrayDim[i,2])
688 nTables = int(arrayDim[i,2])
689 dsDict['dsNumber'] = nTables
689 dsDict['dsNumber'] = nTables
690 dsDict['shape'] = arrayDim[i,3]
690 dsDict['shape'] = arrayDim[i,3]
691 dsDict['nDim'] = 2
691 dsDict['nDim'] = 2
692
692
693 for j in range(nTables):
693 for j in range(nTables):
694 dsDict = dsDict.copy()
694 dsDict = dsDict.copy()
695 dsDict['dsName'] = strtable + str(j)
695 dsDict['dsName'] = strtable + str(j)
696 dsList.append(dsDict)
696 dsList.append(dsDict)
697
697
698 # One-dimension arrays
698 # One-dimension arrays
699 elif len(arrayDim0) == 1:
699 elif len(arrayDim0) == 1:
700 arrayDim[i,3] = arrayDim0[0]
700 arrayDim[i,3] = arrayDim0[0]
701 dsDict['shape'] = arrayDim0[0]
701 dsDict['shape'] = arrayDim0[0]
702 dsDict['dsNumber'] = 1
702 dsDict['dsNumber'] = 1
703 dsDict['dsName'] = strtable + str(0)
703 dsDict['dsName'] = strtable + str(0)
704 dsDict['nDim'] = 1
704 dsDict['nDim'] = 1
705 dsList.append(dsDict)
705 dsList.append(dsDict)
706
706
707 table = numpy.array((self.dataList[i],) + tuple(arrayDim[i,:]),dtype = dtype0)
707 table = numpy.array((self.dataList[i],) + tuple(arrayDim[i,:]),dtype = dtype0)
708 tableList.append(table)
708 tableList.append(table)
709
709
710 # self.arrayDim = arrayDim
710 # self.arrayDim = arrayDim
711 self.dsList = dsList
711 self.dsList = dsList
712 self.tableDim = numpy.array(tableList, dtype = dtype0)
712 self.tableDim = numpy.array(tableList, dtype = dtype0)
713 self.blockIndex = 0
713 self.blockIndex = 0
714
714
715 timeTuple = time.localtime(dataOut.utctime)
715 timeTuple = time.localtime(dataOut.utctime)
716 self.currentDay = timeTuple.tm_yday
716 self.currentDay = timeTuple.tm_yday
717 return 1
717 return 1
718
718
719 def putMetadata(self):
719 def putMetadata(self):
720
720
721 fp = self.createMetadataFile()
721 fp = self.createMetadataFile()
722 self.writeMetadata(fp)
722 self.writeMetadata(fp)
723 fp.close()
723 fp.close()
724 return
724 return
725
725
726 def createMetadataFile(self):
726 def createMetadataFile(self):
727 ext = self.ext
727 ext = self.ext
728 path = self.path
728 path = self.path
729 setFile = self.setFile
729 setFile = self.setFile
730
730
731 timeTuple = time.localtime(self.dataOut.utctime)
731 timeTuple = time.localtime(self.dataOut.utctime)
732
732
733 subfolder = ''
733 subfolder = ''
734 fullpath = os.path.join( path, subfolder )
734 fullpath = os.path.join( path, subfolder )
735
735
736 if not( os.path.exists(fullpath) ):
736 if not( os.path.exists(fullpath) ):
737 os.mkdir(fullpath)
737 os.mkdir(fullpath)
738 setFile = -1 #inicializo mi contador de seteo
738 setFile = -1 #inicializo mi contador de seteo
739
739
740 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
740 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
741 fullpath = os.path.join( path, subfolder )
741 fullpath = os.path.join( path, subfolder )
742
742
743 if not( os.path.exists(fullpath) ):
743 if not( os.path.exists(fullpath) ):
744 os.mkdir(fullpath)
744 os.mkdir(fullpath)
745 setFile = -1 #inicializo mi contador de seteo
745 setFile = -1 #inicializo mi contador de seteo
746
746
747 else:
747 else:
748 filesList = os.listdir( fullpath )
748 filesList = os.listdir( fullpath )
749 filesList = sorted( filesList, key=str.lower )
749 filesList = sorted( filesList, key=str.lower )
750 if len( filesList ) > 0:
750 if len( filesList ) > 0:
751 filesList = [k for k in filesList if 'M' in k]
751 filesList = [k for k in filesList if 'M' in k]
752 filen = filesList[-1]
752 filen = filesList[-1]
753 # el filename debera tener el siguiente formato
753 # el filename debera tener el siguiente formato
754 # 0 1234 567 89A BCDE (hex)
754 # 0 1234 567 89A BCDE (hex)
755 # x YYYY DDD SSS .ext
755 # x YYYY DDD SSS .ext
756 if isNumber( filen[8:11] ):
756 if isNumber( filen[8:11] ):
757 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
757 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
758 else:
758 else:
759 setFile = -1
759 setFile = -1
760 else:
760 else:
761 setFile = -1 #inicializo mi contador de seteo
761 setFile = -1 #inicializo mi contador de seteo
762
762
763 if self.setType is None:
763 if self.setType is None:
764 setFile += 1
764 setFile += 1
765 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
765 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
766 timeTuple.tm_year,
766 timeTuple.tm_year,
767 timeTuple.tm_yday,
767 timeTuple.tm_yday,
768 setFile,
768 setFile,
769 ext )
769 ext )
770 else:
770 else:
771 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
771 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
772 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
772 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
773 timeTuple.tm_year,
773 timeTuple.tm_year,
774 timeTuple.tm_yday,
774 timeTuple.tm_yday,
775 setFile,
775 setFile,
776 ext )
776 ext )
777
777
778 filename = os.path.join( path, subfolder, file )
778 filename = os.path.join( path, subfolder, file )
779 self.metaFile = file
779 self.metaFile = file
780 #Setting HDF5 File
780 #Setting HDF5 File
781 fp = h5py.File(filename,'w')
781 fp = h5py.File(filename,'w')
782
782
783 return fp
783 return fp
784
784
785 def writeMetadata(self, fp):
785 def writeMetadata(self, fp):
786
786
787 grp = fp.create_group("Metadata")
787 grp = fp.create_group("Metadata")
788 grp.create_dataset('array dimensions', data = self.tableDim, dtype = self.dtype)
788 grp.create_dataset('array dimensions', data = self.tableDim, dtype = self.dtype)
789
789
790 for i in range(len(self.metadataList)):
790 for i in range(len(self.metadataList)):
791 grp.create_dataset(self.metadataList[i], data=getattr(self.dataOut, self.metadataList[i]))
791 grp.create_dataset(self.metadataList[i], data=getattr(self.dataOut, self.metadataList[i]))
792 return
792 return
793
793
794 def timeFlag(self):
794 def timeFlag(self):
795 currentTime = self.dataOut.utctime
795 currentTime = self.dataOut.utctime
796
796
797 if self.lastTime is None:
797 if self.lastTime is None:
798 self.lastTime = currentTime
798 self.lastTime = currentTime
799
799
800 #Day
800 #Day
801 timeTuple = time.localtime(currentTime)
801 timeTuple = time.localtime(currentTime)
802 dataDay = timeTuple.tm_yday
802 dataDay = timeTuple.tm_yday
803
803
804 #Time
804 #Time
805 timeDiff = currentTime - self.lastTime
805 timeDiff = currentTime - self.lastTime
806
806
807 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
807 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
808 if dataDay != self.currentDay:
808 if dataDay != self.currentDay:
809 self.currentDay = dataDay
809 self.currentDay = dataDay
810 return True
810 return True
811 elif timeDiff > 3*60*60:
811 elif timeDiff > 3*60*60:
812 self.lastTime = currentTime
812 self.lastTime = currentTime
813 return True
813 return True
814 else:
814 else:
815 self.lastTime = currentTime
815 self.lastTime = currentTime
816 return False
816 return False
817
817
818 def setNextFile(self):
818 def setNextFile(self):
819
819
820 ext = self.ext
820 ext = self.ext
821 path = self.path
821 path = self.path
822 setFile = self.setFile
822 setFile = self.setFile
823 mode = self.mode
823 mode = self.mode
824
824
825 timeTuple = time.localtime(self.dataOut.utctime)
825 timeTuple = time.localtime(self.dataOut.utctime)
826 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
826 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
827
827
828 fullpath = os.path.join( path, subfolder )
828 fullpath = os.path.join( path, subfolder )
829
829
830 if os.path.exists(fullpath):
830 if os.path.exists(fullpath):
831 filesList = os.listdir( fullpath )
831 filesList = os.listdir( fullpath )
832 filesList = [k for k in filesList if 'D' in k]
832 filesList = [k for k in filesList if 'D' in k]
833 if len( filesList ) > 0:
833 if len( filesList ) > 0:
834 filesList = sorted( filesList, key=str.lower )
834 filesList = sorted( filesList, key=str.lower )
835 filen = filesList[-1]
835 filen = filesList[-1]
836 # el filename debera tener el siguiente formato
836 # el filename debera tener el siguiente formato
837 # 0 1234 567 89A BCDE (hex)
837 # 0 1234 567 89A BCDE (hex)
838 # x YYYY DDD SSS .ext
838 # x YYYY DDD SSS .ext
839 if isNumber( filen[8:11] ):
839 if isNumber( filen[8:11] ):
840 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
840 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
841 else:
841 else:
842 setFile = -1
842 setFile = -1
843 else:
843 else:
844 setFile = -1 #inicializo mi contador de seteo
844 setFile = -1 #inicializo mi contador de seteo
845 else:
845 else:
846 os.makedirs(fullpath)
846 os.makedirs(fullpath)
847 setFile = -1 #inicializo mi contador de seteo
847 setFile = -1 #inicializo mi contador de seteo
848
848
849 if self.setType is None:
849 if self.setType is None:
850 setFile += 1
850 setFile += 1
851 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
851 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
852 timeTuple.tm_year,
852 timeTuple.tm_year,
853 timeTuple.tm_yday,
853 timeTuple.tm_yday,
854 setFile,
854 setFile,
855 ext )
855 ext )
856 else:
856 else:
857 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
857 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
858 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
858 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
859 timeTuple.tm_year,
859 timeTuple.tm_year,
860 timeTuple.tm_yday,
860 timeTuple.tm_yday,
861 setFile,
861 setFile,
862 ext )
862 ext )
863
863
864 filename = os.path.join( path, subfolder, file )
864 filename = os.path.join( path, subfolder, file )
865
865
866 #Setting HDF5 File
866 #Setting HDF5 File
867 fp = h5py.File(filename,'w')
867 fp = h5py.File(filename,'w')
868 #write metadata
868 #write metadata
869 self.writeMetadata(fp)
869 self.writeMetadata(fp)
870 #Write data
870 #Write data
871 grp = fp.create_group("Data")
871 grp = fp.create_group("Data")
872 # grp.attrs['metadata'] = self.metaFile
872 # grp.attrs['metadata'] = self.metaFile
873
873
874 # grp.attrs['blocksPerFile'] = 0
874 # grp.attrs['blocksPerFile'] = 0
875 ds = []
875 ds = []
876 data = []
876 data = []
877 dsList = self.dsList
877 dsList = self.dsList
878 i = 0
878 i = 0
879 while i < len(dsList):
879 while i < len(dsList):
880 dsInfo = dsList[i]
880 dsInfo = dsList[i]
881 #One-dimension data
881 #One-dimension data
882 if dsInfo['mode'] == 0:
882 if dsInfo['mode'] == 0:
883 # ds0 = grp.create_dataset(self.dataList[i], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype='S20')
883 # ds0 = grp.create_dataset(self.dataList[i], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype='S20')
884 ds0 = grp.create_dataset(dsInfo['variable'], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype=numpy.float64)
884 ds0 = grp.create_dataset(dsInfo['variable'], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype=numpy.float64)
885 ds.append(ds0)
885 ds.append(ds0)
886 data.append([])
886 data.append([])
887 i += 1
887 i += 1
888 continue
888 continue
889 # nDimsForDs.append(nDims[i])
889 # nDimsForDs.append(nDims[i])
890
890
891 elif dsInfo['mode'] == 2:
891 elif dsInfo['mode'] == 2:
892 grp0 = grp.create_group(dsInfo['variable'])
892 grp0 = grp.create_group(dsInfo['variable'])
893 ds0 = grp0.create_dataset(dsInfo['dsName'], (1,dsInfo['shape']), data = numpy.zeros((1,dsInfo['shape'])) , maxshape=(None,dsInfo['shape']), chunks=True)
893 ds0 = grp0.create_dataset(dsInfo['dsName'], (1,dsInfo['shape']), data = numpy.zeros((1,dsInfo['shape'])) , maxshape=(None,dsInfo['shape']), chunks=True)
894 ds.append(ds0)
894 ds.append(ds0)
895 data.append([])
895 data.append([])
896 i += 1
896 i += 1
897 continue
897 continue
898
898
899 elif dsInfo['mode'] == 1:
899 elif dsInfo['mode'] == 1:
900 grp0 = grp.create_group(dsInfo['variable'])
900 grp0 = grp.create_group(dsInfo['variable'])
901
901
902 for j in range(dsInfo['dsNumber']):
902 for j in range(dsInfo['dsNumber']):
903 dsInfo = dsList[i]
903 dsInfo = dsList[i]
904 tableName = dsInfo['dsName']
904 tableName = dsInfo['dsName']
905 shape = int(dsInfo['shape'])
905 shape = int(dsInfo['shape'])
906
906
907 if dsInfo['nDim'] == 3:
907 if dsInfo['nDim'] == 3:
908 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)
908 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)
909 else:
909 else:
910 ds0 = grp0.create_dataset(tableName, (1,shape), data = numpy.zeros((1,shape)) , maxshape=(None,shape), chunks=True)
910 ds0 = grp0.create_dataset(tableName, (1,shape), data = numpy.zeros((1,shape)) , maxshape=(None,shape), chunks=True)
911
911
912 ds.append(ds0)
912 ds.append(ds0)
913 data.append([])
913 data.append([])
914 i += 1
914 i += 1
915 # nDimsForDs.append(nDims[i])
915 # nDimsForDs.append(nDims[i])
916
916
917 fp.flush()
917 fp.flush()
918 fp.close()
918 fp.close()
919
919
920 # self.nDatas = nDatas
920 # self.nDatas = nDatas
921 # self.nDims = nDims
921 # self.nDims = nDims
922 # self.nDimsForDs = nDimsForDs
922 # self.nDimsForDs = nDimsForDs
923 #Saving variables
923 #Saving variables
924 print 'Writing the file: %s'%filename
924 print 'Writing the file: %s'%filename
925 self.filename = filename
925 self.filename = filename
926 # self.fp = fp
926 # self.fp = fp
927 # self.grp = grp
927 # self.grp = grp
928 # self.grp.attrs.modify('nRecords', 1)
928 # self.grp.attrs.modify('nRecords', 1)
929 self.ds = ds
929 self.ds = ds
930 self.data = data
930 self.data = data
931 # self.setFile = setFile
931 # self.setFile = setFile
932 self.firsttime = True
932 self.firsttime = True
933 self.blockIndex = 0
933 self.blockIndex = 0
934 return
934 return
935
935
936 def putData(self):
936 def putData(self):
937
937
938 if self.blockIndex == self.blocksPerFile or self.timeFlag():
938 if self.blockIndex == self.blocksPerFile or self.timeFlag():
939 self.setNextFile()
939 self.setNextFile()
940
940
941 # if not self.firsttime:
941 # if not self.firsttime:
942 self.readBlock()
942 self.readBlock()
943 self.setBlock() #Prepare data to be written
943 self.setBlock() #Prepare data to be written
944 self.writeBlock() #Write data
944 self.writeBlock() #Write data
945
945
946 return
946 return
947
947
948 def readBlock(self):
948 def readBlock(self):
949
949
950 '''
950 '''
951 data Array configured
951 data Array configured
952
952
953
953
954 self.data
954 self.data
955 '''
955 '''
956 dsList = self.dsList
956 dsList = self.dsList
957 ds = self.ds
957 ds = self.ds
958 #Setting HDF5 File
958 #Setting HDF5 File
959 fp = h5py.File(self.filename,'r+')
959 fp = h5py.File(self.filename,'r+')
960 grp = fp["Data"]
960 grp = fp["Data"]
961 ind = 0
961 ind = 0
962
962
963 # grp.attrs['blocksPerFile'] = 0
963 # grp.attrs['blocksPerFile'] = 0
964 while ind < len(dsList):
964 while ind < len(dsList):
965 dsInfo = dsList[ind]
965 dsInfo = dsList[ind]
966
966
967 if dsInfo['mode'] == 0:
967 if dsInfo['mode'] == 0:
968 ds0 = grp[dsInfo['variable']]
968 ds0 = grp[dsInfo['variable']]
969 ds[ind] = ds0
969 ds[ind] = ds0
970 ind += 1
970 ind += 1
971 else:
971 else:
972
972
973 grp0 = grp[dsInfo['variable']]
973 grp0 = grp[dsInfo['variable']]
974
974
975 for j in range(dsInfo['dsNumber']):
975 for j in range(dsInfo['dsNumber']):
976 dsInfo = dsList[ind]
976 dsInfo = dsList[ind]
977 ds0 = grp0[dsInfo['dsName']]
977 ds0 = grp0[dsInfo['dsName']]
978 ds[ind] = ds0
978 ds[ind] = ds0
979 ind += 1
979 ind += 1
980
980
981 self.fp = fp
981 self.fp = fp
982 self.grp = grp
982 self.grp = grp
983 self.ds = ds
983 self.ds = ds
984
984
985 return
985 return
986
986
987 def setBlock(self):
987 def setBlock(self):
988 '''
988 '''
989 data Array configured
989 data Array configured
990
990
991
991
992 self.data
992 self.data
993 '''
993 '''
994 #Creating Arrays
994 #Creating Arrays
995 dsList = self.dsList
995 dsList = self.dsList
996 data = self.data
996 data = self.data
997 ind = 0
997 ind = 0
998
998
999 while ind < len(dsList):
999 while ind < len(dsList):
1000 dsInfo = dsList[ind]
1000 dsInfo = dsList[ind]
1001 dataAux = getattr(self.dataOut, dsInfo['variable'])
1001 dataAux = getattr(self.dataOut, dsInfo['variable'])
1002
1002
1003 mode = dsInfo['mode']
1003 mode = dsInfo['mode']
1004 nDim = dsInfo['nDim']
1004 nDim = dsInfo['nDim']
1005
1005
1006 if mode == 0 or mode == 2 or nDim == 1:
1006 if mode == 0 or mode == 2 or nDim == 1:
1007 data[ind] = dataAux
1007 data[ind] = dataAux
1008 ind += 1
1008 ind += 1
1009 # elif nDim == 1:
1009 # elif nDim == 1:
1010 # data[ind] = numpy.reshape(dataAux,(numpy.size(dataAux),1))
1010 # data[ind] = numpy.reshape(dataAux,(numpy.size(dataAux),1))
1011 # ind += 1
1011 # ind += 1
1012 elif nDim == 2:
1012 elif nDim == 2:
1013 for j in range(dsInfo['dsNumber']):
1013 for j in range(dsInfo['dsNumber']):
1014 data[ind] = dataAux[j,:]
1014 data[ind] = dataAux[j,:]
1015 ind += 1
1015 ind += 1
1016 elif nDim == 3:
1016 elif nDim == 3:
1017 for j in range(dsInfo['dsNumber']):
1017 for j in range(dsInfo['dsNumber']):
1018 data[ind] = dataAux[:,j,:]
1018 data[ind] = dataAux[:,j,:]
1019 ind += 1
1019 ind += 1
1020
1020
1021 self.data = data
1021 self.data = data
1022 return
1022 return
1023
1023
1024 def writeBlock(self):
1024 def writeBlock(self):
1025 '''
1025 '''
1026 Saves the block in the HDF5 file
1026 Saves the block in the HDF5 file
1027 '''
1027 '''
1028 dsList = self.dsList
1028 dsList = self.dsList
1029
1029
1030 for i in range(len(self.ds)):
1030 for i in range(len(self.ds)):
1031 dsInfo = dsList[i]
1031 dsInfo = dsList[i]
1032 nDim = dsInfo['nDim']
1032 nDim = dsInfo['nDim']
1033 mode = dsInfo['mode']
1033 mode = dsInfo['mode']
1034
1034
1035 # First time
1035 # First time
1036 if self.firsttime:
1036 if self.firsttime:
1037 # self.ds[i].resize(self.data[i].shape)
1037 # self.ds[i].resize(self.data[i].shape)
1038 # self.ds[i][self.blockIndex,:] = self.data[i]
1038 # self.ds[i][self.blockIndex,:] = self.data[i]
1039 if type(self.data[i]) == numpy.ndarray:
1039 if type(self.data[i]) == numpy.ndarray:
1040
1040
1041 if nDim == 3:
1041 if nDim == 3:
1042 self.data[i] = self.data[i].reshape((self.data[i].shape[0],self.data[i].shape[1],1))
1042 self.data[i] = self.data[i].reshape((self.data[i].shape[0],self.data[i].shape[1],1))
1043 self.ds[i].resize(self.data[i].shape)
1043 self.ds[i].resize(self.data[i].shape)
1044 if mode == 2:
1044 if mode == 2:
1045 self.ds[i].resize(self.data[i].shape)
1045 self.ds[i].resize(self.data[i].shape)
1046 self.ds[i][:] = self.data[i]
1046 self.ds[i][:] = self.data[i]
1047 else:
1047 else:
1048
1048
1049 # From second time
1049 # From second time
1050 # Meteors!
1050 # Meteors!
1051 if mode == 2:
1051 if mode == 2:
1052 dataShape = self.data[i].shape
1052 dataShape = self.data[i].shape
1053 dsShape = self.ds[i].shape
1053 dsShape = self.ds[i].shape
1054 self.ds[i].resize((self.ds[i].shape[0] + dataShape[0],self.ds[i].shape[1]))
1054 self.ds[i].resize((self.ds[i].shape[0] + dataShape[0],self.ds[i].shape[1]))
1055 self.ds[i][dsShape[0]:,:] = self.data[i]
1055 self.ds[i][dsShape[0]:,:] = self.data[i]
1056 # No dimension
1056 # No dimension
1057 elif mode == 0:
1057 elif mode == 0:
1058 self.ds[i].resize((self.ds[i].shape[0], self.ds[i].shape[1] + 1))
1058 self.ds[i].resize((self.ds[i].shape[0], self.ds[i].shape[1] + 1))
1059 self.ds[i][0,-1] = self.data[i]
1059 self.ds[i][0,-1] = self.data[i]
1060 # One dimension
1060 # One dimension
1061 elif nDim == 1:
1061 elif nDim == 1:
1062 self.ds[i].resize((self.ds[i].shape[0] + 1, self.ds[i].shape[1]))
1062 self.ds[i].resize((self.ds[i].shape[0] + 1, self.ds[i].shape[1]))
1063 self.ds[i][-1,:] = self.data[i]
1063 self.ds[i][-1,:] = self.data[i]
1064 # Two dimension
1064 # Two dimension
1065 elif nDim == 2:
1065 elif nDim == 2:
1066 self.ds[i].resize((self.ds[i].shape[0] + 1,self.ds[i].shape[1]))
1066 self.ds[i].resize((self.ds[i].shape[0] + 1,self.ds[i].shape[1]))
1067 self.ds[i][self.blockIndex,:] = self.data[i]
1067 self.ds[i][self.blockIndex,:] = self.data[i]
1068 # Three dimensions
1068 # Three dimensions
1069 elif nDim == 3:
1069 elif nDim == 3:
1070 self.ds[i].resize((self.ds[i].shape[0],self.ds[i].shape[1],self.ds[i].shape[2]+1))
1070 self.ds[i].resize((self.ds[i].shape[0],self.ds[i].shape[1],self.ds[i].shape[2]+1))
1071 self.ds[i][:,:,-1] = self.data[i]
1071 self.ds[i][:,:,-1] = self.data[i]
1072
1072
1073 self.firsttime = False
1073 self.firsttime = False
1074 self.blockIndex += 1
1074 self.blockIndex += 1
1075
1075
1076 #Close to save changes
1076 #Close to save changes
1077 self.fp.flush()
1077 self.fp.flush()
1078 self.fp.close()
1078 self.fp.close()
1079 return
1079 return
1080
1080
1081 def run(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, **kwargs):
1081 def run(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, **kwargs):
1082
1082
1083 if not(self.isConfig):
1083 if not(self.isConfig):
1084 flagdata = self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
1084 flagdata = self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
1085 metadataList=metadataList, dataList=dataList, mode=mode, **kwargs)
1085 metadataList=metadataList, dataList=dataList, mode=mode, **kwargs)
1086
1086
1087 if not(flagdata):
1087 if not(flagdata):
1088 return
1088 return
1089
1089
1090 self.isConfig = True
1090 self.isConfig = True
1091 # self.putMetadata()
1091 # self.putMetadata()
1092 self.setNextFile()
1092 self.setNextFile()
1093
1093
1094 self.putData()
1094 self.putData()
1095 return
1095 return
@@ -1,679 +1,698
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
251 blockOk_flag = False
260 blockOk_flag = False
252 fpointer = self.fp.tell()
261 fpointer = self.fp.tell()
253
262
254 spc = numpy.fromfile( self.fp, self.dtype[0], self.pts2read_SelfSpectra )
263 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
264 spc = spc.reshape( (self.nRdChannels, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
256
265
257 if self.processingHeaderObj.flag_cspc:
266 if self.processingHeaderObj.flag_cspc:
258 cspc = numpy.fromfile( self.fp, self.dtype, self.pts2read_CrossSpectra )
267 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
268 cspc = cspc.reshape( (self.nRdPairs, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
260
269
261 if self.processingHeaderObj.flag_dc:
270 if self.processingHeaderObj.flag_dc:
262 dc = numpy.fromfile( self.fp, self.dtype, self.pts2read_DCchannels ) #int(self.processingHeaderObj.nHeights*self.systemHeaderObj.nChannels) )
271 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
272 dc = dc.reshape( (self.systemHeaderObj.nChannels, self.processingHeaderObj.nHeights) ) #transforma a un arreglo 2D
264
273
265
274
266 if not(self.processingHeaderObj.shif_fft):
275 if not(self.processingHeaderObj.shif_fft):
267 #desplaza a la derecha en el eje 2 determinadas posiciones
276 #desplaza a la derecha en el eje 2 determinadas posiciones
268 shift = int(self.processingHeaderObj.profilesPerBlock/2)
277 shift = int(self.processingHeaderObj.profilesPerBlock/2)
269 spc = numpy.roll( spc, shift , axis=2 )
278 spc = numpy.roll( spc, shift , axis=2 )
270
279
271 if self.processingHeaderObj.flag_cspc:
280 if self.processingHeaderObj.flag_cspc:
272 #desplaza a la derecha en el eje 2 determinadas posiciones
281 #desplaza a la derecha en el eje 2 determinadas posiciones
273 cspc = numpy.roll( cspc, shift, axis=2 )
282 cspc = numpy.roll( cspc, shift, axis=2 )
274
283
275 #Dimensions : nChannels, nProfiles, nSamples
284 #Dimensions : nChannels, nProfiles, nSamples
276 spc = numpy.transpose( spc, (0,2,1) )
285 spc = numpy.transpose( spc, (0,2,1) )
277 self.data_spc = spc
286 self.data_spc = spc
287
288 if self.processingHeaderObj.flag_cspc:
278
289
279 if self.processingHeaderObj.flag_cspc:
280 cspc = numpy.transpose( cspc, (0,2,1) )
290 cspc = numpy.transpose( cspc, (0,2,1) )
281 self.data_cspc = cspc['real'] + cspc['imag']*1j
291 self.data_cspc = cspc['real'] + cspc['imag']*1j
282 else:
292 else:
283 self.data_cspc = None
293 self.data_cspc = None
294
284
295
285 if self.processingHeaderObj.flag_dc:
296 if self.processingHeaderObj.flag_dc:
286 self.data_dc = dc['real'] + dc['imag']*1j
297 self.data_dc = dc['real'] + dc['imag']*1j
287 else:
298 else:
288 self.data_dc = None
299 self.data_dc = None
289
300
290 self.flagIsNewFile = 0
301 self.flagIsNewFile = 0
291 self.flagIsNewBlock = 1
302 self.flagIsNewBlock = 1
292
303
293 self.nTotalBlocks += 1
304 self.nTotalBlocks += 1
294 self.nReadBlocks += 1
305 self.nReadBlocks += 1
295
306
296 return 1
307 return 1
297
308
298 def getFirstHeader(self):
309 def getFirstHeader(self):
299
310
300 self.getBasicHeader()
311 self.getBasicHeader()
301
312
302 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
313 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
303
314
304 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
315 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
305
316
306 # self.dataOut.ippSeconds = self.ippSeconds
317 # self.dataOut.ippSeconds = self.ippSeconds
307
318
308 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt * self.processingHeaderObj.nIncohInt * self.processingHeaderObj.profilesPerBlock
319 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt * self.processingHeaderObj.nIncohInt * self.processingHeaderObj.profilesPerBlock
309
320
310 self.dataOut.dtype = self.dtype
321 self.dataOut.dtype = self.dtype
311
322
312 # self.dataOut.nPairs = self.nPairs
323 # self.dataOut.nPairs = self.nPairs
313
324
314 self.dataOut.pairsList = self.rdPairList
325 self.dataOut.pairsList = self.rdPairList
315
326
316 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
327 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
317
328
318 self.dataOut.nFFTPoints = self.processingHeaderObj.profilesPerBlock
329 self.dataOut.nFFTPoints = self.processingHeaderObj.profilesPerBlock
319
330
320 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
331 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
321
332
322 self.dataOut.nIncohInt = self.processingHeaderObj.nIncohInt
333 self.dataOut.nIncohInt = self.processingHeaderObj.nIncohInt
323
334
324 xf = self.processingHeaderObj.firstHeight + self.processingHeaderObj.nHeights*self.processingHeaderObj.deltaHeight
335 xf = self.processingHeaderObj.firstHeight + self.processingHeaderObj.nHeights*self.processingHeaderObj.deltaHeight
325
336
326 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight)
337 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight)
327
338
328 self.dataOut.channelList = range(self.systemHeaderObj.nChannels)
339 self.dataOut.channelList = range(self.systemHeaderObj.nChannels)
329
340
330 self.dataOut.flagShiftFFT = True #Data is always shifted
341 self.dataOut.flagShiftFFT = True #Data is always shifted
331
342
332 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode #asumo q la data no esta decodificada
343 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode #asumo q la data no esta decodificada
333
344
334 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data esta sin flip
345 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data esta sin flip
335
346
336 def getData(self):
347 def getData(self):
337 """
348 """
338 First method to execute before "RUN" is called.
349 First method to execute before "RUN" is called.
339
350
340 Copia el buffer de lectura a la clase "Spectra",
351 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
352 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"
353 lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock"
343
354
344 Return:
355 Return:
345 0 : Si no hay mas archivos disponibles
356 0 : Si no hay mas archivos disponibles
346 1 : Si hizo una buena copia del buffer
357 1 : Si hizo una buena copia del buffer
347
358
348 Affected:
359 Affected:
349 self.dataOut
360 self.dataOut
350
361
351 self.flagDiscontinuousBlock
362 self.flagDiscontinuousBlock
352 self.flagIsNewBlock
363 self.flagIsNewBlock
353 """
364 """
354
365
355 if self.flagNoMoreFiles:
366 if self.flagNoMoreFiles:
356 self.dataOut.flagNoData = True
367 self.dataOut.flagNoData = True
357 print 'Process finished'
368 print 'Process finished'
358 return 0
369 return 0
359
370
360 self.flagDiscontinuousBlock = 0
371 self.flagDiscontinuousBlock = 0
361 self.flagIsNewBlock = 0
372 self.flagIsNewBlock = 0
362
373
363 if self.__hasNotDataInBuffer():
374 if self.__hasNotDataInBuffer():
364
375
365 if not( self.readNextBlock() ):
376 if not( self.readNextBlock() ):
366 self.dataOut.flagNoData = True
377 self.dataOut.flagNoData = True
367 return 0
378 return 0
379
368
380
369 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
381 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
370
382
371 if self.data_spc is None:
383 if self.data_spc is None:
372 self.dataOut.flagNoData = True
384 self.dataOut.flagNoData = True
373 return 0
385 return 0
374
386
375 self.getBasicHeader()
387 self.getBasicHeader()
376
388
377 self.getFirstHeader()
389 self.getFirstHeader()
378
390
379 self.dataOut.data_spc = self.data_spc
391 self.dataOut.data_spc = self.data_spc
380
392
381 self.dataOut.data_cspc = self.data_cspc
393 self.dataOut.data_cspc = self.data_cspc
382
394
383 self.dataOut.data_dc = self.data_dc
395 self.dataOut.data_dc = self.data_dc
384
396
385 self.dataOut.flagNoData = False
397 self.dataOut.flagNoData = False
386
398
387 self.dataOut.realtime = self.online
399 self.dataOut.realtime = self.online
388
400
389 return self.dataOut.data_spc
401 return self.dataOut.data_spc
390
402
391 class SpectraWriter(JRODataWriter, Operation):
403 class SpectraWriter(JRODataWriter, Operation):
392
404
393 """
405 """
394 Esta clase permite escribir datos de espectros a archivos procesados (.pdata). La escritura
406 Esta clase permite escribir datos de espectros a archivos procesados (.pdata). La escritura
395 de los datos siempre se realiza por bloques.
407 de los datos siempre se realiza por bloques.
396 """
408 """
397
409
398 ext = ".pdata"
410 ext = ".pdata"
399
411
400 optchar = "P"
412 optchar = "P"
401
413
402 shape_spc_Buffer = None
414 shape_spc_Buffer = None
403
415
404 shape_cspc_Buffer = None
416 shape_cspc_Buffer = None
405
417
406 shape_dc_Buffer = None
418 shape_dc_Buffer = None
407
419
408 data_spc = None
420 data_spc = None
409
421
410 data_cspc = None
422 data_cspc = None
411
423
412 data_dc = None
424 data_dc = None
413
425
414 # dataOut = None
426 # dataOut = None
415
427
416 def __init__(self, **kwargs):
428 def __init__(self):
417 """
429 """
418 Inicializador de la clase SpectraWriter para la escritura de datos de espectros.
430 Inicializador de la clase SpectraWriter para la escritura de datos de espectros.
431
432 Affected:
419
433
420 Affected:
421 self.dataOut
434 self.dataOut
422 self.basicHeaderObj
435 self.basicHeaderObj
423 self.systemHeaderObj
436 self.systemHeaderObj
424 self.radarControllerHeaderObj
437 self.radarControllerHeaderObj
425 self.processingHeaderObj
438 self.processingHeaderObj
426
439
427 Return: None
440 Return: None
428 """
441 """
429
442
430 Operation.__init__(self, **kwargs)
443 Operation.__init__(self)
431
444
432 self.isConfig = False
445 self.isConfig = False
433
446
434 self.nTotalBlocks = 0
447 self.nTotalBlocks = 0
435
448
436 self.data_spc = None
449 self.data_spc = None
437
450
438 self.data_cspc = None
451 self.data_cspc = None
452
439
453
440 self.data_dc = None
454 self.data_dc = None
441
455
442 self.fp = None
456 self.fp = None
443
457
444 self.flagIsNewFile = 1
458 self.flagIsNewFile = 1
445
459
446 self.nTotalBlocks = 0
460 self.nTotalBlocks = 0
447
461
448 self.flagIsNewBlock = 0
462 self.flagIsNewBlock = 0
449
463
450 self.setFile = None
464 self.setFile = None
451
465
452 self.dtype = None
466 self.dtype = None
453
467
454 self.path = None
468 self.path = None
455
469
456 self.noMoreFiles = 0
470 self.noMoreFiles = 0
457
471
458 self.filename = None
472 self.filename = None
459
473
460 self.basicHeaderObj = BasicHeader(LOCALTIME)
474 self.basicHeaderObj = BasicHeader(LOCALTIME)
461
475
462 self.systemHeaderObj = SystemHeader()
476 self.systemHeaderObj = SystemHeader()
463
477
464 self.radarControllerHeaderObj = RadarControllerHeader()
478 self.radarControllerHeaderObj = RadarControllerHeader()
465
479
466 self.processingHeaderObj = ProcessingHeader()
480 self.processingHeaderObj = ProcessingHeader()
467
481
468
482
469 def hasAllDataInBuffer(self):
483 def hasAllDataInBuffer(self):
470 return 1
484 return 1
471
485
486
472
487
473 def setBlockDimension(self):
488 def setBlockDimension(self):
474 """
489 """
475 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
490 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
476
491
477 Affected:
492 Affected:
478 self.shape_spc_Buffer
493 self.shape_spc_Buffer
479 self.shape_cspc_Buffer
494 self.shape_cspc_Buffer
480 self.shape_dc_Buffer
495 self.shape_dc_Buffer
481
496
482 Return: None
497 Return: None
483 """
498 """
484 self.shape_spc_Buffer = (self.dataOut.nChannels,
499 self.shape_spc_Buffer = (self.dataOut.nChannels,
485 self.processingHeaderObj.nHeights,
500 self.processingHeaderObj.nHeights,
486 self.processingHeaderObj.profilesPerBlock)
501 self.processingHeaderObj.profilesPerBlock)
487
502
488 self.shape_cspc_Buffer = (self.dataOut.nPairs,
503 self.shape_cspc_Buffer = (self.dataOut.nPairs,
489 self.processingHeaderObj.nHeights,
504 self.processingHeaderObj.nHeights,
490 self.processingHeaderObj.profilesPerBlock)
505 self.processingHeaderObj.profilesPerBlock)
491
506
492 self.shape_dc_Buffer = (self.dataOut.nChannels,
507 self.shape_dc_Buffer = (self.dataOut.nChannels,
493 self.processingHeaderObj.nHeights)
508 self.processingHeaderObj.nHeights)
494
509
495
510
496 def writeBlock(self):
511 def writeBlock(self):
497 """
512 """
498 Escribe el buffer en el file designado
513 Escribe el buffer en el file designado
514
499
515
500 Affected:
516 Affected:
501 self.data_spc
517 self.data_spc
502 self.data_cspc
518 self.data_cspc
503 self.data_dc
519 self.data_dc
504 self.flagIsNewFile
520 self.flagIsNewFile
505 self.flagIsNewBlock
521 self.flagIsNewBlock
506 self.nTotalBlocks
522 self.nTotalBlocks
507 self.nWriteBlocks
523 self.nWriteBlocks
508
524
509 Return: None
525 Return: None
510 """
526 """
511
527
512 spc = numpy.transpose( self.data_spc, (0,2,1) )
528 spc = numpy.transpose( self.data_spc, (0,2,1) )
513 if not( self.processingHeaderObj.shif_fft ):
529 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
530 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))
531 data = spc.reshape((-1))
516 data = data.astype(self.dtype[0])
532 data = data.astype(self.dtype[0])
517 data.tofile(self.fp)
533 data.tofile(self.fp)
518
534
519 if self.data_cspc is not None:
535 if self.data_cspc is not None:
520 data = numpy.zeros( self.shape_cspc_Buffer, self.dtype )
536 data = numpy.zeros( self.shape_cspc_Buffer, self.dtype )
521 cspc = numpy.transpose( self.data_cspc, (0,2,1) )
537 cspc = numpy.transpose( self.data_cspc, (0,2,1) )
522 if not( self.processingHeaderObj.shif_fft ):
538 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
539 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
540 data['real'] = cspc.real
525 data['imag'] = cspc.imag
541 data['imag'] = cspc.imag
526 data = data.reshape((-1))
542 data = data.reshape((-1))
527 data.tofile(self.fp)
543 data.tofile(self.fp)
544
528
545
529 if self.data_dc is not None:
546 if self.data_dc is not None:
530 data = numpy.zeros( self.shape_dc_Buffer, self.dtype )
547 data = numpy.zeros( self.shape_dc_Buffer, self.dtype )
531 dc = self.data_dc
548 dc = self.data_dc
532 data['real'] = dc.real
549 data['real'] = dc.real
533 data['imag'] = dc.imag
550 data['imag'] = dc.imag
534 data = data.reshape((-1))
551 data = data.reshape((-1))
535 data.tofile(self.fp)
552 data.tofile(self.fp)
536
553
537 # self.data_spc.fill(0)
554 # self.data_spc.fill(0)
538 #
555 #
539 # if self.data_dc is not None:
556 # if self.data_dc is not None:
540 # self.data_dc.fill(0)
557 # self.data_dc.fill(0)
541 #
558 #
542 # if self.data_cspc is not None:
559 # if self.data_cspc is not None:
543 # self.data_cspc.fill(0)
560 # self.data_cspc.fill(0)
561
544
562
545 self.flagIsNewFile = 0
563 self.flagIsNewFile = 0
546 self.flagIsNewBlock = 1
564 self.flagIsNewBlock = 1
547 self.nTotalBlocks += 1
565 self.nTotalBlocks += 1
548 self.nWriteBlocks += 1
566 self.nWriteBlocks += 1
549 self.blockIndex += 1
567 self.blockIndex += 1
550
568
551 # print "[Writing] Block = %d04" %self.blockIndex
569 # print "[Writing] Block = %d04" %self.blockIndex
552
570
553 def putData(self):
571 def putData(self):
554 """
572 """
555 Setea un bloque de datos y luego los escribe en un file
573 Setea un bloque de datos y luego los escribe en un file
574
556
575
557 Affected:
576 Affected:
558 self.data_spc
577 self.data_spc
559 self.data_cspc
578 self.data_cspc
560 self.data_dc
579 self.data_dc
561
580
562 Return:
581 Return:
563 0 : Si no hay data o no hay mas files que puedan escribirse
582 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
583 1 : Si se escribio la data de un bloque en un file
565 """
584 """
566
585
567 if self.dataOut.flagNoData:
586 if self.dataOut.flagNoData:
568 return 0
587 return 0
569
588
570 self.flagIsNewBlock = 0
589 self.flagIsNewBlock = 0
571
590
572 if self.dataOut.flagDiscontinuousBlock:
591 if self.dataOut.flagDiscontinuousBlock:
573 self.data_spc.fill(0)
592 self.data_spc.fill(0)
574 if self.dataOut.data_cspc is not None:
593 self.data_cspc.fill(0)
575 self.data_cspc.fill(0)
594 self.data_dc.fill(0)
576 if self.dataOut.data_dc is not None:
577 self.data_dc.fill(0)
578 self.setNextFile()
595 self.setNextFile()
579
596
580 if self.flagIsNewFile == 0:
597 if self.flagIsNewFile == 0:
581 self.setBasicHeader()
598 self.setBasicHeader()
582
599
583 self.data_spc = self.dataOut.data_spc.copy()
600 self.data_spc = self.dataOut.data_spc.copy()
584
601
585 if self.dataOut.data_cspc is not None:
602 if self.dataOut.data_cspc is not None:
586 self.data_cspc = self.dataOut.data_cspc.copy()
603 self.data_cspc = self.dataOut.data_cspc.copy()
587
604
588 if self.dataOut.data_dc is not None:
605 if self.dataOut.data_dc is not None:
589 self.data_dc = self.dataOut.data_dc.copy()
606 self.data_dc = self.dataOut.data_dc.copy()
590
607
591 # #self.processingHeaderObj.dataBlocksPerFile)
608 # #self.processingHeaderObj.dataBlocksPerFile)
592 if self.hasAllDataInBuffer():
609 if self.hasAllDataInBuffer():
593 # self.setFirstHeader()
610 # self.setFirstHeader()
594 self.writeNextBlock()
611 self.writeNextBlock()
595
612
596 return 1
613 return 1
614
597
615
598 def __getBlockSize(self):
616 def __getBlockSize(self):
599 '''
617 '''
600 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Spectra
618 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Spectra
601 '''
619 '''
602
620
603 dtype_width = self.getDtypeWidth()
621 dtype_width = self.getDtypeWidth()
604
622
605 pts2write = self.dataOut.nHeights * self.dataOut.nFFTPoints
623 pts2write = self.dataOut.nHeights * self.dataOut.nFFTPoints
606
624
607 pts2write_SelfSpectra = int(self.dataOut.nChannels * pts2write)
625 pts2write_SelfSpectra = int(self.dataOut.nChannels * pts2write)
608 blocksize = (pts2write_SelfSpectra*dtype_width)
626 blocksize = (pts2write_SelfSpectra*dtype_width)
609
627
610 if self.dataOut.data_cspc is not None:
628 if self.dataOut.data_cspc is not None:
611 pts2write_CrossSpectra = int(self.dataOut.nPairs * pts2write)
629 pts2write_CrossSpectra = int(self.dataOut.nPairs * pts2write)
612 blocksize += (pts2write_CrossSpectra*dtype_width*2)
630 blocksize += (pts2write_CrossSpectra*dtype_width*2)
613
631
614 if self.dataOut.data_dc is not None:
632 if self.dataOut.data_dc is not None:
615 pts2write_DCchannels = int(self.dataOut.nChannels * self.dataOut.nHeights)
633 pts2write_DCchannels = int(self.dataOut.nChannels * self.dataOut.nHeights)
616 blocksize += (pts2write_DCchannels*dtype_width*2)
634 blocksize += (pts2write_DCchannels*dtype_width*2)
617
635
618 # blocksize = blocksize #* datatypeValue * 2 #CORREGIR ESTO
636 # blocksize = blocksize #* datatypeValue * 2 #CORREGIR ESTO
619
637
620 return blocksize
638 return blocksize
621
639
622 def setFirstHeader(self):
640 def setFirstHeader(self):
623
641
624 """
642 """
625 Obtiene una copia del First Header
643 Obtiene una copia del First Header
626
644
627 Affected:
645 Affected:
628 self.systemHeaderObj
646 self.systemHeaderObj
629 self.radarControllerHeaderObj
647 self.radarControllerHeaderObj
630 self.dtype
648 self.dtype
631
649
632 Return:
650 Return:
633 None
651 None
634 """
652 """
635
653
636 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
654 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
637 self.systemHeaderObj.nChannels = self.dataOut.nChannels
655 self.systemHeaderObj.nChannels = self.dataOut.nChannels
638 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
656 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
639
657
640 self.processingHeaderObj.dtype = 1 # Spectra
658 self.processingHeaderObj.dtype = 1 # Spectra
641 self.processingHeaderObj.blockSize = self.__getBlockSize()
659 self.processingHeaderObj.blockSize = self.__getBlockSize()
642 self.processingHeaderObj.profilesPerBlock = self.dataOut.nFFTPoints
660 self.processingHeaderObj.profilesPerBlock = self.dataOut.nFFTPoints
643 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
661 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
644 self.processingHeaderObj.nWindows = 1 #podria ser 1 o self.dataOut.processingHeaderObj.nWindows
662 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
663 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt# Se requiere para determinar el valor de timeInterval
646 self.processingHeaderObj.nIncohInt = self.dataOut.nIncohInt
664 self.processingHeaderObj.nIncohInt = self.dataOut.nIncohInt
647 self.processingHeaderObj.totalSpectra = self.dataOut.nPairs + self.dataOut.nChannels
665 self.processingHeaderObj.totalSpectra = self.dataOut.nPairs + self.dataOut.nChannels
648 self.processingHeaderObj.shif_fft = self.dataOut.flagShiftFFT
666 self.processingHeaderObj.shif_fft = self.dataOut.flagShiftFFT
667
649
668
650 if self.processingHeaderObj.totalSpectra > 0:
669 if self.processingHeaderObj.totalSpectra > 0:
651 channelList = []
670 channelList = []
652 for channel in range(self.dataOut.nChannels):
671 for channel in range(self.dataOut.nChannels):
653 channelList.append(channel)
672 channelList.append(channel)
654 channelList.append(channel)
673 channelList.append(channel)
655
674
656 pairsList = []
675 pairsList = []
657 if self.dataOut.nPairs > 0:
676 if self.dataOut.nPairs > 0:
658 for pair in self.dataOut.pairsList:
677 for pair in self.dataOut.pairsList:
659 pairsList.append(pair[0])
678 pairsList.append(pair[0])
660 pairsList.append(pair[1])
679 pairsList.append(pair[1])
661
680
662 spectraComb = channelList + pairsList
681 spectraComb = channelList + pairsList
663 spectraComb = numpy.array(spectraComb, dtype="u1")
682 spectraComb = numpy.array(spectraComb, dtype="u1")
664 self.processingHeaderObj.spectraComb = spectraComb
683 self.processingHeaderObj.spectraComb = spectraComb
665
684
666 if self.dataOut.code is not None:
685 if self.dataOut.code is not None:
667 self.processingHeaderObj.code = self.dataOut.code
686 self.processingHeaderObj.code = self.dataOut.code
668 self.processingHeaderObj.nCode = self.dataOut.nCode
687 self.processingHeaderObj.nCode = self.dataOut.nCode
669 self.processingHeaderObj.nBaud = self.dataOut.nBaud
688 self.processingHeaderObj.nBaud = self.dataOut.nBaud
670
689
671 if self.processingHeaderObj.nWindows != 0:
690 if self.processingHeaderObj.nWindows != 0:
672 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
691 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
673 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
692 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
674 self.processingHeaderObj.nHeights = self.dataOut.nHeights
693 self.processingHeaderObj.nHeights = self.dataOut.nHeights
675 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
694 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
676
695
677 self.processingHeaderObj.processFlags = self.getProcessFlags()
696 self.processingHeaderObj.processFlags = self.getProcessFlags()
678
697
679 self.setBasicHeader()
698 self.setBasicHeader()
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: 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
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