##// 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
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,7 +1,7
1 1 '''
2 2 Created on Feb 7, 2012
3 3
4 4 @author $Author$
5 5 @version $Id$
6 6 '''
7 __version__ = "2.3"
7 __version__ = '2.3'
@@ -1,1220 +1,1229
1 1 '''
2 2
3 3 $Author: murco $
4 4 $Id: JROData.py 173 2012-11-20 15:06:21Z murco $
5 5 '''
6 6
7 7 import copy
8 8 import numpy
9 9 import datetime
10 10
11 11 from jroheaderIO import SystemHeader, RadarControllerHeader
12 12 from schainpy import cSchain
13 13
14 14
15 15 def getNumpyDtype(dataTypeCode):
16 16
17 17 if dataTypeCode == 0:
18 18 numpyDtype = numpy.dtype([('real','<i1'),('imag','<i1')])
19 19 elif dataTypeCode == 1:
20 20 numpyDtype = numpy.dtype([('real','<i2'),('imag','<i2')])
21 21 elif dataTypeCode == 2:
22 22 numpyDtype = numpy.dtype([('real','<i4'),('imag','<i4')])
23 23 elif dataTypeCode == 3:
24 24 numpyDtype = numpy.dtype([('real','<i8'),('imag','<i8')])
25 25 elif dataTypeCode == 4:
26 26 numpyDtype = numpy.dtype([('real','<f4'),('imag','<f4')])
27 27 elif dataTypeCode == 5:
28 28 numpyDtype = numpy.dtype([('real','<f8'),('imag','<f8')])
29 29 else:
30 30 raise ValueError, 'dataTypeCode was not defined'
31 31
32 32 return numpyDtype
33 33
34 34 def getDataTypeCode(numpyDtype):
35 35
36 36 if numpyDtype == numpy.dtype([('real','<i1'),('imag','<i1')]):
37 37 datatype = 0
38 38 elif numpyDtype == numpy.dtype([('real','<i2'),('imag','<i2')]):
39 39 datatype = 1
40 40 elif numpyDtype == numpy.dtype([('real','<i4'),('imag','<i4')]):
41 41 datatype = 2
42 42 elif numpyDtype == numpy.dtype([('real','<i8'),('imag','<i8')]):
43 43 datatype = 3
44 44 elif numpyDtype == numpy.dtype([('real','<f4'),('imag','<f4')]):
45 45 datatype = 4
46 46 elif numpyDtype == numpy.dtype([('real','<f8'),('imag','<f8')]):
47 47 datatype = 5
48 48 else:
49 49 datatype = None
50 50
51 51 return datatype
52 52
53 53 def hildebrand_sekhon(data, navg):
54 54 """
55 55 This method is for the objective determination of the noise level in Doppler spectra. This
56 56 implementation technique is based on the fact that the standard deviation of the spectral
57 57 densities is equal to the mean spectral density for white Gaussian noise
58 58
59 59 Inputs:
60 60 Data : heights
61 61 navg : numbers of averages
62 62
63 63 Return:
64 64 -1 : any error
65 65 anoise : noise's level
66 66 """
67 67
68 68 sortdata = numpy.sort(data, axis=None)
69 69 # lenOfData = len(sortdata)
70 70 # nums_min = lenOfData*0.2
71 71 #
72 72 # if nums_min <= 5:
73 73 # nums_min = 5
74 74 #
75 75 # sump = 0.
76 76 #
77 77 # sumq = 0.
78 78 #
79 79 # j = 0
80 80 #
81 81 # cont = 1
82 82 #
83 83 # while((cont==1)and(j<lenOfData)):
84 84 #
85 85 # sump += sortdata[j]
86 86 #
87 87 # sumq += sortdata[j]**2
88 88 #
89 89 # if j > nums_min:
90 90 # rtest = float(j)/(j-1) + 1.0/navg
91 91 # if ((sumq*j) > (rtest*sump**2)):
92 92 # j = j - 1
93 93 # sump = sump - sortdata[j]
94 94 # sumq = sumq - sortdata[j]**2
95 95 # cont = 0
96 96 #
97 97 # j += 1
98 98 #
99 99 # lnoise = sump /j
100 100 #
101 101 # return lnoise
102 102
103 103 return cSchain.hildebrand_sekhon(sortdata, navg)
104 104
105 105
106 106 class Beam:
107 107
108 108 def __init__(self):
109 109 self.codeList = []
110 110 self.azimuthList = []
111 111 self.zenithList = []
112 112
113 113 class GenericData(object):
114 114
115 115 flagNoData = True
116 116
117 117 def copy(self, inputObj=None):
118 118
119 119 if inputObj == None:
120 120 return copy.deepcopy(self)
121 121
122 122 for key in inputObj.__dict__.keys():
123 123
124 124 attribute = inputObj.__dict__[key]
125 125
126 126 #If this attribute is a tuple or list
127 127 if type(inputObj.__dict__[key]) in (tuple, list):
128 128 self.__dict__[key] = attribute[:]
129 129 continue
130 130
131 131 #If this attribute is another object or instance
132 132 if hasattr(attribute, '__dict__'):
133 133 self.__dict__[key] = attribute.copy()
134 134 continue
135 135
136 136 self.__dict__[key] = inputObj.__dict__[key]
137 137
138 138 def deepcopy(self):
139 139
140 140 return copy.deepcopy(self)
141 141
142 142 def isEmpty(self):
143 143
144 144 return self.flagNoData
145 145
146 146 class JROData(GenericData):
147 147
148 148 # m_BasicHeader = BasicHeader()
149 149 # m_ProcessingHeader = ProcessingHeader()
150 150
151 151 systemHeaderObj = SystemHeader()
152 152
153 153 radarControllerHeaderObj = RadarControllerHeader()
154 154
155 155 # data = None
156 156
157 157 type = None
158 158
159 159 datatype = None #dtype but in string
160 160
161 161 # dtype = None
162 162
163 163 # nChannels = None
164 164
165 165 # nHeights = None
166 166
167 167 nProfiles = None
168 168
169 169 heightList = None
170 170
171 171 channelList = None
172 172
173 173 flagDiscontinuousBlock = False
174 174
175 175 useLocalTime = False
176 176
177 177 utctime = None
178 178
179 179 timeZone = None
180 180
181 181 dstFlag = None
182 182
183 183 errorCount = None
184 184
185 185 blocksize = None
186 186
187 187 # nCode = None
188 188 #
189 189 # nBaud = None
190 190 #
191 191 # code = None
192 192
193 193 flagDecodeData = False #asumo q la data no esta decodificada
194 194
195 195 flagDeflipData = False #asumo q la data no esta sin flip
196 196
197 197 flagShiftFFT = False
198 198
199 199 # ippSeconds = None
200 200
201 201 # timeInterval = None
202 202
203 203 nCohInt = None
204 204
205 205 # noise = None
206 206
207 207 windowOfFilter = 1
208 208
209 209 #Speed of ligth
210 210 C = 3e8
211 211
212 212 frequency = 49.92e6
213 213
214 214 realtime = False
215 215
216 216 beacon_heiIndexList = None
217 217
218 218 last_block = None
219 219
220 220 blocknow = None
221 221
222 222 azimuth = None
223 223
224 224 zenith = None
225 225
226 226 beam = Beam()
227 227
228 228 profileIndex = None
229 229
230 230 def getNoise(self):
231 231
232 232 raise NotImplementedError
233 233
234 234 def getNChannels(self):
235 235
236 236 return len(self.channelList)
237 237
238 238 def getChannelIndexList(self):
239 239
240 240 return range(self.nChannels)
241 241
242 242 def getNHeights(self):
243 243
244 244 return len(self.heightList)
245 245
246 246 def getHeiRange(self, extrapoints=0):
247 247
248 248 heis = self.heightList
249 249 # deltah = self.heightList[1] - self.heightList[0]
250 250 #
251 251 # heis.append(self.heightList[-1])
252 252
253 253 return heis
254 254
255 255 def getDeltaH(self):
256 256
257 257 delta = self.heightList[1] - self.heightList[0]
258 258
259 259 return delta
260 260
261 261 def getltctime(self):
262 262
263 263 if self.useLocalTime:
264 264 return self.utctime - self.timeZone*60
265 265
266 266 return self.utctime
267 267
268 268 def getDatatime(self):
269 269
270 270 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
271 271 return datatimeValue
272 272
273 273 def getTimeRange(self):
274 274
275 275 datatime = []
276 276
277 277 datatime.append(self.ltctime)
278 278 datatime.append(self.ltctime + self.timeInterval+1)
279 279
280 280 datatime = numpy.array(datatime)
281 281
282 282 return datatime
283 283
284 284 def getFmaxTimeResponse(self):
285 285
286 286 period = (10**-6)*self.getDeltaH()/(0.15)
287 287
288 288 PRF = 1./(period * self.nCohInt)
289 289
290 290 fmax = PRF
291 291
292 292 return fmax
293 293
294 294 def getFmax(self):
295 295
296 296 PRF = 1./(self.ippSeconds * self.nCohInt)
297 297
298 298 fmax = PRF
299 299
300 300 return fmax
301 301
302 302 def getVmax(self):
303 303
304 304 _lambda = self.C/self.frequency
305 305
306 306 vmax = self.getFmax() * _lambda/2
307 307
308 308 return vmax
309 309
310 310 def get_ippSeconds(self):
311 311 '''
312 312 '''
313 313 return self.radarControllerHeaderObj.ippSeconds
314 314
315 315 def set_ippSeconds(self, ippSeconds):
316 316 '''
317 317 '''
318 318
319 319 self.radarControllerHeaderObj.ippSeconds = ippSeconds
320 320
321 321 return
322 322
323 323 def get_dtype(self):
324 324 '''
325 325 '''
326 326 return getNumpyDtype(self.datatype)
327 327
328 328 def set_dtype(self, numpyDtype):
329 329 '''
330 330 '''
331 331
332 332 self.datatype = getDataTypeCode(numpyDtype)
333 333
334 334 def get_code(self):
335 335 '''
336 336 '''
337 337 return self.radarControllerHeaderObj.code
338 338
339 339 def set_code(self, code):
340 340 '''
341 341 '''
342 342 self.radarControllerHeaderObj.code = code
343 343
344 344 return
345 345
346 346 def get_ncode(self):
347 347 '''
348 348 '''
349 349 return self.radarControllerHeaderObj.nCode
350 350
351 351 def set_ncode(self, nCode):
352 352 '''
353 353 '''
354 354 self.radarControllerHeaderObj.nCode = nCode
355 355
356 356 return
357 357
358 358 def get_nbaud(self):
359 359 '''
360 360 '''
361 361 return self.radarControllerHeaderObj.nBaud
362 362
363 363 def set_nbaud(self, nBaud):
364 364 '''
365 365 '''
366 366 self.radarControllerHeaderObj.nBaud = nBaud
367 367
368 368 return
369 369
370 370 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
371 371 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
372 372 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
373 373 #noise = property(getNoise, "I'm the 'nHeights' property.")
374 374 datatime = property(getDatatime, "I'm the 'datatime' property")
375 375 ltctime = property(getltctime, "I'm the 'ltctime' property")
376 376 ippSeconds = property(get_ippSeconds, set_ippSeconds)
377 377 dtype = property(get_dtype, set_dtype)
378 378 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
379 379 code = property(get_code, set_code)
380 380 nCode = property(get_ncode, set_ncode)
381 381 nBaud = property(get_nbaud, set_nbaud)
382 382
383 383 class Voltage(JROData):
384 384
385 385 #data es un numpy array de 2 dmensiones (canales, alturas)
386 386 data = None
387 387
388 388 def __init__(self):
389 389 '''
390 390 Constructor
391 391 '''
392 392
393 393 self.useLocalTime = True
394 394
395 395 self.radarControllerHeaderObj = RadarControllerHeader()
396 396
397 397 self.systemHeaderObj = SystemHeader()
398 398
399 399 self.type = "Voltage"
400 400
401 401 self.data = None
402 402
403 403 # self.dtype = None
404 404
405 405 # self.nChannels = 0
406 406
407 407 # self.nHeights = 0
408 408
409 409 self.nProfiles = None
410 410
411 411 self.heightList = None
412 412
413 413 self.channelList = None
414 414
415 415 # self.channelIndexList = None
416 416
417 417 self.flagNoData = True
418 418
419 419 self.flagDiscontinuousBlock = False
420 420
421 421 self.utctime = None
422 422
423 423 self.timeZone = None
424 424
425 425 self.dstFlag = None
426 426
427 427 self.errorCount = None
428 428
429 429 self.nCohInt = None
430 430
431 431 self.blocksize = None
432 432
433 433 self.flagDecodeData = False #asumo q la data no esta decodificada
434 434
435 435 self.flagDeflipData = False #asumo q la data no esta sin flip
436 436
437 437 self.flagShiftFFT = False
438 438
439 439 self.flagDataAsBlock = False #Asumo que la data es leida perfil a perfil
440 440
441 441 self.profileIndex = 0
442 442
443 443 def getNoisebyHildebrand(self, channel = None):
444 444 """
445 445 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
446 446
447 447 Return:
448 448 noiselevel
449 449 """
450 450
451 451 if channel != None:
452 452 data = self.data[channel]
453 453 nChannels = 1
454 454 else:
455 455 data = self.data
456 456 nChannels = self.nChannels
457 457
458 458 noise = numpy.zeros(nChannels)
459 459 power = data * numpy.conjugate(data)
460 460
461 461 for thisChannel in range(nChannels):
462 462 if nChannels == 1:
463 463 daux = power[:].real
464 464 else:
465 465 daux = power[thisChannel,:].real
466 466 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
467 467
468 468 return noise
469 469
470 470 def getNoise(self, type = 1, channel = None):
471 471
472 472 if type == 1:
473 473 noise = self.getNoisebyHildebrand(channel)
474 474
475 475 return noise
476 476
477 477 def getPower(self, channel = None):
478 478
479 479 if channel != None:
480 480 data = self.data[channel]
481 481 else:
482 482 data = self.data
483 483
484 484 power = data * numpy.conjugate(data)
485 485 powerdB = 10*numpy.log10(power.real)
486 486 powerdB = numpy.squeeze(powerdB)
487 487
488 488 return powerdB
489 489
490 490 def getTimeInterval(self):
491 491
492 492 timeInterval = self.ippSeconds * self.nCohInt
493 493
494 494 return timeInterval
495 495
496 496 noise = property(getNoise, "I'm the 'nHeights' property.")
497 497 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
498 498
499 499 class Spectra(JROData):
500 500
501 501 #data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
502 502 data_spc = None
503 503
504 504 #data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
505 505 data_cspc = None
506 506
507 507 #data dc es un numpy array de 2 dmensiones (canales, alturas)
508 508 data_dc = None
509 509
510 510 #data power
511 511 data_pwr = None
512 512
513 513 nFFTPoints = None
514 514
515 515 # nPairs = None
516 516
517 517 pairsList = None
518 518
519 519 nIncohInt = None
520 520
521 521 wavelength = None #Necesario para cacular el rango de velocidad desde la frecuencia
522 522
523 523 nCohInt = None #se requiere para determinar el valor de timeInterval
524 524
525 525 ippFactor = None
526 526
527 527 profileIndex = 0
528 528
529 529 plotting = "spectra"
530 530
531 531 def __init__(self):
532 532 '''
533 533 Constructor
534 534 '''
535 535
536 536 self.useLocalTime = True
537 537
538 538 self.radarControllerHeaderObj = RadarControllerHeader()
539 539
540 540 self.systemHeaderObj = SystemHeader()
541 541
542 542 self.type = "Spectra"
543 543
544 544 # self.data = None
545 545
546 546 # self.dtype = None
547 547
548 548 # self.nChannels = 0
549 549
550 550 # self.nHeights = 0
551 551
552 552 self.nProfiles = None
553 553
554 554 self.heightList = None
555 555
556 556 self.channelList = None
557 557
558 558 # self.channelIndexList = None
559 559
560 560 self.pairsList = None
561 561
562 562 self.flagNoData = True
563 563
564 564 self.flagDiscontinuousBlock = False
565 565
566 566 self.utctime = None
567 567
568 568 self.nCohInt = None
569 569
570 570 self.nIncohInt = None
571 571
572 572 self.blocksize = None
573 573
574 574 self.nFFTPoints = None
575 575
576 576 self.wavelength = None
577 577
578 578 self.flagDecodeData = False #asumo q la data no esta decodificada
579 579
580 580 self.flagDeflipData = False #asumo q la data no esta sin flip
581 581
582 582 self.flagShiftFFT = False
583 583
584 584 self.ippFactor = 1
585 585
586 586 #self.noise = None
587 587
588 588 self.beacon_heiIndexList = []
589 589
590 590 self.noise_estimation = None
591 591
592 592
593 593 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
594 594 """
595 595 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
596 596
597 597 Return:
598 598 noiselevel
599 599 """
600 600
601 601 noise = numpy.zeros(self.nChannels)
602 602
603 603 for channel in range(self.nChannels):
604 604 daux = self.data_spc[channel,xmin_index:xmax_index,ymin_index:ymax_index]
605 605 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
606 606
607 607 return noise
608 608
609 609 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
610 610
611 611 if self.noise_estimation is not None:
612 612 return self.noise_estimation #this was estimated by getNoise Operation defined in jroproc_spectra.py
613 613 else:
614 614 noise = self.getNoisebyHildebrand(xmin_index, xmax_index, ymin_index, ymax_index)
615 615 return noise
616 616
617 617 def getFreqRangeTimeResponse(self, extrapoints=0):
618 618
619 619 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints*self.ippFactor)
620 620 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
621 621
622 622 return freqrange
623 623
624 624 def getAcfRange(self, extrapoints=0):
625 625
626 626 deltafreq = 10./(self.getFmax() / (self.nFFTPoints*self.ippFactor))
627 627 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
628 628
629 629 return freqrange
630 630
631 631 def getFreqRange(self, extrapoints=0):
632 632
633 633 deltafreq = self.getFmax() / (self.nFFTPoints*self.ippFactor)
634 634 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
635 635
636 636 return freqrange
637 637
638 638 def getVelRange(self, extrapoints=0):
639 639
640 640 deltav = self.getVmax() / (self.nFFTPoints*self.ippFactor)
641 641 velrange = deltav*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) #- deltav/2
642 642
643 643 return velrange
644 644
645 645 def getNPairs(self):
646 646
647 647 return len(self.pairsList)
648 648
649 649 def getPairsIndexList(self):
650 650
651 651 return range(self.nPairs)
652 652
653 653 def getNormFactor(self):
654 654
655 655 pwcode = 1
656 656
657 657 if self.flagDecodeData:
658 658 pwcode = numpy.sum(self.code[0]**2)
659 659 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
660 660 normFactor = self.nProfiles*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
661 661
662 662 return normFactor
663 663
664 664 def getFlagCspc(self):
665 665
666 666 if self.data_cspc is None:
667 667 return True
668 668
669 669 return False
670 670
671 671 def getFlagDc(self):
672 672
673 673 if self.data_dc is None:
674 674 return True
675 675
676 676 return False
677 677
678 678 def getTimeInterval(self):
679 679
680 680 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles
681 681
682 682 return timeInterval
683 683
684 684 def getPower(self):
685 685
686 686 factor = self.normFactor
687 687 z = self.data_spc/factor
688 688 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
689 689 avg = numpy.average(z, axis=1)
690 690
691 691 return 10*numpy.log10(avg)
692 692
693 693 def getCoherence(self, pairsList=None, phase=False):
694 694
695 695 z = []
696 696 if pairsList is None:
697 697 pairsIndexList = self.pairsIndexList
698 698 else:
699 699 pairsIndexList = []
700 700 for pair in pairsList:
701 701 if pair not in self.pairsList:
702 702 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
703 703 pairsIndexList.append(self.pairsList.index(pair))
704 704 for i in range(len(pairsIndexList)):
705 705 pair = self.pairsList[pairsIndexList[i]]
706 706 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
707 707 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
708 708 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
709 709 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
710 710 if phase:
711 711 data = numpy.arctan2(avgcoherenceComplex.imag,
712 712 avgcoherenceComplex.real)*180/numpy.pi
713 713 else:
714 714 data = numpy.abs(avgcoherenceComplex)
715 715
716 716 z.append(data)
717 717
718 718 return numpy.array(z)
719 719
720 720 def setValue(self, value):
721 721
722 722 print "This property should not be initialized"
723 723
724 724 return
725 725
726 726 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
727 727 pairsIndexList = property(getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
728 728 normFactor = property(getNormFactor, setValue, "I'm the 'getNormFactor' property.")
729 729 flag_cspc = property(getFlagCspc, setValue)
730 730 flag_dc = property(getFlagDc, setValue)
731 731 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
732 732 timeInterval = property(getTimeInterval, setValue, "I'm the 'timeInterval' property")
733 733
734 734 class SpectraHeis(Spectra):
735 735
736 736 data_spc = None
737 737
738 738 data_cspc = None
739 739
740 740 data_dc = None
741 741
742 742 nFFTPoints = None
743 743
744 744 # nPairs = None
745 745
746 746 pairsList = None
747 747
748 748 nCohInt = None
749 749
750 750 nIncohInt = None
751 751
752 752 def __init__(self):
753 753
754 754 self.radarControllerHeaderObj = RadarControllerHeader()
755 755
756 756 self.systemHeaderObj = SystemHeader()
757 757
758 758 self.type = "SpectraHeis"
759 759
760 760 # self.dtype = None
761 761
762 762 # self.nChannels = 0
763 763
764 764 # self.nHeights = 0
765 765
766 766 self.nProfiles = None
767 767
768 768 self.heightList = None
769 769
770 770 self.channelList = None
771 771
772 772 # self.channelIndexList = None
773 773
774 774 self.flagNoData = True
775 775
776 776 self.flagDiscontinuousBlock = False
777 777
778 778 # self.nPairs = 0
779 779
780 780 self.utctime = None
781 781
782 782 self.blocksize = None
783 783
784 784 self.profileIndex = 0
785 785
786 786 self.nCohInt = 1
787 787
788 788 self.nIncohInt = 1
789 789
790 790 def getNormFactor(self):
791 791 pwcode = 1
792 792 if self.flagDecodeData:
793 793 pwcode = numpy.sum(self.code[0]**2)
794 794
795 795 normFactor = self.nIncohInt*self.nCohInt*pwcode
796 796
797 797 return normFactor
798 798
799 799 def getTimeInterval(self):
800 800
801 801 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
802 802
803 803 return timeInterval
804 804
805 805 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
806 806 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
807 807
808 808 class Fits(JROData):
809 809
810 810 heightList = None
811 811
812 812 channelList = None
813 813
814 814 flagNoData = True
815 815
816 816 flagDiscontinuousBlock = False
817 817
818 818 useLocalTime = False
819 819
820 820 utctime = None
821 821
822 822 timeZone = None
823 823
824 824 # ippSeconds = None
825 825
826 826 # timeInterval = None
827 827
828 828 nCohInt = None
829 829
830 830 nIncohInt = None
831 831
832 832 noise = None
833 833
834 834 windowOfFilter = 1
835 835
836 836 #Speed of ligth
837 837 C = 3e8
838 838
839 839 frequency = 49.92e6
840 840
841 841 realtime = False
842 842
843 843
844 844 def __init__(self):
845 845
846 846 self.type = "Fits"
847 847
848 848 self.nProfiles = None
849 849
850 850 self.heightList = None
851 851
852 852 self.channelList = None
853 853
854 854 # self.channelIndexList = None
855 855
856 856 self.flagNoData = True
857 857
858 858 self.utctime = None
859 859
860 860 self.nCohInt = 1
861 861
862 862 self.nIncohInt = 1
863 863
864 864 self.useLocalTime = True
865 865
866 866 self.profileIndex = 0
867 867
868 868 # self.utctime = None
869 869 # self.timeZone = None
870 870 # self.ltctime = None
871 871 # self.timeInterval = None
872 872 # self.header = None
873 873 # self.data_header = None
874 874 # self.data = None
875 875 # self.datatime = None
876 876 # self.flagNoData = False
877 877 # self.expName = ''
878 878 # self.nChannels = None
879 879 # self.nSamples = None
880 880 # self.dataBlocksPerFile = None
881 881 # self.comments = ''
882 882 #
883 883
884 884
885 885 def getltctime(self):
886 886
887 887 if self.useLocalTime:
888 888 return self.utctime - self.timeZone*60
889 889
890 890 return self.utctime
891 891
892 892 def getDatatime(self):
893 893
894 894 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
895 895 return datatime
896 896
897 897 def getTimeRange(self):
898 898
899 899 datatime = []
900 900
901 901 datatime.append(self.ltctime)
902 902 datatime.append(self.ltctime + self.timeInterval)
903 903
904 904 datatime = numpy.array(datatime)
905 905
906 906 return datatime
907 907
908 908 def getHeiRange(self):
909 909
910 910 heis = self.heightList
911 911
912 912 return heis
913 913
914 914 def getNHeights(self):
915 915
916 916 return len(self.heightList)
917 917
918 918 def getNChannels(self):
919 919
920 920 return len(self.channelList)
921 921
922 922 def getChannelIndexList(self):
923 923
924 924 return range(self.nChannels)
925 925
926 926 def getNoise(self, type = 1):
927 927
928 928 #noise = numpy.zeros(self.nChannels)
929 929
930 930 if type == 1:
931 931 noise = self.getNoisebyHildebrand()
932 932
933 933 if type == 2:
934 934 noise = self.getNoisebySort()
935 935
936 936 if type == 3:
937 937 noise = self.getNoisebyWindow()
938 938
939 939 return noise
940 940
941 941 def getTimeInterval(self):
942 942
943 943 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
944 944
945 945 return timeInterval
946 946
947 947 datatime = property(getDatatime, "I'm the 'datatime' property")
948 948 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
949 949 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
950 950 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
951 951 noise = property(getNoise, "I'm the 'nHeights' property.")
952 952
953 953 ltctime = property(getltctime, "I'm the 'ltctime' property")
954 954 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
955 955
956 956
957 957 class Correlation(JROData):
958 958
959 959 noise = None
960 960
961 961 SNR = None
962 962
963 963 #--------------------------------------------------
964 964
965 965 mode = None
966 966
967 967 split = False
968 968
969 969 data_cf = None
970 970
971 971 lags = None
972 972
973 973 lagRange = None
974 974
975 975 pairsList = None
976 976
977 977 normFactor = None
978 978
979 979 #--------------------------------------------------
980 980
981 981 # calculateVelocity = None
982 982
983 983 nLags = None
984 984
985 985 nPairs = None
986 986
987 987 nAvg = None
988 988
989 989
990 990 def __init__(self):
991 991 '''
992 992 Constructor
993 993 '''
994 994 self.radarControllerHeaderObj = RadarControllerHeader()
995 995
996 996 self.systemHeaderObj = SystemHeader()
997 997
998 998 self.type = "Correlation"
999 999
1000 1000 self.data = None
1001 1001
1002 1002 self.dtype = None
1003 1003
1004 1004 self.nProfiles = None
1005 1005
1006 1006 self.heightList = None
1007 1007
1008 1008 self.channelList = None
1009 1009
1010 1010 self.flagNoData = True
1011 1011
1012 1012 self.flagDiscontinuousBlock = False
1013 1013
1014 1014 self.utctime = None
1015 1015
1016 1016 self.timeZone = None
1017 1017
1018 1018 self.dstFlag = None
1019 1019
1020 1020 self.errorCount = None
1021 1021
1022 1022 self.blocksize = None
1023 1023
1024 1024 self.flagDecodeData = False #asumo q la data no esta decodificada
1025 1025
1026 1026 self.flagDeflipData = False #asumo q la data no esta sin flip
1027 1027
1028 1028 self.pairsList = None
1029 1029
1030 1030 self.nPoints = None
1031 1031
1032 1032 def getPairsList(self):
1033 1033
1034 1034 return self.pairsList
1035 1035
1036 1036 def getNoise(self, mode = 2):
1037 1037
1038 1038 indR = numpy.where(self.lagR == 0)[0][0]
1039 1039 indT = numpy.where(self.lagT == 0)[0][0]
1040 1040
1041 1041 jspectra0 = self.data_corr[:,:,indR,:]
1042 1042 jspectra = copy.copy(jspectra0)
1043 1043
1044 1044 num_chan = jspectra.shape[0]
1045 1045 num_hei = jspectra.shape[2]
1046 1046
1047 1047 freq_dc = jspectra.shape[1]/2
1048 1048 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
1049 1049
1050 1050 if ind_vel[0]<0:
1051 1051 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
1052 1052
1053 1053 if mode == 1:
1054 1054 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
1055 1055
1056 1056 if mode == 2:
1057 1057
1058 1058 vel = numpy.array([-2,-1,1,2])
1059 1059 xx = numpy.zeros([4,4])
1060 1060
1061 1061 for fil in range(4):
1062 1062 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
1063 1063
1064 1064 xx_inv = numpy.linalg.inv(xx)
1065 1065 xx_aux = xx_inv[0,:]
1066 1066
1067 1067 for ich in range(num_chan):
1068 1068 yy = jspectra[ich,ind_vel,:]
1069 1069 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
1070 1070
1071 1071 junkid = jspectra[ich,freq_dc,:]<=0
1072 1072 cjunkid = sum(junkid)
1073 1073
1074 1074 if cjunkid.any():
1075 1075 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
1076 1076
1077 1077 noise = jspectra0[:,freq_dc,:] - jspectra[:,freq_dc,:]
1078 1078
1079 1079 return noise
1080 1080
1081 1081 def getTimeInterval(self):
1082 1082
1083 1083 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
1084 1084
1085 1085 return timeInterval
1086 1086
1087 1087 def splitFunctions(self):
1088 1088
1089 1089 pairsList = self.pairsList
1090 1090 ccf_pairs = []
1091 1091 acf_pairs = []
1092 1092 ccf_ind = []
1093 1093 acf_ind = []
1094 1094 for l in range(len(pairsList)):
1095 1095 chan0 = pairsList[l][0]
1096 1096 chan1 = pairsList[l][1]
1097 1097
1098 1098 #Obteniendo pares de Autocorrelacion
1099 1099 if chan0 == chan1:
1100 1100 acf_pairs.append(chan0)
1101 1101 acf_ind.append(l)
1102 1102 else:
1103 1103 ccf_pairs.append(pairsList[l])
1104 1104 ccf_ind.append(l)
1105 1105
1106 1106 data_acf = self.data_cf[acf_ind]
1107 1107 data_ccf = self.data_cf[ccf_ind]
1108 1108
1109 1109 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1110 1110
1111 1111 def getNormFactor(self):
1112 1112 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1113 1113 acf_pairs = numpy.array(acf_pairs)
1114 1114 normFactor = numpy.zeros((self.nPairs,self.nHeights))
1115 1115
1116 1116 for p in range(self.nPairs):
1117 1117 pair = self.pairsList[p]
1118 1118
1119 1119 ch0 = pair[0]
1120 1120 ch1 = pair[1]
1121 1121
1122 1122 ch0_max = numpy.max(data_acf[acf_pairs==ch0,:,:], axis=1)
1123 1123 ch1_max = numpy.max(data_acf[acf_pairs==ch1,:,:], axis=1)
1124 1124 normFactor[p,:] = numpy.sqrt(ch0_max*ch1_max)
1125 1125
1126 1126 return normFactor
1127 1127
1128 1128 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1129 1129 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1130 1130
1131 1131 class Parameters(Spectra):
1132 1132
1133 1133 experimentInfo = None #Information about the experiment
1134 1134
1135 1135 #Information from previous data
1136 1136
1137 1137 inputUnit = None #Type of data to be processed
1138 1138
1139 1139 operation = None #Type of operation to parametrize
1140 1140
1141 1141 #normFactor = None #Normalization Factor
1142 1142
1143 1143 groupList = None #List of Pairs, Groups, etc
1144 1144
1145 1145 #Parameters
1146 1146
1147 1147 data_param = None #Parameters obtained
1148 1148
1149 1149 data_pre = None #Data Pre Parametrization
1150 1150
1151 1151 data_SNR = None #Signal to Noise Ratio
1152 1152
1153 1153 # heightRange = None #Heights
1154 1154
1155 1155 abscissaList = None #Abscissa, can be velocities, lags or time
1156 1156
1157 1157 # noise = None #Noise Potency
1158 1158
1159 1159 utctimeInit = None #Initial UTC time
1160 1160
1161 1161 paramInterval = None #Time interval to calculate Parameters in seconds
1162 1162
1163 1163 useLocalTime = True
1164 1164
1165 1165 #Fitting
1166 1166
1167 1167 data_error = None #Error of the estimation
1168 1168
1169 1169 constants = None
1170 1170
1171 1171 library = None
1172 1172
1173 1173 #Output signal
1174 1174
1175 1175 outputInterval = None #Time interval to calculate output signal in seconds
1176 1176
1177 1177 data_output = None #Out signal
1178 1178
1179 1179 nAvg = None
1180 1180
1181 1181 noise_estimation = None
1182
1183 GauSPC = None #Fit gaussian SPC
1182 1184
1183 1185
1184 1186 def __init__(self):
1185 1187 '''
1186 1188 Constructor
1187 1189 '''
1188 1190 self.radarControllerHeaderObj = RadarControllerHeader()
1189 1191
1190 1192 self.systemHeaderObj = SystemHeader()
1191 1193
1192 1194 self.type = "Parameters"
1193 1195
1194 1196 def getTimeRange1(self, interval):
1195 1197
1196 1198 datatime = []
1197 1199
1198 1200 if self.useLocalTime:
1199 1201 time1 = self.utctimeInit - self.timeZone*60
1200 1202 else:
1201 1203 time1 = self.utctimeInit
1202 1204
1203 1205 datatime.append(time1)
1204 1206 datatime.append(time1 + interval)
1205 1207 datatime = numpy.array(datatime)
1206 1208
1207 1209 return datatime
1208 1210
1209 1211 def getTimeInterval(self):
1210 1212
1211 1213 if hasattr(self, 'timeInterval1'):
1212 1214 return self.timeInterval1
1213 1215 else:
1214 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 1224 def getNoise(self):
1217 1225
1218 1226 return self.spc_noise
1219 1227
1220 1228 timeInterval = property(getTimeInterval)
1229 noise = property(getNoise, setValue, "I'm the 'Noise' property.")
@@ -1,187 +1,187
1 1 import os
2 2 import datetime
3 3 import numpy
4 4 import copy
5 5 from schainpy.model import *
6 6 from figure import Figure, isRealtime
7 7
8 8 class CorrelationPlot(Figure):
9 9 isConfig = None
10 10 __nsubplots = None
11
11
12 12 WIDTHPROF = None
13 13 HEIGHTPROF = None
14 14 PREFIX = 'corr'
15
16 def __init__(self, **kwargs):
17 Figure.__init__(self, **kwargs)
15
16 def __init__(self):
17
18 18 self.isConfig = False
19 19 self.__nsubplots = 1
20
20
21 21 self.WIDTH = 280
22 22 self.HEIGHT = 250
23 23 self.WIDTHPROF = 120
24 24 self.HEIGHTPROF = 0
25 25 self.counter_imagwr = 0
26
26
27 27 self.PLOT_CODE = 1
28 28 self.FTP_WEI = None
29 29 self.EXP_CODE = None
30 30 self.SUB_EXP_CODE = None
31 31 self.PLOT_POS = None
32
32
33 33 def getSubplots(self):
34
34
35 35 ncol = int(numpy.sqrt(self.nplots)+0.9)
36 36 nrow = int(self.nplots*1./ncol + 0.9)
37
37
38 38 return nrow, ncol
39
39
40 40 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
41
42 showprofile = False
41
42 showprofile = False
43 43 self.__showprofile = showprofile
44 44 self.nplots = nplots
45
45
46 46 ncolspan = 1
47 47 colspan = 1
48 48 if showprofile:
49 49 ncolspan = 3
50 50 colspan = 2
51 51 self.__nsubplots = 2
52
52
53 53 self.createFigure(id = id,
54 54 wintitle = wintitle,
55 55 widthplot = self.WIDTH + self.WIDTHPROF,
56 56 heightplot = self.HEIGHT + self.HEIGHTPROF,
57 57 show=show)
58
58
59 59 nrow, ncol = self.getSubplots()
60
60
61 61 counter = 0
62 62 for y in range(nrow):
63 63 for x in range(ncol):
64
64
65 65 if counter >= self.nplots:
66 66 break
67
67
68 68 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
69
69
70 70 if showprofile:
71 71 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
72
72
73 73 counter += 1
74
74
75 75 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
76 76 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
77 77 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
78 78 server=None, folder=None, username=None, password=None,
79 79 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
80
80
81 81 """
82
82
83 83 Input:
84 84 dataOut :
85 85 id :
86 86 wintitle :
87 87 channelList :
88 88 showProfile :
89 89 xmin : None,
90 90 xmax : None,
91 91 ymin : None,
92 92 ymax : None,
93 93 zmin : None,
94 94 zmax : None
95 95 """
96
96
97 97 if dataOut.flagNoData:
98 98 return None
99
99
100 100 if realtime:
101 101 if not(isRealtime(utcdatatime = dataOut.utctime)):
102 102 print 'Skipping this plot function'
103 103 return
104
104
105 105 if channelList == None:
106 106 channelIndexList = dataOut.channelIndexList
107 107 else:
108 108 channelIndexList = []
109 109 for channel in channelList:
110 110 if channel not in dataOut.channelList:
111 111 raise ValueError, "Channel %d is not in dataOut.channelList"
112 112 channelIndexList.append(dataOut.channelList.index(channel))
113
113
114 114 factor = dataOut.normFactor
115 115 lenfactor = factor.shape[1]
116 116 x = dataOut.getLagTRange(1)
117 117 y = dataOut.getHeiRange()
118
118
119 119 z = copy.copy(dataOut.data_corr[:,:,0,:])
120 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 122 zdB = numpy.abs(z)
123
123
124 124 avg = numpy.average(z, axis=1)
125 125 # avg = numpy.nanmean(z, axis=1)
126 126 # noise = dataOut.noise/factor
127
127
128 128 #thisDatetime = dataOut.datatime
129 129 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
130 title = wintitle + " Correlation"
130 title = wintitle + " Correlation"
131 131 xlabel = "Lag T (s)"
132 132 ylabel = "Range (Km)"
133
133
134 134 if not self.isConfig:
135
136 nplots = dataOut.data_corr.shape[0]
137
135
136 nplots = dataOut.data_corr.shape[0]
137
138 138 self.setup(id=id,
139 139 nplots=nplots,
140 140 wintitle=wintitle,
141 141 showprofile=showprofile,
142 142 show=show)
143
143
144 144 if xmin == None: xmin = numpy.nanmin(x)
145 145 if xmax == None: xmax = numpy.nanmax(x)
146 146 if ymin == None: ymin = numpy.nanmin(y)
147 147 if ymax == None: ymax = numpy.nanmax(y)
148 148 if zmin == None: zmin = 0
149 149 if zmax == None: zmax = 1
150
150
151 151 self.FTP_WEI = ftp_wei
152 152 self.EXP_CODE = exp_code
153 153 self.SUB_EXP_CODE = sub_exp_code
154 154 self.PLOT_POS = plot_pos
155
155
156 156 self.isConfig = True
157
157
158 158 self.setWinTitle(title)
159
159
160 160 for i in range(self.nplots):
161 161 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
162 162 title = "Channel %d and %d: : %s" %(dataOut.pairsList[i][0],dataOut.pairsList[i][1] , str_datetime)
163 163 axes = self.axesList[i*self.__nsubplots]
164 164 axes.pcolor(x, y, zdB[i,:,:],
165 165 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
166 166 xlabel=xlabel, ylabel=ylabel, title=title,
167 167 ticksize=9, cblabel='')
168
168
169 169 # if self.__showprofile:
170 170 # axes = self.axesList[i*self.__nsubplots +1]
171 171 # axes.pline(avgdB[i], y,
172 172 # xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
173 173 # xlabel='dB', ylabel='', title='',
174 174 # ytick_visible=False,
175 175 # grid='x')
176 #
176 #
177 177 # noiseline = numpy.repeat(noisedB[i], len(y))
178 178 # axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
179
179
180 180 self.draw()
181
181
182 182 self.save(figpath=figpath,
183 183 figfile=figfile,
184 184 save=save,
185 185 ftp=ftp,
186 186 wr_period=wr_period,
187 thisDatetime=thisDatetime)
187 thisDatetime=thisDatetime)
@@ -1,782 +1,819
1 1
2 2 import os
3 3 import time
4 4 import glob
5 5 import datetime
6 6 from multiprocessing import Process
7 7
8 8 import zmq
9 9 import numpy
10 10 import matplotlib
11 11 import matplotlib.pyplot as plt
12 12 from mpl_toolkits.axes_grid1 import make_axes_locatable
13 13 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
14 14
15 15 from schainpy.model.proc.jroproc_base import Operation
16 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 29 class PlotData(Operation, Process):
24 30 '''
25 31 Base class for Schain plotting operations
26 32 '''
27 33
28 34 CODE = 'Figure'
29 35 colormap = 'jro'
30 36 bgcolor = 'white'
31 37 CONFLATE = False
32 38 __MAXNUMX = 80
33 39 __missing = 1E30
34 40
35 41 def __init__(self, **kwargs):
36 42
37 43 Operation.__init__(self, plot=True, **kwargs)
38 44 Process.__init__(self)
39 45 self.kwargs['code'] = self.CODE
40 46 self.mp = False
41 47 self.data = None
42 48 self.isConfig = False
43 49 self.figures = []
44 50 self.axes = []
45 51 self.cb_axes = []
46 52 self.localtime = kwargs.pop('localtime', True)
47 53 self.show = kwargs.get('show', True)
48 54 self.save = kwargs.get('save', False)
49 55 self.colormap = kwargs.get('colormap', self.colormap)
50 56 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
51 57 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
52 58 self.colormaps = kwargs.get('colormaps', None)
53 59 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
54 60 self.showprofile = kwargs.get('showprofile', False)
55 61 self.title = kwargs.get('wintitle', self.CODE.upper())
56 62 self.cb_label = kwargs.get('cb_label', None)
57 63 self.cb_labels = kwargs.get('cb_labels', None)
58 64 self.xaxis = kwargs.get('xaxis', 'frequency')
59 65 self.zmin = kwargs.get('zmin', None)
60 66 self.zmax = kwargs.get('zmax', None)
61 67 self.zlimits = kwargs.get('zlimits', None)
62 self.xmin = kwargs.get('xmin', None)
63 if self.xmin is not None:
64 self.xmin += 5
68 self.xmin = kwargs.get('xmin', None)
65 69 self.xmax = kwargs.get('xmax', None)
66 70 self.xrange = kwargs.get('xrange', 24)
67 71 self.ymin = kwargs.get('ymin', None)
68 72 self.ymax = kwargs.get('ymax', None)
69 73 self.xlabel = kwargs.get('xlabel', None)
70 74 self.__MAXNUMY = kwargs.get('decimation', 100)
71 75 self.showSNR = kwargs.get('showSNR', False)
72 76 self.oneFigure = kwargs.get('oneFigure', True)
73 77 self.width = kwargs.get('width', None)
74 78 self.height = kwargs.get('height', None)
75 79 self.colorbar = kwargs.get('colorbar', True)
76 80 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
77 81 self.titles = ['' for __ in range(16)]
78 82
79 83 def __setup(self):
80 84 '''
81 85 Common setup for all figures, here figures and axes are created
82 86 '''
83 87
84 88 self.setup()
85 89
90 self.time_label = 'LT' if self.localtime else 'UTC'
91
86 92 if self.width is None:
87 93 self.width = 8
88 94
89 95 self.figures = []
90 96 self.axes = []
91 97 self.cb_axes = []
92 98 self.pf_axes = []
93 99 self.cmaps = []
94 100
95 101 size = '15%' if self.ncols==1 else '30%'
96 102 pad = '4%' if self.ncols==1 else '8%'
97 103
98 104 if self.oneFigure:
99 105 if self.height is None:
100 106 self.height = 1.4*self.nrows + 1
101 107 fig = plt.figure(figsize=(self.width, self.height),
102 108 edgecolor='k',
103 109 facecolor='w')
104 110 self.figures.append(fig)
105 111 for n in range(self.nplots):
106 112 ax = fig.add_subplot(self.nrows, self.ncols, n+1)
107 113 ax.tick_params(labelsize=8)
108 114 ax.firsttime = True
115 ax.index = 0
109 116 self.axes.append(ax)
110 117 if self.showprofile:
111 118 cax = self.__add_axes(ax, size=size, pad=pad)
112 119 cax.tick_params(labelsize=8)
113 120 self.pf_axes.append(cax)
114 121 else:
115 122 if self.height is None:
116 123 self.height = 3
117 124 for n in range(self.nplots):
118 125 fig = plt.figure(figsize=(self.width, self.height),
119 126 edgecolor='k',
120 127 facecolor='w')
121 128 ax = fig.add_subplot(1, 1, 1)
122 129 ax.tick_params(labelsize=8)
123 130 ax.firsttime = True
131 ax.index = 0
124 132 self.figures.append(fig)
125 133 self.axes.append(ax)
126 134 if self.showprofile:
127 135 cax = self.__add_axes(ax, size=size, pad=pad)
128 136 cax.tick_params(labelsize=8)
129 137 self.pf_axes.append(cax)
130 138
131 139 for n in range(self.nrows):
132 140 if self.colormaps is not None:
133 141 cmap = plt.get_cmap(self.colormaps[n])
134 142 else:
135 143 cmap = plt.get_cmap(self.colormap)
136 144 cmap.set_bad(self.bgcolor, 1.)
137 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 170 def __add_axes(self, ax, size='30%', pad='8%'):
140 171 '''
141 172 Add new axes to the given figure
142 173 '''
143 174 divider = make_axes_locatable(ax)
144 175 nax = divider.new_horizontal(size=size, pad=pad)
145 176 ax.figure.add_axes(nax)
146 177 return nax
147 178
179 self.setup()
148 180
149 181 def setup(self):
150 182 '''
151 183 This method should be implemented in the child class, the following
152 184 attributes should be set:
153 185
154 186 self.nrows: number of rows
155 187 self.ncols: number of cols
156 188 self.nplots: number of plots (channels or pairs)
157 189 self.ylabel: label for Y axes
158 190 self.titles: list of axes title
159 191
160 192 '''
161 193 raise(NotImplementedError, 'Implement this method in child class')
162 194
163 195 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
164 196 '''
165 197 Create a masked array for missing data
166 198 '''
167 199 if x_buffer.shape[0] < 2:
168 200 return x_buffer, y_buffer, z_buffer
169 201
170 202 deltas = x_buffer[1:] - x_buffer[0:-1]
171 203 x_median = numpy.median(deltas)
172 204
173 205 index = numpy.where(deltas > 5*x_median)
174 206
175 207 if len(index[0]) != 0:
176 208 z_buffer[::, index[0], ::] = self.__missing
177 209 z_buffer = numpy.ma.masked_inside(z_buffer,
178 210 0.99*self.__missing,
179 211 1.01*self.__missing)
180 212
181 213 return x_buffer, y_buffer, z_buffer
182 214
183 215 def decimate(self):
184 216
185 217 # dx = int(len(self.x)/self.__MAXNUMX) + 1
186 218 dy = int(len(self.y)/self.__MAXNUMY) + 1
187 219
188 220 # x = self.x[::dx]
189 221 x = self.x
190 222 y = self.y[::dy]
191 223 z = self.z[::, ::, ::dy]
192 224
193 225 return x, y, z
194 226
195 227 def format(self):
196 228 '''
197 229 Set min and max values, labels, ticks and titles
198 230 '''
199 231
200 232 if self.xmin is None:
201 233 xmin = self.min_time
202 234 else:
203 235 if self.xaxis is 'time':
204 236 dt = datetime.datetime.fromtimestamp(self.min_time)
205 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 239 else:
208 240 xmin = self.xmin
209 241
210 242 if self.xmax is None:
211 243 xmax = xmin+self.xrange*60*60
212 244 else:
213 245 if self.xaxis is 'time':
214 246 dt = datetime.datetime.fromtimestamp(self.min_time)
215 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 249 else:
218 250 xmax = self.xmax
219 251
220 252 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
221 253 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
222 254
223 255 ystep = 200 if ymax>= 800 else 100 if ymax>=400 else 50 if ymax>=200 else 20
224 256
225 257 for n, ax in enumerate(self.axes):
226 258 if ax.firsttime:
227 259 ax.set_facecolor(self.bgcolor)
228 260 ax.yaxis.set_major_locator(MultipleLocator(ystep))
229 261 if self.xaxis is 'time':
230 262 ax.xaxis.set_major_formatter(FuncFormatter(func))
231 263 ax.xaxis.set_major_locator(LinearLocator(9))
232 264 if self.xlabel is not None:
233 265 ax.set_xlabel(self.xlabel)
234 266 ax.set_ylabel(self.ylabel)
235 267 ax.firsttime = False
236 268 if self.showprofile:
237 269 self.pf_axes[n].set_ylim(ymin, ymax)
238 270 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
239 271 self.pf_axes[n].set_xlabel('dB')
240 272 self.pf_axes[n].grid(b=True, axis='x')
241 273 [tick.set_visible(False) for tick in self.pf_axes[n].get_yticklabels()]
242 274 if self.colorbar:
243 cb = plt.colorbar(ax.plt, ax=ax, pad=0.02)
244 cb.ax.tick_params(labelsize=8)
275 ax.cbar = plt.colorbar(ax.plt, ax=ax, pad=0.02, aspect=10)
276 ax.cbar.ax.tick_params(labelsize=8)
245 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 279 elif self.cb_labels:
248 cb.set_label(self.cb_labels[n], size=8)
249
250 ax.set_title('{} - {} UTC'.format(
280 ax.cbar.set_label(self.cb_labels[n], size=8)
281
282 ax.set_title('{} - {} {}'.format(
251 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 286 size=8)
254 287 ax.set_xlim(xmin, xmax)
255 288 ax.set_ylim(ymin, ymax)
256
257 289
258 290 def __plot(self):
259 291 '''
260 292 '''
261 293 log.success('Plotting', self.name)
262 294
263 295 self.plot()
264 296 self.format()
265 297
266 298 for n, fig in enumerate(self.figures):
267 299 if self.nrows == 0 or self.nplots == 0:
268 300 log.warning('No data', self.name)
269 301 continue
270 302 if self.show:
271 303 fig.show()
272 304
273 305 fig.tight_layout()
274 306 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
275 307 datetime.datetime.fromtimestamp(self.max_time).strftime('%Y/%m/%d')))
276 308 # fig.canvas.draw()
277 309
278 310 if self.save and self.data.ended:
279 311 channels = range(self.nrows)
280 312 if self.oneFigure:
281 313 label = ''
282 314 else:
283 315 label = '_{}'.format(channels[n])
284 316 figname = os.path.join(
285 317 self.save,
286 318 '{}{}_{}.png'.format(
287 319 self.CODE,
288 320 label,
289 321 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')
290 322 )
291 323 )
292 324 print 'Saving figure: {}'.format(figname)
293 325 fig.savefig(figname)
294 326
295 327 def plot(self):
296 328 '''
297 329 '''
298 330 raise(NotImplementedError, 'Implement this method in child class')
299 331
300 332 def run(self):
301 333
302 334 log.success('Starting', self.name)
303 335
304 336 context = zmq.Context()
305 337 receiver = context.socket(zmq.SUB)
306 338 receiver.setsockopt(zmq.SUBSCRIBE, '')
307 339 receiver.setsockopt(zmq.CONFLATE, self.CONFLATE)
308 340
309 341 if 'server' in self.kwargs['parent']:
310 342 receiver.connect('ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
311 343 else:
312 344 receiver.connect("ipc:///tmp/zmq.plots")
313 345
314 346 while True:
315 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]
319 self.max_time = self.data.times[-1]
350 if self.localtime:
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 358 if self.isConfig is False:
322 359 self.__setup()
323 360 self.isConfig = True
324 361
325 362 self.__plot()
326 363
327 364 except zmq.Again as e:
328 365 log.log('Waiting for data...')
329 366 if self.data:
330 367 plt.pause(self.data.throttle)
331 368 else:
332 369 time.sleep(2)
333 370
334 371 def close(self):
335 372 if self.data:
336 373 self.__plot()
337 374
338
339 375 class PlotSpectraData(PlotData):
340 376 '''
341 377 Plot for Spectra data
342 378 '''
343 379
344 380 CODE = 'spc'
345 381 colormap = 'jro'
346 382
347 383 def setup(self):
348 384 self.nplots = len(self.data.channels)
349 385 self.ncols = int(numpy.sqrt(self.nplots)+ 0.9)
350 386 self.nrows = int((1.0*self.nplots/self.ncols) + 0.9)
351 387 self.width = 3.4*self.ncols
352 388 self.height = 3*self.nrows
353 389 self.cb_label = 'dB'
354 390 if self.showprofile:
355 391 self.width += 0.8*self.ncols
356 392
357 393 self.ylabel = 'Range [Km]'
358 394
359 395 def plot(self):
360 396 if self.xaxis == "frequency":
361 397 x = self.data.xrange[0]
362 398 self.xlabel = "Frequency (kHz)"
363 399 elif self.xaxis == "time":
364 400 x = self.data.xrange[1]
365 401 self.xlabel = "Time (ms)"
366 402 else:
367 403 x = self.data.xrange[2]
368 404 self.xlabel = "Velocity (m/s)"
369 405
370 406 if self.CODE == 'spc_mean':
371 407 x = self.data.xrange[2]
372 408 self.xlabel = "Velocity (m/s)"
373 409
374 410 self.titles = []
375 411
376 412 y = self.data.heights
377 413 self.y = y
378 414 z = self.data['spc']
379 415
380 416 for n, ax in enumerate(self.axes):
381 417 noise = self.data['noise'][n][-1]
382 418 if self.CODE == 'spc_mean':
383 419 mean = self.data['mean'][n][-1]
384 420 if ax.firsttime:
385 421 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
386 422 self.xmin = self.xmin if self.xmin else -self.xmax
387 423 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
388 424 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
389 425 ax.plt = ax.pcolormesh(x, y, z[n].T,
390 426 vmin=self.zmin,
391 427 vmax=self.zmax,
392 428 cmap=plt.get_cmap(self.colormap)
393 429 )
394 430
395 431 if self.showprofile:
396 432 ax.plt_profile= self.pf_axes[n].plot(self.data['rti'][n][-1], y)[0]
397 433 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
398 434 color="k", linestyle="dashed", lw=1)[0]
399 435 if self.CODE == 'spc_mean':
400 436 ax.plt_mean = ax.plot(mean, y, color='k')[0]
401 437 else:
402 438 ax.plt.set_array(z[n].T.ravel())
403 439 if self.showprofile:
404 440 ax.plt_profile.set_data(self.data['rti'][n][-1], y)
405 441 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
406 442 if self.CODE == 'spc_mean':
407 443 ax.plt_mean.set_data(mean, y)
408 444
409 445 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
410 446 self.saveTime = self.max_time
411 447
412 448
413 449 class PlotCrossSpectraData(PlotData):
414 450
415 451 CODE = 'cspc'
416 452 zmin_coh = None
417 453 zmax_coh = None
418 454 zmin_phase = None
419 455 zmax_phase = None
420 456
421 457 def setup(self):
422 458
423 459 self.ncols = 4
424 460 self.nrows = len(self.data.pairs)
425 461 self.nplots = self.nrows*4
426 462 self.width = 3.4*self.ncols
427 463 self.height = 3*self.nrows
428 464 self.ylabel = 'Range [Km]'
429 465 self.showprofile = False
430 466
431 467 def plot(self):
432 468
433 469 if self.xaxis == "frequency":
434 470 x = self.data.xrange[0]
435 471 self.xlabel = "Frequency (kHz)"
436 472 elif self.xaxis == "time":
437 473 x = self.data.xrange[1]
438 474 self.xlabel = "Time (ms)"
439 475 else:
440 476 x = self.data.xrange[2]
441 477 self.xlabel = "Velocity (m/s)"
442 478
443 479 self.titles = []
444 480
445 481 y = self.data.heights
446 482 self.y = y
447 483 spc = self.data['spc']
448 484 cspc = self.data['cspc']
449 485
450 486 for n in range(self.nrows):
451 487 noise = self.data['noise'][n][-1]
452 488 pair = self.data.pairs[n]
453 489 ax = self.axes[4*n]
454 490 ax3 = self.axes[4*n+3]
455 491 if ax.firsttime:
456 492 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
457 493 self.xmin = self.xmin if self.xmin else -self.xmax
458 494 self.zmin = self.zmin if self.zmin else numpy.nanmin(spc)
459 495 self.zmax = self.zmax if self.zmax else numpy.nanmax(spc)
460 496 ax.plt = ax.pcolormesh(x, y, spc[pair[0]].T,
461 497 vmin=self.zmin,
462 498 vmax=self.zmax,
463 499 cmap=plt.get_cmap(self.colormap)
464 500 )
465 501 else:
466 502 ax.plt.set_array(spc[pair[0]].T.ravel())
467 503 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
468 504
469 505 ax = self.axes[4*n+1]
470 506 if ax.firsttime:
471 507 ax.plt = ax.pcolormesh(x, y, spc[pair[1]].T,
472 508 vmin=self.zmin,
473 509 vmax=self.zmax,
474 510 cmap=plt.get_cmap(self.colormap)
475 511 )
476 512 else:
477 513 ax.plt.set_array(spc[pair[1]].T.ravel())
478 514 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
479 515
480 516 out = cspc[n]/numpy.sqrt(spc[pair[0]]*spc[pair[1]])
481 517 coh = numpy.abs(out)
482 518 phase = numpy.arctan2(out.imag, out.real)*180/numpy.pi
483 519
484 520 ax = self.axes[4*n+2]
485 521 if ax.firsttime:
486 522 ax.plt = ax.pcolormesh(x, y, coh.T,
487 523 vmin=0,
488 524 vmax=1,
489 525 cmap=plt.get_cmap(self.colormap_coh)
490 526 )
491 527 else:
492 528 ax.plt.set_array(coh.T.ravel())
493 529 self.titles.append('Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
494 530
495 531 ax = self.axes[4*n+3]
496 532 if ax.firsttime:
497 533 ax.plt = ax.pcolormesh(x, y, phase.T,
498 534 vmin=-180,
499 535 vmax=180,
500 536 cmap=plt.get_cmap(self.colormap_phase)
501 537 )
502 538 else:
503 539 ax.plt.set_array(phase.T.ravel())
504 540 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
505 541
506 542 self.saveTime = self.max_time
507 543
508 544
509 545 class PlotSpectraMeanData(PlotSpectraData):
510 546 '''
511 547 Plot for Spectra and Mean
512 548 '''
513 549 CODE = 'spc_mean'
514 550 colormap = 'jro'
515 551
516 552
517 553 class PlotRTIData(PlotData):
518 554 '''
519 555 Plot for RTI data
520 556 '''
521 557
522 558 CODE = 'rti'
523 559 colormap = 'jro'
524 560
525 561 def setup(self):
526 562 self.xaxis = 'time'
527 563 self.ncols = 1
528 564 self.nrows = len(self.data.channels)
529 565 self.nplots = len(self.data.channels)
530 566 self.ylabel = 'Range [Km]'
531 567 self.cb_label = 'dB'
532 568 self.titles = ['{} Channel {}'.format(self.CODE.upper(), x) for x in range(self.nrows)]
533 569
534 570 def plot(self):
535 self.x = self.data.times
571 self.x = self.times
536 572 self.y = self.data.heights
537 573 self.z = self.data[self.CODE]
538 574 self.z = numpy.ma.masked_invalid(self.z)
539 575
540 576 for n, ax in enumerate(self.axes):
541 577 x, y, z = self.fill_gaps(*self.decimate())
542 578 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
543 579 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
544 580 if ax.firsttime:
545 581 ax.plt = ax.pcolormesh(x, y, z[n].T,
546 582 vmin=self.zmin,
547 583 vmax=self.zmax,
548 584 cmap=plt.get_cmap(self.colormap)
549 585 )
550 586 if self.showprofile:
551 587 ax.plot_profile= self.pf_axes[n].plot(self.data['rti'][n][-1], self.y)[0]
552 588 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y,
553 589 color="k", linestyle="dashed", lw=1)[0]
554 590 else:
555 591 ax.collections.remove(ax.collections[0])
556 592 ax.plt = ax.pcolormesh(x, y, z[n].T,
557 593 vmin=self.zmin,
558 594 vmax=self.zmax,
559 595 cmap=plt.get_cmap(self.colormap)
560 596 )
561 597 if self.showprofile:
562 598 ax.plot_profile.set_data(self.data['rti'][n][-1], self.y)
563 599 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y)
564 600
565 601 self.saveTime = self.min_time
566 602
567 603
568 604 class PlotCOHData(PlotRTIData):
569 605 '''
570 606 Plot for Coherence data
571 607 '''
572 608
573 609 CODE = 'coh'
574 610
575 611 def setup(self):
576 612 self.xaxis = 'time'
577 613 self.ncols = 1
578 614 self.nrows = len(self.data.pairs)
579 615 self.nplots = len(self.data.pairs)
580 616 self.ylabel = 'Range [Km]'
581 617 if self.CODE == 'coh':
582 618 self.cb_label = ''
583 619 self.titles = ['Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
584 620 else:
585 621 self.cb_label = 'Degrees'
586 622 self.titles = ['Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
587 623
588 624
589 625 class PlotPHASEData(PlotCOHData):
590 626 '''
591 627 Plot for Phase map data
592 628 '''
593 629
594 630 CODE = 'phase'
595 631 colormap = 'seismic'
596 632
597 633
598 634 class PlotNoiseData(PlotData):
599 635 '''
600 636 Plot for noise
601 637 '''
602 638
603 639 CODE = 'noise'
604 640
605 641 def setup(self):
606 642 self.xaxis = 'time'
607 643 self.ncols = 1
608 644 self.nrows = 1
609 645 self.nplots = 1
610 646 self.ylabel = 'Intensity [dB]'
611 647 self.titles = ['Noise']
612 648 self.colorbar = False
613 649
614 650 def plot(self):
615 651
616 x = self.data.times
652 x = self.times
617 653 xmin = self.min_time
618 654 xmax = xmin+self.xrange*60*60
619 655 Y = self.data[self.CODE]
620 656
621 657 if self.axes[0].firsttime:
622 658 for ch in self.data.channels:
623 659 y = Y[ch]
624 660 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
625 661 plt.legend()
626 662 else:
627 663 for ch in self.data.channels:
628 664 y = Y[ch]
629 665 self.axes[0].lines[ch].set_data(x, y)
630 666
631 667 self.ymin = numpy.nanmin(Y) - 5
632 668 self.ymax = numpy.nanmax(Y) + 5
633 669 self.saveTime = self.min_time
634 670
635 671
636 672 class PlotSNRData(PlotRTIData):
637 673 '''
638 674 Plot for SNR Data
639 675 '''
640 676
641 677 CODE = 'snr'
642 678 colormap = 'jet'
643 679
644 680
645 681 class PlotDOPData(PlotRTIData):
646 682 '''
647 683 Plot for DOPPLER Data
648 684 '''
649 685
650 686 CODE = 'dop'
651 687 colormap = 'jet'
652 688
653 689
654 690 class PlotSkyMapData(PlotData):
655 691 '''
656 692 Plot for meteors detection data
657 693 '''
658 694
659 695 CODE = 'met'
660 696
661 697 def setup(self):
662 698
663 699 self.ncols = 1
664 700 self.nrows = 1
665 701 self.width = 7.2
666 702 self.height = 7.2
667 703
668 704 self.xlabel = 'Zonal Zenith Angle (deg)'
669 705 self.ylabel = 'Meridional Zenith Angle (deg)'
670 706
671 707 if self.figure is None:
672 708 self.figure = plt.figure(figsize=(self.width, self.height),
673 709 edgecolor='k',
674 710 facecolor='w')
675 711 else:
676 712 self.figure.clf()
677 713
678 714 self.ax = plt.subplot2grid((self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
679 715 self.ax.firsttime = True
680 716
681 717
682 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 721 error = arrayParameters[:,-1]
686 722 indValid = numpy.where(error == 0)[0]
687 723 finalMeteor = arrayParameters[indValid,:]
688 724 finalAzimuth = finalMeteor[:,3]
689 725 finalZenith = finalMeteor[:,4]
690 726
691 727 x = finalAzimuth*numpy.pi/180
692 728 y = finalZenith
693 729
694 730 if self.ax.firsttime:
695 731 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
696 732 self.ax.set_ylim(0,90)
697 733 self.ax.set_yticks(numpy.arange(0,90,20))
698 734 self.ax.set_xlabel(self.xlabel)
699 735 self.ax.set_ylabel(self.ylabel)
700 736 self.ax.yaxis.labelpad = 40
701 737 self.ax.firsttime = False
702 738 else:
703 739 self.ax.plot.set_data(x, y)
704 740
705 741
706 742 dt1 = datetime.datetime.fromtimestamp(self.min_time).strftime('%y/%m/%d %H:%M:%S')
707 743 dt2 = datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')
708 744 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
709 745 dt2,
710 746 len(x))
711 747 self.ax.set_title(title, size=8)
712 748
713 749 self.saveTime = self.max_time
714 750
715 751 class PlotParamData(PlotRTIData):
716 752 '''
717 753 Plot for data_param object
718 754 '''
719 755
720 756 CODE = 'param'
721 757 colormap = 'seismic'
722 758
723 759 def setup(self):
724 760 self.xaxis = 'time'
725 761 self.ncols = 1
726 762 self.nrows = self.data.shape(self.CODE)[0]
727 763 self.nplots = self.nrows
728 764 if self.showSNR:
729 765 self.nrows += 1
766 self.nplots += 1
730 767
731 768 self.ylabel = 'Height [Km]'
732 769 self.titles = self.data.parameters \
733 770 if self.data.parameters else ['Param {}'.format(x) for x in xrange(self.nrows)]
734 771 if self.showSNR:
735 772 self.titles.append('SNR')
736 773
737 774 def plot(self):
738 775 self.data.normalize_heights()
739 self.x = self.data.times
776 self.x = self.times
740 777 self.y = self.data.heights
741 778 if self.showSNR:
742 779 self.z = numpy.concatenate(
743 780 (self.data[self.CODE], self.data['snr'])
744 781 )
745 782 else:
746 783 self.z = self.data[self.CODE]
747 784
748 785 self.z = numpy.ma.masked_invalid(self.z)
749 786
750 787 for n, ax in enumerate(self.axes):
751 788
752 789 x, y, z = self.fill_gaps(*self.decimate())
753 790
754 791 if ax.firsttime:
755 792 if self.zlimits is not None:
756 793 self.zmin, self.zmax = self.zlimits[n]
757 794 self.zmax = self.zmax if self.zmax is not None else numpy.nanmax(abs(self.z[:-1, :]))
758 795 self.zmin = self.zmin if self.zmin is not None else -self.zmax
759 796 ax.plt = ax.pcolormesh(x, y, z[n, :, :].T*self.factors[n],
760 797 vmin=self.zmin,
761 798 vmax=self.zmax,
762 799 cmap=self.cmaps[n]
763 800 )
764 801 else:
765 802 if self.zlimits is not None:
766 803 self.zmin, self.zmax = self.zlimits[n]
767 804 ax.collections.remove(ax.collections[0])
768 805 ax.plt = ax.pcolormesh(x, y, z[n, :, :].T*self.factors[n],
769 806 vmin=self.zmin,
770 807 vmax=self.zmax,
771 808 cmap=self.cmaps[n]
772 809 )
773 810
774 811 self.saveTime = self.min_time
775 812
776 813 class PlotOuputData(PlotParamData):
777 814 '''
778 815 Plot data_output object
779 816 '''
780 817
781 818 CODE = 'output'
782 colormap = 'seismic' No newline at end of file
819 colormap = 'seismic'
@@ -1,329 +1,328
1 1 '''
2 2 Created on Jul 9, 2014
3 3
4 4 @author: roj-idl71
5 5 '''
6 6 import os
7 7 import datetime
8 8 import numpy
9 9
10 10 from figure import Figure, isRealtime
11 11 from plotting_codes import *
12 12
13 13 class SpectraHeisScope(Figure):
14
15
14
15
16 16 isConfig = None
17 17 __nsubplots = None
18
18
19 19 WIDTHPROF = None
20 20 HEIGHTPROF = None
21 21 PREFIX = 'spc'
22
23 def __init__(self, **kwargs):
24
25 Figure.__init__(self, **kwargs)
22
23 def __init__(self):
24
26 25 self.isConfig = False
27 26 self.__nsubplots = 1
28
27
29 28 self.WIDTH = 230
30 29 self.HEIGHT = 250
31 30 self.WIDTHPROF = 120
32 31 self.HEIGHTPROF = 0
33 32 self.counter_imagwr = 0
34
33
35 34 self.PLOT_CODE = SPEC_CODE
36
35
37 36 def getSubplots(self):
38
37
39 38 ncol = int(numpy.sqrt(self.nplots)+0.9)
40 39 nrow = int(self.nplots*1./ncol + 0.9)
41
40
42 41 return nrow, ncol
43
42
44 43 def setup(self, id, nplots, wintitle, show):
45
44
46 45 showprofile = False
47 46 self.__showprofile = showprofile
48 47 self.nplots = nplots
49
48
50 49 ncolspan = 1
51 50 colspan = 1
52 51 if showprofile:
53 52 ncolspan = 3
54 53 colspan = 2
55 54 self.__nsubplots = 2
56
55
57 56 self.createFigure(id = id,
58 57 wintitle = wintitle,
59 58 widthplot = self.WIDTH + self.WIDTHPROF,
60 59 heightplot = self.HEIGHT + self.HEIGHTPROF,
61 60 show = show)
62
61
63 62 nrow, ncol = self.getSubplots()
64
63
65 64 counter = 0
66 65 for y in range(nrow):
67 66 for x in range(ncol):
68
67
69 68 if counter >= self.nplots:
70 69 break
71
70
72 71 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
73
72
74 73 if showprofile:
75 74 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
76
75
77 76 counter += 1
78 77
79
78
80 79 def run(self, dataOut, id, wintitle="", channelList=None,
81 80 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
82 81 figpath='./', figfile=None, ftp=False, wr_period=1, show=True,
83 82 server=None, folder=None, username=None, password=None,
84 83 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
85
84
86 85 """
87
86
88 87 Input:
89 88 dataOut :
90 89 id :
91 90 wintitle :
92 91 channelList :
93 92 xmin : None,
94 93 xmax : None,
95 94 ymin : None,
96 95 ymax : None,
97 96 """
98
97
99 98 if dataOut.realtime:
100 99 if not(isRealtime(utcdatatime = dataOut.utctime)):
101 100 print 'Skipping this plot function'
102 101 return
103
102
104 103 if channelList == None:
105 104 channelIndexList = dataOut.channelIndexList
106 105 else:
107 106 channelIndexList = []
108 107 for channel in channelList:
109 108 if channel not in dataOut.channelList:
110 109 raise ValueError, "Channel %d is not in dataOut.channelList"
111 110 channelIndexList.append(dataOut.channelList.index(channel))
112
111
113 112 # x = dataOut.heightList
114 c = 3E8
113 c = 3E8
115 114 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
116 115 #deberia cambiar para el caso de 1Mhz y 100KHz
117 116 x = numpy.arange(-1*dataOut.nHeights/2.,dataOut.nHeights/2.)*(c/(2*deltaHeight*dataOut.nHeights*1000))
118 117 #para 1Mhz descomentar la siguiente linea
119 118 #x= x/(10000.0)
120 119 # y = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
121 120 # y = y.real
122 121 factor = dataOut.normFactor
123 122 data = dataOut.data_spc / factor
124 123 datadB = 10.*numpy.log10(data)
125 124 y = datadB
126
125
127 126 #thisDatetime = dataOut.datatime
128 127 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
129 128 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
130 129 xlabel = ""
131 130 #para 1Mhz descomentar la siguiente linea
132 131 #xlabel = "Frequency x 10000"
133 132 ylabel = "Intensity (dB)"
134
133
135 134 if not self.isConfig:
136 135 nplots = len(channelIndexList)
137
136
138 137 self.setup(id=id,
139 138 nplots=nplots,
140 139 wintitle=wintitle,
141 140 show=show)
142
141
143 142 if xmin == None: xmin = numpy.nanmin(x)
144 143 if xmax == None: xmax = numpy.nanmax(x)
145 144 if ymin == None: ymin = numpy.nanmin(y)
146 145 if ymax == None: ymax = numpy.nanmax(y)
147
146
148 147 self.FTP_WEI = ftp_wei
149 148 self.EXP_CODE = exp_code
150 149 self.SUB_EXP_CODE = sub_exp_code
151 150 self.PLOT_POS = plot_pos
152
151
153 152 self.isConfig = True
154
153
155 154 self.setWinTitle(title)
156
155
157 156 for i in range(len(self.axesList)):
158 157 ychannel = y[i,:]
159 158 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
160 159 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[channelIndexList[i]], numpy.max(ychannel), str_datetime)
161 160 axes = self.axesList[i]
162 161 axes.pline(x, ychannel,
163 162 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
164 163 xlabel=xlabel, ylabel=ylabel, title=title, grid='both')
165
166
164
165
167 166 self.draw()
168
167
169 168 self.save(figpath=figpath,
170 169 figfile=figfile,
171 170 save=save,
172 171 ftp=ftp,
173 172 wr_period=wr_period,
174 173 thisDatetime=thisDatetime)
175 174
176 175 class RTIfromSpectraHeis(Figure):
177
176
178 177 isConfig = None
179 178 __nsubplots = None
180 179
181 180 PREFIX = 'rtinoise'
182
183 def __init__(self, **kwargs):
184 Figure.__init__(self, **kwargs)
181
182 def __init__(self):
183
185 184 self.timerange = 24*60*60
186 185 self.isConfig = False
187 186 self.__nsubplots = 1
188
187
189 188 self.WIDTH = 820
190 189 self.HEIGHT = 200
191 190 self.WIDTHPROF = 120
192 191 self.HEIGHTPROF = 0
193 192 self.counter_imagwr = 0
194 193 self.xdata = None
195 194 self.ydata = None
196 195 self.figfile = None
197
196
198 197 self.PLOT_CODE = RTI_CODE
199
198
200 199 def getSubplots(self):
201
200
202 201 ncol = 1
203 202 nrow = 1
204
203
205 204 return nrow, ncol
206
205
207 206 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
208
207
209 208 self.__showprofile = showprofile
210 209 self.nplots = nplots
211
210
212 211 ncolspan = 7
213 212 colspan = 6
214 213 self.__nsubplots = 2
215
214
216 215 self.createFigure(id = id,
217 216 wintitle = wintitle,
218 217 widthplot = self.WIDTH+self.WIDTHPROF,
219 218 heightplot = self.HEIGHT+self.HEIGHTPROF,
220 219 show = show)
221
220
222 221 nrow, ncol = self.getSubplots()
223
222
224 223 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
225
226
224
225
227 226 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
228 227 xmin=None, xmax=None, ymin=None, ymax=None,
229 228 timerange=None,
230 229 save=False, figpath='./', figfile=None, ftp=False, wr_period=1, show=True,
231 230 server=None, folder=None, username=None, password=None,
232 231 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
233
232
234 233 if channelList == None:
235 234 channelIndexList = dataOut.channelIndexList
236 235 channelList = dataOut.channelList
237 236 else:
238 237 channelIndexList = []
239 238 for channel in channelList:
240 239 if channel not in dataOut.channelList:
241 240 raise ValueError, "Channel %d is not in dataOut.channelList"
242 241 channelIndexList.append(dataOut.channelList.index(channel))
243
242
244 243 if timerange != None:
245 244 self.timerange = timerange
246
245
247 246 x = dataOut.getTimeRange()
248 247 y = dataOut.getHeiRange()
249
248
250 249 factor = dataOut.normFactor
251 250 data = dataOut.data_spc / factor
252 251 data = numpy.average(data,axis=1)
253 252 datadB = 10*numpy.log10(data)
254
253
255 254 # factor = dataOut.normFactor
256 255 # noise = dataOut.getNoise()/factor
257 256 # noisedB = 10*numpy.log10(noise)
258
257
259 258 #thisDatetime = dataOut.datatime
260 259 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
261 260 title = wintitle + " RTI: %s" %(thisDatetime.strftime("%d-%b-%Y"))
262 261 xlabel = "Local Time"
263 262 ylabel = "Intensity (dB)"
264
263
265 264 if not self.isConfig:
266
265
267 266 nplots = 1
268
267
269 268 self.setup(id=id,
270 269 nplots=nplots,
271 270 wintitle=wintitle,
272 271 showprofile=showprofile,
273 272 show=show)
274
273
275 274 self.tmin, self.tmax = self.getTimeLim(x, xmin, xmax)
276
275
277 276 if ymin == None: ymin = numpy.nanmin(datadB)
278 277 if ymax == None: ymax = numpy.nanmax(datadB)
279
278
280 279 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
281 280 self.isConfig = True
282 281 self.figfile = figfile
283 282 self.xdata = numpy.array([])
284 283 self.ydata = numpy.array([])
285
284
286 285 self.FTP_WEI = ftp_wei
287 286 self.EXP_CODE = exp_code
288 287 self.SUB_EXP_CODE = sub_exp_code
289 288 self.PLOT_POS = plot_pos
290
289
291 290 self.setWinTitle(title)
292
293
291
292
294 293 # title = "RTI %s" %(thisDatetime.strftime("%d-%b-%Y"))
295 294 title = "RTI - %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
296
295
297 296 legendlabels = ["channel %d"%idchannel for idchannel in channelList]
298 297 axes = self.axesList[0]
299
298
300 299 self.xdata = numpy.hstack((self.xdata, x[0:1]))
301
300
302 301 if len(self.ydata)==0:
303 302 self.ydata = datadB[channelIndexList].reshape(-1,1)
304 303 else:
305 304 self.ydata = numpy.hstack((self.ydata, datadB[channelIndexList].reshape(-1,1)))
306
307
305
306
308 307 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
309 308 xmin=self.tmin, xmax=self.tmax, ymin=ymin, ymax=ymax,
310 309 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='.', markersize=8, linestyle="solid", grid='both',
311 310 XAxisAsTime=True
312 311 )
313
312
314 313 self.draw()
315
314
316 315 update_figfile = False
317
316
318 317 if dataOut.ltctime >= self.tmax:
319 318 self.counter_imagwr = wr_period
320 319 self.isConfig = False
321 320 update_figfile = True
322
321
323 322 self.save(figpath=figpath,
324 323 figfile=figfile,
325 324 save=save,
326 325 ftp=ftp,
327 326 wr_period=wr_period,
328 327 thisDatetime=thisDatetime,
329 328 update_figfile=update_figfile)
@@ -1,1945 +1,2151
1 1 import os
2 2 import datetime
3 3 import numpy
4 4 import inspect
5 5 from figure import Figure, isRealtime, isTimeInHourRange
6 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 220 class MomentsPlot(Figure):
10 221
11 222 isConfig = None
12 223 __nsubplots = None
13 224
14 225 WIDTHPROF = None
15 226 HEIGHTPROF = None
16 227 PREFIX = 'prm'
17 228 def __init__(self, **kwargs):
18 229 Figure.__init__(self, **kwargs)
19 230 self.isConfig = False
20 231 self.__nsubplots = 1
21 232
22 233 self.WIDTH = 280
23 234 self.HEIGHT = 250
24 235 self.WIDTHPROF = 120
25 236 self.HEIGHTPROF = 0
26 237 self.counter_imagwr = 0
27 238
28 239 self.PLOT_CODE = MOMENTS_CODE
29 240
30 241 self.FTP_WEI = None
31 242 self.EXP_CODE = None
32 243 self.SUB_EXP_CODE = None
33 244 self.PLOT_POS = None
34 245
35 246 def getSubplots(self):
36 247
37 248 ncol = int(numpy.sqrt(self.nplots)+0.9)
38 249 nrow = int(self.nplots*1./ncol + 0.9)
39 250
40 251 return nrow, ncol
41 252
42 253 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
43 254
44 255 self.__showprofile = showprofile
45 256 self.nplots = nplots
46 257
47 258 ncolspan = 1
48 259 colspan = 1
49 260 if showprofile:
50 261 ncolspan = 3
51 262 colspan = 2
52 263 self.__nsubplots = 2
53 264
54 265 self.createFigure(id = id,
55 266 wintitle = wintitle,
56 267 widthplot = self.WIDTH + self.WIDTHPROF,
57 268 heightplot = self.HEIGHT + self.HEIGHTPROF,
58 269 show=show)
59 270
60 271 nrow, ncol = self.getSubplots()
61 272
62 273 counter = 0
63 274 for y in range(nrow):
64 275 for x in range(ncol):
65 276
66 277 if counter >= self.nplots:
67 278 break
68 279
69 280 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
70 281
71 282 if showprofile:
72 283 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
73 284
74 285 counter += 1
75 286
76 287 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
77 288 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
78 289 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
79 290 server=None, folder=None, username=None, password=None,
80 291 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
81 292
82 293 """
83 294
84 295 Input:
85 296 dataOut :
86 297 id :
87 298 wintitle :
88 299 channelList :
89 300 showProfile :
90 301 xmin : None,
91 302 xmax : None,
92 303 ymin : None,
93 304 ymax : None,
94 305 zmin : None,
95 306 zmax : None
96 307 """
97 308
98 309 if dataOut.flagNoData:
99 310 return None
100 311
101 312 if realtime:
102 313 if not(isRealtime(utcdatatime = dataOut.utctime)):
103 314 print 'Skipping this plot function'
104 315 return
105 316
106 317 if channelList == None:
107 318 channelIndexList = dataOut.channelIndexList
108 319 else:
109 320 channelIndexList = []
110 321 for channel in channelList:
111 322 if channel not in dataOut.channelList:
112 323 raise ValueError, "Channel %d is not in dataOut.channelList"
113 324 channelIndexList.append(dataOut.channelList.index(channel))
114 325
115 326 factor = dataOut.normFactor
116 327 x = dataOut.abscissaList
117 328 y = dataOut.heightList
118 329
119 330 z = dataOut.data_pre[channelIndexList,:,:]/factor
120 331 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
121 332 avg = numpy.average(z, axis=1)
122 333 noise = dataOut.noise/factor
123 334
124 335 zdB = 10*numpy.log10(z)
125 336 avgdB = 10*numpy.log10(avg)
126 337 noisedB = 10*numpy.log10(noise)
127 338
128 339 #thisDatetime = dataOut.datatime
129 340 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
130 341 title = wintitle + " Parameters"
131 342 xlabel = "Velocity (m/s)"
132 343 ylabel = "Range (Km)"
133 344
134 345 update_figfile = False
135 346
136 347 if not self.isConfig:
137 348
138 349 nplots = len(channelIndexList)
139 350
140 351 self.setup(id=id,
141 352 nplots=nplots,
142 353 wintitle=wintitle,
143 354 showprofile=showprofile,
144 355 show=show)
145 356
146 357 if xmin == None: xmin = numpy.nanmin(x)
147 358 if xmax == None: xmax = numpy.nanmax(x)
148 359 if ymin == None: ymin = numpy.nanmin(y)
149 360 if ymax == None: ymax = numpy.nanmax(y)
150 361 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
151 362 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
152 363
153 364 self.FTP_WEI = ftp_wei
154 365 self.EXP_CODE = exp_code
155 366 self.SUB_EXP_CODE = sub_exp_code
156 367 self.PLOT_POS = plot_pos
157 368
158 369 self.isConfig = True
159 370 update_figfile = True
160 371
161 372 self.setWinTitle(title)
162 373
163 374 for i in range(self.nplots):
164 375 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
165 376 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
166 377 axes = self.axesList[i*self.__nsubplots]
167 378 axes.pcolor(x, y, zdB[i,:,:],
168 379 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
169 380 xlabel=xlabel, ylabel=ylabel, title=title,
170 381 ticksize=9, cblabel='')
171 382 #Mean Line
172 383 mean = dataOut.data_param[i, 1, :]
173 384 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
174 385
175 386 if self.__showprofile:
176 387 axes = self.axesList[i*self.__nsubplots +1]
177 388 axes.pline(avgdB[i], y,
178 389 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
179 390 xlabel='dB', ylabel='', title='',
180 391 ytick_visible=False,
181 392 grid='x')
182 393
183 394 noiseline = numpy.repeat(noisedB[i], len(y))
184 395 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
185 396
186 397 self.draw()
187 398
188 399 self.save(figpath=figpath,
189 400 figfile=figfile,
190 401 save=save,
191 402 ftp=ftp,
192 403 wr_period=wr_period,
193 404 thisDatetime=thisDatetime)
194 405
195 406
196 407
197 408 class SkyMapPlot(Figure):
198 409
199 410 __isConfig = None
200 411 __nsubplots = None
201 412
202 413 WIDTHPROF = None
203 414 HEIGHTPROF = None
204 415 PREFIX = 'mmap'
205 416
206 417 def __init__(self, **kwargs):
207 418 Figure.__init__(self, **kwargs)
208 419 self.isConfig = False
209 420 self.__nsubplots = 1
210 421
211 422 # self.WIDTH = 280
212 423 # self.HEIGHT = 250
213 424 self.WIDTH = 600
214 425 self.HEIGHT = 600
215 426 self.WIDTHPROF = 120
216 427 self.HEIGHTPROF = 0
217 428 self.counter_imagwr = 0
218 429
219 430 self.PLOT_CODE = MSKYMAP_CODE
220 431
221 432 self.FTP_WEI = None
222 433 self.EXP_CODE = None
223 434 self.SUB_EXP_CODE = None
224 435 self.PLOT_POS = None
225 436
226 437 def getSubplots(self):
227 438
228 439 ncol = int(numpy.sqrt(self.nplots)+0.9)
229 440 nrow = int(self.nplots*1./ncol + 0.9)
230 441
231 442 return nrow, ncol
232 443
233 444 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
234 445
235 446 self.__showprofile = showprofile
236 447 self.nplots = nplots
237 448
238 449 ncolspan = 1
239 450 colspan = 1
240 451
241 452 self.createFigure(id = id,
242 453 wintitle = wintitle,
243 454 widthplot = self.WIDTH, #+ self.WIDTHPROF,
244 455 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
245 456 show=show)
246 457
247 458 nrow, ncol = 1,1
248 459 counter = 0
249 460 x = 0
250 461 y = 0
251 462 self.addAxes(1, 1, 0, 0, 1, 1, True)
252 463
253 464 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
254 465 tmin=0, tmax=24, timerange=None,
255 466 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
256 467 server=None, folder=None, username=None, password=None,
257 468 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
258 469
259 470 """
260 471
261 472 Input:
262 473 dataOut :
263 474 id :
264 475 wintitle :
265 476 channelList :
266 477 showProfile :
267 478 xmin : None,
268 479 xmax : None,
269 480 ymin : None,
270 481 ymax : None,
271 482 zmin : None,
272 483 zmax : None
273 484 """
274 485
275 486 arrayParameters = dataOut.data_param
276 487 error = arrayParameters[:,-1]
277 488 indValid = numpy.where(error == 0)[0]
278 489 finalMeteor = arrayParameters[indValid,:]
279 490 finalAzimuth = finalMeteor[:,3]
280 491 finalZenith = finalMeteor[:,4]
281 492
282 493 x = finalAzimuth*numpy.pi/180
283 494 y = finalZenith
284 495 x1 = [dataOut.ltctime, dataOut.ltctime]
285 496
286 497 #thisDatetime = dataOut.datatime
287 498 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
288 499 title = wintitle + " Parameters"
289 500 xlabel = "Zonal Zenith Angle (deg) "
290 501 ylabel = "Meridional Zenith Angle (deg)"
291 502 update_figfile = False
292 503
293 504 if not self.isConfig:
294 505
295 506 nplots = 1
296 507
297 508 self.setup(id=id,
298 509 nplots=nplots,
299 510 wintitle=wintitle,
300 511 showprofile=showprofile,
301 512 show=show)
302 513
303 514 if self.xmin is None and self.xmax is None:
304 515 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
305 516
306 517 if timerange != None:
307 518 self.timerange = timerange
308 519 else:
309 520 self.timerange = self.xmax - self.xmin
310 521
311 522 self.FTP_WEI = ftp_wei
312 523 self.EXP_CODE = exp_code
313 524 self.SUB_EXP_CODE = sub_exp_code
314 525 self.PLOT_POS = plot_pos
315 526 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
316 527 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
317 528 self.isConfig = True
318 529 update_figfile = True
319 530
320 531 self.setWinTitle(title)
321 532
322 533 i = 0
323 534 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
324 535
325 536 axes = self.axesList[i*self.__nsubplots]
326 537 nevents = axes.x_buffer.shape[0] + x.shape[0]
327 538 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
328 539 axes.polar(x, y,
329 540 title=title, xlabel=xlabel, ylabel=ylabel,
330 541 ticksize=9, cblabel='')
331 542
332 543 self.draw()
333 544
334 545 self.save(figpath=figpath,
335 546 figfile=figfile,
336 547 save=save,
337 548 ftp=ftp,
338 549 wr_period=wr_period,
339 550 thisDatetime=thisDatetime,
340 551 update_figfile=update_figfile)
341 552
342 553 if dataOut.ltctime >= self.xmax:
343 554 self.isConfigmagwr = wr_period
344 555 self.isConfig = False
345 556 update_figfile = True
346 557 axes.__firsttime = True
347 558 self.xmin += self.timerange
348 559 self.xmax += self.timerange
349 560
350 561
351 562
352 563
353 564 class WindProfilerPlot(Figure):
354 565
355 566 __isConfig = None
356 567 __nsubplots = None
357 568
358 569 WIDTHPROF = None
359 570 HEIGHTPROF = None
360 571 PREFIX = 'wind'
361 572
362 573 def __init__(self, **kwargs):
363 574 Figure.__init__(self, **kwargs)
364 575 self.timerange = None
365 576 self.isConfig = False
366 577 self.__nsubplots = 1
367 578
368 579 self.WIDTH = 800
369 580 self.HEIGHT = 300
370 581 self.WIDTHPROF = 120
371 582 self.HEIGHTPROF = 0
372 583 self.counter_imagwr = 0
373 584
374 585 self.PLOT_CODE = WIND_CODE
375 586
376 587 self.FTP_WEI = None
377 588 self.EXP_CODE = None
378 589 self.SUB_EXP_CODE = None
379 590 self.PLOT_POS = None
380 591 self.tmin = None
381 592 self.tmax = None
382 593
383 594 self.xmin = None
384 595 self.xmax = None
385 596
386 597 self.figfile = None
387 598
388 599 def getSubplots(self):
389 600
390 601 ncol = 1
391 602 nrow = self.nplots
392 603
393 604 return nrow, ncol
394 605
395 606 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
396 607
397 608 self.__showprofile = showprofile
398 609 self.nplots = nplots
399 610
400 611 ncolspan = 1
401 612 colspan = 1
402 613
403 614 self.createFigure(id = id,
404 615 wintitle = wintitle,
405 616 widthplot = self.WIDTH + self.WIDTHPROF,
406 617 heightplot = self.HEIGHT + self.HEIGHTPROF,
407 618 show=show)
408 619
409 620 nrow, ncol = self.getSubplots()
410 621
411 622 counter = 0
412 623 for y in range(nrow):
413 624 if counter >= self.nplots:
414 625 break
415 626
416 627 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
417 628 counter += 1
418 629
419 630 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
420 631 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
421 632 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
422 633 timerange=None, SNRthresh = None,
423 634 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
424 635 server=None, folder=None, username=None, password=None,
425 636 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
426 637 """
427 638
428 639 Input:
429 640 dataOut :
430 641 id :
431 642 wintitle :
432 643 channelList :
433 644 showProfile :
434 645 xmin : None,
435 646 xmax : None,
436 647 ymin : None,
437 648 ymax : None,
438 649 zmin : None,
439 650 zmax : None
440 651 """
441 652
442 653 # if timerange is not None:
443 654 # self.timerange = timerange
444 655 #
445 656 # tmin = None
446 657 # tmax = None
447 658
448
449 x = dataOut.getTimeRange1(dataOut.outputInterval)
450 y = dataOut.heightList
451 z = dataOut.data_output.copy()
659 x = dataOut.getTimeRange1(dataOut.paramInterval)
660 y = dataOut.heightList
661 z = dataOut.data_output.copy()
452 662 nplots = z.shape[0] #Number of wind dimensions estimated
453 663 nplotsw = nplots
454 664
455 665
456 666 #If there is a SNR function defined
457 667 if dataOut.data_SNR is not None:
458 668 nplots += 1
459 669 SNR = dataOut.data_SNR
460 670 SNRavg = numpy.average(SNR, axis=0)
461 671
462 672 SNRdB = 10*numpy.log10(SNR)
463 673 SNRavgdB = 10*numpy.log10(SNRavg)
464 674
465 675 if SNRthresh == None: SNRthresh = -5.0
466 676 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
467 677
468 678 for i in range(nplotsw):
469 679 z[i,ind] = numpy.nan
470 680
471 681 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
472 682 #thisDatetime = datetime.datetime.now()
473 683 title = wintitle + "Wind"
474 684 xlabel = ""
475 685 ylabel = "Height (km)"
476 686 update_figfile = False
477 687
478 688 if not self.isConfig:
479 689
480 690 self.setup(id=id,
481 691 nplots=nplots,
482 692 wintitle=wintitle,
483 693 showprofile=showprofile,
484 694 show=show)
485 695
486 696 if timerange is not None:
487 697 self.timerange = timerange
488 698
489 699 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
490 700
491 701 if ymin == None: ymin = numpy.nanmin(y)
492 702 if ymax == None: ymax = numpy.nanmax(y)
493 703
494 704 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
495 705 #if numpy.isnan(zmax): zmax = 50
496 706 if zmin == None: zmin = -zmax
497 707
498 708 if nplotsw == 3:
499 709 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
500 710 if zmin_ver == None: zmin_ver = -zmax_ver
501 711
502 712 if dataOut.data_SNR is not None:
503 713 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
504 714 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
505 715
506 716
507 717 self.FTP_WEI = ftp_wei
508 718 self.EXP_CODE = exp_code
509 719 self.SUB_EXP_CODE = sub_exp_code
510 720 self.PLOT_POS = plot_pos
511 721
512 722 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
513 723 self.isConfig = True
514 724 self.figfile = figfile
515 725 update_figfile = True
516 726
517 727 self.setWinTitle(title)
518 728
519 729 if ((self.xmax - x[1]) < (x[1]-x[0])):
520 730 x[1] = self.xmax
521 731
522 732 strWind = ['Zonal', 'Meridional', 'Vertical']
523 733 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
524 734 zmaxVector = [zmax, zmax, zmax_ver]
525 735 zminVector = [zmin, zmin, zmin_ver]
526 736 windFactor = [1,1,100]
527 737
528 738 for i in range(nplotsw):
529 739
530 740 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
531 741 axes = self.axesList[i*self.__nsubplots]
532 742
533 743 z1 = z[i,:].reshape((1,-1))*windFactor[i]
534 744 #z1=numpy.ma.masked_where(z1==0.,z1)
535 745
536 746 axes.pcolorbuffer(x, y, z1,
537 747 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
538 748 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
539 749 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
540 750
541 751 if dataOut.data_SNR is not None:
542 752 i += 1
543 753 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
544 754 axes = self.axesList[i*self.__nsubplots]
545 755 SNRavgdB = SNRavgdB.reshape((1,-1))
546 756 axes.pcolorbuffer(x, y, SNRavgdB,
547 757 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
548 758 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
549 759 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
550 760
551 761 self.draw()
552 762
553 763 self.save(figpath=figpath,
554 764 figfile=figfile,
555 765 save=save,
556 766 ftp=ftp,
557 767 wr_period=wr_period,
558 768 thisDatetime=thisDatetime,
559 769 update_figfile=update_figfile)
560 770
561 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
771 if dataOut.ltctime + dataOut.paramInterval >= self.xmax:
562 772 self.counter_imagwr = wr_period
563 773 self.isConfig = False
564 774 update_figfile = True
565 775
566 776
567 777 class ParametersPlot(Figure):
568 778
569 779 __isConfig = None
570 780 __nsubplots = None
571 781
572 782 WIDTHPROF = None
573 783 HEIGHTPROF = None
574 784 PREFIX = 'param'
575 785
576 786 nplots = None
577 787 nchan = None
578 788
579 789 def __init__(self, **kwargs):
580 790 Figure.__init__(self, **kwargs)
581 791 self.timerange = None
582 792 self.isConfig = False
583 793 self.__nsubplots = 1
584 794
585 795 self.WIDTH = 800
586 796 self.HEIGHT = 180
587 797 self.WIDTHPROF = 120
588 798 self.HEIGHTPROF = 0
589 799 self.counter_imagwr = 0
590 800
591 801 self.PLOT_CODE = RTI_CODE
592 802
593 803 self.FTP_WEI = None
594 804 self.EXP_CODE = None
595 805 self.SUB_EXP_CODE = None
596 806 self.PLOT_POS = None
597 807 self.tmin = None
598 808 self.tmax = None
599 809
600 810 self.xmin = None
601 811 self.xmax = None
602 812
603 813 self.figfile = None
604 814
605 815 def getSubplots(self):
606 816
607 817 ncol = 1
608 818 nrow = self.nplots
609 819
610 820 return nrow, ncol
611 821
612 822 def setup(self, id, nplots, wintitle, show=True):
613 823
614 824 self.nplots = nplots
615 825
616 826 ncolspan = 1
617 827 colspan = 1
618 828
619 829 self.createFigure(id = id,
620 830 wintitle = wintitle,
621 831 widthplot = self.WIDTH + self.WIDTHPROF,
622 832 heightplot = self.HEIGHT + self.HEIGHTPROF,
623 833 show=show)
624 834
625 835 nrow, ncol = self.getSubplots()
626 836
627 837 counter = 0
628 838 for y in range(nrow):
629 839 for x in range(ncol):
630 840
631 841 if counter >= self.nplots:
632 842 break
633 843
634 844 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
635 845
636 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 849 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
640 850 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
641 851 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
642 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 856 Input:
647 857 dataOut :
648 858 id :
649 859 wintitle :
650 860 channelList :
651 861 showProfile :
652 862 xmin : None,
653 863 xmax : None,
654 864 ymin : None,
655 865 ymax : None,
656 866 zmin : None,
657 867 zmax : None
658 868 """
659
660 if colormap:
661 colormap="jet"
662 else:
663 colormap="RdBu_r"
664
869
870 if HEIGHT is not None:
871 self.HEIGHT = HEIGHT
872
873
665 874 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
666 875 return
667 876
668 877 if channelList == None:
669 878 channelIndexList = range(dataOut.data_param.shape[0])
670 879 else:
671 880 channelIndexList = []
672 881 for channel in channelList:
673 882 if channel not in dataOut.channelList:
674 883 raise ValueError, "Channel %d is not in dataOut.channelList"
675 884 channelIndexList.append(dataOut.channelList.index(channel))
676 885
677 886 x = dataOut.getTimeRange1(dataOut.paramInterval)
678 887 y = dataOut.getHeiRange()
679 888
680 889 if dataOut.data_param.ndim == 3:
681 890 z = dataOut.data_param[channelIndexList,paramIndex,:]
682 891 else:
683 892 z = dataOut.data_param[channelIndexList,:]
684 893
685 894 if showSNR:
686 895 #SNR data
687 896 SNRarray = dataOut.data_SNR[channelIndexList,:]
688 897 SNRdB = 10*numpy.log10(SNRarray)
689 898 ind = numpy.where(SNRdB < SNRthresh)
690 899 z[ind] = numpy.nan
691 900
692 901 thisDatetime = dataOut.datatime
693 902 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
694 903 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
695 904 xlabel = ""
696 905 ylabel = "Range (Km)"
697 906
698 907 update_figfile = False
699 908
700 909 if not self.isConfig:
701 910
702 911 nchan = len(channelIndexList)
703 912 self.nchan = nchan
704 913 self.plotFact = 1
705 914 nplots = nchan
706 915
707 916 if showSNR:
708 917 nplots = nchan*2
709 918 self.plotFact = 2
710 919 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
711 920 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
712 921
713 922 self.setup(id=id,
714 923 nplots=nplots,
715 924 wintitle=wintitle,
716 925 show=show)
717 926
718 927 if timerange != None:
719 928 self.timerange = timerange
720 929
721 930 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
722 931
723 932 if ymin == None: ymin = numpy.nanmin(y)
724 933 if ymax == None: ymax = numpy.nanmax(y)
725 934 if zmin == None: zmin = numpy.nanmin(z)
726 935 if zmax == None: zmax = numpy.nanmax(z)
727 936
728 937 self.FTP_WEI = ftp_wei
729 938 self.EXP_CODE = exp_code
730 939 self.SUB_EXP_CODE = sub_exp_code
731 940 self.PLOT_POS = plot_pos
732 941
733 942 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
734 943 self.isConfig = True
735 944 self.figfile = figfile
736 945 update_figfile = True
737 946
738 947 self.setWinTitle(title)
739 948
740 949 for i in range(self.nchan):
741 950 index = channelIndexList[i]
742 951 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
743 952 axes = self.axesList[i*self.plotFact]
744 953 z1 = z[i,:].reshape((1,-1))
745 954 axes.pcolorbuffer(x, y, z1,
746 955 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
747 956 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
748 957 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
749 958
750 959 if showSNR:
751 960 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
752 961 axes = self.axesList[i*self.plotFact + 1]
753 962 SNRdB1 = SNRdB[i,:].reshape((1,-1))
754 963 axes.pcolorbuffer(x, y, SNRdB1,
755 964 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
756 965 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
757 966 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
758 967
759 968
760 969 self.draw()
761 970
762 971 if dataOut.ltctime >= self.xmax:
763 972 self.counter_imagwr = wr_period
764 973 self.isConfig = False
765 974 update_figfile = True
766 975
767 976 self.save(figpath=figpath,
768 977 figfile=figfile,
769 978 save=save,
770 979 ftp=ftp,
771 980 wr_period=wr_period,
772 981 thisDatetime=thisDatetime,
773 982 update_figfile=update_figfile)
774 983
775 984
776 985
777 986 class Parameters1Plot(Figure):
778 987
779 988 __isConfig = None
780 989 __nsubplots = None
781 990
782 991 WIDTHPROF = None
783 992 HEIGHTPROF = None
784 993 PREFIX = 'prm'
785 994
786 995 def __init__(self, **kwargs):
787 996 Figure.__init__(self, **kwargs)
788 997 self.timerange = 2*60*60
789 998 self.isConfig = False
790 999 self.__nsubplots = 1
791 1000
792 1001 self.WIDTH = 800
793 1002 self.HEIGHT = 180
794 1003 self.WIDTHPROF = 120
795 1004 self.HEIGHTPROF = 0
796 1005 self.counter_imagwr = 0
797 1006
798 1007 self.PLOT_CODE = PARMS_CODE
799 1008
800 1009 self.FTP_WEI = None
801 1010 self.EXP_CODE = None
802 1011 self.SUB_EXP_CODE = None
803 1012 self.PLOT_POS = None
804 1013 self.tmin = None
805 1014 self.tmax = None
806 1015
807 1016 self.xmin = None
808 1017 self.xmax = None
809 1018
810 1019 self.figfile = None
811 1020
812 1021 def getSubplots(self):
813 1022
814 1023 ncol = 1
815 1024 nrow = self.nplots
816 1025
817 1026 return nrow, ncol
818 1027
819 1028 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
820 1029
821 1030 self.__showprofile = showprofile
822 1031 self.nplots = nplots
823 1032
824 1033 ncolspan = 1
825 1034 colspan = 1
826 1035
827 1036 self.createFigure(id = id,
828 1037 wintitle = wintitle,
829 1038 widthplot = self.WIDTH + self.WIDTHPROF,
830 1039 heightplot = self.HEIGHT + self.HEIGHTPROF,
831 1040 show=show)
832 1041
833 1042 nrow, ncol = self.getSubplots()
834 1043
835 1044 counter = 0
836 1045 for y in range(nrow):
837 1046 for x in range(ncol):
838 1047
839 1048 if counter >= self.nplots:
840 1049 break
841 1050
842 1051 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
843 1052
844 1053 if showprofile:
845 1054 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
846 1055
847 1056 counter += 1
848 1057
849 1058 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
850 1059 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
851 1060 parameterIndex = None, onlyPositive = False,
852 1061 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
853 1062 DOP = True,
854 1063 zlabel = "", parameterName = "", parameterObject = "data_param",
855 1064 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
856 1065 server=None, folder=None, username=None, password=None,
857 1066 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
858 1067 #print inspect.getargspec(self.run).args
859 1068 """
860 1069
861 1070 Input:
862 1071 dataOut :
863 1072 id :
864 1073 wintitle :
865 1074 channelList :
866 1075 showProfile :
867 1076 xmin : None,
868 1077 xmax : None,
869 1078 ymin : None,
870 1079 ymax : None,
871 1080 zmin : None,
872 1081 zmax : None
873 1082 """
874 1083
875 1084 data_param = getattr(dataOut, parameterObject)
876 1085
877 1086 if channelList == None:
878 1087 channelIndexList = numpy.arange(data_param.shape[0])
879 1088 else:
880 1089 channelIndexList = numpy.array(channelList)
881 1090
882 1091 nchan = len(channelIndexList) #Number of channels being plotted
883 1092
884 1093 if nchan < 1:
885 1094 return
886 1095
887 1096 nGraphsByChannel = 0
888 1097
889 1098 if SNR:
890 1099 nGraphsByChannel += 1
891 1100 if DOP:
892 1101 nGraphsByChannel += 1
893 1102
894 1103 if nGraphsByChannel < 1:
895 1104 return
896 1105
897 1106 nplots = nGraphsByChannel*nchan
898 1107
899 1108 if timerange is not None:
900 1109 self.timerange = timerange
901 1110
902 1111 #tmin = None
903 1112 #tmax = None
904 1113 if parameterIndex == None:
905 1114 parameterIndex = 1
906 1115
907 1116 x = dataOut.getTimeRange1(dataOut.paramInterval)
908 1117 y = dataOut.heightList
909 z = data_param[channelIndexList,parameterIndex,:].copy()
910 1118
911 zRange = dataOut.abscissaList
912 # nChannels = z.shape[0] #Number of wind dimensions estimated
913 # thisDatetime = dataOut.datatime
1119 if dataOut.data_param.ndim == 3:
1120 z = dataOut.data_param[channelIndexList,parameterIndex,:]
1121 else:
1122 z = dataOut.data_param[channelIndexList,:]
914 1123
915 1124 if dataOut.data_SNR is not None:
916 SNRarray = dataOut.data_SNR[channelIndexList,:]
917 SNRdB = 10*numpy.log10(SNRarray)
918 # SNRavgdB = 10*numpy.log10(SNRavg)
919 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
920 z[ind] = numpy.nan
1125 if dataOut.data_SNR.ndim == 2:
1126 SNRavg = numpy.average(dataOut.data_SNR, axis=0)
1127 else:
1128 SNRavg = dataOut.data_SNR
1129 SNRdB = 10*numpy.log10(SNRavg)
921 1130
922 1131 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
923 1132 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
924 1133 xlabel = ""
925 ylabel = "Range (Km)"
926
927 if (SNR and not onlySNR): nplots = 2*nplots
1134 ylabel = "Range (Km)"
928 1135
929 1136 if onlyPositive:
930 1137 colormap = "jet"
931 1138 zmin = 0
932 1139 else: colormap = "RdBu_r"
933 1140
934 1141 if not self.isConfig:
935 1142
936 1143 self.setup(id=id,
937 1144 nplots=nplots,
938 1145 wintitle=wintitle,
939 1146 showprofile=showprofile,
940 1147 show=show)
941 1148
942 1149 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
943 1150
944 1151 if ymin == None: ymin = numpy.nanmin(y)
945 1152 if ymax == None: ymax = numpy.nanmax(y)
946 if zmin == None: zmin = numpy.nanmin(zRange)
947 if zmax == None: zmax = numpy.nanmax(zRange)
1153 if zmin == None: zmin = numpy.nanmin(z)
1154 if zmax == None: zmax = numpy.nanmax(z)
948 1155
949 1156 if SNR:
950 1157 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
951 1158 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
952 1159
953 1160 self.FTP_WEI = ftp_wei
954 1161 self.EXP_CODE = exp_code
955 1162 self.SUB_EXP_CODE = sub_exp_code
956 1163 self.PLOT_POS = plot_pos
957 1164
958 1165 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
959 1166 self.isConfig = True
960 1167 self.figfile = figfile
961 1168
962 1169 self.setWinTitle(title)
963 1170
964 1171 if ((self.xmax - x[1]) < (x[1]-x[0])):
965 1172 x[1] = self.xmax
966 1173
967 1174 for i in range(nchan):
968 1175
969 1176 if (SNR and not onlySNR): j = 2*i
970 1177 else: j = i
971 1178
972 1179 j = nGraphsByChannel*i
973 1180
974 1181 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
975 1182 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
976 1183
977 1184 if not onlySNR:
978 1185 axes = self.axesList[j*self.__nsubplots]
979 1186 z1 = z[i,:].reshape((1,-1))
980 1187 axes.pcolorbuffer(x, y, z1,
981 1188 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
982 1189 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
983 1190 ticksize=9, cblabel=zlabel, cbsize="1%")
984 1191
985 1192 if DOP:
986 1193 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
987 1194
988 1195 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
989 1196 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
990 1197 axes = self.axesList[j]
991 1198 z1 = z[i,:].reshape((1,-1))
992 1199 axes.pcolorbuffer(x, y, z1,
993 1200 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
994 1201 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
995 1202 ticksize=9, cblabel=zlabel, cbsize="1%")
996 1203
997 if SNR:
998 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]
1000 if not onlySNR:
1001 axes = self.axesList[(j + 1)*self.__nsubplots]
1002
1003 axes = self.axesList[(j + nGraphsByChannel-1)]
1204 if SNR:
1205 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1206 axes = self.axesList[(j)*self.__nsubplots]
1207 if not onlySNR:
1208 axes = self.axesList[(j + 1)*self.__nsubplots]
1004 1209
1005 z1 = SNRdB[i,:].reshape((1,-1))
1006 axes.pcolorbuffer(x, y, z1,
1007 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1008 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1009 ticksize=9, cblabel=zlabel, cbsize="1%")
1210 axes = self.axesList[(j + nGraphsByChannel-1)]
1211 z1 = SNRdB.reshape((1,-1))
1212 axes.pcolorbuffer(x, y, z1,
1213 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
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 1219 self.draw()
1014 1220
1015 1221 if x[1] >= self.axesList[0].xmax:
1016 1222 self.counter_imagwr = wr_period
1017 1223 self.isConfig = False
1018 1224 self.figfile = None
1019 1225
1020 1226 self.save(figpath=figpath,
1021 1227 figfile=figfile,
1022 1228 save=save,
1023 1229 ftp=ftp,
1024 1230 wr_period=wr_period,
1025 1231 thisDatetime=thisDatetime,
1026 1232 update_figfile=False)
1027 1233
1028 1234 class SpectralFittingPlot(Figure):
1029 1235
1030 1236 __isConfig = None
1031 1237 __nsubplots = None
1032 1238
1033 1239 WIDTHPROF = None
1034 1240 HEIGHTPROF = None
1035 1241 PREFIX = 'prm'
1036 1242
1037 1243
1038 1244 N = None
1039 1245 ippSeconds = None
1040 1246
1041 1247 def __init__(self, **kwargs):
1042 1248 Figure.__init__(self, **kwargs)
1043 1249 self.isConfig = False
1044 1250 self.__nsubplots = 1
1045 1251
1046 1252 self.PLOT_CODE = SPECFIT_CODE
1047 1253
1048 1254 self.WIDTH = 450
1049 1255 self.HEIGHT = 250
1050 1256 self.WIDTHPROF = 0
1051 1257 self.HEIGHTPROF = 0
1052 1258
1053 1259 def getSubplots(self):
1054 1260
1055 1261 ncol = int(numpy.sqrt(self.nplots)+0.9)
1056 1262 nrow = int(self.nplots*1./ncol + 0.9)
1057 1263
1058 1264 return nrow, ncol
1059 1265
1060 1266 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1061 1267
1062 1268 showprofile = False
1063 1269 self.__showprofile = showprofile
1064 1270 self.nplots = nplots
1065 1271
1066 1272 ncolspan = 5
1067 1273 colspan = 4
1068 1274 if showprofile:
1069 1275 ncolspan = 5
1070 1276 colspan = 4
1071 1277 self.__nsubplots = 2
1072 1278
1073 1279 self.createFigure(id = id,
1074 1280 wintitle = wintitle,
1075 1281 widthplot = self.WIDTH + self.WIDTHPROF,
1076 1282 heightplot = self.HEIGHT + self.HEIGHTPROF,
1077 1283 show=show)
1078 1284
1079 1285 nrow, ncol = self.getSubplots()
1080 1286
1081 1287 counter = 0
1082 1288 for y in range(nrow):
1083 1289 for x in range(ncol):
1084 1290
1085 1291 if counter >= self.nplots:
1086 1292 break
1087 1293
1088 1294 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1089 1295
1090 1296 if showprofile:
1091 1297 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1092 1298
1093 1299 counter += 1
1094 1300
1095 1301 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1096 1302 xmin=None, xmax=None, ymin=None, ymax=None,
1097 1303 save=False, figpath='./', figfile=None, show=True):
1098 1304
1099 1305 """
1100 1306
1101 1307 Input:
1102 1308 dataOut :
1103 1309 id :
1104 1310 wintitle :
1105 1311 channelList :
1106 1312 showProfile :
1107 1313 xmin : None,
1108 1314 xmax : None,
1109 1315 zmin : None,
1110 1316 zmax : None
1111 1317 """
1112 1318
1113 1319 if cutHeight==None:
1114 1320 h=270
1115 1321 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1116 1322 cutHeight = dataOut.heightList[heightindex]
1117 1323
1118 1324 factor = dataOut.normFactor
1119 1325 x = dataOut.abscissaList[:-1]
1120 1326 #y = dataOut.getHeiRange()
1121 1327
1122 1328 z = dataOut.data_pre[:,:,heightindex]/factor
1123 1329 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1124 1330 avg = numpy.average(z, axis=1)
1125 1331 listChannels = z.shape[0]
1126 1332
1127 1333 #Reconstruct Function
1128 1334 if fit==True:
1129 1335 groupArray = dataOut.groupList
1130 1336 listChannels = groupArray.reshape((groupArray.size))
1131 1337 listChannels.sort()
1132 1338 spcFitLine = numpy.zeros(z.shape)
1133 1339 constants = dataOut.constants
1134 1340
1135 1341 nGroups = groupArray.shape[0]
1136 1342 nChannels = groupArray.shape[1]
1137 1343 nProfiles = z.shape[1]
1138 1344
1139 1345 for f in range(nGroups):
1140 1346 groupChann = groupArray[f,:]
1141 1347 p = dataOut.data_param[f,:,heightindex]
1142 1348 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1143 1349 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1144 1350 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1145 1351 spcFitLine[groupChann,:] = fitLineAux
1146 1352 # spcFitLine = spcFitLine/factor
1147 1353
1148 1354 z = z[listChannels,:]
1149 1355 spcFitLine = spcFitLine[listChannels,:]
1150 1356 spcFitLinedB = 10*numpy.log10(spcFitLine)
1151 1357
1152 1358 zdB = 10*numpy.log10(z)
1153 1359 #thisDatetime = dataOut.datatime
1154 1360 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1155 1361 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1156 1362 xlabel = "Velocity (m/s)"
1157 1363 ylabel = "Spectrum"
1158 1364
1159 1365 if not self.isConfig:
1160 1366
1161 1367 nplots = listChannels.size
1162 1368
1163 1369 self.setup(id=id,
1164 1370 nplots=nplots,
1165 1371 wintitle=wintitle,
1166 1372 showprofile=showprofile,
1167 1373 show=show)
1168 1374
1169 1375 if xmin == None: xmin = numpy.nanmin(x)
1170 1376 if xmax == None: xmax = numpy.nanmax(x)
1171 1377 if ymin == None: ymin = numpy.nanmin(zdB)
1172 1378 if ymax == None: ymax = numpy.nanmax(zdB)+2
1173 1379
1174 1380 self.isConfig = True
1175 1381
1176 1382 self.setWinTitle(title)
1177 1383 for i in range(self.nplots):
1178 1384 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1179 1385 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1180 1386 axes = self.axesList[i*self.__nsubplots]
1181 1387 if fit == False:
1182 1388 axes.pline(x, zdB[i,:],
1183 1389 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1184 1390 xlabel=xlabel, ylabel=ylabel, title=title
1185 1391 )
1186 1392 if fit == True:
1187 1393 fitline=spcFitLinedB[i,:]
1188 1394 y=numpy.vstack([zdB[i,:],fitline] )
1189 1395 legendlabels=['Data','Fitting']
1190 1396 axes.pmultilineyaxis(x, y,
1191 1397 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1192 1398 xlabel=xlabel, ylabel=ylabel, title=title,
1193 1399 legendlabels=legendlabels, marker=None,
1194 1400 linestyle='solid', grid='both')
1195 1401
1196 1402 self.draw()
1197 1403
1198 1404 self.save(figpath=figpath,
1199 1405 figfile=figfile,
1200 1406 save=save,
1201 1407 ftp=ftp,
1202 1408 wr_period=wr_period,
1203 1409 thisDatetime=thisDatetime)
1204 1410
1205 1411
1206 1412 class EWDriftsPlot(Figure):
1207 1413
1208 1414 __isConfig = None
1209 1415 __nsubplots = None
1210 1416
1211 1417 WIDTHPROF = None
1212 1418 HEIGHTPROF = None
1213 1419 PREFIX = 'drift'
1214 1420
1215 1421 def __init__(self, **kwargs):
1216 1422 Figure.__init__(self, **kwargs)
1217 1423 self.timerange = 2*60*60
1218 1424 self.isConfig = False
1219 1425 self.__nsubplots = 1
1220 1426
1221 1427 self.WIDTH = 800
1222 1428 self.HEIGHT = 150
1223 1429 self.WIDTHPROF = 120
1224 1430 self.HEIGHTPROF = 0
1225 1431 self.counter_imagwr = 0
1226 1432
1227 1433 self.PLOT_CODE = EWDRIFT_CODE
1228 1434
1229 1435 self.FTP_WEI = None
1230 1436 self.EXP_CODE = None
1231 1437 self.SUB_EXP_CODE = None
1232 1438 self.PLOT_POS = None
1233 1439 self.tmin = None
1234 1440 self.tmax = None
1235 1441
1236 1442 self.xmin = None
1237 1443 self.xmax = None
1238 1444
1239 1445 self.figfile = None
1240 1446
1241 1447 def getSubplots(self):
1242 1448
1243 1449 ncol = 1
1244 1450 nrow = self.nplots
1245 1451
1246 1452 return nrow, ncol
1247 1453
1248 1454 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1249 1455
1250 1456 self.__showprofile = showprofile
1251 1457 self.nplots = nplots
1252 1458
1253 1459 ncolspan = 1
1254 1460 colspan = 1
1255 1461
1256 1462 self.createFigure(id = id,
1257 1463 wintitle = wintitle,
1258 1464 widthplot = self.WIDTH + self.WIDTHPROF,
1259 1465 heightplot = self.HEIGHT + self.HEIGHTPROF,
1260 1466 show=show)
1261 1467
1262 1468 nrow, ncol = self.getSubplots()
1263 1469
1264 1470 counter = 0
1265 1471 for y in range(nrow):
1266 1472 if counter >= self.nplots:
1267 1473 break
1268 1474
1269 1475 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1270 1476 counter += 1
1271 1477
1272 1478 def run(self, dataOut, id, wintitle="", channelList=None,
1273 1479 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1274 1480 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1275 1481 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1276 1482 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1277 1483 server=None, folder=None, username=None, password=None,
1278 1484 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1279 1485 """
1280 1486
1281 1487 Input:
1282 1488 dataOut :
1283 1489 id :
1284 1490 wintitle :
1285 1491 channelList :
1286 1492 showProfile :
1287 1493 xmin : None,
1288 1494 xmax : None,
1289 1495 ymin : None,
1290 1496 ymax : None,
1291 1497 zmin : None,
1292 1498 zmax : None
1293 1499 """
1294 1500
1295 1501 if timerange is not None:
1296 1502 self.timerange = timerange
1297 1503
1298 1504 tmin = None
1299 1505 tmax = None
1300 1506
1301 1507 x = dataOut.getTimeRange1(dataOut.outputInterval)
1302 1508 # y = dataOut.heightList
1303 1509 y = dataOut.heightList
1304 1510
1305 1511 z = dataOut.data_output
1306 1512 nplots = z.shape[0] #Number of wind dimensions estimated
1307 1513 nplotsw = nplots
1308 1514
1309 1515 #If there is a SNR function defined
1310 1516 if dataOut.data_SNR is not None:
1311 1517 nplots += 1
1312 1518 SNR = dataOut.data_SNR
1313 1519
1314 1520 if SNR_1:
1315 1521 SNR += 1
1316 1522
1317 1523 SNRavg = numpy.average(SNR, axis=0)
1318 1524
1319 1525 SNRdB = 10*numpy.log10(SNR)
1320 1526 SNRavgdB = 10*numpy.log10(SNRavg)
1321 1527
1322 1528 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1323 1529
1324 1530 for i in range(nplotsw):
1325 1531 z[i,ind] = numpy.nan
1326 1532
1327 1533
1328 1534 showprofile = False
1329 1535 # thisDatetime = dataOut.datatime
1330 1536 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1331 1537 title = wintitle + " EW Drifts"
1332 1538 xlabel = ""
1333 1539 ylabel = "Height (Km)"
1334 1540
1335 1541 if not self.isConfig:
1336 1542
1337 1543 self.setup(id=id,
1338 1544 nplots=nplots,
1339 1545 wintitle=wintitle,
1340 1546 showprofile=showprofile,
1341 1547 show=show)
1342 1548
1343 1549 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1344 1550
1345 1551 if ymin == None: ymin = numpy.nanmin(y)
1346 1552 if ymax == None: ymax = numpy.nanmax(y)
1347 1553
1348 1554 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1349 1555 if zminZonal == None: zminZonal = -zmaxZonal
1350 1556 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1351 1557 if zminVertical == None: zminVertical = -zmaxVertical
1352 1558
1353 1559 if dataOut.data_SNR is not None:
1354 1560 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1355 1561 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1356 1562
1357 1563 self.FTP_WEI = ftp_wei
1358 1564 self.EXP_CODE = exp_code
1359 1565 self.SUB_EXP_CODE = sub_exp_code
1360 1566 self.PLOT_POS = plot_pos
1361 1567
1362 1568 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1363 1569 self.isConfig = True
1364 1570
1365 1571
1366 1572 self.setWinTitle(title)
1367 1573
1368 1574 if ((self.xmax - x[1]) < (x[1]-x[0])):
1369 1575 x[1] = self.xmax
1370 1576
1371 1577 strWind = ['Zonal','Vertical']
1372 1578 strCb = 'Velocity (m/s)'
1373 1579 zmaxVector = [zmaxZonal, zmaxVertical]
1374 1580 zminVector = [zminZonal, zminVertical]
1375 1581
1376 1582 for i in range(nplotsw):
1377 1583
1378 1584 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1379 1585 axes = self.axesList[i*self.__nsubplots]
1380 1586
1381 1587 z1 = z[i,:].reshape((1,-1))
1382 1588
1383 1589 axes.pcolorbuffer(x, y, z1,
1384 1590 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1385 1591 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1386 1592 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1387 1593
1388 1594 if dataOut.data_SNR is not None:
1389 1595 i += 1
1390 1596 if SNR_1:
1391 1597 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1392 1598 else:
1393 1599 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1394 1600 axes = self.axesList[i*self.__nsubplots]
1395 1601 SNRavgdB = SNRavgdB.reshape((1,-1))
1396 1602
1397 1603 axes.pcolorbuffer(x, y, SNRavgdB,
1398 1604 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1399 1605 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1400 1606 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1401 1607
1402 1608 self.draw()
1403 1609
1404 1610 if x[1] >= self.axesList[0].xmax:
1405 1611 self.counter_imagwr = wr_period
1406 1612 self.isConfig = False
1407 1613 self.figfile = None
1408 1614
1409 1615
1410 1616
1411 1617
1412 1618 class PhasePlot(Figure):
1413 1619
1414 1620 __isConfig = None
1415 1621 __nsubplots = None
1416 1622
1417 1623 PREFIX = 'mphase'
1418 1624
1419 1625
1420 1626 def __init__(self, **kwargs):
1421 1627 Figure.__init__(self, **kwargs)
1422 1628 self.timerange = 24*60*60
1423 1629 self.isConfig = False
1424 1630 self.__nsubplots = 1
1425 1631 self.counter_imagwr = 0
1426 1632 self.WIDTH = 600
1427 1633 self.HEIGHT = 300
1428 1634 self.WIDTHPROF = 120
1429 1635 self.HEIGHTPROF = 0
1430 1636 self.xdata = None
1431 1637 self.ydata = None
1432 1638
1433 1639 self.PLOT_CODE = MPHASE_CODE
1434 1640
1435 1641 self.FTP_WEI = None
1436 1642 self.EXP_CODE = None
1437 1643 self.SUB_EXP_CODE = None
1438 1644 self.PLOT_POS = None
1439 1645
1440 1646
1441 1647 self.filename_phase = None
1442 1648
1443 1649 self.figfile = None
1444 1650
1445 1651 def getSubplots(self):
1446 1652
1447 1653 ncol = 1
1448 1654 nrow = 1
1449 1655
1450 1656 return nrow, ncol
1451 1657
1452 1658 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1453 1659
1454 1660 self.__showprofile = showprofile
1455 1661 self.nplots = nplots
1456 1662
1457 1663 ncolspan = 7
1458 1664 colspan = 6
1459 1665 self.__nsubplots = 2
1460 1666
1461 1667 self.createFigure(id = id,
1462 1668 wintitle = wintitle,
1463 1669 widthplot = self.WIDTH+self.WIDTHPROF,
1464 1670 heightplot = self.HEIGHT+self.HEIGHTPROF,
1465 1671 show=show)
1466 1672
1467 1673 nrow, ncol = self.getSubplots()
1468 1674
1469 1675 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1470 1676
1471 1677
1472 1678 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1473 1679 xmin=None, xmax=None, ymin=None, ymax=None,
1474 1680 timerange=None,
1475 1681 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1476 1682 server=None, folder=None, username=None, password=None,
1477 1683 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1478 1684
1479 1685
1480 1686 tmin = None
1481 1687 tmax = None
1482 1688 x = dataOut.getTimeRange1(dataOut.outputInterval)
1483 1689 y = dataOut.getHeiRange()
1484 1690
1485 1691
1486 1692 #thisDatetime = dataOut.datatime
1487 1693 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1488 1694 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1489 1695 xlabel = "Local Time"
1490 1696 ylabel = "Phase"
1491 1697
1492 1698
1493 1699 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1494 1700 phase_beacon = dataOut.data_output
1495 1701 update_figfile = False
1496 1702
1497 1703 if not self.isConfig:
1498 1704
1499 1705 self.nplots = phase_beacon.size
1500 1706
1501 1707 self.setup(id=id,
1502 1708 nplots=self.nplots,
1503 1709 wintitle=wintitle,
1504 1710 showprofile=showprofile,
1505 1711 show=show)
1506 1712
1507 1713 if timerange is not None:
1508 1714 self.timerange = timerange
1509 1715
1510 1716 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1511 1717
1512 1718 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1513 1719 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1514 1720
1515 1721 self.FTP_WEI = ftp_wei
1516 1722 self.EXP_CODE = exp_code
1517 1723 self.SUB_EXP_CODE = sub_exp_code
1518 1724 self.PLOT_POS = plot_pos
1519 1725
1520 1726 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1521 1727 self.isConfig = True
1522 1728 self.figfile = figfile
1523 1729 self.xdata = numpy.array([])
1524 1730 self.ydata = numpy.array([])
1525 1731
1526 1732 #open file beacon phase
1527 1733 path = '%s%03d' %(self.PREFIX, self.id)
1528 1734 beacon_file = os.path.join(path,'%s.txt'%self.name)
1529 1735 self.filename_phase = os.path.join(figpath,beacon_file)
1530 1736 update_figfile = True
1531 1737
1532 1738
1533 1739 #store data beacon phase
1534 1740 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1535 1741
1536 1742 self.setWinTitle(title)
1537 1743
1538 1744
1539 1745 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1540 1746
1541 1747 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1542 1748
1543 1749 axes = self.axesList[0]
1544 1750
1545 1751 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1546 1752
1547 1753 if len(self.ydata)==0:
1548 1754 self.ydata = phase_beacon.reshape(-1,1)
1549 1755 else:
1550 1756 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1551 1757
1552 1758
1553 1759 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1554 1760 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1555 1761 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1556 1762 XAxisAsTime=True, grid='both'
1557 1763 )
1558 1764
1559 1765 self.draw()
1560 1766
1561 1767 self.save(figpath=figpath,
1562 1768 figfile=figfile,
1563 1769 save=save,
1564 1770 ftp=ftp,
1565 1771 wr_period=wr_period,
1566 1772 thisDatetime=thisDatetime,
1567 1773 update_figfile=update_figfile)
1568 1774
1569 1775 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1570 1776 self.counter_imagwr = wr_period
1571 1777 self.isConfig = False
1572 1778 update_figfile = True
1573 1779
1574 1780
1575 1781
1576 1782 class NSMeteorDetection1Plot(Figure):
1577 1783
1578 1784 isConfig = None
1579 1785 __nsubplots = None
1580 1786
1581 1787 WIDTHPROF = None
1582 1788 HEIGHTPROF = None
1583 1789 PREFIX = 'nsm'
1584 1790
1585 1791 zminList = None
1586 1792 zmaxList = None
1587 1793 cmapList = None
1588 1794 titleList = None
1589 1795 nPairs = None
1590 1796 nChannels = None
1591 1797 nParam = None
1592 1798
1593 1799 def __init__(self, **kwargs):
1594 1800 Figure.__init__(self, **kwargs)
1595 1801 self.isConfig = False
1596 1802 self.__nsubplots = 1
1597 1803
1598 1804 self.WIDTH = 750
1599 1805 self.HEIGHT = 250
1600 1806 self.WIDTHPROF = 120
1601 1807 self.HEIGHTPROF = 0
1602 1808 self.counter_imagwr = 0
1603 1809
1604 1810 self.PLOT_CODE = SPEC_CODE
1605 1811
1606 1812 self.FTP_WEI = None
1607 1813 self.EXP_CODE = None
1608 1814 self.SUB_EXP_CODE = None
1609 1815 self.PLOT_POS = None
1610 1816
1611 1817 self.__xfilter_ena = False
1612 1818 self.__yfilter_ena = False
1613 1819
1614 1820 def getSubplots(self):
1615 1821
1616 1822 ncol = 3
1617 1823 nrow = int(numpy.ceil(self.nplots/3.0))
1618 1824
1619 1825 return nrow, ncol
1620 1826
1621 1827 def setup(self, id, nplots, wintitle, show=True):
1622 1828
1623 1829 self.nplots = nplots
1624 1830
1625 1831 ncolspan = 1
1626 1832 colspan = 1
1627 1833
1628 1834 self.createFigure(id = id,
1629 1835 wintitle = wintitle,
1630 1836 widthplot = self.WIDTH + self.WIDTHPROF,
1631 1837 heightplot = self.HEIGHT + self.HEIGHTPROF,
1632 1838 show=show)
1633 1839
1634 1840 nrow, ncol = self.getSubplots()
1635 1841
1636 1842 counter = 0
1637 1843 for y in range(nrow):
1638 1844 for x in range(ncol):
1639 1845
1640 1846 if counter >= self.nplots:
1641 1847 break
1642 1848
1643 1849 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1644 1850
1645 1851 counter += 1
1646 1852
1647 1853 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1648 1854 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1649 1855 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1650 1856 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1651 1857 server=None, folder=None, username=None, password=None,
1652 1858 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1653 1859 xaxis="frequency"):
1654 1860
1655 1861 """
1656 1862
1657 1863 Input:
1658 1864 dataOut :
1659 1865 id :
1660 1866 wintitle :
1661 1867 channelList :
1662 1868 showProfile :
1663 1869 xmin : None,
1664 1870 xmax : None,
1665 1871 ymin : None,
1666 1872 ymax : None,
1667 1873 zmin : None,
1668 1874 zmax : None
1669 1875 """
1670 1876 #SEPARAR EN DOS PLOTS
1671 1877 nParam = dataOut.data_param.shape[1] - 3
1672 1878
1673 1879 utctime = dataOut.data_param[0,0]
1674 1880 tmet = dataOut.data_param[:,1].astype(int)
1675 1881 hmet = dataOut.data_param[:,2].astype(int)
1676 1882
1677 1883 x = dataOut.abscissaList
1678 1884 y = dataOut.heightList
1679 1885
1680 1886 z = numpy.zeros((nParam, y.size, x.size - 1))
1681 1887 z[:,:] = numpy.nan
1682 1888 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1683 1889 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1684 1890
1685 1891 xlabel = "Time (s)"
1686 1892 ylabel = "Range (km)"
1687 1893
1688 1894 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1689 1895
1690 1896 if not self.isConfig:
1691 1897
1692 1898 nplots = nParam
1693 1899
1694 1900 self.setup(id=id,
1695 1901 nplots=nplots,
1696 1902 wintitle=wintitle,
1697 1903 show=show)
1698 1904
1699 1905 if xmin is None: xmin = numpy.nanmin(x)
1700 1906 if xmax is None: xmax = numpy.nanmax(x)
1701 1907 if ymin is None: ymin = numpy.nanmin(y)
1702 1908 if ymax is None: ymax = numpy.nanmax(y)
1703 1909 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1704 1910 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1705 1911 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1706 1912 if vmin is None: vmin = -vmax
1707 1913 if wmin is None: wmin = 0
1708 1914 if wmax is None: wmax = 50
1709 1915
1710 1916 pairsList = dataOut.groupList
1711 1917 self.nPairs = len(dataOut.groupList)
1712 1918
1713 1919 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1714 1920 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1715 1921 titleList = ["SNR","Radial Velocity","Coherence"]
1716 1922 cmapList = ["jet","RdBu_r","jet"]
1717 1923
1718 1924 for i in range(self.nPairs):
1719 1925 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1720 1926 titleList = titleList + [strAux1]
1721 1927 cmapList = cmapList + ["RdBu_r"]
1722 1928
1723 1929 self.zminList = zminList
1724 1930 self.zmaxList = zmaxList
1725 1931 self.cmapList = cmapList
1726 1932 self.titleList = titleList
1727 1933
1728 1934 self.FTP_WEI = ftp_wei
1729 1935 self.EXP_CODE = exp_code
1730 1936 self.SUB_EXP_CODE = sub_exp_code
1731 1937 self.PLOT_POS = plot_pos
1732 1938
1733 1939 self.isConfig = True
1734 1940
1735 1941 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1736 1942
1737 1943 for i in range(nParam):
1738 1944 title = self.titleList[i] + ": " +str_datetime
1739 1945 axes = self.axesList[i]
1740 1946 axes.pcolor(x, y, z[i,:].T,
1741 1947 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1742 1948 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1743 1949 self.draw()
1744 1950
1745 1951 if figfile == None:
1746 1952 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1747 1953 name = str_datetime
1748 1954 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1749 1955 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1750 1956 figfile = self.getFilename(name)
1751 1957
1752 1958 self.save(figpath=figpath,
1753 1959 figfile=figfile,
1754 1960 save=save,
1755 1961 ftp=ftp,
1756 1962 wr_period=wr_period,
1757 1963 thisDatetime=thisDatetime)
1758 1964
1759 1965
1760 1966 class NSMeteorDetection2Plot(Figure):
1761 1967
1762 1968 isConfig = None
1763 1969 __nsubplots = None
1764 1970
1765 1971 WIDTHPROF = None
1766 1972 HEIGHTPROF = None
1767 1973 PREFIX = 'nsm'
1768 1974
1769 1975 zminList = None
1770 1976 zmaxList = None
1771 1977 cmapList = None
1772 1978 titleList = None
1773 1979 nPairs = None
1774 1980 nChannels = None
1775 1981 nParam = None
1776 1982
1777 1983 def __init__(self, **kwargs):
1778 1984 Figure.__init__(self, **kwargs)
1779 1985 self.isConfig = False
1780 1986 self.__nsubplots = 1
1781 1987
1782 1988 self.WIDTH = 750
1783 1989 self.HEIGHT = 250
1784 1990 self.WIDTHPROF = 120
1785 1991 self.HEIGHTPROF = 0
1786 1992 self.counter_imagwr = 0
1787 1993
1788 1994 self.PLOT_CODE = SPEC_CODE
1789 1995
1790 1996 self.FTP_WEI = None
1791 1997 self.EXP_CODE = None
1792 1998 self.SUB_EXP_CODE = None
1793 1999 self.PLOT_POS = None
1794 2000
1795 2001 self.__xfilter_ena = False
1796 2002 self.__yfilter_ena = False
1797 2003
1798 2004 def getSubplots(self):
1799 2005
1800 2006 ncol = 3
1801 2007 nrow = int(numpy.ceil(self.nplots/3.0))
1802 2008
1803 2009 return nrow, ncol
1804 2010
1805 2011 def setup(self, id, nplots, wintitle, show=True):
1806 2012
1807 2013 self.nplots = nplots
1808 2014
1809 2015 ncolspan = 1
1810 2016 colspan = 1
1811 2017
1812 2018 self.createFigure(id = id,
1813 2019 wintitle = wintitle,
1814 2020 widthplot = self.WIDTH + self.WIDTHPROF,
1815 2021 heightplot = self.HEIGHT + self.HEIGHTPROF,
1816 2022 show=show)
1817 2023
1818 2024 nrow, ncol = self.getSubplots()
1819 2025
1820 2026 counter = 0
1821 2027 for y in range(nrow):
1822 2028 for x in range(ncol):
1823 2029
1824 2030 if counter >= self.nplots:
1825 2031 break
1826 2032
1827 2033 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1828 2034
1829 2035 counter += 1
1830 2036
1831 2037 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1832 2038 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1833 2039 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1834 2040 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1835 2041 server=None, folder=None, username=None, password=None,
1836 2042 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1837 2043 xaxis="frequency"):
1838 2044
1839 2045 """
1840 2046
1841 2047 Input:
1842 2048 dataOut :
1843 2049 id :
1844 2050 wintitle :
1845 2051 channelList :
1846 2052 showProfile :
1847 2053 xmin : None,
1848 2054 xmax : None,
1849 2055 ymin : None,
1850 2056 ymax : None,
1851 2057 zmin : None,
1852 2058 zmax : None
1853 2059 """
1854 2060 #Rebuild matrix
1855 2061 utctime = dataOut.data_param[0,0]
1856 2062 cmet = dataOut.data_param[:,1].astype(int)
1857 2063 tmet = dataOut.data_param[:,2].astype(int)
1858 2064 hmet = dataOut.data_param[:,3].astype(int)
1859 2065
1860 2066 nParam = 3
1861 2067 nChan = len(dataOut.groupList)
1862 2068 x = dataOut.abscissaList
1863 2069 y = dataOut.heightList
1864 2070
1865 2071 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
1866 2072 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
1867 2073 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
1868 2074 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
1869 2075
1870 2076 xlabel = "Time (s)"
1871 2077 ylabel = "Range (km)"
1872 2078
1873 2079 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1874 2080
1875 2081 if not self.isConfig:
1876 2082
1877 2083 nplots = nParam*nChan
1878 2084
1879 2085 self.setup(id=id,
1880 2086 nplots=nplots,
1881 2087 wintitle=wintitle,
1882 2088 show=show)
1883 2089
1884 2090 if xmin is None: xmin = numpy.nanmin(x)
1885 2091 if xmax is None: xmax = numpy.nanmax(x)
1886 2092 if ymin is None: ymin = numpy.nanmin(y)
1887 2093 if ymax is None: ymax = numpy.nanmax(y)
1888 2094 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1889 2095 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1890 2096 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1891 2097 if vmin is None: vmin = -vmax
1892 2098 if wmin is None: wmin = 0
1893 2099 if wmax is None: wmax = 50
1894 2100
1895 2101 self.nChannels = nChan
1896 2102
1897 2103 zminList = []
1898 2104 zmaxList = []
1899 2105 titleList = []
1900 2106 cmapList = []
1901 2107 for i in range(self.nChannels):
1902 2108 strAux1 = "SNR Channel "+ str(i)
1903 2109 strAux2 = "Radial Velocity Channel "+ str(i)
1904 2110 strAux3 = "Spectral Width Channel "+ str(i)
1905 2111
1906 2112 titleList = titleList + [strAux1,strAux2,strAux3]
1907 2113 cmapList = cmapList + ["jet","RdBu_r","jet"]
1908 2114 zminList = zminList + [SNRmin,vmin,wmin]
1909 2115 zmaxList = zmaxList + [SNRmax,vmax,wmax]
1910 2116
1911 2117 self.zminList = zminList
1912 2118 self.zmaxList = zmaxList
1913 2119 self.cmapList = cmapList
1914 2120 self.titleList = titleList
1915 2121
1916 2122 self.FTP_WEI = ftp_wei
1917 2123 self.EXP_CODE = exp_code
1918 2124 self.SUB_EXP_CODE = sub_exp_code
1919 2125 self.PLOT_POS = plot_pos
1920 2126
1921 2127 self.isConfig = True
1922 2128
1923 2129 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1924 2130
1925 2131 for i in range(self.nplots):
1926 2132 title = self.titleList[i] + ": " +str_datetime
1927 2133 axes = self.axesList[i]
1928 2134 axes.pcolor(x, y, z[i,:].T,
1929 2135 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1930 2136 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1931 2137 self.draw()
1932 2138
1933 2139 if figfile == None:
1934 2140 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1935 2141 name = str_datetime
1936 2142 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1937 2143 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1938 2144 figfile = self.getFilename(name)
1939 2145
1940 2146 self.save(figpath=figpath,
1941 2147 figfile=figfile,
1942 2148 save=save,
1943 2149 ftp=ftp,
1944 2150 wr_period=wr_period,
1945 2151 thisDatetime=thisDatetime)
@@ -1,1535 +1,1542
1 1 '''
2 2 Created on Jul 9, 2014
3 3
4 4 @author: roj-idl71
5 5 '''
6 6 import os
7 7 import datetime
8 8 import numpy
9 9
10 10 from figure import Figure, isRealtime, isTimeInHourRange
11 11 from plotting_codes import *
12 12
13 13
14 14 class SpectraPlot(Figure):
15 15
16 16 isConfig = None
17 17 __nsubplots = None
18 18
19 19 WIDTHPROF = None
20 20 HEIGHTPROF = None
21 21 PREFIX = 'spc'
22 22
23 23 def __init__(self, **kwargs):
24 24 Figure.__init__(self, **kwargs)
25 25 self.isConfig = False
26 26 self.__nsubplots = 1
27 27
28 28 self.WIDTH = 250
29 29 self.HEIGHT = 250
30 30 self.WIDTHPROF = 120
31 31 self.HEIGHTPROF = 0
32 32 self.counter_imagwr = 0
33 33
34 34 self.PLOT_CODE = SPEC_CODE
35 35
36 36 self.FTP_WEI = None
37 37 self.EXP_CODE = None
38 38 self.SUB_EXP_CODE = None
39 39 self.PLOT_POS = None
40 40
41 41 self.__xfilter_ena = False
42 42 self.__yfilter_ena = False
43 43
44 44 def getSubplots(self):
45 45
46 46 ncol = int(numpy.sqrt(self.nplots)+0.9)
47 47 nrow = int(self.nplots*1./ncol + 0.9)
48 48
49 49 return nrow, ncol
50 50
51 51 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
52 52
53 53 self.__showprofile = showprofile
54 54 self.nplots = nplots
55 55
56 56 ncolspan = 1
57 57 colspan = 1
58 58 if showprofile:
59 59 ncolspan = 3
60 60 colspan = 2
61 61 self.__nsubplots = 2
62 62
63 63 self.createFigure(id = id,
64 64 wintitle = wintitle,
65 65 widthplot = self.WIDTH + self.WIDTHPROF,
66 66 heightplot = self.HEIGHT + self.HEIGHTPROF,
67 67 show=show)
68 68
69 69 nrow, ncol = self.getSubplots()
70 70
71 71 counter = 0
72 72 for y in range(nrow):
73 73 for x in range(ncol):
74 74
75 75 if counter >= self.nplots:
76 76 break
77 77
78 78 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
79 79
80 80 if showprofile:
81 81 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
82 82
83 83 counter += 1
84 84
85 85 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
86 86 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
87 87 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
88 88 server=None, folder=None, username=None, password=None,
89 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 94 Input:
95 95 dataOut :
96 96 id :
97 97 wintitle :
98 98 channelList :
99 99 showProfile :
100 100 xmin : None,
101 101 xmax : None,
102 102 ymin : None,
103 103 ymax : None,
104 104 zmin : None,
105 105 zmax : None
106 106 """
107
108 colormap = kwargs.get('colormap','jet')
109
110 107 if realtime:
111 108 if not(isRealtime(utcdatatime = dataOut.utctime)):
112 109 print 'Skipping this plot function'
113 110 return
114 111
115 112 if channelList == None:
116 113 channelIndexList = dataOut.channelIndexList
117 114 else:
118 115 channelIndexList = []
119 116 for channel in channelList:
120 117 if channel not in dataOut.channelList:
121 118 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
122 119 channelIndexList.append(dataOut.channelList.index(channel))
123 120
124 factor = dataOut.normFactor
125
121 if normFactor is None:
122 factor = dataOut.normFactor
123 else:
124 factor = normFactor
126 125 if xaxis == "frequency":
127 126 x = dataOut.getFreqRange(1)/1000.
128 127 xlabel = "Frequency (kHz)"
129 128
130 129 elif xaxis == "time":
131 130 x = dataOut.getAcfRange(1)
132 131 xlabel = "Time (ms)"
133 132
134 133 else:
135 134 x = dataOut.getVelRange(1)
136 135 xlabel = "Velocity (m/s)"
137 136
138 137 ylabel = "Range (Km)"
139 138
140 139 y = dataOut.getHeiRange()
141 140
142 141 z = dataOut.data_spc/factor
143 142 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
144 143 zdB = 10*numpy.log10(z)
145 144
146 145 avg = numpy.average(z, axis=1)
147 146 avgdB = 10*numpy.log10(avg)
148 147
149 148 noise = dataOut.getNoise()/factor
150 149 noisedB = 10*numpy.log10(noise)
151 150
152 151 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
153 152 title = wintitle + " Spectra"
154 153 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
155 154 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
156 155
157 156 if not self.isConfig:
158 157
159 158 nplots = len(channelIndexList)
160 159
161 160 self.setup(id=id,
162 161 nplots=nplots,
163 162 wintitle=wintitle,
164 163 showprofile=showprofile,
165 164 show=show)
166 165
167 166 if xmin == None: xmin = numpy.nanmin(x)
168 167 if xmax == None: xmax = numpy.nanmax(x)
169 168 if ymin == None: ymin = numpy.nanmin(y)
170 169 if ymax == None: ymax = numpy.nanmax(y)
171 170 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
172 171 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
173 172
174 173 self.FTP_WEI = ftp_wei
175 174 self.EXP_CODE = exp_code
176 175 self.SUB_EXP_CODE = sub_exp_code
177 176 self.PLOT_POS = plot_pos
178 177
179 178 self.isConfig = True
180 179
181 180 self.setWinTitle(title)
182 181
183 182 for i in range(self.nplots):
184 183 index = channelIndexList[i]
185 184 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
186 185 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
187 186 if len(dataOut.beam.codeList) != 0:
188 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 189 axes = self.axesList[i*self.__nsubplots]
191 190 axes.pcolor(x, y, zdB[index,:,:],
192 191 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
193 192 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
194 193 ticksize=9, cblabel='')
195 194
196 195 if self.__showprofile:
197 196 axes = self.axesList[i*self.__nsubplots +1]
198 197 axes.pline(avgdB[index,:], y,
199 198 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
200 199 xlabel='dB', ylabel='', title='',
201 200 ytick_visible=False,
202 201 grid='x')
203 202
204 203 noiseline = numpy.repeat(noisedB[index], len(y))
205 204 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
206 205
207 206 self.draw()
208 207
209 208 if figfile == None:
210 209 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
211 210 name = str_datetime
212 211 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
213 212 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
214 213 figfile = self.getFilename(name)
215 214
216 215 self.save(figpath=figpath,
217 216 figfile=figfile,
218 217 save=save,
219 218 ftp=ftp,
220 219 wr_period=wr_period,
221 220 thisDatetime=thisDatetime)
222 221
223 222 class CrossSpectraPlot(Figure):
224 223
225 224 isConfig = None
226 225 __nsubplots = None
227 226
228 227 WIDTH = None
229 228 HEIGHT = None
230 229 WIDTHPROF = None
231 230 HEIGHTPROF = None
232 231 PREFIX = 'cspc'
233 232
234 233 def __init__(self, **kwargs):
235 234 Figure.__init__(self, **kwargs)
236 235 self.isConfig = False
237 236 self.__nsubplots = 4
238 237 self.counter_imagwr = 0
239 238 self.WIDTH = 250
240 239 self.HEIGHT = 250
241 240 self.WIDTHPROF = 0
242 241 self.HEIGHTPROF = 0
243 242
244 243 self.PLOT_CODE = CROSS_CODE
245 244 self.FTP_WEI = None
246 245 self.EXP_CODE = None
247 246 self.SUB_EXP_CODE = None
248 247 self.PLOT_POS = None
249 248
250 249 def getSubplots(self):
251 250
252 251 ncol = 4
253 252 nrow = self.nplots
254 253
255 254 return nrow, ncol
256 255
257 256 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
258 257
259 258 self.__showprofile = showprofile
260 259 self.nplots = nplots
261 260
262 261 ncolspan = 1
263 262 colspan = 1
264 263
265 264 self.createFigure(id = id,
266 265 wintitle = wintitle,
267 266 widthplot = self.WIDTH + self.WIDTHPROF,
268 267 heightplot = self.HEIGHT + self.HEIGHTPROF,
269 268 show=True)
270 269
271 270 nrow, ncol = self.getSubplots()
272 271
273 272 counter = 0
274 273 for y in range(nrow):
275 274 for x in range(ncol):
276 275 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
277 276
278 277 counter += 1
279 278
280 279 def run(self, dataOut, id, wintitle="", pairsList=None,
281 280 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
282 281 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
283 282 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
284 283 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
285 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 286 xaxis='frequency'):
288 287
289 288 """
290 289
291 290 Input:
292 291 dataOut :
293 292 id :
294 293 wintitle :
295 294 channelList :
296 295 showProfile :
297 296 xmin : None,
298 297 xmax : None,
299 298 ymin : None,
300 299 ymax : None,
301 300 zmin : None,
302 301 zmax : None
303 302 """
304 303
305 304 if pairsList == None:
306 305 pairsIndexList = dataOut.pairsIndexList
307 306 else:
308 307 pairsIndexList = []
309 308 for pair in pairsList:
310 309 if pair not in dataOut.pairsList:
311 310 raise ValueError, "Pair %s is not in dataOut.pairsList" %str(pair)
312 311 pairsIndexList.append(dataOut.pairsList.index(pair))
313 312
314 313 if not pairsIndexList:
315 314 return
316 315
317 316 if len(pairsIndexList) > 4:
318 317 pairsIndexList = pairsIndexList[0:4]
319
320 factor = dataOut.normFactor
318
319 if normFactor is None:
320 factor = dataOut.normFactor
321 else:
322 factor = normFactor
321 323 x = dataOut.getVelRange(1)
322 324 y = dataOut.getHeiRange()
323 325 z = dataOut.data_spc[:,:,:]/factor
324 326 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
325 327
326 328 noise = dataOut.noise/factor
327 329
328 330 zdB = 10*numpy.log10(z)
329 331 noisedB = 10*numpy.log10(noise)
330 332
331 333 if coh_min == None:
332 334 coh_min = 0.0
333 335 if coh_max == None:
334 336 coh_max = 1.0
335 337
336 338 if phase_min == None:
337 339 phase_min = -180
338 340 if phase_max == None:
339 341 phase_max = 180
340 342
341 343 #thisDatetime = dataOut.datatime
342 344 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
343 345 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
344 346 # xlabel = "Velocity (m/s)"
345 347 ylabel = "Range (Km)"
346 348
347 349 if xaxis == "frequency":
348 350 x = dataOut.getFreqRange(1)/1000.
349 351 xlabel = "Frequency (kHz)"
350 352
351 353 elif xaxis == "time":
352 354 x = dataOut.getAcfRange(1)
353 355 xlabel = "Time (ms)"
354 356
355 357 else:
356 358 x = dataOut.getVelRange(1)
357 359 xlabel = "Velocity (m/s)"
358 360
359 361 if not self.isConfig:
360 362
361 363 nplots = len(pairsIndexList)
362 364
363 365 self.setup(id=id,
364 366 nplots=nplots,
365 367 wintitle=wintitle,
366 368 showprofile=False,
367 369 show=show)
368 370
369 371 avg = numpy.abs(numpy.average(z, axis=1))
370 372 avgdB = 10*numpy.log10(avg)
371 373
372 374 if xmin == None: xmin = numpy.nanmin(x)
373 375 if xmax == None: xmax = numpy.nanmax(x)
374 376 if ymin == None: ymin = numpy.nanmin(y)
375 377 if ymax == None: ymax = numpy.nanmax(y)
376 378 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
377 379 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
378 380
379 381 self.FTP_WEI = ftp_wei
380 382 self.EXP_CODE = exp_code
381 383 self.SUB_EXP_CODE = sub_exp_code
382 384 self.PLOT_POS = plot_pos
383 385
384 386 self.isConfig = True
385 387
386 388 self.setWinTitle(title)
387 389
388 390 for i in range(self.nplots):
389 391 pair = dataOut.pairsList[pairsIndexList[i]]
390 392
391 393 chan_index0 = dataOut.channelList.index(pair[0])
392 394 chan_index1 = dataOut.channelList.index(pair[1])
393 395
394 396 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
395 397 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
396 398 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
397 399 axes0 = self.axesList[i*self.__nsubplots]
398 400 axes0.pcolor(x, y, zdB,
399 401 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
400 402 xlabel=xlabel, ylabel=ylabel, title=title,
401 403 ticksize=9, colormap=power_cmap, cblabel='')
402 404
403 405 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
404 406 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
405 407 axes0 = self.axesList[i*self.__nsubplots+1]
406 408 axes0.pcolor(x, y, zdB,
407 409 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
408 410 xlabel=xlabel, ylabel=ylabel, title=title,
409 411 ticksize=9, colormap=power_cmap, cblabel='')
410 412
411 413 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:])
412 414 coherence = numpy.abs(coherenceComplex)
413 415 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
414 416 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
415 417
416 418 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
417 419 axes0 = self.axesList[i*self.__nsubplots+2]
418 420 axes0.pcolor(x, y, coherence,
419 421 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
420 422 xlabel=xlabel, ylabel=ylabel, title=title,
421 423 ticksize=9, colormap=coherence_cmap, cblabel='')
422 424
423 425 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
424 426 axes0 = self.axesList[i*self.__nsubplots+3]
425 427 axes0.pcolor(x, y, phase,
426 428 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
427 429 xlabel=xlabel, ylabel=ylabel, title=title,
428 430 ticksize=9, colormap=phase_cmap, cblabel='')
429 431
430 432
431 433
432 434 self.draw()
433 435
434 436 self.save(figpath=figpath,
435 437 figfile=figfile,
436 438 save=save,
437 439 ftp=ftp,
438 440 wr_period=wr_period,
439 441 thisDatetime=thisDatetime)
440 442
441 443
442 444 class RTIPlot(Figure):
443 445
444 446 __isConfig = None
445 447 __nsubplots = None
446 448
447 449 WIDTHPROF = None
448 450 HEIGHTPROF = None
449 451 PREFIX = 'rti'
450 452
451 453 def __init__(self, **kwargs):
452 454
453 455 Figure.__init__(self, **kwargs)
454 456 self.timerange = None
455 457 self.isConfig = False
456 458 self.__nsubplots = 1
457 459
458 460 self.WIDTH = 800
459 461 self.HEIGHT = 180
460 462 self.WIDTHPROF = 120
461 463 self.HEIGHTPROF = 0
462 464 self.counter_imagwr = 0
463 465
464 466 self.PLOT_CODE = RTI_CODE
465 467
466 468 self.FTP_WEI = None
467 469 self.EXP_CODE = None
468 470 self.SUB_EXP_CODE = None
469 471 self.PLOT_POS = None
470 472 self.tmin = None
471 473 self.tmax = None
472 474
473 475 self.xmin = None
474 476 self.xmax = None
475 477
476 478 self.figfile = None
477 479
478 480 def getSubplots(self):
479 481
480 482 ncol = 1
481 483 nrow = self.nplots
482 484
483 485 return nrow, ncol
484 486
485 487 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
486 488
487 489 self.__showprofile = showprofile
488 490 self.nplots = nplots
489 491
490 492 ncolspan = 1
491 493 colspan = 1
492 494 if showprofile:
493 495 ncolspan = 7
494 496 colspan = 6
495 497 self.__nsubplots = 2
496 498
497 499 self.createFigure(id = id,
498 500 wintitle = wintitle,
499 501 widthplot = self.WIDTH + self.WIDTHPROF,
500 502 heightplot = self.HEIGHT + self.HEIGHTPROF,
501 503 show=show)
502 504
503 505 nrow, ncol = self.getSubplots()
504 506
505 507 counter = 0
506 508 for y in range(nrow):
507 509 for x in range(ncol):
508 510
509 511 if counter >= self.nplots:
510 512 break
511 513
512 514 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
513 515
514 516 if showprofile:
515 517 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
516 518
517 519 counter += 1
518 520
519 521 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
520 522 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
521 timerange=None,
523 timerange=None, colormap='jet',
522 524 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
523 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 530 Input:
529 531 dataOut :
530 532 id :
531 533 wintitle :
532 534 channelList :
533 535 showProfile :
534 536 xmin : None,
535 537 xmax : None,
536 538 ymin : None,
537 539 ymax : None,
538 540 zmin : None,
539 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 548 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
544 549 return
545 550
546 551 if channelList == None:
547 552 channelIndexList = dataOut.channelIndexList
548 553 else:
549 554 channelIndexList = []
550 555 for channel in channelList:
551 556 if channel not in dataOut.channelList:
552 557 raise ValueError, "Channel %d is not in dataOut.channelList"
553 558 channelIndexList.append(dataOut.channelList.index(channel))
554 559
555 if hasattr(dataOut, 'normFactor'):
560 if normFactor is None:
556 561 factor = dataOut.normFactor
557 562 else:
558 factor = 1
563 factor = normFactor
559 564
560 565 # factor = dataOut.normFactor
561 566 x = dataOut.getTimeRange()
562 567 y = dataOut.getHeiRange()
563 568
564 # z = dataOut.data_spc/factor
565 # z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
566 # avg = numpy.average(z, axis=1)
567 # avgdB = 10.*numpy.log10(avg)
568 avgdB = dataOut.getPower()
569 z = dataOut.data_spc/factor
570 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
571 avg = numpy.average(z, axis=1)
572 avgdB = 10.*numpy.log10(avg)
573 # avgdB = dataOut.getPower()
574
569 575
570 576 thisDatetime = dataOut.datatime
571 577 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
572 578 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
573 579 xlabel = ""
574 580 ylabel = "Range (Km)"
575 581
576 582 update_figfile = False
577 583
578 584 if dataOut.ltctime >= self.xmax:
579 585 self.counter_imagwr = wr_period
580 586 self.isConfig = False
581 587 update_figfile = True
582 588
583 589 if not self.isConfig:
584 590
585 591 nplots = len(channelIndexList)
586 592
587 593 self.setup(id=id,
588 594 nplots=nplots,
589 595 wintitle=wintitle,
590 596 showprofile=showprofile,
591 597 show=show)
592 598
593 599 if timerange != None:
594 600 self.timerange = timerange
595 601
596 602 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
597 603
598 604 noise = dataOut.noise/factor
599 605 noisedB = 10*numpy.log10(noise)
600 606
601 607 if ymin == None: ymin = numpy.nanmin(y)
602 608 if ymax == None: ymax = numpy.nanmax(y)
603 609 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
604 610 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
605 611
606 612 self.FTP_WEI = ftp_wei
607 613 self.EXP_CODE = exp_code
608 614 self.SUB_EXP_CODE = sub_exp_code
609 615 self.PLOT_POS = plot_pos
610 616
611 617 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
612 618 self.isConfig = True
613 619 self.figfile = figfile
614 620 update_figfile = True
615 621
616 622 self.setWinTitle(title)
617 623
618 624 for i in range(self.nplots):
619 625 index = channelIndexList[i]
620 626 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
621 627 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
622 628 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
623 629 axes = self.axesList[i*self.__nsubplots]
624 630 zdB = avgdB[index].reshape((1,-1))
625 631 axes.pcolorbuffer(x, y, zdB,
626 632 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
627 633 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
628 634 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
629 635
630 636 if self.__showprofile:
631 637 axes = self.axesList[i*self.__nsubplots +1]
632 638 axes.pline(avgdB[index], y,
633 639 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
634 640 xlabel='dB', ylabel='', title='',
635 641 ytick_visible=False,
636 642 grid='x')
637 643
638 644 self.draw()
639 645
640 646 self.save(figpath=figpath,
641 647 figfile=figfile,
642 648 save=save,
643 649 ftp=ftp,
644 650 wr_period=wr_period,
645 651 thisDatetime=thisDatetime,
646 652 update_figfile=update_figfile)
647 653
648 654 class CoherenceMap(Figure):
649 655 isConfig = None
650 656 __nsubplots = None
651 657
652 658 WIDTHPROF = None
653 659 HEIGHTPROF = None
654 660 PREFIX = 'cmap'
655 661
656 662 def __init__(self, **kwargs):
657 663 Figure.__init__(self, **kwargs)
658 664 self.timerange = 2*60*60
659 665 self.isConfig = False
660 666 self.__nsubplots = 1
661 667
662 668 self.WIDTH = 800
663 669 self.HEIGHT = 180
664 670 self.WIDTHPROF = 120
665 671 self.HEIGHTPROF = 0
666 672 self.counter_imagwr = 0
667 673
668 674 self.PLOT_CODE = COH_CODE
669 675
670 676 self.FTP_WEI = None
671 677 self.EXP_CODE = None
672 678 self.SUB_EXP_CODE = None
673 679 self.PLOT_POS = None
674 680 self.counter_imagwr = 0
675 681
676 682 self.xmin = None
677 683 self.xmax = None
678 684
679 685 def getSubplots(self):
680 686 ncol = 1
681 687 nrow = self.nplots*2
682 688
683 689 return nrow, ncol
684 690
685 691 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
686 692 self.__showprofile = showprofile
687 693 self.nplots = nplots
688 694
689 695 ncolspan = 1
690 696 colspan = 1
691 697 if showprofile:
692 698 ncolspan = 7
693 699 colspan = 6
694 700 self.__nsubplots = 2
695 701
696 702 self.createFigure(id = id,
697 703 wintitle = wintitle,
698 704 widthplot = self.WIDTH + self.WIDTHPROF,
699 705 heightplot = self.HEIGHT + self.HEIGHTPROF,
700 706 show=True)
701 707
702 708 nrow, ncol = self.getSubplots()
703 709
704 710 for y in range(nrow):
705 711 for x in range(ncol):
706 712
707 713 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
708 714
709 715 if showprofile:
710 716 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
711 717
712 718 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
713 719 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
714 720 timerange=None, phase_min=None, phase_max=None,
715 721 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
716 722 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
717 723 server=None, folder=None, username=None, password=None,
718 724 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
719 725
720 726 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
721 727 return
722 728
723 729 if pairsList == None:
724 730 pairsIndexList = dataOut.pairsIndexList
725 731 else:
726 732 pairsIndexList = []
727 733 for pair in pairsList:
728 734 if pair not in dataOut.pairsList:
729 735 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
730 736 pairsIndexList.append(dataOut.pairsList.index(pair))
731 737
732 738 if pairsIndexList == []:
733 739 return
734 740
735 741 if len(pairsIndexList) > 4:
736 742 pairsIndexList = pairsIndexList[0:4]
737 743
738 744 if phase_min == None:
739 745 phase_min = -180
740 746 if phase_max == None:
741 747 phase_max = 180
742 748
743 749 x = dataOut.getTimeRange()
744 750 y = dataOut.getHeiRange()
745 751
746 752 thisDatetime = dataOut.datatime
747 753
748 754 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
749 755 xlabel = ""
750 756 ylabel = "Range (Km)"
751 757 update_figfile = False
752 758
753 759 if not self.isConfig:
754 760 nplots = len(pairsIndexList)
755 761 self.setup(id=id,
756 762 nplots=nplots,
757 763 wintitle=wintitle,
758 764 showprofile=showprofile,
759 765 show=show)
760 766
761 767 if timerange != None:
762 768 self.timerange = timerange
763 769
764 770 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
765 771
766 772 if ymin == None: ymin = numpy.nanmin(y)
767 773 if ymax == None: ymax = numpy.nanmax(y)
768 774 if zmin == None: zmin = 0.
769 775 if zmax == None: zmax = 1.
770 776
771 777 self.FTP_WEI = ftp_wei
772 778 self.EXP_CODE = exp_code
773 779 self.SUB_EXP_CODE = sub_exp_code
774 780 self.PLOT_POS = plot_pos
775 781
776 782 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
777 783
778 784 self.isConfig = True
779 785 update_figfile = True
780 786
781 787 self.setWinTitle(title)
782 788
783 789 for i in range(self.nplots):
784 790
785 791 pair = dataOut.pairsList[pairsIndexList[i]]
786 792
787 793 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
788 794 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
789 795 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
790 796
791 797
792 798 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
793 799 coherence = numpy.abs(avgcoherenceComplex)
794 800
795 801 z = coherence.reshape((1,-1))
796 802
797 803 counter = 0
798 804
799 805 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
800 806 axes = self.axesList[i*self.__nsubplots*2]
801 807 axes.pcolorbuffer(x, y, z,
802 808 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
803 809 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
804 810 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
805 811
806 812 if self.__showprofile:
807 813 counter += 1
808 814 axes = self.axesList[i*self.__nsubplots*2 + counter]
809 815 axes.pline(coherence, y,
810 816 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
811 817 xlabel='', ylabel='', title='', ticksize=7,
812 818 ytick_visible=False, nxticks=5,
813 819 grid='x')
814 820
815 821 counter += 1
816 822
817 823 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
818 824
819 825 z = phase.reshape((1,-1))
820 826
821 827 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
822 828 axes = self.axesList[i*self.__nsubplots*2 + counter]
823 829 axes.pcolorbuffer(x, y, z,
824 830 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
825 831 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
826 832 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
827 833
828 834 if self.__showprofile:
829 835 counter += 1
830 836 axes = self.axesList[i*self.__nsubplots*2 + counter]
831 837 axes.pline(phase, y,
832 838 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
833 839 xlabel='', ylabel='', title='', ticksize=7,
834 840 ytick_visible=False, nxticks=4,
835 841 grid='x')
836 842
837 843 self.draw()
838 844
839 845 if dataOut.ltctime >= self.xmax:
840 846 self.counter_imagwr = wr_period
841 847 self.isConfig = False
842 848 update_figfile = True
843 849
844 850 self.save(figpath=figpath,
845 851 figfile=figfile,
846 852 save=save,
847 853 ftp=ftp,
848 854 wr_period=wr_period,
849 855 thisDatetime=thisDatetime,
850 856 update_figfile=update_figfile)
851 857
852 858 class PowerProfilePlot(Figure):
853 859
854 860 isConfig = None
855 861 __nsubplots = None
856 862
857 863 WIDTHPROF = None
858 864 HEIGHTPROF = None
859 865 PREFIX = 'spcprofile'
860 866
861 867 def __init__(self, **kwargs):
862 868 Figure.__init__(self, **kwargs)
863 869 self.isConfig = False
864 870 self.__nsubplots = 1
865 871
866 872 self.PLOT_CODE = POWER_CODE
867 873
868 874 self.WIDTH = 300
869 875 self.HEIGHT = 500
870 876 self.counter_imagwr = 0
871 877
872 878 def getSubplots(self):
873 879 ncol = 1
874 880 nrow = 1
875 881
876 882 return nrow, ncol
877 883
878 884 def setup(self, id, nplots, wintitle, show):
879 885
880 886 self.nplots = nplots
881 887
882 888 ncolspan = 1
883 889 colspan = 1
884 890
885 891 self.createFigure(id = id,
886 892 wintitle = wintitle,
887 893 widthplot = self.WIDTH,
888 894 heightplot = self.HEIGHT,
889 895 show=show)
890 896
891 897 nrow, ncol = self.getSubplots()
892 898
893 899 counter = 0
894 900 for y in range(nrow):
895 901 for x in range(ncol):
896 902 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
897 903
898 904 def run(self, dataOut, id, wintitle="", channelList=None,
899 905 xmin=None, xmax=None, ymin=None, ymax=None,
900 906 save=False, figpath='./', figfile=None, show=True,
901 907 ftp=False, wr_period=1, server=None,
902 908 folder=None, username=None, password=None):
903 909
904 910
905 911 if channelList == None:
906 912 channelIndexList = dataOut.channelIndexList
907 913 channelList = dataOut.channelList
908 914 else:
909 915 channelIndexList = []
910 916 for channel in channelList:
911 917 if channel not in dataOut.channelList:
912 918 raise ValueError, "Channel %d is not in dataOut.channelList"
913 919 channelIndexList.append(dataOut.channelList.index(channel))
914 920
915 921 factor = dataOut.normFactor
916 922
917 923 y = dataOut.getHeiRange()
918 924
919 925 #for voltage
920 926 if dataOut.type == 'Voltage':
921 927 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
922 928 x = x.real
923 929 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
924 930
925 931 #for spectra
926 932 if dataOut.type == 'Spectra':
927 933 x = dataOut.data_spc[channelIndexList,:,:]/factor
928 934 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
929 935 x = numpy.average(x, axis=1)
930 936
931 937
932 938 xdB = 10*numpy.log10(x)
933 939
934 940 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
935 941 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
936 942 xlabel = "dB"
937 943 ylabel = "Range (Km)"
938 944
939 945 if not self.isConfig:
940 946
941 947 nplots = 1
942 948
943 949 self.setup(id=id,
944 950 nplots=nplots,
945 951 wintitle=wintitle,
946 952 show=show)
947 953
948 954 if ymin == None: ymin = numpy.nanmin(y)
949 955 if ymax == None: ymax = numpy.nanmax(y)
950 956 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
951 957 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
952 958
953 959 self.isConfig = True
954 960
955 961 self.setWinTitle(title)
956 962
957 963 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
958 964 axes = self.axesList[0]
959 965
960 966 legendlabels = ["channel %d"%x for x in channelList]
961 967 axes.pmultiline(xdB, y,
962 968 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
963 969 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
964 970 ytick_visible=True, nxticks=5,
965 971 grid='x')
966 972
967 973 self.draw()
968 974
969 975 self.save(figpath=figpath,
970 976 figfile=figfile,
971 977 save=save,
972 978 ftp=ftp,
973 979 wr_period=wr_period,
974 980 thisDatetime=thisDatetime)
975 981
976 982 class SpectraCutPlot(Figure):
977 983
978 984 isConfig = None
979 985 __nsubplots = None
980 986
981 987 WIDTHPROF = None
982 988 HEIGHTPROF = None
983 989 PREFIX = 'spc_cut'
984 990
985 991 def __init__(self, **kwargs):
986 992 Figure.__init__(self, **kwargs)
987 993 self.isConfig = False
988 994 self.__nsubplots = 1
989 995
990 996 self.PLOT_CODE = POWER_CODE
991 997
992 998 self.WIDTH = 700
993 999 self.HEIGHT = 500
994 1000 self.counter_imagwr = 0
995 1001
996 1002 def getSubplots(self):
997 1003 ncol = 1
998 1004 nrow = 1
999 1005
1000 1006 return nrow, ncol
1001 1007
1002 1008 def setup(self, id, nplots, wintitle, show):
1003 1009
1004 1010 self.nplots = nplots
1005 1011
1006 1012 ncolspan = 1
1007 1013 colspan = 1
1008 1014
1009 1015 self.createFigure(id = id,
1010 1016 wintitle = wintitle,
1011 1017 widthplot = self.WIDTH,
1012 1018 heightplot = self.HEIGHT,
1013 1019 show=show)
1014 1020
1015 1021 nrow, ncol = self.getSubplots()
1016 1022
1017 1023 counter = 0
1018 1024 for y in range(nrow):
1019 1025 for x in range(ncol):
1020 1026 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1021 1027
1022 1028 def run(self, dataOut, id, wintitle="", channelList=None,
1023 1029 xmin=None, xmax=None, ymin=None, ymax=None,
1024 1030 save=False, figpath='./', figfile=None, show=True,
1025 1031 ftp=False, wr_period=1, server=None,
1026 1032 folder=None, username=None, password=None,
1027 1033 xaxis="frequency"):
1028 1034
1029 1035
1030 1036 if channelList == None:
1031 1037 channelIndexList = dataOut.channelIndexList
1032 1038 channelList = dataOut.channelList
1033 1039 else:
1034 1040 channelIndexList = []
1035 1041 for channel in channelList:
1036 1042 if channel not in dataOut.channelList:
1037 1043 raise ValueError, "Channel %d is not in dataOut.channelList"
1038 1044 channelIndexList.append(dataOut.channelList.index(channel))
1039 1045
1040 1046 factor = dataOut.normFactor
1041 1047
1042 1048 y = dataOut.getHeiRange()
1043 1049
1044 1050 z = dataOut.data_spc/factor
1045 1051 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1046 1052
1047 1053 hei_index = numpy.arange(25)*3 + 20
1048 1054
1049 1055 if xaxis == "frequency":
1050 1056 x = dataOut.getFreqRange()/1000.
1051 1057 zdB = 10*numpy.log10(z[0,:,hei_index])
1052 1058 xlabel = "Frequency (kHz)"
1053 1059 ylabel = "Power (dB)"
1054 1060
1055 1061 elif xaxis == "time":
1056 1062 x = dataOut.getAcfRange()
1057 1063 zdB = z[0,:,hei_index]
1058 1064 xlabel = "Time (ms)"
1059 1065 ylabel = "ACF"
1060 1066
1061 1067 else:
1062 1068 x = dataOut.getVelRange()
1063 1069 zdB = 10*numpy.log10(z[0,:,hei_index])
1064 1070 xlabel = "Velocity (m/s)"
1065 1071 ylabel = "Power (dB)"
1066 1072
1067 1073 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1068 1074 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1069 1075
1070 1076 if not self.isConfig:
1071 1077
1072 1078 nplots = 1
1073 1079
1074 1080 self.setup(id=id,
1075 1081 nplots=nplots,
1076 1082 wintitle=wintitle,
1077 1083 show=show)
1078 1084
1079 1085 if xmin == None: xmin = numpy.nanmin(x)*0.9
1080 1086 if xmax == None: xmax = numpy.nanmax(x)*1.1
1081 1087 if ymin == None: ymin = numpy.nanmin(zdB)
1082 1088 if ymax == None: ymax = numpy.nanmax(zdB)
1083 1089
1084 1090 self.isConfig = True
1085 1091
1086 1092 self.setWinTitle(title)
1087 1093
1088 1094 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1089 1095 axes = self.axesList[0]
1090 1096
1091 1097 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1092 1098
1093 1099 axes.pmultilineyaxis( x, zdB,
1094 1100 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1095 1101 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1096 1102 ytick_visible=True, nxticks=5,
1097 1103 grid='x')
1098 1104
1099 1105 self.draw()
1100 1106
1101 1107 self.save(figpath=figpath,
1102 1108 figfile=figfile,
1103 1109 save=save,
1104 1110 ftp=ftp,
1105 1111 wr_period=wr_period,
1106 1112 thisDatetime=thisDatetime)
1107 1113
1108 1114 class Noise(Figure):
1109 1115
1110 1116 isConfig = None
1111 1117 __nsubplots = None
1112 1118
1113 1119 PREFIX = 'noise'
1114 1120
1121
1115 1122 def __init__(self, **kwargs):
1116 1123 Figure.__init__(self, **kwargs)
1117 1124 self.timerange = 24*60*60
1118 1125 self.isConfig = False
1119 1126 self.__nsubplots = 1
1120 1127 self.counter_imagwr = 0
1121 1128 self.WIDTH = 800
1122 1129 self.HEIGHT = 400
1123 1130 self.WIDTHPROF = 120
1124 1131 self.HEIGHTPROF = 0
1125 1132 self.xdata = None
1126 1133 self.ydata = None
1127 1134
1128 1135 self.PLOT_CODE = NOISE_CODE
1129 1136
1130 1137 self.FTP_WEI = None
1131 1138 self.EXP_CODE = None
1132 1139 self.SUB_EXP_CODE = None
1133 1140 self.PLOT_POS = None
1134 1141 self.figfile = None
1135 1142
1136 1143 self.xmin = None
1137 1144 self.xmax = None
1138 1145
1139 1146 def getSubplots(self):
1140 1147
1141 1148 ncol = 1
1142 1149 nrow = 1
1143 1150
1144 1151 return nrow, ncol
1145 1152
1146 1153 def openfile(self, filename):
1147 1154 dirname = os.path.dirname(filename)
1148 1155
1149 1156 if not os.path.exists(dirname):
1150 1157 os.mkdir(dirname)
1151 1158
1152 1159 f = open(filename,'w+')
1153 1160 f.write('\n\n')
1154 1161 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1155 1162 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1156 1163 f.close()
1157 1164
1158 1165 def save_data(self, filename_phase, data, data_datetime):
1159 1166
1160 1167 f=open(filename_phase,'a')
1161 1168
1162 1169 timetuple_data = data_datetime.timetuple()
1163 1170 day = str(timetuple_data.tm_mday)
1164 1171 month = str(timetuple_data.tm_mon)
1165 1172 year = str(timetuple_data.tm_year)
1166 1173 hour = str(timetuple_data.tm_hour)
1167 1174 minute = str(timetuple_data.tm_min)
1168 1175 second = str(timetuple_data.tm_sec)
1169 1176
1170 1177 data_msg = ''
1171 1178 for i in range(len(data)):
1172 1179 data_msg += str(data[i]) + ' '
1173 1180
1174 1181 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1175 1182 f.close()
1176 1183
1177 1184
1178 1185 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1179 1186
1180 1187 self.__showprofile = showprofile
1181 1188 self.nplots = nplots
1182 1189
1183 1190 ncolspan = 7
1184 1191 colspan = 6
1185 1192 self.__nsubplots = 2
1186 1193
1187 1194 self.createFigure(id = id,
1188 1195 wintitle = wintitle,
1189 1196 widthplot = self.WIDTH+self.WIDTHPROF,
1190 1197 heightplot = self.HEIGHT+self.HEIGHTPROF,
1191 1198 show=show)
1192 1199
1193 1200 nrow, ncol = self.getSubplots()
1194 1201
1195 1202 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1196 1203
1197 1204
1198 1205 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1199 1206 xmin=None, xmax=None, ymin=None, ymax=None,
1200 1207 timerange=None,
1201 1208 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1202 1209 server=None, folder=None, username=None, password=None,
1203 1210 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1204 1211
1205 1212 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1206 1213 return
1207 1214
1208 1215 if channelList == None:
1209 1216 channelIndexList = dataOut.channelIndexList
1210 1217 channelList = dataOut.channelList
1211 1218 else:
1212 1219 channelIndexList = []
1213 1220 for channel in channelList:
1214 1221 if channel not in dataOut.channelList:
1215 1222 raise ValueError, "Channel %d is not in dataOut.channelList"
1216 1223 channelIndexList.append(dataOut.channelList.index(channel))
1217 1224
1218 1225 x = dataOut.getTimeRange()
1219 1226 #y = dataOut.getHeiRange()
1220 1227 factor = dataOut.normFactor
1221 1228 noise = dataOut.noise[channelIndexList]/factor
1222 1229 noisedB = 10*numpy.log10(noise)
1223 1230
1224 1231 thisDatetime = dataOut.datatime
1225 1232
1226 1233 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1227 1234 xlabel = ""
1228 1235 ylabel = "Intensity (dB)"
1229 1236 update_figfile = False
1230 1237
1231 1238 if not self.isConfig:
1232 1239
1233 1240 nplots = 1
1234 1241
1235 1242 self.setup(id=id,
1236 1243 nplots=nplots,
1237 1244 wintitle=wintitle,
1238 1245 showprofile=showprofile,
1239 1246 show=show)
1240 1247
1241 1248 if timerange != None:
1242 1249 self.timerange = timerange
1243 1250
1244 1251 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1245 1252
1246 1253 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1247 1254 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1248 1255
1249 1256 self.FTP_WEI = ftp_wei
1250 1257 self.EXP_CODE = exp_code
1251 1258 self.SUB_EXP_CODE = sub_exp_code
1252 1259 self.PLOT_POS = plot_pos
1253 1260
1254 1261
1255 1262 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1256 1263 self.isConfig = True
1257 1264 self.figfile = figfile
1258 1265 self.xdata = numpy.array([])
1259 1266 self.ydata = numpy.array([])
1260 1267
1261 1268 update_figfile = True
1262 1269
1263 1270 #open file beacon phase
1264 1271 path = '%s%03d' %(self.PREFIX, self.id)
1265 1272 noise_file = os.path.join(path,'%s.txt'%self.name)
1266 1273 self.filename_noise = os.path.join(figpath,noise_file)
1267 1274
1268 1275 self.setWinTitle(title)
1269 1276
1270 1277 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1271 1278
1272 1279 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1273 1280 axes = self.axesList[0]
1274 1281
1275 1282 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1276 1283
1277 1284 if len(self.ydata)==0:
1278 1285 self.ydata = noisedB.reshape(-1,1)
1279 1286 else:
1280 1287 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1281 1288
1282 1289
1283 1290 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1284 1291 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1285 1292 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1286 1293 XAxisAsTime=True, grid='both'
1287 1294 )
1288 1295
1289 1296 self.draw()
1290 1297
1291 1298 if dataOut.ltctime >= self.xmax:
1292 1299 self.counter_imagwr = wr_period
1293 1300 self.isConfig = False
1294 1301 update_figfile = True
1295 1302
1296 1303 self.save(figpath=figpath,
1297 1304 figfile=figfile,
1298 1305 save=save,
1299 1306 ftp=ftp,
1300 1307 wr_period=wr_period,
1301 1308 thisDatetime=thisDatetime,
1302 1309 update_figfile=update_figfile)
1303 1310
1304 1311 #store data beacon phase
1305 1312 if save:
1306 1313 self.save_data(self.filename_noise, noisedB, thisDatetime)
1307 1314
1308 1315 class BeaconPhase(Figure):
1309 1316
1310 1317 __isConfig = None
1311 1318 __nsubplots = None
1312 1319
1313 1320 PREFIX = 'beacon_phase'
1314 1321
1315 1322 def __init__(self, **kwargs):
1316 1323 Figure.__init__(self, **kwargs)
1317 1324 self.timerange = 24*60*60
1318 1325 self.isConfig = False
1319 1326 self.__nsubplots = 1
1320 1327 self.counter_imagwr = 0
1321 1328 self.WIDTH = 800
1322 1329 self.HEIGHT = 400
1323 1330 self.WIDTHPROF = 120
1324 1331 self.HEIGHTPROF = 0
1325 1332 self.xdata = None
1326 1333 self.ydata = None
1327 1334
1328 1335 self.PLOT_CODE = BEACON_CODE
1329 1336
1330 1337 self.FTP_WEI = None
1331 1338 self.EXP_CODE = None
1332 1339 self.SUB_EXP_CODE = None
1333 1340 self.PLOT_POS = None
1334 1341
1335 1342 self.filename_phase = None
1336 1343
1337 1344 self.figfile = None
1338 1345
1339 1346 self.xmin = None
1340 1347 self.xmax = None
1341 1348
1342 1349 def getSubplots(self):
1343 1350
1344 1351 ncol = 1
1345 1352 nrow = 1
1346 1353
1347 1354 return nrow, ncol
1348 1355
1349 1356 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1350 1357
1351 1358 self.__showprofile = showprofile
1352 1359 self.nplots = nplots
1353 1360
1354 1361 ncolspan = 7
1355 1362 colspan = 6
1356 1363 self.__nsubplots = 2
1357 1364
1358 1365 self.createFigure(id = id,
1359 1366 wintitle = wintitle,
1360 1367 widthplot = self.WIDTH+self.WIDTHPROF,
1361 1368 heightplot = self.HEIGHT+self.HEIGHTPROF,
1362 1369 show=show)
1363 1370
1364 1371 nrow, ncol = self.getSubplots()
1365 1372
1366 1373 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1367 1374
1368 1375 def save_phase(self, filename_phase):
1369 1376 f = open(filename_phase,'w+')
1370 1377 f.write('\n\n')
1371 1378 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1372 1379 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1373 1380 f.close()
1374 1381
1375 1382 def save_data(self, filename_phase, data, data_datetime):
1376 1383 f=open(filename_phase,'a')
1377 1384 timetuple_data = data_datetime.timetuple()
1378 1385 day = str(timetuple_data.tm_mday)
1379 1386 month = str(timetuple_data.tm_mon)
1380 1387 year = str(timetuple_data.tm_year)
1381 1388 hour = str(timetuple_data.tm_hour)
1382 1389 minute = str(timetuple_data.tm_min)
1383 1390 second = str(timetuple_data.tm_sec)
1384 1391 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1385 1392 f.close()
1386 1393
1387 1394
1388 1395 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1389 1396 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1390 1397 timerange=None,
1391 1398 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1392 1399 server=None, folder=None, username=None, password=None,
1393 1400 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1394 1401
1395 1402 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1396 1403 return
1397 1404
1398 1405 if pairsList == None:
1399 1406 pairsIndexList = dataOut.pairsIndexList[:10]
1400 1407 else:
1401 1408 pairsIndexList = []
1402 1409 for pair in pairsList:
1403 1410 if pair not in dataOut.pairsList:
1404 1411 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
1405 1412 pairsIndexList.append(dataOut.pairsList.index(pair))
1406 1413
1407 1414 if pairsIndexList == []:
1408 1415 return
1409 1416
1410 1417 # if len(pairsIndexList) > 4:
1411 1418 # pairsIndexList = pairsIndexList[0:4]
1412 1419
1413 1420 hmin_index = None
1414 1421 hmax_index = None
1415 1422
1416 1423 if hmin != None and hmax != None:
1417 1424 indexes = numpy.arange(dataOut.nHeights)
1418 1425 hmin_list = indexes[dataOut.heightList >= hmin]
1419 1426 hmax_list = indexes[dataOut.heightList <= hmax]
1420 1427
1421 1428 if hmin_list.any():
1422 1429 hmin_index = hmin_list[0]
1423 1430
1424 1431 if hmax_list.any():
1425 1432 hmax_index = hmax_list[-1]+1
1426 1433
1427 1434 x = dataOut.getTimeRange()
1428 1435 #y = dataOut.getHeiRange()
1429 1436
1430 1437
1431 1438 thisDatetime = dataOut.datatime
1432 1439
1433 1440 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1434 1441 xlabel = "Local Time"
1435 1442 ylabel = "Phase (degrees)"
1436 1443
1437 1444 update_figfile = False
1438 1445
1439 1446 nplots = len(pairsIndexList)
1440 1447 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1441 1448 phase_beacon = numpy.zeros(len(pairsIndexList))
1442 1449 for i in range(nplots):
1443 1450 pair = dataOut.pairsList[pairsIndexList[i]]
1444 1451 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1445 1452 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1446 1453 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1447 1454 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1448 1455 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1449 1456
1450 1457 #print "Phase %d%d" %(pair[0], pair[1])
1451 1458 #print phase[dataOut.beacon_heiIndexList]
1452 1459
1453 1460 if dataOut.beacon_heiIndexList:
1454 1461 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1455 1462 else:
1456 1463 phase_beacon[i] = numpy.average(phase)
1457 1464
1458 1465 if not self.isConfig:
1459 1466
1460 1467 nplots = len(pairsIndexList)
1461 1468
1462 1469 self.setup(id=id,
1463 1470 nplots=nplots,
1464 1471 wintitle=wintitle,
1465 1472 showprofile=showprofile,
1466 1473 show=show)
1467 1474
1468 1475 if timerange != None:
1469 1476 self.timerange = timerange
1470 1477
1471 1478 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1472 1479
1473 1480 if ymin == None: ymin = 0
1474 1481 if ymax == None: ymax = 360
1475 1482
1476 1483 self.FTP_WEI = ftp_wei
1477 1484 self.EXP_CODE = exp_code
1478 1485 self.SUB_EXP_CODE = sub_exp_code
1479 1486 self.PLOT_POS = plot_pos
1480 1487
1481 1488 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1482 1489 self.isConfig = True
1483 1490 self.figfile = figfile
1484 1491 self.xdata = numpy.array([])
1485 1492 self.ydata = numpy.array([])
1486 1493
1487 1494 update_figfile = True
1488 1495
1489 1496 #open file beacon phase
1490 1497 path = '%s%03d' %(self.PREFIX, self.id)
1491 1498 beacon_file = os.path.join(path,'%s.txt'%self.name)
1492 1499 self.filename_phase = os.path.join(figpath,beacon_file)
1493 1500 #self.save_phase(self.filename_phase)
1494 1501
1495 1502
1496 1503 #store data beacon phase
1497 1504 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1498 1505
1499 1506 self.setWinTitle(title)
1500 1507
1501 1508
1502 1509 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1503 1510
1504 1511 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1505 1512
1506 1513 axes = self.axesList[0]
1507 1514
1508 1515 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1509 1516
1510 1517 if len(self.ydata)==0:
1511 1518 self.ydata = phase_beacon.reshape(-1,1)
1512 1519 else:
1513 1520 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1514 1521
1515 1522
1516 1523 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1517 1524 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1518 1525 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1519 1526 XAxisAsTime=True, grid='both'
1520 1527 )
1521 1528
1522 1529 self.draw()
1523 1530
1524 1531 if dataOut.ltctime >= self.xmax:
1525 1532 self.counter_imagwr = wr_period
1526 1533 self.isConfig = False
1527 1534 update_figfile = True
1528 1535
1529 1536 self.save(figpath=figpath,
1530 1537 figfile=figfile,
1531 1538 save=save,
1532 1539 ftp=ftp,
1533 1540 wr_period=wr_period,
1534 1541 thisDatetime=thisDatetime,
1535 1542 update_figfile=update_figfile)
@@ -1,468 +1,481
1 1 import numpy
2 2 import datetime
3 3 import sys
4 4 import matplotlib
5 5
6 6 if 'linux' in sys.platform:
7 matplotlib.use("TKAgg")
7 matplotlib.use("GTK3Agg")
8 8
9 9 if 'darwin' in sys.platform:
10 10 matplotlib.use('TKAgg')
11 11 #Qt4Agg', 'GTK', 'GTKAgg', 'ps', 'agg', 'cairo', 'MacOSX', 'GTKCairo', 'WXAgg', 'template', 'TkAgg', 'GTK3Cairo', 'GTK3Agg', 'svg', 'WebAgg', 'CocoaAgg', 'emf', 'gdk', 'WX'
12 12 import matplotlib.pyplot
13 13
14 14 from mpl_toolkits.axes_grid1 import make_axes_locatable
15 15 from matplotlib.ticker import FuncFormatter, LinearLocator
16 16
17 17 ###########################################
18 18 #Actualizacion de las funciones del driver
19 19 ###########################################
20 20
21 21 # create jro colormap
22 22
23 23 jet_values = matplotlib.pyplot.get_cmap("jet", 100)(numpy.arange(100))[10:90]
24 24 blu_values = matplotlib.pyplot.get_cmap("seismic_r", 20)(numpy.arange(20))[10:15]
25 25 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list("jro", numpy.vstack((blu_values, jet_values)))
26 26 matplotlib.pyplot.register_cmap(cmap=ncmap)
27 27
28 28 def createFigure(id, wintitle, width, height, facecolor="w", show=True, dpi = 80):
29 29
30 30 matplotlib.pyplot.ioff()
31 31
32 32 fig = matplotlib.pyplot.figure(num=id, facecolor=facecolor, figsize=(1.0*width/dpi, 1.0*height/dpi))
33 33 fig.canvas.manager.set_window_title(wintitle)
34 34 # fig.canvas.manager.resize(width, height)
35 35 matplotlib.pyplot.ion()
36 36
37 37 if show:
38 38 matplotlib.pyplot.show()
39 39
40 40 return fig
41 41
42 42 def closeFigure(show=False, fig=None):
43 43
44 44 # matplotlib.pyplot.ioff()
45 45 # matplotlib.pyplot.pause(0)
46 46
47 47 if show:
48 48 matplotlib.pyplot.show()
49 49
50 50 if fig != None:
51 51 matplotlib.pyplot.close(fig)
52 52 # matplotlib.pyplot.pause(0)
53 53 # matplotlib.pyplot.ion()
54 54
55 55 return
56 56
57 57 matplotlib.pyplot.close("all")
58 58 # matplotlib.pyplot.pause(0)
59 59 # matplotlib.pyplot.ion()
60 60
61 61 return
62 62
63 63 def saveFigure(fig, filename):
64 64
65 65 # matplotlib.pyplot.ioff()
66 66 fig.savefig(filename, dpi=matplotlib.pyplot.gcf().dpi)
67 67 # matplotlib.pyplot.ion()
68 68
69 69 def clearFigure(fig):
70 70
71 71 fig.clf()
72 72
73 73 def setWinTitle(fig, title):
74 74
75 75 fig.canvas.manager.set_window_title(title)
76 76
77 77 def setTitle(fig, title):
78 78
79 79 fig.suptitle(title)
80 80
81 81 def createAxes(fig, nrow, ncol, xpos, ypos, colspan, rowspan, polar=False):
82 82
83 83 matplotlib.pyplot.ioff()
84 84 matplotlib.pyplot.figure(fig.number)
85 85 axes = matplotlib.pyplot.subplot2grid((nrow, ncol),
86 86 (xpos, ypos),
87 87 colspan=colspan,
88 88 rowspan=rowspan,
89 89 polar=polar)
90 90
91 axes.grid(True)
92
91 93 matplotlib.pyplot.ion()
92 94 return axes
93 95
94 96 def setAxesText(ax, text):
95 97
96 98 ax.annotate(text,
97 99 xy = (.1, .99),
98 100 xycoords = 'figure fraction',
99 101 horizontalalignment = 'left',
100 102 verticalalignment = 'top',
101 103 fontsize = 10)
102 104
103 105 def printLabels(ax, xlabel, ylabel, title):
104 106
105 107 ax.set_xlabel(xlabel, size=11)
106 108 ax.set_ylabel(ylabel, size=11)
107 109 ax.set_title(title, size=8)
108 110
109 111 def createPline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='',
110 112 ticksize=9, xtick_visible=True, ytick_visible=True,
111 113 nxticks=4, nyticks=10,
112 114 grid=None,color='blue'):
113 115
114 116 """
115 117
116 118 Input:
117 119 grid : None, 'both', 'x', 'y'
118 120 """
119 121
120 122 matplotlib.pyplot.ioff()
121 123
122 124 ax.set_xlim([xmin,xmax])
123 125 ax.set_ylim([ymin,ymax])
124 126
125 127 printLabels(ax, xlabel, ylabel, title)
126 128
127 129 ######################################################
128 130 if (xmax-xmin)<=1:
129 131 xtickspos = numpy.linspace(xmin,xmax,nxticks)
130 132 xtickspos = numpy.array([float("%.1f"%i) for i in xtickspos])
131 133 ax.set_xticks(xtickspos)
132 134 else:
133 135 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
134 136 # xtickspos = numpy.arange(nxticks)*float(xmax-xmin)/float(nxticks) + int(xmin)
135 137 ax.set_xticks(xtickspos)
136 138
137 139 for tick in ax.get_xticklabels():
138 140 tick.set_visible(xtick_visible)
139 141
140 142 for tick in ax.xaxis.get_major_ticks():
141 143 tick.label.set_fontsize(ticksize)
142 144
143 145 ######################################################
144 146 for tick in ax.get_yticklabels():
145 147 tick.set_visible(ytick_visible)
146 148
147 149 for tick in ax.yaxis.get_major_ticks():
148 150 tick.label.set_fontsize(ticksize)
149 151
150 152 ax.plot(x, y, color=color)
151 153 iplot = ax.lines[-1]
152 154
153 155 ######################################################
154 156 if '0.' in matplotlib.__version__[0:2]:
155 157 print "The matplotlib version has to be updated to 1.1 or newer"
156 158 return iplot
157 159
158 160 if '1.0.' in matplotlib.__version__[0:4]:
159 161 print "The matplotlib version has to be updated to 1.1 or newer"
160 162 return iplot
161 163
162 164 if grid != None:
163 165 ax.grid(b=True, which='major', axis=grid)
164 166
165 167 matplotlib.pyplot.tight_layout()
166 168
167 169 matplotlib.pyplot.ion()
168 170
169 171 return iplot
170 172
171 173 def set_linedata(ax, x, y, idline):
172 174
173 175 ax.lines[idline].set_data(x,y)
174 176
175 177 def pline(iplot, x, y, xlabel='', ylabel='', title=''):
176 178
177 ax = iplot.axes
179 ax = iplot.get_axes()
178 180
179 181 printLabels(ax, xlabel, ylabel, title)
180 182
181 183 set_linedata(ax, x, y, idline=0)
182 184
183 185 def addpline(ax, x, y, color, linestyle, lw):
184 186
185 187 ax.plot(x,y,color=color,linestyle=linestyle,lw=lw)
186 188
187 189
188 190 def createPcolor(ax, x, y, z, xmin, xmax, ymin, ymax, zmin, zmax,
189 191 xlabel='', ylabel='', title='', ticksize = 9,
190 192 colormap='jet',cblabel='', cbsize="5%",
191 193 XAxisAsTime=False):
192 194
193 195 matplotlib.pyplot.ioff()
194 196
195 197 divider = make_axes_locatable(ax)
196 198 ax_cb = divider.new_horizontal(size=cbsize, pad=0.05)
197 199 fig = ax.get_figure()
198 200 fig.add_axes(ax_cb)
199 201
200 202 ax.set_xlim([xmin,xmax])
201 203 ax.set_ylim([ymin,ymax])
202 204
203 205 printLabels(ax, xlabel, ylabel, title)
204 206
205 207 z = numpy.ma.masked_invalid(z)
206 208 cmap=matplotlib.pyplot.get_cmap(colormap)
207 cmap.set_bad('black', 1.)
209 cmap.set_bad('white',1.)
208 210 imesh = ax.pcolormesh(x,y,z.T, vmin=zmin, vmax=zmax, cmap=cmap)
209 211 cb = matplotlib.pyplot.colorbar(imesh, cax=ax_cb)
210 212 cb.set_label(cblabel)
211 213
212 214 # for tl in ax_cb.get_yticklabels():
213 215 # tl.set_visible(True)
214 216
215 217 for tick in ax.yaxis.get_major_ticks():
216 218 tick.label.set_fontsize(ticksize)
217 219
218 220 for tick in ax.xaxis.get_major_ticks():
219 221 tick.label.set_fontsize(ticksize)
220 222
221 223 for tick in cb.ax.get_yticklabels():
222 224 tick.set_fontsize(ticksize)
223 225
224 226 ax_cb.yaxis.tick_right()
225 227
226 228 if '0.' in matplotlib.__version__[0:2]:
227 229 print "The matplotlib version has to be updated to 1.1 or newer"
228 230 return imesh
229 231
230 232 if '1.0.' in matplotlib.__version__[0:4]:
231 233 print "The matplotlib version has to be updated to 1.1 or newer"
232 234 return imesh
233 235
234 236 matplotlib.pyplot.tight_layout()
235 237
236 238 if XAxisAsTime:
237 239
238 240 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
239 241 ax.xaxis.set_major_formatter(FuncFormatter(func))
240 242 ax.xaxis.set_major_locator(LinearLocator(7))
241 243
244 ax.grid(True)
242 245 matplotlib.pyplot.ion()
243 246 return imesh
244 247
245 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 255 z = z.T
248 ax = imesh.axes
256 ax = imesh.get_axes()
249 257 printLabels(ax, xlabel, ylabel, title)
250 258 imesh.set_array(z.ravel())
259 ax.grid(True)
260
251 261
252 262 def addpcolor(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
253 263
254 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 268 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
269 ax.grid(True)
257 270
258 271 def addpcolorbuffer(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
259 272
260 273 printLabels(ax, xlabel, ylabel, title)
261 274
262 275 ax.collections.remove(ax.collections[0])
263 276
264 277 z = numpy.ma.masked_invalid(z)
265
278
266 279 cmap=matplotlib.pyplot.get_cmap(colormap)
267 cmap.set_bad('black', 1.)
268
280 cmap.set_bad('white',1.)
269 281
270 282 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=cmap)
283 ax.grid(True)
284
271 285
272 286 def createPmultiline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
273 287 ticksize=9, xtick_visible=True, ytick_visible=True,
274 288 nxticks=4, nyticks=10,
275 289 grid=None):
276 290
277 291 """
278 292
279 293 Input:
280 294 grid : None, 'both', 'x', 'y'
281 295 """
282 296
283 297 matplotlib.pyplot.ioff()
284 298
285 299 lines = ax.plot(x.T, y)
286 300 leg = ax.legend(lines, legendlabels, loc='upper right')
287 301 leg.get_frame().set_alpha(0.5)
288 302 ax.set_xlim([xmin,xmax])
289 303 ax.set_ylim([ymin,ymax])
290 304 printLabels(ax, xlabel, ylabel, title)
291 305
292 306 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
293 307 ax.set_xticks(xtickspos)
294 308
295 309 for tick in ax.get_xticklabels():
296 310 tick.set_visible(xtick_visible)
297 311
298 312 for tick in ax.xaxis.get_major_ticks():
299 313 tick.label.set_fontsize(ticksize)
300 314
301 315 for tick in ax.get_yticklabels():
302 316 tick.set_visible(ytick_visible)
303 317
304 318 for tick in ax.yaxis.get_major_ticks():
305 319 tick.label.set_fontsize(ticksize)
306 320
307 321 iplot = ax.lines[-1]
308 322
309 323 if '0.' in matplotlib.__version__[0:2]:
310 324 print "The matplotlib version has to be updated to 1.1 or newer"
311 325 return iplot
312 326
313 327 if '1.0.' in matplotlib.__version__[0:4]:
314 328 print "The matplotlib version has to be updated to 1.1 or newer"
315 329 return iplot
316 330
317 331 if grid != None:
318 332 ax.grid(b=True, which='major', axis=grid)
319 333
320 334 matplotlib.pyplot.tight_layout()
321 335
322 336 matplotlib.pyplot.ion()
323 337
324 338 return iplot
325 339
326 340
327 341 def pmultiline(iplot, x, y, xlabel='', ylabel='', title=''):
328 342
329 ax = iplot.axes
343 ax = iplot.get_axes()
330 344
331 345 printLabels(ax, xlabel, ylabel, title)
332 346
333 347 for i in range(len(ax.lines)):
334 348 line = ax.lines[i]
335 349 line.set_data(x[i,:],y)
336 350
337 351 def createPmultilineYAxis(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
338 352 ticksize=9, xtick_visible=True, ytick_visible=True,
339 353 nxticks=4, nyticks=10, marker='.', markersize=10, linestyle="None",
340 354 grid=None, XAxisAsTime=False):
341 355
342 356 """
343 357
344 358 Input:
345 359 grid : None, 'both', 'x', 'y'
346 360 """
347 361
348 362 matplotlib.pyplot.ioff()
349 363
350 364 # lines = ax.plot(x, y.T, marker=marker,markersize=markersize,linestyle=linestyle)
351 365 lines = ax.plot(x, y.T)
352 366 # leg = ax.legend(lines, legendlabels, loc=2, bbox_to_anchor=(1.01, 1.00), numpoints=1, handlelength=1.5, \
353 367 # handletextpad=0.5, borderpad=0.5, labelspacing=0.5, borderaxespad=0.)
354 368
355 369 leg = ax.legend(lines, legendlabels,
356 370 loc='upper right', bbox_to_anchor=(1.16, 1), borderaxespad=0)
357 371
358 372 for label in leg.get_texts(): label.set_fontsize(9)
359 373
360 374 ax.set_xlim([xmin,xmax])
361 375 ax.set_ylim([ymin,ymax])
362 376 printLabels(ax, xlabel, ylabel, title)
363 377
364 378 # xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
365 379 # ax.set_xticks(xtickspos)
366 380
367 381 for tick in ax.get_xticklabels():
368 382 tick.set_visible(xtick_visible)
369 383
370 384 for tick in ax.xaxis.get_major_ticks():
371 385 tick.label.set_fontsize(ticksize)
372 386
373 387 for tick in ax.get_yticklabels():
374 388 tick.set_visible(ytick_visible)
375 389
376 390 for tick in ax.yaxis.get_major_ticks():
377 391 tick.label.set_fontsize(ticksize)
378 392
379 393 iplot = ax.lines[-1]
380 394
381 395 if '0.' in matplotlib.__version__[0:2]:
382 396 print "The matplotlib version has to be updated to 1.1 or newer"
383 397 return iplot
384 398
385 399 if '1.0.' in matplotlib.__version__[0:4]:
386 400 print "The matplotlib version has to be updated to 1.1 or newer"
387 401 return iplot
388 402
389 403 if grid != None:
390 404 ax.grid(b=True, which='major', axis=grid)
391 405
392 406 matplotlib.pyplot.tight_layout()
393 407
394 408 if XAxisAsTime:
395 409
396 410 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
397 411 ax.xaxis.set_major_formatter(FuncFormatter(func))
398 412 ax.xaxis.set_major_locator(LinearLocator(7))
399 413
400 414 matplotlib.pyplot.ion()
401 415
402 416 return iplot
403 417
404 418 def pmultilineyaxis(iplot, x, y, xlabel='', ylabel='', title=''):
405 419
406 ax = iplot.axes
407
420 ax = iplot.get_axes()
408 421 printLabels(ax, xlabel, ylabel, title)
409 422
410 423 for i in range(len(ax.lines)):
411 424 line = ax.lines[i]
412 425 line.set_data(x,y[i,:])
413 426
414 427 def createPolar(ax, x, y,
415 428 xlabel='', ylabel='', title='', ticksize = 9,
416 429 colormap='jet',cblabel='', cbsize="5%",
417 430 XAxisAsTime=False):
418 431
419 432 matplotlib.pyplot.ioff()
420 433
421 434 ax.plot(x,y,'bo', markersize=5)
422 435 # ax.set_rmax(90)
423 436 ax.set_ylim(0,90)
424 437 ax.set_yticks(numpy.arange(0,90,20))
425 438 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center' ,size='11')
426 439 # ax.text(0, 50, ylabel, rotation='vertical', va ='center', ha = 'left' ,size='11')
427 440 # ax.text(100, 100, 'example', ha='left', va='center', rotation='vertical')
428 ax.yaxis.labelpad = 40
441 ax.yaxis.labelpad = 230
429 442 printLabels(ax, xlabel, ylabel, title)
430 443 iplot = ax.lines[-1]
431 444
432 445 if '0.' in matplotlib.__version__[0:2]:
433 446 print "The matplotlib version has to be updated to 1.1 or newer"
434 447 return iplot
435 448
436 449 if '1.0.' in matplotlib.__version__[0:4]:
437 450 print "The matplotlib version has to be updated to 1.1 or newer"
438 451 return iplot
439 452
440 453 # if grid != None:
441 454 # ax.grid(b=True, which='major', axis=grid)
442 455
443 456 matplotlib.pyplot.tight_layout()
444 457
445 458 matplotlib.pyplot.ion()
446 459
447 460
448 461 return iplot
449 462
450 463 def polar(iplot, x, y, xlabel='', ylabel='', title=''):
451 464
452 ax = iplot.axes
465 ax = iplot.get_axes()
453 466
454 467 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center',size='11')
455 468 printLabels(ax, xlabel, ylabel, title)
456 469
457 470 set_linedata(ax, x, y, idline=0)
458 471
459 472 def draw(fig):
460 473
461 474 if type(fig) == 'int':
462 475 raise ValueError, "Error drawing: Fig parameter should be a matplotlib figure object figure"
463 476
464 477 fig.canvas.draw()
465 478
466 479 def pause(interval=0.000001):
467 480
468 481 matplotlib.pyplot.pause(interval)
@@ -1,14 +1,20
1 1 '''
2 2
3 3 $Author: murco $
4 4 $Id: JRODataIO.py 169 2012-11-19 21:57:03Z murco $
5 5 '''
6 6
7 7 from jroIO_voltage import *
8 8 from jroIO_spectra import *
9 9 from jroIO_heispectra import *
10 10 from jroIO_usrp import *
11 11
12 12 from jroIO_kamisr import *
13 13 from jroIO_param import *
14 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 2 Created on Jul 2, 2014
3 3
4 4 @author: roj-idl71
5 5 '''
6 6 import os
7 7 import sys
8 8 import glob
9 9 import time
10 10 import numpy
11 11 import fnmatch
12 12 import inspect
13 13 import time, datetime
14 14 import traceback
15 15 import zmq
16 16
17 17 try:
18 18 from gevent import sleep
19 19 except:
20 20 from time import sleep
21 21
22 22 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
23 23 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
24 24
25 25 LOCALTIME = True
26 26
27 27 def isNumber(cad):
28 28 """
29 29 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
30 30
31 31 Excepciones:
32 32 Si un determinado string no puede ser convertido a numero
33 33 Input:
34 34 str, string al cual se le analiza para determinar si convertible a un numero o no
35 35
36 36 Return:
37 37 True : si el string es uno numerico
38 38 False : no es un string numerico
39 39 """
40 40 try:
41 41 float( cad )
42 42 return True
43 43 except:
44 44 return False
45 45
46 46 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
47 47 """
48 48 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
49 49
50 50 Inputs:
51 51 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
52 52
53 53 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
54 54 segundos contados desde 01/01/1970.
55 55 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
56 56 segundos contados desde 01/01/1970.
57 57
58 58 Return:
59 59 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
60 60 fecha especificado, de lo contrario retorna False.
61 61
62 62 Excepciones:
63 63 Si el archivo no existe o no puede ser abierto
64 64 Si la cabecera no puede ser leida.
65 65
66 66 """
67 67 basicHeaderObj = BasicHeader(LOCALTIME)
68 68
69 69 try:
70 70 fp = open(filename,'rb')
71 71 except IOError:
72 72 print "The file %s can't be opened" %(filename)
73 73 return 0
74 74
75 75 sts = basicHeaderObj.read(fp)
76 76 fp.close()
77 77
78 78 if not(sts):
79 79 print "Skipping the file %s because it has not a valid header" %(filename)
80 80 return 0
81 81
82 82 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
83 83 return 0
84 84
85 85 return 1
86 86
87 87 def isTimeInRange(thisTime, startTime, endTime):
88 88
89 89 if endTime >= startTime:
90 90 if (thisTime < startTime) or (thisTime > endTime):
91 91 return 0
92 92
93 93 return 1
94 94 else:
95 95 if (thisTime < startTime) and (thisTime > endTime):
96 96 return 0
97 97
98 98 return 1
99 99
100 100 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
101 101 """
102 102 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
103 103
104 104 Inputs:
105 105 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
106 106
107 107 startDate : fecha inicial del rango seleccionado en formato datetime.date
108 108
109 109 endDate : fecha final del rango seleccionado en formato datetime.date
110 110
111 111 startTime : tiempo inicial del rango seleccionado en formato datetime.time
112 112
113 113 endTime : tiempo final del rango seleccionado en formato datetime.time
114 114
115 115 Return:
116 116 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
117 117 fecha especificado, de lo contrario retorna False.
118 118
119 119 Excepciones:
120 120 Si el archivo no existe o no puede ser abierto
121 121 Si la cabecera no puede ser leida.
122 122
123 123 """
124 124
125 125
126 126 try:
127 127 fp = open(filename,'rb')
128 128 except IOError:
129 129 print "The file %s can't be opened" %(filename)
130 130 return None
131 131
132 132 firstBasicHeaderObj = BasicHeader(LOCALTIME)
133 133 systemHeaderObj = SystemHeader()
134 134 radarControllerHeaderObj = RadarControllerHeader()
135 135 processingHeaderObj = ProcessingHeader()
136 136
137 137 lastBasicHeaderObj = BasicHeader(LOCALTIME)
138 138
139 139 sts = firstBasicHeaderObj.read(fp)
140 140
141 141 if not(sts):
142 142 print "[Reading] Skipping the file %s because it has not a valid header" %(filename)
143 143 return None
144 144
145 145 if not systemHeaderObj.read(fp):
146 146 return None
147 147
148 148 if not radarControllerHeaderObj.read(fp):
149 149 return None
150 150
151 151 if not processingHeaderObj.read(fp):
152 152 return None
153 153
154 154 filesize = os.path.getsize(filename)
155 155
156 156 offset = processingHeaderObj.blockSize + 24 #header size
157 157
158 158 if filesize <= offset:
159 159 print "[Reading] %s: This file has not enough data" %filename
160 160 return None
161 161
162 162 fp.seek(-offset, 2)
163 163
164 164 sts = lastBasicHeaderObj.read(fp)
165 165
166 166 fp.close()
167 167
168 168 thisDatetime = lastBasicHeaderObj.datatime
169 169 thisTime_last_block = thisDatetime.time()
170 170
171 171 thisDatetime = firstBasicHeaderObj.datatime
172 172 thisDate = thisDatetime.date()
173 173 thisTime_first_block = thisDatetime.time()
174 174
175 175 #General case
176 176 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
177 177 #-----------o----------------------------o-----------
178 178 # startTime endTime
179 179
180 180 if endTime >= startTime:
181 181 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
182 182 return None
183 183
184 184 return thisDatetime
185 185
186 186 #If endTime < startTime then endTime belongs to the next day
187 187
188 188
189 189 #<<<<<<<<<<<o o>>>>>>>>>>>
190 190 #-----------o----------------------------o-----------
191 191 # endTime startTime
192 192
193 193 if (thisDate == startDate) and (thisTime_last_block < startTime):
194 194 return None
195 195
196 196 if (thisDate == endDate) and (thisTime_first_block > endTime):
197 197 return None
198 198
199 199 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
200 200 return None
201 201
202 202 return thisDatetime
203 203
204 204 def isFolderInDateRange(folder, startDate=None, endDate=None):
205 205 """
206 206 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
207 207
208 208 Inputs:
209 209 folder : nombre completo del directorio.
210 210 Su formato deberia ser "/path_root/?YYYYDDD"
211 211
212 212 siendo:
213 213 YYYY : Anio (ejemplo 2015)
214 214 DDD : Dia del anio (ejemplo 305)
215 215
216 216 startDate : fecha inicial del rango seleccionado en formato datetime.date
217 217
218 218 endDate : fecha final del rango seleccionado en formato datetime.date
219 219
220 220 Return:
221 221 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
222 222 fecha especificado, de lo contrario retorna False.
223 223 Excepciones:
224 224 Si el directorio no tiene el formato adecuado
225 225 """
226 226
227 227 basename = os.path.basename(folder)
228 228
229 229 if not isRadarFolder(basename):
230 230 print "The folder %s has not the rigth format" %folder
231 231 return 0
232 232
233 233 if startDate and endDate:
234 234 thisDate = getDateFromRadarFolder(basename)
235 235
236 236 if thisDate < startDate:
237 237 return 0
238 238
239 239 if thisDate > endDate:
240 240 return 0
241 241
242 242 return 1
243 243
244 244 def isFileInDateRange(filename, startDate=None, endDate=None):
245 245 """
246 246 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
247 247
248 248 Inputs:
249 249 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
250 250
251 251 Su formato deberia ser "?YYYYDDDsss"
252 252
253 253 siendo:
254 254 YYYY : Anio (ejemplo 2015)
255 255 DDD : Dia del anio (ejemplo 305)
256 256 sss : set
257 257
258 258 startDate : fecha inicial del rango seleccionado en formato datetime.date
259 259
260 260 endDate : fecha final del rango seleccionado en formato datetime.date
261 261
262 262 Return:
263 263 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
264 264 fecha especificado, de lo contrario retorna False.
265 265 Excepciones:
266 266 Si el archivo no tiene el formato adecuado
267 267 """
268 268
269 269 basename = os.path.basename(filename)
270 270
271 271 if not isRadarFile(basename):
272 272 print "The filename %s has not the rigth format" %filename
273 273 return 0
274 274
275 275 if startDate and endDate:
276 276 thisDate = getDateFromRadarFile(basename)
277 277
278 278 if thisDate < startDate:
279 279 return 0
280 280
281 281 if thisDate > endDate:
282 282 return 0
283 283
284 284 return 1
285 285
286 286 def getFileFromSet(path, ext, set):
287 287 validFilelist = []
288 288 fileList = os.listdir(path)
289 289
290 290 # 0 1234 567 89A BCDE
291 291 # H YYYY DDD SSS .ext
292 292
293 293 for thisFile in fileList:
294 294 try:
295 295 year = int(thisFile[1:5])
296 296 doy = int(thisFile[5:8])
297 297 except:
298 298 continue
299 299
300 300 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
301 301 continue
302 302
303 303 validFilelist.append(thisFile)
304 304
305 305 myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set))
306 306
307 307 if len(myfile)!= 0:
308 308 return myfile[0]
309 309 else:
310 310 filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower())
311 311 print 'the filename %s does not exist'%filename
312 312 print '...going to the last file: '
313 313
314 314 if validFilelist:
315 315 validFilelist = sorted( validFilelist, key=str.lower )
316 316 return validFilelist[-1]
317 317
318 318 return None
319 319
320 320 def getlastFileFromPath(path, ext):
321 321 """
322 322 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
323 323 al final de la depuracion devuelve el ultimo file de la lista que quedo.
324 324
325 325 Input:
326 326 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
327 327 ext : extension de los files contenidos en una carpeta
328 328
329 329 Return:
330 330 El ultimo file de una determinada carpeta, no se considera el path.
331 331 """
332 332 validFilelist = []
333 333 fileList = os.listdir(path)
334 334
335 335 # 0 1234 567 89A BCDE
336 336 # H YYYY DDD SSS .ext
337 337
338 338 for thisFile in fileList:
339 339
340 340 year = thisFile[1:5]
341 341 if not isNumber(year):
342 342 continue
343 343
344 344 doy = thisFile[5:8]
345 345 if not isNumber(doy):
346 346 continue
347 347
348 348 year = int(year)
349 349 doy = int(doy)
350 350
351 351 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
352 352 continue
353 353
354 354 validFilelist.append(thisFile)
355 355
356 356 if validFilelist:
357 357 validFilelist = sorted( validFilelist, key=str.lower )
358 358 return validFilelist[-1]
359 359
360 360 return None
361 361
362 362 def checkForRealPath(path, foldercounter, year, doy, set, ext):
363 363 """
364 364 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
365 365 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
366 366 el path exacto de un determinado file.
367 367
368 368 Example :
369 369 nombre correcto del file es .../.../D2009307/P2009307367.ext
370 370
371 371 Entonces la funcion prueba con las siguientes combinaciones
372 372 .../.../y2009307367.ext
373 373 .../.../Y2009307367.ext
374 374 .../.../x2009307/y2009307367.ext
375 375 .../.../x2009307/Y2009307367.ext
376 376 .../.../X2009307/y2009307367.ext
377 377 .../.../X2009307/Y2009307367.ext
378 378 siendo para este caso, la ultima combinacion de letras, identica al file buscado
379 379
380 380 Return:
381 381 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
382 382 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
383 383 para el filename
384 384 """
385 385 fullfilename = None
386 386 find_flag = False
387 387 filename = None
388 388
389 389 prefixDirList = [None,'d','D']
390 390 if ext.lower() == ".r": #voltage
391 391 prefixFileList = ['d','D']
392 392 elif ext.lower() == ".pdata": #spectra
393 393 prefixFileList = ['p','P']
394 394 else:
395 395 return None, filename
396 396
397 397 #barrido por las combinaciones posibles
398 398 for prefixDir in prefixDirList:
399 399 thispath = path
400 400 if prefixDir != None:
401 401 #formo el nombre del directorio xYYYYDDD (x=d o x=D)
402 402 if foldercounter == 0:
403 403 thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy ))
404 404 else:
405 405 thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter))
406 406 for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D"
407 407 filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
408 408 fullfilename = os.path.join( thispath, filename ) #formo el path completo
409 409
410 410 if os.path.exists( fullfilename ): #verifico que exista
411 411 find_flag = True
412 412 break
413 413 if find_flag:
414 414 break
415 415
416 416 if not(find_flag):
417 417 return None, filename
418 418
419 419 return fullfilename, filename
420 420
421 421 def isRadarFolder(folder):
422 422 try:
423 423 year = int(folder[1:5])
424 424 doy = int(folder[5:8])
425 425 except:
426 426 return 0
427 427
428 428 return 1
429 429
430 430 def isRadarFile(file):
431 431 try:
432 432 year = int(file[1:5])
433 433 doy = int(file[5:8])
434 434 set = int(file[8:11])
435 435 except:
436 436 return 0
437 437
438 438 return 1
439 439
440 440 def getDateFromRadarFile(file):
441 441 try:
442 442 year = int(file[1:5])
443 443 doy = int(file[5:8])
444 444 set = int(file[8:11])
445 445 except:
446 446 return None
447 447
448 448 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
449 449 return thisDate
450 450
451 451 def getDateFromRadarFolder(folder):
452 452 try:
453 453 year = int(folder[1:5])
454 454 doy = int(folder[5:8])
455 455 except:
456 456 return None
457 457
458 458 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
459 459 return thisDate
460 460
461 461 class JRODataIO:
462 462
463 463 c = 3E8
464 464
465 465 isConfig = False
466 466
467 467 basicHeaderObj = None
468 468
469 469 systemHeaderObj = None
470 470
471 471 radarControllerHeaderObj = None
472 472
473 473 processingHeaderObj = None
474 474
475 475 dtype = None
476 476
477 477 pathList = []
478 478
479 479 filenameList = []
480 480
481 481 filename = None
482 482
483 483 ext = None
484 484
485 485 flagIsNewFile = 1
486 486
487 487 flagDiscontinuousBlock = 0
488 488
489 489 flagIsNewBlock = 0
490 490
491 491 fp = None
492 492
493 493 firstHeaderSize = 0
494 494
495 495 basicHeaderSize = 24
496 496
497 497 versionFile = 1103
498 498
499 499 fileSize = None
500 500
501 501 # ippSeconds = None
502 502
503 503 fileSizeByHeader = None
504 504
505 505 fileIndex = None
506 506
507 507 profileIndex = None
508 508
509 509 blockIndex = None
510 510
511 511 nTotalBlocks = None
512 512
513 513 maxTimeStep = 30
514 514
515 515 lastUTTime = None
516 516
517 517 datablock = None
518 518
519 519 dataOut = None
520 520
521 521 blocksize = None
522 522
523 523 getByBlock = False
524 524
525 525 def __init__(self):
526 526
527 527 raise NotImplementedError
528 528
529 529 def run(self):
530 530
531 531 raise NotImplementedError
532 532
533 533 def getDtypeWidth(self):
534 534
535 535 dtype_index = get_dtype_index(self.dtype)
536 536 dtype_width = get_dtype_width(dtype_index)
537 537
538 538 return dtype_width
539 539
540 540 def getAllowedArgs(self):
541 541 return inspect.getargspec(self.run).args
542 542
543 543 class JRODataReader(JRODataIO):
544 544
545 545 online = 0
546 546
547 547 realtime = 0
548 548
549 549 nReadBlocks = 0
550 550
551 551 delay = 10 #number of seconds waiting a new file
552 552
553 553 nTries = 3 #quantity tries
554 554
555 555 nFiles = 3 #number of files for searching
556 556
557 557 path = None
558 558
559 559 foldercounter = 0
560 560
561 561 flagNoMoreFiles = 0
562 562
563 563 datetimeList = []
564 564
565 565 __isFirstTimeOnline = 1
566 566
567 567 __printInfo = True
568 568
569 569 profileIndex = None
570 570
571 571 nTxs = 1
572 572
573 573 txIndex = None
574 574
575 575 #Added--------------------
576 576
577 577 selBlocksize = None
578 578
579 579 selBlocktime = None
580 580
581 581 def __init__(self):
582 582
583 583 """
584 584 This class is used to find data files
585 585
586 586 Example:
587 587 reader = JRODataReader()
588 588 fileList = reader.findDataFiles()
589 589
590 590 """
591 591 pass
592 592
593 593
594 594 def createObjByDefault(self):
595 595 """
596 596
597 597 """
598 598 raise NotImplementedError
599 599
600 600 def getBlockDimension(self):
601 601
602 602 raise NotImplementedError
603 603
604 604 def searchFilesOffLine(self,
605 605 path,
606 606 startDate=None,
607 607 endDate=None,
608 608 startTime=datetime.time(0,0,0),
609 609 endTime=datetime.time(23,59,59),
610 610 set=None,
611 611 expLabel='',
612 612 ext='.r',
613 613 cursor=None,
614 614 skip=None,
615 615 walk=True):
616 616
617 617 self.filenameList = []
618 618 self.datetimeList = []
619 619
620 620 pathList = []
621 621
622 622 dateList, pathList = self.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
623 623
624 624 if dateList == []:
625 625 return [], []
626 626
627 627 if len(dateList) > 1:
628 628 print "[Reading] Data found for date range [%s - %s]: total days = %d" %(startDate, endDate, len(dateList))
629 629 else:
630 630 print "[Reading] Data found for date range [%s - %s]: date = %s" %(startDate, endDate, dateList[0])
631 631
632 632 filenameList = []
633 633 datetimeList = []
634 634
635 635 for thisPath in pathList:
636 636
637 637 fileList = glob.glob1(thisPath, "*%s" %ext)
638 638 fileList.sort()
639 639
640 640 skippedFileList = []
641 641
642 642 if cursor is not None and skip is not None:
643 643
644 644 if skip == 0:
645 645 skippedFileList = []
646 646 else:
647 647 skippedFileList = fileList[cursor*skip: cursor*skip + skip]
648 648
649 649 else:
650 650 skippedFileList = fileList
651 651
652 652 for file in skippedFileList:
653 653
654 654 filename = os.path.join(thisPath,file)
655 655
656 656 if not isFileInDateRange(filename, startDate, endDate):
657 657 continue
658 658
659 659 thisDatetime = isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
660 660
661 661 if not(thisDatetime):
662 662 continue
663 663
664 664 filenameList.append(filename)
665 665 datetimeList.append(thisDatetime)
666 666
667 667 if not(filenameList):
668 668 print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" %(startTime, endTime, ext, path)
669 669 return [], []
670 670
671 671 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
672 672 print
673 673
674 674 # for i in range(len(filenameList)):
675 675 # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
676 676
677 677 self.filenameList = filenameList
678 678 self.datetimeList = datetimeList
679 679
680 680 return pathList, filenameList
681 681
682 682 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
683 683
684 684 """
685 685 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
686 686 devuelve el archivo encontrado ademas de otros datos.
687 687
688 688 Input:
689 689 path : carpeta donde estan contenidos los files que contiene data
690 690
691 691 expLabel : Nombre del subexperimento (subfolder)
692 692
693 693 ext : extension de los files
694 694
695 695 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
696 696
697 697 Return:
698 698 directory : eL directorio donde esta el file encontrado
699 699 filename : el ultimo file de una determinada carpeta
700 700 year : el anho
701 701 doy : el numero de dia del anho
702 702 set : el set del archivo
703 703
704 704
705 705 """
706 706 if not os.path.isdir(path):
707 707 return None, None, None, None, None, None
708 708
709 709 dirList = []
710 710
711 711 if not walk:
712 712 fullpath = path
713 713 foldercounter = 0
714 714 else:
715 715 #Filtra solo los directorios
716 716 for thisPath in os.listdir(path):
717 717 if not os.path.isdir(os.path.join(path,thisPath)):
718 718 continue
719 719 if not isRadarFolder(thisPath):
720 720 continue
721 721
722 722 dirList.append(thisPath)
723 723
724 724 if not(dirList):
725 725 return None, None, None, None, None, None
726 726
727 727 dirList = sorted( dirList, key=str.lower )
728 728
729 729 doypath = dirList[-1]
730 730 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
731 731 fullpath = os.path.join(path, doypath, expLabel)
732 732
733 733
734 734 print "[Reading] %s folder was found: " %(fullpath )
735 735
736 736 if set == None:
737 737 filename = getlastFileFromPath(fullpath, ext)
738 738 else:
739 739 filename = getFileFromSet(fullpath, ext, set)
740 740
741 741 if not(filename):
742 742 return None, None, None, None, None, None
743 743
744 744 print "[Reading] %s file was found" %(filename)
745 745
746 746 if not(self.__verifyFile(os.path.join(fullpath, filename))):
747 747 return None, None, None, None, None, None
748 748
749 749 year = int( filename[1:5] )
750 750 doy = int( filename[5:8] )
751 751 set = int( filename[8:11] )
752 752
753 753 return fullpath, foldercounter, filename, year, doy, set
754 754
755 755 def __setNextFileOffline(self):
756 756
757 757 idFile = self.fileIndex
758 758
759 759 while (True):
760 760 idFile += 1
761 761 if not(idFile < len(self.filenameList)):
762 762 self.flagNoMoreFiles = 1
763 763 # print "[Reading] No more Files"
764 764 return 0
765 765
766 766 filename = self.filenameList[idFile]
767 767
768 768 if not(self.__verifyFile(filename)):
769 769 continue
770 770
771 771 fileSize = os.path.getsize(filename)
772 772 fp = open(filename,'rb')
773 773 break
774 774
775 775 self.flagIsNewFile = 1
776 776 self.fileIndex = idFile
777 777 self.filename = filename
778 778 self.fileSize = fileSize
779 779 self.fp = fp
780 780
781 781 # print "[Reading] Setting the file: %s"%self.filename
782 782
783 783 return 1
784 784
785 785 def __setNextFileOnline(self):
786 786 """
787 787 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
788 788 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
789 789 siguientes.
790 790
791 791 Affected:
792 792 self.flagIsNewFile
793 793 self.filename
794 794 self.fileSize
795 795 self.fp
796 796 self.set
797 797 self.flagNoMoreFiles
798 798
799 799 Return:
800 800 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
801 801 1 : si el file fue abierto con exito y esta listo a ser leido
802 802
803 803 Excepciones:
804 804 Si un determinado file no puede ser abierto
805 805 """
806 806 nFiles = 0
807 807 fileOk_flag = False
808 808 firstTime_flag = True
809 809
810 810 self.set += 1
811 811
812 812 if self.set > 999:
813 813 self.set = 0
814 814 self.foldercounter += 1
815 815
816 816 #busca el 1er file disponible
817 817 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
818 818 if fullfilename:
819 819 if self.__verifyFile(fullfilename, False):
820 820 fileOk_flag = True
821 821
822 822 #si no encuentra un file entonces espera y vuelve a buscar
823 823 if not(fileOk_flag):
824 824 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
825 825
826 826 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
827 827 tries = self.nTries
828 828 else:
829 829 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
830 830
831 831 for nTries in range( tries ):
832 832 if firstTime_flag:
833 833 print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
834 834 sleep( self.delay )
835 835 else:
836 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 838 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
839 839 if fullfilename:
840 840 if self.__verifyFile(fullfilename):
841 841 fileOk_flag = True
842 842 break
843 843
844 844 if fileOk_flag:
845 845 break
846 846
847 847 firstTime_flag = False
848 848
849 849 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
850 850 self.set += 1
851 851
852 852 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
853 853 self.set = 0
854 854 self.doy += 1
855 855 self.foldercounter = 0
856 856
857 857 if fileOk_flag:
858 858 self.fileSize = os.path.getsize( fullfilename )
859 859 self.filename = fullfilename
860 860 self.flagIsNewFile = 1
861 861 if self.fp != None: self.fp.close()
862 862 self.fp = open(fullfilename, 'rb')
863 863 self.flagNoMoreFiles = 0
864 864 # print '[Reading] Setting the file: %s' % fullfilename
865 865 else:
866 866 self.fileSize = 0
867 867 self.filename = None
868 868 self.flagIsNewFile = 0
869 869 self.fp = None
870 870 self.flagNoMoreFiles = 1
871 871 # print '[Reading] No more files to read'
872 872
873 873 return fileOk_flag
874 874
875 875 def setNextFile(self):
876 876 if self.fp != None:
877 877 self.fp.close()
878 878
879 879 if self.online:
880 880 newFile = self.__setNextFileOnline()
881 881 else:
882 882 newFile = self.__setNextFileOffline()
883 883
884 884 if not(newFile):
885 885 print '[Reading] No more files to read'
886 886 return 0
887 887
888 888 if self.verbose:
889 889 print '[Reading] Setting the file: %s' % self.filename
890 890
891 891 self.__readFirstHeader()
892 892 self.nReadBlocks = 0
893 893 return 1
894 894
895 895 def __waitNewBlock(self):
896 896 """
897 897 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
898 898
899 899 Si el modo de lectura es OffLine siempre retorn 0
900 900 """
901 901 if not self.online:
902 902 return 0
903 903
904 904 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
905 905 return 0
906 906
907 907 currentPointer = self.fp.tell()
908 908
909 909 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
910 910
911 911 for nTries in range( self.nTries ):
912 912
913 913 self.fp.close()
914 914 self.fp = open( self.filename, 'rb' )
915 915 self.fp.seek( currentPointer )
916 916
917 917 self.fileSize = os.path.getsize( self.filename )
918 918 currentSize = self.fileSize - currentPointer
919 919
920 920 if ( currentSize >= neededSize ):
921 921 self.basicHeaderObj.read(self.fp)
922 922 return 1
923 923
924 924 if self.fileSize == self.fileSizeByHeader:
925 925 # self.flagEoF = True
926 926 return 0
927 927
928 928 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
929 929 sleep( self.delay )
930 930
931 931
932 932 return 0
933 933
934 934 def waitDataBlock(self,pointer_location):
935 935
936 936 currentPointer = pointer_location
937 937
938 938 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
939 939
940 940 for nTries in range( self.nTries ):
941 941 self.fp.close()
942 942 self.fp = open( self.filename, 'rb' )
943 943 self.fp.seek( currentPointer )
944 944
945 945 self.fileSize = os.path.getsize( self.filename )
946 946 currentSize = self.fileSize - currentPointer
947 947
948 948 if ( currentSize >= neededSize ):
949 949 return 1
950 950
951 951 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
952 952 sleep( self.delay )
953 953
954 954 return 0
955 955
956 956 def __jumpToLastBlock(self):
957 957
958 958 if not(self.__isFirstTimeOnline):
959 959 return
960 960
961 961 csize = self.fileSize - self.fp.tell()
962 962 blocksize = self.processingHeaderObj.blockSize
963 963
964 964 #salta el primer bloque de datos
965 965 if csize > self.processingHeaderObj.blockSize:
966 966 self.fp.seek(self.fp.tell() + blocksize)
967 967 else:
968 968 return
969 969
970 970 csize = self.fileSize - self.fp.tell()
971 971 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
972 972 while True:
973 973
974 974 if self.fp.tell()<self.fileSize:
975 975 self.fp.seek(self.fp.tell() + neededsize)
976 976 else:
977 977 self.fp.seek(self.fp.tell() - neededsize)
978 978 break
979 979
980 980 # csize = self.fileSize - self.fp.tell()
981 981 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
982 982 # factor = int(csize/neededsize)
983 983 # if factor > 0:
984 984 # self.fp.seek(self.fp.tell() + factor*neededsize)
985 985
986 986 self.flagIsNewFile = 0
987 987 self.__isFirstTimeOnline = 0
988 988
989 989 def __setNewBlock(self):
990 990 #if self.server is None:
991 991 if self.fp == None:
992 992 return 0
993 993
994 994 # if self.online:
995 995 # self.__jumpToLastBlock()
996 996
997 997 if self.flagIsNewFile:
998 998 self.lastUTTime = self.basicHeaderObj.utc
999 999 return 1
1000 1000
1001 1001 if self.realtime:
1002 1002 self.flagDiscontinuousBlock = 1
1003 1003 if not(self.setNextFile()):
1004 1004 return 0
1005 1005 else:
1006 1006 return 1
1007 1007 #if self.server is None:
1008 1008 currentSize = self.fileSize - self.fp.tell()
1009 1009 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1010 1010 if (currentSize >= neededSize):
1011 1011 self.basicHeaderObj.read(self.fp)
1012 1012 self.lastUTTime = self.basicHeaderObj.utc
1013 1013 return 1
1014 1014 # else:
1015 1015 # self.basicHeaderObj.read(self.zHeader)
1016 1016 # self.lastUTTime = self.basicHeaderObj.utc
1017 1017 # return 1
1018 1018 if self.__waitNewBlock():
1019 1019 self.lastUTTime = self.basicHeaderObj.utc
1020 1020 return 1
1021 1021 #if self.server is None:
1022 1022 if not(self.setNextFile()):
1023 1023 return 0
1024 1024
1025 1025 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
1026 1026 self.lastUTTime = self.basicHeaderObj.utc
1027 1027
1028 1028 self.flagDiscontinuousBlock = 0
1029 1029
1030 1030 if deltaTime > self.maxTimeStep:
1031 1031 self.flagDiscontinuousBlock = 1
1032 1032
1033 1033 return 1
1034 1034
1035 1035 def readNextBlock(self):
1036 1036
1037 1037 #Skip block out of startTime and endTime
1038 1038 while True:
1039 1039 if not(self.__setNewBlock()):
1040 1040 return 0
1041 1041
1042 1042 if not(self.readBlock()):
1043 1043 return 0
1044 1044
1045 1045 self.getBasicHeader()
1046 1046
1047 1047 if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime):
1048 1048
1049 1049 print "[Reading] Block No. %d/%d -> %s [Skipping]" %(self.nReadBlocks,
1050 1050 self.processingHeaderObj.dataBlocksPerFile,
1051 1051 self.dataOut.datatime.ctime())
1052 1052 continue
1053 1053
1054 1054 break
1055 1055
1056 1056 if self.verbose:
1057 1057 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1058 1058 self.processingHeaderObj.dataBlocksPerFile,
1059 1059 self.dataOut.datatime.ctime())
1060 1060 return 1
1061 1061
1062 1062 def __readFirstHeader(self):
1063 1063
1064 1064 self.basicHeaderObj.read(self.fp)
1065 1065 self.systemHeaderObj.read(self.fp)
1066 1066 self.radarControllerHeaderObj.read(self.fp)
1067 1067 self.processingHeaderObj.read(self.fp)
1068 1068
1069 1069 self.firstHeaderSize = self.basicHeaderObj.size
1070 1070
1071 1071 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
1072 1072 if datatype == 0:
1073 1073 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
1074 1074 elif datatype == 1:
1075 1075 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
1076 1076 elif datatype == 2:
1077 1077 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
1078 1078 elif datatype == 3:
1079 1079 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
1080 1080 elif datatype == 4:
1081 1081 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
1082 1082 elif datatype == 5:
1083 1083 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
1084 1084 else:
1085 1085 raise ValueError, 'Data type was not defined'
1086 1086
1087 1087 self.dtype = datatype_str
1088 1088 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1089 1089 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
1090 1090 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1091 1091 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1092 1092 self.getBlockDimension()
1093 1093
1094 1094 def __verifyFile(self, filename, msgFlag=True):
1095 1095
1096 1096 msg = None
1097 1097
1098 1098 try:
1099 1099 fp = open(filename, 'rb')
1100 1100 except IOError:
1101 1101
1102 1102 if msgFlag:
1103 1103 print "[Reading] File %s can't be opened" % (filename)
1104 1104
1105 1105 return False
1106 1106
1107 1107 currentPosition = fp.tell()
1108 1108 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1109 1109
1110 1110 if neededSize == 0:
1111 1111 basicHeaderObj = BasicHeader(LOCALTIME)
1112 1112 systemHeaderObj = SystemHeader()
1113 1113 radarControllerHeaderObj = RadarControllerHeader()
1114 1114 processingHeaderObj = ProcessingHeader()
1115 1115
1116 1116 if not( basicHeaderObj.read(fp) ):
1117 1117 fp.close()
1118 1118 return False
1119 1119
1120 1120 if not( systemHeaderObj.read(fp) ):
1121 1121 fp.close()
1122 1122 return False
1123 1123
1124 1124 if not( radarControllerHeaderObj.read(fp) ):
1125 1125 fp.close()
1126 1126 return False
1127 1127
1128 1128 if not( processingHeaderObj.read(fp) ):
1129 1129 fp.close()
1130 1130 return False
1131 1131
1132 1132 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1133 1133 else:
1134 1134 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
1135 1135
1136 1136 fp.close()
1137 1137
1138 1138 fileSize = os.path.getsize(filename)
1139 1139 currentSize = fileSize - currentPosition
1140 1140
1141 1141 if currentSize < neededSize:
1142 1142 if msgFlag and (msg != None):
1143 1143 print msg
1144 1144 return False
1145 1145
1146 1146 return True
1147 1147
1148 1148 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1149 1149
1150 1150 path_empty = True
1151 1151
1152 1152 dateList = []
1153 1153 pathList = []
1154 1154
1155 1155 multi_path = path.split(',')
1156 1156
1157 1157 if not walk:
1158 1158
1159 1159 for single_path in multi_path:
1160 1160
1161 1161 if not os.path.isdir(single_path):
1162 1162 continue
1163 1163
1164 1164 fileList = glob.glob1(single_path, "*"+ext)
1165 1165
1166 1166 if not fileList:
1167 1167 continue
1168 1168
1169 1169 path_empty = False
1170 1170
1171 1171 fileList.sort()
1172 1172
1173 1173 for thisFile in fileList:
1174 1174
1175 1175 if not os.path.isfile(os.path.join(single_path, thisFile)):
1176 1176 continue
1177 1177
1178 1178 if not isRadarFile(thisFile):
1179 1179 continue
1180 1180
1181 1181 if not isFileInDateRange(thisFile, startDate, endDate):
1182 1182 continue
1183 1183
1184 1184 thisDate = getDateFromRadarFile(thisFile)
1185 1185
1186 1186 if thisDate in dateList:
1187 1187 continue
1188 1188
1189 1189 dateList.append(thisDate)
1190 1190 pathList.append(single_path)
1191 1191
1192 1192 else:
1193 1193 for single_path in multi_path:
1194 1194
1195 1195 if not os.path.isdir(single_path):
1196 1196 continue
1197 1197
1198 1198 dirList = []
1199 1199
1200 1200 for thisPath in os.listdir(single_path):
1201 1201
1202 1202 if not os.path.isdir(os.path.join(single_path,thisPath)):
1203 1203 continue
1204 1204
1205 1205 if not isRadarFolder(thisPath):
1206 1206 continue
1207 1207
1208 1208 if not isFolderInDateRange(thisPath, startDate, endDate):
1209 1209 continue
1210 1210
1211 1211 dirList.append(thisPath)
1212 1212
1213 1213 if not dirList:
1214 1214 continue
1215 1215
1216 1216 dirList.sort()
1217 1217
1218 1218 for thisDir in dirList:
1219 1219
1220 1220 datapath = os.path.join(single_path, thisDir, expLabel)
1221 1221 fileList = glob.glob1(datapath, "*"+ext)
1222 1222
1223 1223 if not fileList:
1224 1224 continue
1225 1225
1226 1226 path_empty = False
1227 1227
1228 1228 thisDate = getDateFromRadarFolder(thisDir)
1229 1229
1230 1230 pathList.append(datapath)
1231 1231 dateList.append(thisDate)
1232 1232
1233 1233 dateList.sort()
1234 1234
1235 1235 if walk:
1236 1236 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1237 1237 else:
1238 1238 pattern_path = multi_path[0]
1239 1239
1240 1240 if path_empty:
1241 1241 print "[Reading] No *%s files in %s for %s to %s" %(ext, pattern_path, startDate, endDate)
1242 1242 else:
1243 1243 if not dateList:
1244 1244 print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
1245 1245
1246 1246 if include_path:
1247 1247 return dateList, pathList
1248 1248
1249 1249 return dateList
1250 1250
1251 1251 def setup(self,
1252 1252 path=None,
1253 1253 startDate=None,
1254 1254 endDate=None,
1255 1255 startTime=datetime.time(0,0,0),
1256 1256 endTime=datetime.time(23,59,59),
1257 1257 set=None,
1258 1258 expLabel = "",
1259 1259 ext = None,
1260 1260 online = False,
1261 1261 delay = 60,
1262 1262 walk = True,
1263 1263 getblock = False,
1264 1264 nTxs = 1,
1265 1265 realtime=False,
1266 1266 blocksize=None,
1267 1267 blocktime=None,
1268 1268 skip=None,
1269 1269 cursor=None,
1270 1270 warnings=True,
1271 1271 verbose=True,
1272 server=None):
1272 server=None,
1273 format=None,
1274 oneDDict=None,
1275 twoDDict=None,
1276 ind2DList=None):
1273 1277 if server is not None:
1274 1278 if 'tcp://' in server:
1275 1279 address = server
1276 1280 else:
1277 1281 address = 'ipc:///tmp/%s' % server
1278 1282 self.server = address
1279 1283 self.context = zmq.Context()
1280 1284 self.receiver = self.context.socket(zmq.PULL)
1281 1285 self.receiver.connect(self.server)
1282 1286 time.sleep(0.5)
1283 1287 print '[Starting] ReceiverData from {}'.format(self.server)
1284 1288 else:
1285 1289 self.server = None
1286 1290 if path == None:
1287 1291 raise ValueError, "[Reading] The path is not valid"
1288 1292
1289 1293 if ext == None:
1290 1294 ext = self.ext
1291 1295
1292 1296 if online:
1293 1297 print "[Reading] Searching files in online mode..."
1294 1298
1295 1299 for nTries in range( self.nTries ):
1296 1300 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1297 1301
1298 1302 if fullpath:
1299 1303 break
1300 1304
1301 1305 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
1302 1306 sleep( self.delay )
1303 1307
1304 1308 if not(fullpath):
1305 1309 print "[Reading] There 'isn't any valid file in %s" % path
1306 1310 return
1307 1311
1308 1312 self.year = year
1309 1313 self.doy = doy
1310 1314 self.set = set - 1
1311 1315 self.path = path
1312 1316 self.foldercounter = foldercounter
1313 1317 last_set = None
1314 1318 else:
1315 1319 print "[Reading] Searching files in offline mode ..."
1316 1320 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1317 1321 startTime=startTime, endTime=endTime,
1318 1322 set=set, expLabel=expLabel, ext=ext,
1319 1323 walk=walk, cursor=cursor,
1320 1324 skip=skip)
1321 1325
1322 1326 if not(pathList):
1323 1327 self.fileIndex = -1
1324 1328 self.pathList = []
1325 1329 self.filenameList = []
1326 1330 return
1327 1331
1328 1332 self.fileIndex = -1
1329 1333 self.pathList = pathList
1330 1334 self.filenameList = filenameList
1331 1335 file_name = os.path.basename(filenameList[-1])
1332 1336 basename, ext = os.path.splitext(file_name)
1333 1337 last_set = int(basename[-3:])
1334 1338
1335 1339 self.online = online
1336 1340 self.realtime = realtime
1337 1341 self.delay = delay
1338 1342 ext = ext.lower()
1339 1343 self.ext = ext
1340 1344 self.getByBlock = getblock
1341 1345 self.nTxs = nTxs
1342 1346 self.startTime = startTime
1343 1347 self.endTime = endTime
1344 1348
1345 1349 #Added-----------------
1346 1350 self.selBlocksize = blocksize
1347 1351 self.selBlocktime = blocktime
1348 1352
1349 1353 # Verbose-----------
1350 1354 self.verbose = verbose
1351 1355 self.warnings = warnings
1352 1356
1353 1357 if not(self.setNextFile()):
1354 1358 if (startDate!=None) and (endDate!=None):
1355 1359 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1356 1360 elif startDate != None:
1357 1361 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1358 1362 else:
1359 1363 print "[Reading] No files"
1360 1364
1361 1365 self.fileIndex = -1
1362 1366 self.pathList = []
1363 1367 self.filenameList = []
1364 1368 return
1365 1369
1366 1370 # self.getBasicHeader()
1367 1371
1368 1372 if last_set != None:
1369 1373 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1370 1374 return
1371 1375
1372 1376 def getBasicHeader(self):
1373 1377
1374 1378 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1375 1379
1376 1380 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1377 1381
1378 1382 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1379 1383
1380 1384 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1381 1385
1382 1386 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1383 1387
1384 1388 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1385 1389
1386 1390 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1387 1391
1388 1392 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1389 1393
1390 1394
1391 1395 def getFirstHeader(self):
1392 1396
1393 1397 raise NotImplementedError
1394 1398
1395 1399 def getData(self):
1396 1400
1397 1401 raise NotImplementedError
1398 1402
1399 1403 def hasNotDataInBuffer(self):
1400 1404
1401 1405 raise NotImplementedError
1402 1406
1403 1407 def readBlock(self):
1404 1408
1405 1409 raise NotImplementedError
1406 1410
1407 1411 def isEndProcess(self):
1408 1412
1409 1413 return self.flagNoMoreFiles
1410 1414
1411 1415 def printReadBlocks(self):
1412 1416
1413 1417 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1414 1418
1415 1419 def printTotalBlocks(self):
1416 1420
1417 1421 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1418 1422
1419 1423 def printNumberOfBlock(self):
1424 'SPAM!'
1420 1425
1421 if self.flagIsNewBlock:
1422 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1423 self.processingHeaderObj.dataBlocksPerFile,
1424 self.dataOut.datatime.ctime())
1426 # if self.flagIsNewBlock:
1427 # print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1428 # self.processingHeaderObj.dataBlocksPerFile,
1429 # self.dataOut.datatime.ctime())
1425 1430
1426 1431 def printInfo(self):
1427 1432
1428 1433 if self.__printInfo == False:
1429 1434 return
1430 1435
1431 1436 self.basicHeaderObj.printInfo()
1432 1437 self.systemHeaderObj.printInfo()
1433 1438 self.radarControllerHeaderObj.printInfo()
1434 1439 self.processingHeaderObj.printInfo()
1435 1440
1436 1441 self.__printInfo = False
1437 1442
1438 1443 def run(self,
1439 1444 path=None,
1440 1445 startDate=None,
1441 1446 endDate=None,
1442 1447 startTime=datetime.time(0,0,0),
1443 1448 endTime=datetime.time(23,59,59),
1444 1449 set=None,
1445 1450 expLabel = "",
1446 1451 ext = None,
1447 1452 online = False,
1448 1453 delay = 60,
1449 1454 walk = True,
1450 1455 getblock = False,
1451 1456 nTxs = 1,
1452 1457 realtime=False,
1453 1458 blocksize=None,
1454 1459 blocktime=None,
1455 1460 skip=None,
1456 1461 cursor=None,
1457 1462 warnings=True,
1458 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 1470 if not(self.isConfig):
1462 1471 self.setup(path=path,
1463 1472 startDate=startDate,
1464 1473 endDate=endDate,
1465 1474 startTime=startTime,
1466 1475 endTime=endTime,
1467 1476 set=set,
1468 1477 expLabel=expLabel,
1469 1478 ext=ext,
1470 1479 online=online,
1471 1480 delay=delay,
1472 1481 walk=walk,
1473 1482 getblock=getblock,
1474 1483 nTxs=nTxs,
1475 1484 realtime=realtime,
1476 1485 blocksize=blocksize,
1477 1486 blocktime=blocktime,
1478 1487 skip=skip,
1479 1488 cursor=cursor,
1480 1489 warnings=warnings,
1481 1490 server=server,
1482 verbose=verbose)
1491 verbose=verbose,
1492 format=format,
1493 oneDDict=oneDDict,
1494 twoDDict=twoDDict,
1495 ind2DList=ind2DList)
1483 1496 self.isConfig = True
1484 1497 if server is None:
1485 1498 self.getData()
1486 1499 else:
1487 1500 self.getFromServer()
1488 1501
1489 1502 class JRODataWriter(JRODataIO):
1490 1503
1491 1504 """
1492 1505 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1493 1506 de los datos siempre se realiza por bloques.
1494 1507 """
1495 1508
1496 1509 blockIndex = 0
1497 1510
1498 1511 path = None
1499 1512
1500 1513 setFile = None
1501 1514
1502 1515 profilesPerBlock = None
1503 1516
1504 1517 blocksPerFile = None
1505 1518
1506 1519 nWriteBlocks = 0
1507 1520
1508 1521 fileDate = None
1509 1522
1510 1523 def __init__(self, dataOut=None):
1511 1524 raise NotImplementedError
1512 1525
1513 1526
1514 1527 def hasAllDataInBuffer(self):
1515 1528 raise NotImplementedError
1516 1529
1517 1530
1518 1531 def setBlockDimension(self):
1519 1532 raise NotImplementedError
1520 1533
1521 1534
1522 1535 def writeBlock(self):
1523 1536 raise NotImplementedError
1524 1537
1525 1538
1526 1539 def putData(self):
1527 1540 raise NotImplementedError
1528 1541
1529 1542
1530 1543 def getProcessFlags(self):
1531 1544
1532 1545 processFlags = 0
1533 1546
1534 1547 dtype_index = get_dtype_index(self.dtype)
1535 1548 procflag_dtype = get_procflag_dtype(dtype_index)
1536 1549
1537 1550 processFlags += procflag_dtype
1538 1551
1539 1552 if self.dataOut.flagDecodeData:
1540 1553 processFlags += PROCFLAG.DECODE_DATA
1541 1554
1542 1555 if self.dataOut.flagDeflipData:
1543 1556 processFlags += PROCFLAG.DEFLIP_DATA
1544 1557
1545 1558 if self.dataOut.code is not None:
1546 1559 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1547 1560
1548 1561 if self.dataOut.nCohInt > 1:
1549 1562 processFlags += PROCFLAG.COHERENT_INTEGRATION
1550 1563
1551 1564 if self.dataOut.type == "Spectra":
1552 1565 if self.dataOut.nIncohInt > 1:
1553 1566 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1554 1567
1555 1568 if self.dataOut.data_dc is not None:
1556 1569 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1557 1570
1558 1571 if self.dataOut.flagShiftFFT:
1559 1572 processFlags += PROCFLAG.SHIFT_FFT_DATA
1560 1573
1561 1574 return processFlags
1562 1575
1563 1576 def setBasicHeader(self):
1564 1577
1565 1578 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1566 1579 self.basicHeaderObj.version = self.versionFile
1567 1580 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1568 1581
1569 1582 utc = numpy.floor(self.dataOut.utctime)
1570 1583 milisecond = (self.dataOut.utctime - utc)* 1000.0
1571 1584
1572 1585 self.basicHeaderObj.utc = utc
1573 1586 self.basicHeaderObj.miliSecond = milisecond
1574 1587 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1575 1588 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1576 1589 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1577 1590
1578 1591 def setFirstHeader(self):
1579 1592 """
1580 1593 Obtiene una copia del First Header
1581 1594
1582 1595 Affected:
1583 1596
1584 1597 self.basicHeaderObj
1585 1598 self.systemHeaderObj
1586 1599 self.radarControllerHeaderObj
1587 1600 self.processingHeaderObj self.
1588 1601
1589 1602 Return:
1590 1603 None
1591 1604 """
1592 1605
1593 1606 raise NotImplementedError
1594 1607
1595 1608 def __writeFirstHeader(self):
1596 1609 """
1597 1610 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1598 1611
1599 1612 Affected:
1600 1613 __dataType
1601 1614
1602 1615 Return:
1603 1616 None
1604 1617 """
1605 1618
1606 1619 # CALCULAR PARAMETROS
1607 1620
1608 1621 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1609 1622 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1610 1623
1611 1624 self.basicHeaderObj.write(self.fp)
1612 1625 self.systemHeaderObj.write(self.fp)
1613 1626 self.radarControllerHeaderObj.write(self.fp)
1614 1627 self.processingHeaderObj.write(self.fp)
1615 1628
1616 1629 def __setNewBlock(self):
1617 1630 """
1618 1631 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1619 1632
1620 1633 Return:
1621 1634 0 : si no pudo escribir nada
1622 1635 1 : Si escribio el Basic el First Header
1623 1636 """
1624 1637 if self.fp == None:
1625 1638 self.setNextFile()
1626 1639
1627 1640 if self.flagIsNewFile:
1628 1641 return 1
1629 1642
1630 1643 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1631 1644 self.basicHeaderObj.write(self.fp)
1632 1645 return 1
1633 1646
1634 1647 if not( self.setNextFile() ):
1635 1648 return 0
1636 1649
1637 1650 return 1
1638 1651
1639 1652
1640 1653 def writeNextBlock(self):
1641 1654 """
1642 1655 Selecciona el bloque siguiente de datos y los escribe en un file
1643 1656
1644 1657 Return:
1645 1658 0 : Si no hizo pudo escribir el bloque de datos
1646 1659 1 : Si no pudo escribir el bloque de datos
1647 1660 """
1648 1661 if not( self.__setNewBlock() ):
1649 1662 return 0
1650 1663
1651 1664 self.writeBlock()
1652 1665
1653 1666 print "[Writing] Block No. %d/%d" %(self.blockIndex,
1654 1667 self.processingHeaderObj.dataBlocksPerFile)
1655 1668
1656 1669 return 1
1657 1670
1658 1671 def setNextFile(self):
1659 1672 """
1660 1673 Determina el siguiente file que sera escrito
1661 1674
1662 1675 Affected:
1663 1676 self.filename
1664 1677 self.subfolder
1665 1678 self.fp
1666 1679 self.setFile
1667 1680 self.flagIsNewFile
1668 1681
1669 1682 Return:
1670 1683 0 : Si el archivo no puede ser escrito
1671 1684 1 : Si el archivo esta listo para ser escrito
1672 1685 """
1673 1686 ext = self.ext
1674 1687 path = self.path
1675 1688
1676 1689 if self.fp != None:
1677 1690 self.fp.close()
1678 1691
1679 1692 timeTuple = time.localtime( self.dataOut.utctime)
1680 1693 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1681 1694
1682 1695 fullpath = os.path.join( path, subfolder )
1683 1696 setFile = self.setFile
1684 1697
1685 1698 if not( os.path.exists(fullpath) ):
1686 1699 os.mkdir(fullpath)
1687 1700 setFile = -1 #inicializo mi contador de seteo
1688 1701 else:
1689 1702 filesList = os.listdir( fullpath )
1690 1703 if len( filesList ) > 0:
1691 1704 filesList = sorted( filesList, key=str.lower )
1692 1705 filen = filesList[-1]
1693 1706 # el filename debera tener el siguiente formato
1694 1707 # 0 1234 567 89A BCDE (hex)
1695 1708 # x YYYY DDD SSS .ext
1696 1709 if isNumber( filen[8:11] ):
1697 1710 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1698 1711 else:
1699 1712 setFile = -1
1700 1713 else:
1701 1714 setFile = -1 #inicializo mi contador de seteo
1702 1715
1703 1716 setFile += 1
1704 1717
1705 1718 #If this is a new day it resets some values
1706 1719 if self.dataOut.datatime.date() > self.fileDate:
1707 1720 setFile = 0
1708 1721 self.nTotalBlocks = 0
1709 1722
1710 1723 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext )
1711 1724
1712 1725 filename = os.path.join( path, subfolder, filen )
1713 1726
1714 1727 fp = open( filename,'wb' )
1715 1728
1716 1729 self.blockIndex = 0
1717 1730
1718 1731 #guardando atributos
1719 1732 self.filename = filename
1720 1733 self.subfolder = subfolder
1721 1734 self.fp = fp
1722 1735 self.setFile = setFile
1723 1736 self.flagIsNewFile = 1
1724 1737 self.fileDate = self.dataOut.datatime.date()
1725 1738
1726 1739 self.setFirstHeader()
1727 1740
1728 1741 print '[Writing] Opening file: %s'%self.filename
1729 1742
1730 1743 self.__writeFirstHeader()
1731 1744
1732 1745 return 1
1733 1746
1734 1747 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1735 1748 """
1736 1749 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1737 1750
1738 1751 Inputs:
1739 1752 path : directory where data will be saved
1740 1753 profilesPerBlock : number of profiles per block
1741 1754 set : initial file set
1742 1755 datatype : An integer number that defines data type:
1743 1756 0 : int8 (1 byte)
1744 1757 1 : int16 (2 bytes)
1745 1758 2 : int32 (4 bytes)
1746 1759 3 : int64 (8 bytes)
1747 1760 4 : float32 (4 bytes)
1748 1761 5 : double64 (8 bytes)
1749 1762
1750 1763 Return:
1751 1764 0 : Si no realizo un buen seteo
1752 1765 1 : Si realizo un buen seteo
1753 1766 """
1754 1767
1755 1768 if ext == None:
1756 1769 ext = self.ext
1757 1770
1758 1771 self.ext = ext.lower()
1759 1772
1760 1773 self.path = path
1761 1774
1762 1775 if set is None:
1763 1776 self.setFile = -1
1764 1777 else:
1765 1778 self.setFile = set - 1
1766 1779
1767 1780 self.blocksPerFile = blocksPerFile
1768 1781
1769 1782 self.profilesPerBlock = profilesPerBlock
1770 1783
1771 1784 self.dataOut = dataOut
1772 1785 self.fileDate = self.dataOut.datatime.date()
1773 1786 #By default
1774 1787 self.dtype = self.dataOut.dtype
1775 1788
1776 1789 if datatype is not None:
1777 1790 self.dtype = get_numpy_dtype(datatype)
1778 1791
1779 1792 if not(self.setNextFile()):
1780 1793 print "[Writing] There isn't a next file"
1781 1794 return 0
1782 1795
1783 1796 self.setBlockDimension()
1784 1797
1785 1798 return 1
1786 1799
1787 1800 def run(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1788 1801
1789 1802 if not(self.isConfig):
1790 1803
1791 1804 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock, set=set, ext=ext, datatype=datatype, **kwargs)
1792 1805 self.isConfig = True
1793 1806
1794 1807 self.putData()
@@ -1,1095 +1,1095
1 1 import numpy
2 2 import time
3 3 import os
4 4 import h5py
5 5 import re
6 6 import datetime
7 7
8 8 from schainpy.model.data.jrodata import *
9 9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
10 10 # from jroIO_base import *
11 11 from schainpy.model.io.jroIO_base import *
12 12 import schainpy
13 13
14 14
15 15 class ParamReader(ProcessingUnit):
16 16 '''
17 17 Reads HDF5 format files
18 18
19 19 path
20 20
21 21 startDate
22 22
23 23 endDate
24 24
25 25 startTime
26 26
27 27 endTime
28 28 '''
29 29
30 30 ext = ".hdf5"
31 31
32 32 optchar = "D"
33 33
34 34 timezone = None
35 35
36 36 startTime = None
37 37
38 38 endTime = None
39 39
40 40 fileIndex = None
41 41
42 42 utcList = None #To select data in the utctime list
43 43
44 44 blockList = None #List to blocks to be read from the file
45 45
46 46 blocksPerFile = None #Number of blocks to be read
47 47
48 48 blockIndex = None
49 49
50 50 path = None
51 51
52 52 #List of Files
53 53
54 54 filenameList = None
55 55
56 56 datetimeList = None
57 57
58 58 #Hdf5 File
59 59
60 60 listMetaname = None
61 61
62 62 listMeta = None
63 63
64 64 listDataname = None
65 65
66 66 listData = None
67 67
68 68 listShapes = None
69 69
70 70 fp = None
71 71
72 72 #dataOut reconstruction
73 73
74 74 dataOut = None
75 75
76 76
77 77 def __init__(self, **kwargs):
78 78 ProcessingUnit.__init__(self, **kwargs)
79 79 self.dataOut = Parameters()
80 80 return
81 81
82 82 def setup(self, **kwargs):
83 83
84 84 path = kwargs['path']
85 85 startDate = kwargs['startDate']
86 86 endDate = kwargs['endDate']
87 87 startTime = kwargs['startTime']
88 88 endTime = kwargs['endTime']
89 89 walk = kwargs['walk']
90 90 if kwargs.has_key('ext'):
91 91 ext = kwargs['ext']
92 92 else:
93 93 ext = '.hdf5'
94 94 if kwargs.has_key('timezone'):
95 95 self.timezone = kwargs['timezone']
96 96 else:
97 97 self.timezone = 'lt'
98 98
99 99 print "[Reading] Searching files in offline mode ..."
100 100 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
101 101 startTime=startTime, endTime=endTime,
102 102 ext=ext, walk=walk)
103 103
104 104 if not(filenameList):
105 105 print "There is no files into the folder: %s"%(path)
106 106 sys.exit(-1)
107 107
108 108 self.fileIndex = -1
109 109 self.startTime = startTime
110 110 self.endTime = endTime
111 111
112 112 self.__readMetadata()
113 113
114 114 self.__setNextFileOffline()
115 115
116 116 return
117 117
118 118 def searchFilesOffLine(self,
119 119 path,
120 120 startDate=None,
121 121 endDate=None,
122 122 startTime=datetime.time(0,0,0),
123 123 endTime=datetime.time(23,59,59),
124 124 ext='.hdf5',
125 125 walk=True):
126 126
127 127 expLabel = ''
128 128 self.filenameList = []
129 129 self.datetimeList = []
130 130
131 131 pathList = []
132 132
133 133 JRODataObj = JRODataReader()
134 134 dateList, pathList = JRODataObj.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
135 135
136 136 if dateList == []:
137 137 print "[Reading] No *%s files in %s from %s to %s)"%(ext, path,
138 138 datetime.datetime.combine(startDate,startTime).ctime(),
139 139 datetime.datetime.combine(endDate,endTime).ctime())
140 140
141 141 return None, None
142 142
143 143 if len(dateList) > 1:
144 144 print "[Reading] %d days were found in date range: %s - %s" %(len(dateList), startDate, endDate)
145 145 else:
146 146 print "[Reading] data was found for the date %s" %(dateList[0])
147 147
148 148 filenameList = []
149 149 datetimeList = []
150 150
151 151 #----------------------------------------------------------------------------------
152 152
153 153 for thisPath in pathList:
154 154 # thisPath = pathList[pathDict[file]]
155 155
156 156 fileList = glob.glob1(thisPath, "*%s" %ext)
157 157 fileList.sort()
158 158
159 159 for file in fileList:
160 160
161 161 filename = os.path.join(thisPath,file)
162 162
163 163 if not isFileInDateRange(filename, startDate, endDate):
164 164 continue
165 165
166 166 thisDatetime = self.__isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
167 167
168 168 if not(thisDatetime):
169 169 continue
170 170
171 171 filenameList.append(filename)
172 172 datetimeList.append(thisDatetime)
173 173
174 174 if not(filenameList):
175 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 176 return None, None
177 177
178 178 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
179 179 print
180 180
181 for i in range(len(filenameList)):
182 print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
181 # for i in range(len(filenameList)):
182 # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
183 183
184 184 self.filenameList = filenameList
185 185 self.datetimeList = datetimeList
186 186
187 187 return pathList, filenameList
188 188
189 189 def __isFileInTimeRange(self,filename, startDate, endDate, startTime, endTime):
190 190
191 191 """
192 192 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
193 193
194 194 Inputs:
195 195 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
196 196
197 197 startDate : fecha inicial del rango seleccionado en formato datetime.date
198 198
199 199 endDate : fecha final del rango seleccionado en formato datetime.date
200 200
201 201 startTime : tiempo inicial del rango seleccionado en formato datetime.time
202 202
203 203 endTime : tiempo final del rango seleccionado en formato datetime.time
204 204
205 205 Return:
206 206 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
207 207 fecha especificado, de lo contrario retorna False.
208 208
209 209 Excepciones:
210 210 Si el archivo no existe o no puede ser abierto
211 211 Si la cabecera no puede ser leida.
212 212
213 213 """
214 214
215 215 try:
216 216 fp = h5py.File(filename,'r')
217 217 grp1 = fp['Data']
218 218
219 219 except IOError:
220 220 traceback.print_exc()
221 221 raise IOError, "The file %s can't be opened" %(filename)
222 222 #chino rata
223 223 #In case has utctime attribute
224 224 grp2 = grp1['utctime']
225 225 # thisUtcTime = grp2.value[0] - 5*3600 #To convert to local time
226 226 thisUtcTime = grp2.value[0]
227 227
228 228 fp.close()
229 229
230 230 if self.timezone == 'lt':
231 231 thisUtcTime -= 5*3600
232 232
233 233 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
234 234 # thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0])
235 235 thisDate = thisDatetime.date()
236 236 thisTime = thisDatetime.time()
237 237
238 238 startUtcTime = (datetime.datetime.combine(thisDate,startTime)- datetime.datetime(1970, 1, 1)).total_seconds()
239 239 endUtcTime = (datetime.datetime.combine(thisDate,endTime)- datetime.datetime(1970, 1, 1)).total_seconds()
240 240
241 241 #General case
242 242 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
243 243 #-----------o----------------------------o-----------
244 244 # startTime endTime
245 245
246 246 if endTime >= startTime:
247 247 thisUtcLog = numpy.logical_and(thisUtcTime > startUtcTime, thisUtcTime < endUtcTime)
248 248 if numpy.any(thisUtcLog): #If there is one block between the hours mentioned
249 249 return thisDatetime
250 250 return None
251 251
252 252 #If endTime < startTime then endTime belongs to the next day
253 253 #<<<<<<<<<<<o o>>>>>>>>>>>
254 254 #-----------o----------------------------o-----------
255 255 # endTime startTime
256 256
257 257 if (thisDate == startDate) and numpy.all(thisUtcTime < startUtcTime):
258 258 return None
259 259
260 260 if (thisDate == endDate) and numpy.all(thisUtcTime > endUtcTime):
261 261 return None
262 262
263 263 if numpy.all(thisUtcTime < startUtcTime) and numpy.all(thisUtcTime > endUtcTime):
264 264 return None
265 265
266 266 return thisDatetime
267 267
268 268 def __setNextFileOffline(self):
269 269
270 270 self.fileIndex += 1
271 271 idFile = self.fileIndex
272 272
273 273 if not(idFile < len(self.filenameList)):
274 274 print "No more Files"
275 275 return 0
276 276
277 277 filename = self.filenameList[idFile]
278 278
279 279 filePointer = h5py.File(filename,'r')
280 280
281 281 self.filename = filename
282 282
283 283 self.fp = filePointer
284 284
285 285 print "Setting the file: %s"%self.filename
286 286
287 287 # self.__readMetadata()
288 288 self.__setBlockList()
289 289 self.__readData()
290 290 # self.nRecords = self.fp['Data'].attrs['blocksPerFile']
291 291 # self.nRecords = self.fp['Data'].attrs['nRecords']
292 292 self.blockIndex = 0
293 293 return 1
294 294
295 295 def __setBlockList(self):
296 296 '''
297 297 Selects the data within the times defined
298 298
299 299 self.fp
300 300 self.startTime
301 301 self.endTime
302 302
303 303 self.blockList
304 304 self.blocksPerFile
305 305
306 306 '''
307 307 fp = self.fp
308 308 startTime = self.startTime
309 309 endTime = self.endTime
310 310
311 311 grp = fp['Data']
312 312 thisUtcTime = grp['utctime'].value.astype(numpy.float)[0]
313 313
314 314 #ERROOOOR
315 315 if self.timezone == 'lt':
316 316 thisUtcTime -= 5*3600
317 317
318 318 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
319 319
320 320 thisDate = thisDatetime.date()
321 321 thisTime = thisDatetime.time()
322 322
323 323 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
324 324 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
325 325
326 326 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
327 327
328 328 self.blockList = ind
329 329 self.blocksPerFile = len(ind)
330 330
331 331 return
332 332
333 333 def __readMetadata(self):
334 334 '''
335 335 Reads Metadata
336 336
337 337 self.pathMeta
338 338
339 339 self.listShapes
340 340 self.listMetaname
341 341 self.listMeta
342 342
343 343 '''
344 344
345 345 # grp = self.fp['Data']
346 346 # pathMeta = os.path.join(self.path, grp.attrs['metadata'])
347 347 #
348 348 # if pathMeta == self.pathMeta:
349 349 # return
350 350 # else:
351 351 # self.pathMeta = pathMeta
352 352 #
353 353 # filePointer = h5py.File(self.pathMeta,'r')
354 354 # groupPointer = filePointer['Metadata']
355 355
356 356 filename = self.filenameList[0]
357 357
358 358 fp = h5py.File(filename,'r')
359 359
360 360 gp = fp['Metadata']
361 361
362 362 listMetaname = []
363 363 listMetadata = []
364 364 for item in gp.items():
365 365 name = item[0]
366 366
367 367 if name=='array dimensions':
368 368 table = gp[name][:]
369 369 listShapes = {}
370 370 for shapes in table:
371 371 listShapes[shapes[0]] = numpy.array([shapes[1],shapes[2],shapes[3],shapes[4],shapes[5]])
372 372 else:
373 373 data = gp[name].value
374 374 listMetaname.append(name)
375 375 listMetadata.append(data)
376 376
377 377 # if name=='type':
378 378 # self.__initDataOut(data)
379 379
380 380 self.listShapes = listShapes
381 381 self.listMetaname = listMetaname
382 382 self.listMeta = listMetadata
383 383
384 384 fp.close()
385 385 return
386 386
387 387 def __readData(self):
388 388 grp = self.fp['Data']
389 389 listdataname = []
390 390 listdata = []
391 391
392 392 for item in grp.items():
393 393 name = item[0]
394 394 listdataname.append(name)
395 395
396 396 array = self.__setDataArray(grp[name],self.listShapes[name])
397 397 listdata.append(array)
398 398
399 399 self.listDataname = listdataname
400 400 self.listData = listdata
401 401 return
402 402
403 403 def __setDataArray(self, dataset, shapes):
404 404
405 405 nDims = shapes[0]
406 406
407 407 nDim2 = shapes[1] #Dimension 0
408 408
409 409 nDim1 = shapes[2] #Dimension 1, number of Points or Parameters
410 410
411 411 nDim0 = shapes[3] #Dimension 2, number of samples or ranges
412 412
413 413 mode = shapes[4] #Mode of storing
414 414
415 415 blockList = self.blockList
416 416
417 417 blocksPerFile = self.blocksPerFile
418 418
419 419 #Depending on what mode the data was stored
420 420 if mode == 0: #Divided in channels
421 421 arrayData = dataset.value.astype(numpy.float)[0][blockList]
422 422 if mode == 1: #Divided in parameter
423 423 strds = 'table'
424 424 nDatas = nDim1
425 425 newShapes = (blocksPerFile,nDim2,nDim0)
426 426 elif mode==2: #Concatenated in a table
427 427 strds = 'table0'
428 428 arrayData = dataset[strds].value
429 429 #Selecting part of the dataset
430 430 utctime = arrayData[:,0]
431 431 u, indices = numpy.unique(utctime, return_index=True)
432 432
433 433 if blockList.size != indices.size:
434 434 indMin = indices[blockList[0]]
435 435 if blockList[1] + 1 >= indices.size:
436 436 arrayData = arrayData[indMin:,:]
437 437 else:
438 438 indMax = indices[blockList[1] + 1]
439 439 arrayData = arrayData[indMin:indMax,:]
440 440 return arrayData
441 441
442 442 # One dimension
443 443 if nDims == 0:
444 444 arrayData = dataset.value.astype(numpy.float)[0][blockList]
445 445
446 446 # Two dimensions
447 447 elif nDims == 2:
448 448 arrayData = numpy.zeros((blocksPerFile,nDim1,nDim0))
449 449 newShapes = (blocksPerFile,nDim0)
450 450 nDatas = nDim1
451 451
452 452 for i in range(nDatas):
453 453 data = dataset[strds + str(i)].value
454 454 arrayData[:,i,:] = data[blockList,:]
455 455
456 456 # Three dimensions
457 457 else:
458 458 arrayData = numpy.zeros((blocksPerFile,nDim2,nDim1,nDim0))
459 459 for i in range(nDatas):
460 460
461 461 data = dataset[strds + str(i)].value
462 462
463 463 for b in range(blockList.size):
464 464 arrayData[b,:,i,:] = data[:,:,blockList[b]]
465 465
466 466 return arrayData
467 467
468 468 def __setDataOut(self):
469 469 listMeta = self.listMeta
470 470 listMetaname = self.listMetaname
471 471 listDataname = self.listDataname
472 472 listData = self.listData
473 473 listShapes = self.listShapes
474 474
475 475 blockIndex = self.blockIndex
476 476 # blockList = self.blockList
477 477
478 478 for i in range(len(listMeta)):
479 479 setattr(self.dataOut,listMetaname[i],listMeta[i])
480 480
481 481 for j in range(len(listData)):
482 482 nShapes = listShapes[listDataname[j]][0]
483 483 mode = listShapes[listDataname[j]][4]
484 484 if nShapes == 1:
485 485 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
486 486 elif nShapes > 1:
487 487 setattr(self.dataOut,listDataname[j],listData[j][blockIndex,:])
488 488 elif mode==0:
489 489 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
490 490 #Mode Meteors
491 491 elif mode ==2:
492 492 selectedData = self.__selectDataMode2(listData[j], blockIndex)
493 493 setattr(self.dataOut, listDataname[j], selectedData)
494 494 return
495 495
496 496 def __selectDataMode2(self, data, blockIndex):
497 497 utctime = data[:,0]
498 498 aux, indices = numpy.unique(utctime, return_inverse=True)
499 499 selInd = numpy.where(indices == blockIndex)[0]
500 500 selData = data[selInd,:]
501 501
502 502 return selData
503 503
504 504 def getData(self):
505 505
506 506 # if self.flagNoMoreFiles:
507 507 # self.dataOut.flagNoData = True
508 508 # print 'Process finished'
509 509 # return 0
510 510 #
511 511 if self.blockIndex==self.blocksPerFile:
512 512 if not( self.__setNextFileOffline() ):
513 513 self.dataOut.flagNoData = True
514 514 return 0
515 515
516 516 # if self.datablock == None: # setear esta condicion cuando no hayan datos por leers
517 517 # self.dataOut.flagNoData = True
518 518 # return 0
519 519 # self.__readData()
520 520 self.__setDataOut()
521 521 self.dataOut.flagNoData = False
522 522
523 523 self.blockIndex += 1
524 524
525 525 return
526 526
527 527 def run(self, **kwargs):
528 528
529 529 if not(self.isConfig):
530 530 self.setup(**kwargs)
531 531 # self.setObjProperties()
532 532 self.isConfig = True
533 533
534 534 self.getData()
535 535
536 536 return
537 537
538 538 class ParamWriter(Operation):
539 539 '''
540 540 HDF5 Writer, stores parameters data in HDF5 format files
541 541
542 542 path: path where the files will be stored
543 543
544 544 blocksPerFile: number of blocks that will be saved in per HDF5 format file
545 545
546 546 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
547 547
548 548 metadataList: list of attributes that will be stored as metadata
549 549
550 550 dataList: list of attributes that will be stores as data
551 551
552 552 '''
553 553
554 554
555 555 ext = ".hdf5"
556 556
557 557 optchar = "D"
558 558
559 559 metaoptchar = "M"
560 560
561 561 metaFile = None
562 562
563 563 filename = None
564 564
565 565 path = None
566 566
567 567 setFile = None
568 568
569 569 fp = None
570 570
571 571 grp = None
572 572
573 573 ds = None
574 574
575 575 firsttime = True
576 576
577 577 #Configurations
578 578
579 579 blocksPerFile = None
580 580
581 581 blockIndex = None
582 582
583 583 dataOut = None
584 584
585 585 #Data Arrays
586 586
587 587 dataList = None
588 588
589 589 metadataList = None
590 590
591 591 # arrayDim = None
592 592
593 593 dsList = None #List of dictionaries with dataset properties
594 594
595 595 tableDim = None
596 596
597 597 # dtype = [('arrayName', 'S20'),('nChannels', 'i'), ('nPoints', 'i'), ('nSamples', 'i'),('mode', 'b')]
598 598
599 599 dtype = [('arrayName', 'S20'),('nDimensions', 'i'), ('dim2', 'i'), ('dim1', 'i'),('dim0', 'i'),('mode', 'b')]
600 600
601 601 currentDay = None
602 602
603 603 lastTime = None
604 604
605 605 def __init__(self, **kwargs):
606 606 Operation.__init__(self, **kwargs)
607 607 self.isConfig = False
608 608 return
609 609
610 610 def setup(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, **kwargs):
611 611 self.path = path
612 612 self.blocksPerFile = blocksPerFile
613 613 self.metadataList = metadataList
614 614 self.dataList = dataList
615 615 self.dataOut = dataOut
616 616 self.mode = mode
617 617
618 618 if self.mode is not None:
619 619 self.mode = numpy.zeros(len(self.dataList)) + mode
620 620 else:
621 621 self.mode = numpy.ones(len(self.dataList))
622 622
623 623 arrayDim = numpy.zeros((len(self.dataList),5))
624 624
625 625 #Table dimensions
626 626 dtype0 = self.dtype
627 627 tableList = []
628 628
629 629 #Dictionary and list of tables
630 630 dsList = []
631 631
632 632 for i in range(len(self.dataList)):
633 633 dsDict = {}
634 634 dataAux = getattr(self.dataOut, self.dataList[i])
635 635 dsDict['variable'] = self.dataList[i]
636 636 #--------------------- Conditionals ------------------------
637 637 #There is no data
638 638 if dataAux is None:
639 639 return 0
640 640
641 641 #Not array, just a number
642 642 #Mode 0
643 643 if type(dataAux)==float or type(dataAux)==int:
644 644 dsDict['mode'] = 0
645 645 dsDict['nDim'] = 0
646 646 arrayDim[i,0] = 0
647 647 dsList.append(dsDict)
648 648
649 649 #Mode 2: meteors
650 650 elif mode[i] == 2:
651 651 # dsDict['nDim'] = 0
652 652 dsDict['dsName'] = 'table0'
653 653 dsDict['mode'] = 2 # Mode meteors
654 654 dsDict['shape'] = dataAux.shape[-1]
655 655 dsDict['nDim'] = 0
656 656 dsDict['dsNumber'] = 1
657 657
658 658 arrayDim[i,3] = dataAux.shape[-1]
659 659 arrayDim[i,4] = mode[i] #Mode the data was stored
660 660
661 661 dsList.append(dsDict)
662 662
663 663 #Mode 1
664 664 else:
665 665 arrayDim0 = dataAux.shape #Data dimensions
666 666 arrayDim[i,0] = len(arrayDim0) #Number of array dimensions
667 667 arrayDim[i,4] = mode[i] #Mode the data was stored
668 668
669 669 strtable = 'table'
670 670 dsDict['mode'] = 1 # Mode parameters
671 671
672 672 # Three-dimension arrays
673 673 if len(arrayDim0) == 3:
674 674 arrayDim[i,1:-1] = numpy.array(arrayDim0)
675 675 nTables = int(arrayDim[i,2])
676 676 dsDict['dsNumber'] = nTables
677 677 dsDict['shape'] = arrayDim[i,2:4]
678 678 dsDict['nDim'] = 3
679 679
680 680 for j in range(nTables):
681 681 dsDict = dsDict.copy()
682 682 dsDict['dsName'] = strtable + str(j)
683 683 dsList.append(dsDict)
684 684
685 685 # Two-dimension arrays
686 686 elif len(arrayDim0) == 2:
687 687 arrayDim[i,2:-1] = numpy.array(arrayDim0)
688 688 nTables = int(arrayDim[i,2])
689 689 dsDict['dsNumber'] = nTables
690 690 dsDict['shape'] = arrayDim[i,3]
691 691 dsDict['nDim'] = 2
692 692
693 693 for j in range(nTables):
694 694 dsDict = dsDict.copy()
695 695 dsDict['dsName'] = strtable + str(j)
696 696 dsList.append(dsDict)
697 697
698 698 # One-dimension arrays
699 699 elif len(arrayDim0) == 1:
700 700 arrayDim[i,3] = arrayDim0[0]
701 701 dsDict['shape'] = arrayDim0[0]
702 702 dsDict['dsNumber'] = 1
703 703 dsDict['dsName'] = strtable + str(0)
704 704 dsDict['nDim'] = 1
705 705 dsList.append(dsDict)
706 706
707 707 table = numpy.array((self.dataList[i],) + tuple(arrayDim[i,:]),dtype = dtype0)
708 708 tableList.append(table)
709 709
710 710 # self.arrayDim = arrayDim
711 711 self.dsList = dsList
712 712 self.tableDim = numpy.array(tableList, dtype = dtype0)
713 713 self.blockIndex = 0
714 714
715 715 timeTuple = time.localtime(dataOut.utctime)
716 716 self.currentDay = timeTuple.tm_yday
717 717 return 1
718 718
719 719 def putMetadata(self):
720 720
721 721 fp = self.createMetadataFile()
722 722 self.writeMetadata(fp)
723 723 fp.close()
724 724 return
725 725
726 726 def createMetadataFile(self):
727 727 ext = self.ext
728 728 path = self.path
729 729 setFile = self.setFile
730 730
731 731 timeTuple = time.localtime(self.dataOut.utctime)
732 732
733 733 subfolder = ''
734 734 fullpath = os.path.join( path, subfolder )
735 735
736 736 if not( os.path.exists(fullpath) ):
737 737 os.mkdir(fullpath)
738 738 setFile = -1 #inicializo mi contador de seteo
739 739
740 740 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
741 741 fullpath = os.path.join( path, subfolder )
742 742
743 743 if not( os.path.exists(fullpath) ):
744 744 os.mkdir(fullpath)
745 745 setFile = -1 #inicializo mi contador de seteo
746 746
747 747 else:
748 748 filesList = os.listdir( fullpath )
749 749 filesList = sorted( filesList, key=str.lower )
750 750 if len( filesList ) > 0:
751 751 filesList = [k for k in filesList if 'M' in k]
752 752 filen = filesList[-1]
753 753 # el filename debera tener el siguiente formato
754 754 # 0 1234 567 89A BCDE (hex)
755 755 # x YYYY DDD SSS .ext
756 756 if isNumber( filen[8:11] ):
757 757 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
758 758 else:
759 759 setFile = -1
760 760 else:
761 761 setFile = -1 #inicializo mi contador de seteo
762 762
763 763 if self.setType is None:
764 764 setFile += 1
765 765 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
766 766 timeTuple.tm_year,
767 767 timeTuple.tm_yday,
768 768 setFile,
769 769 ext )
770 770 else:
771 771 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
772 772 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
773 773 timeTuple.tm_year,
774 774 timeTuple.tm_yday,
775 775 setFile,
776 776 ext )
777 777
778 778 filename = os.path.join( path, subfolder, file )
779 779 self.metaFile = file
780 780 #Setting HDF5 File
781 781 fp = h5py.File(filename,'w')
782 782
783 783 return fp
784 784
785 785 def writeMetadata(self, fp):
786 786
787 787 grp = fp.create_group("Metadata")
788 788 grp.create_dataset('array dimensions', data = self.tableDim, dtype = self.dtype)
789 789
790 790 for i in range(len(self.metadataList)):
791 791 grp.create_dataset(self.metadataList[i], data=getattr(self.dataOut, self.metadataList[i]))
792 792 return
793 793
794 794 def timeFlag(self):
795 795 currentTime = self.dataOut.utctime
796 796
797 797 if self.lastTime is None:
798 798 self.lastTime = currentTime
799 799
800 800 #Day
801 801 timeTuple = time.localtime(currentTime)
802 802 dataDay = timeTuple.tm_yday
803 803
804 804 #Time
805 805 timeDiff = currentTime - self.lastTime
806 806
807 807 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
808 808 if dataDay != self.currentDay:
809 809 self.currentDay = dataDay
810 810 return True
811 811 elif timeDiff > 3*60*60:
812 812 self.lastTime = currentTime
813 813 return True
814 814 else:
815 815 self.lastTime = currentTime
816 816 return False
817 817
818 818 def setNextFile(self):
819 819
820 820 ext = self.ext
821 821 path = self.path
822 822 setFile = self.setFile
823 823 mode = self.mode
824 824
825 825 timeTuple = time.localtime(self.dataOut.utctime)
826 826 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
827 827
828 828 fullpath = os.path.join( path, subfolder )
829 829
830 830 if os.path.exists(fullpath):
831 831 filesList = os.listdir( fullpath )
832 832 filesList = [k for k in filesList if 'D' in k]
833 833 if len( filesList ) > 0:
834 834 filesList = sorted( filesList, key=str.lower )
835 835 filen = filesList[-1]
836 836 # el filename debera tener el siguiente formato
837 837 # 0 1234 567 89A BCDE (hex)
838 838 # x YYYY DDD SSS .ext
839 839 if isNumber( filen[8:11] ):
840 840 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
841 841 else:
842 842 setFile = -1
843 843 else:
844 844 setFile = -1 #inicializo mi contador de seteo
845 845 else:
846 846 os.makedirs(fullpath)
847 847 setFile = -1 #inicializo mi contador de seteo
848 848
849 849 if self.setType is None:
850 850 setFile += 1
851 851 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
852 852 timeTuple.tm_year,
853 853 timeTuple.tm_yday,
854 854 setFile,
855 855 ext )
856 856 else:
857 857 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
858 858 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
859 859 timeTuple.tm_year,
860 860 timeTuple.tm_yday,
861 861 setFile,
862 862 ext )
863 863
864 864 filename = os.path.join( path, subfolder, file )
865 865
866 866 #Setting HDF5 File
867 867 fp = h5py.File(filename,'w')
868 868 #write metadata
869 869 self.writeMetadata(fp)
870 870 #Write data
871 871 grp = fp.create_group("Data")
872 872 # grp.attrs['metadata'] = self.metaFile
873 873
874 874 # grp.attrs['blocksPerFile'] = 0
875 875 ds = []
876 876 data = []
877 877 dsList = self.dsList
878 878 i = 0
879 879 while i < len(dsList):
880 880 dsInfo = dsList[i]
881 881 #One-dimension data
882 882 if dsInfo['mode'] == 0:
883 883 # ds0 = grp.create_dataset(self.dataList[i], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype='S20')
884 884 ds0 = grp.create_dataset(dsInfo['variable'], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype=numpy.float64)
885 885 ds.append(ds0)
886 886 data.append([])
887 887 i += 1
888 888 continue
889 889 # nDimsForDs.append(nDims[i])
890 890
891 891 elif dsInfo['mode'] == 2:
892 892 grp0 = grp.create_group(dsInfo['variable'])
893 893 ds0 = grp0.create_dataset(dsInfo['dsName'], (1,dsInfo['shape']), data = numpy.zeros((1,dsInfo['shape'])) , maxshape=(None,dsInfo['shape']), chunks=True)
894 894 ds.append(ds0)
895 895 data.append([])
896 896 i += 1
897 897 continue
898 898
899 899 elif dsInfo['mode'] == 1:
900 900 grp0 = grp.create_group(dsInfo['variable'])
901 901
902 902 for j in range(dsInfo['dsNumber']):
903 903 dsInfo = dsList[i]
904 904 tableName = dsInfo['dsName']
905 905 shape = int(dsInfo['shape'])
906 906
907 907 if dsInfo['nDim'] == 3:
908 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 909 else:
910 910 ds0 = grp0.create_dataset(tableName, (1,shape), data = numpy.zeros((1,shape)) , maxshape=(None,shape), chunks=True)
911 911
912 912 ds.append(ds0)
913 913 data.append([])
914 914 i += 1
915 915 # nDimsForDs.append(nDims[i])
916 916
917 917 fp.flush()
918 918 fp.close()
919 919
920 920 # self.nDatas = nDatas
921 921 # self.nDims = nDims
922 922 # self.nDimsForDs = nDimsForDs
923 923 #Saving variables
924 924 print 'Writing the file: %s'%filename
925 925 self.filename = filename
926 926 # self.fp = fp
927 927 # self.grp = grp
928 928 # self.grp.attrs.modify('nRecords', 1)
929 929 self.ds = ds
930 930 self.data = data
931 931 # self.setFile = setFile
932 932 self.firsttime = True
933 933 self.blockIndex = 0
934 934 return
935 935
936 936 def putData(self):
937 937
938 938 if self.blockIndex == self.blocksPerFile or self.timeFlag():
939 939 self.setNextFile()
940 940
941 941 # if not self.firsttime:
942 942 self.readBlock()
943 943 self.setBlock() #Prepare data to be written
944 944 self.writeBlock() #Write data
945 945
946 946 return
947 947
948 948 def readBlock(self):
949 949
950 950 '''
951 951 data Array configured
952 952
953 953
954 954 self.data
955 955 '''
956 956 dsList = self.dsList
957 957 ds = self.ds
958 958 #Setting HDF5 File
959 959 fp = h5py.File(self.filename,'r+')
960 960 grp = fp["Data"]
961 961 ind = 0
962 962
963 963 # grp.attrs['blocksPerFile'] = 0
964 964 while ind < len(dsList):
965 965 dsInfo = dsList[ind]
966 966
967 967 if dsInfo['mode'] == 0:
968 968 ds0 = grp[dsInfo['variable']]
969 969 ds[ind] = ds0
970 970 ind += 1
971 971 else:
972 972
973 973 grp0 = grp[dsInfo['variable']]
974 974
975 975 for j in range(dsInfo['dsNumber']):
976 976 dsInfo = dsList[ind]
977 977 ds0 = grp0[dsInfo['dsName']]
978 978 ds[ind] = ds0
979 979 ind += 1
980 980
981 981 self.fp = fp
982 982 self.grp = grp
983 983 self.ds = ds
984 984
985 985 return
986 986
987 987 def setBlock(self):
988 988 '''
989 989 data Array configured
990 990
991 991
992 992 self.data
993 993 '''
994 994 #Creating Arrays
995 995 dsList = self.dsList
996 996 data = self.data
997 997 ind = 0
998 998
999 999 while ind < len(dsList):
1000 1000 dsInfo = dsList[ind]
1001 1001 dataAux = getattr(self.dataOut, dsInfo['variable'])
1002 1002
1003 1003 mode = dsInfo['mode']
1004 1004 nDim = dsInfo['nDim']
1005 1005
1006 1006 if mode == 0 or mode == 2 or nDim == 1:
1007 1007 data[ind] = dataAux
1008 1008 ind += 1
1009 1009 # elif nDim == 1:
1010 1010 # data[ind] = numpy.reshape(dataAux,(numpy.size(dataAux),1))
1011 1011 # ind += 1
1012 1012 elif nDim == 2:
1013 1013 for j in range(dsInfo['dsNumber']):
1014 1014 data[ind] = dataAux[j,:]
1015 1015 ind += 1
1016 1016 elif nDim == 3:
1017 1017 for j in range(dsInfo['dsNumber']):
1018 1018 data[ind] = dataAux[:,j,:]
1019 1019 ind += 1
1020 1020
1021 1021 self.data = data
1022 1022 return
1023 1023
1024 1024 def writeBlock(self):
1025 1025 '''
1026 1026 Saves the block in the HDF5 file
1027 1027 '''
1028 1028 dsList = self.dsList
1029 1029
1030 1030 for i in range(len(self.ds)):
1031 1031 dsInfo = dsList[i]
1032 1032 nDim = dsInfo['nDim']
1033 1033 mode = dsInfo['mode']
1034 1034
1035 1035 # First time
1036 1036 if self.firsttime:
1037 1037 # self.ds[i].resize(self.data[i].shape)
1038 1038 # self.ds[i][self.blockIndex,:] = self.data[i]
1039 1039 if type(self.data[i]) == numpy.ndarray:
1040 1040
1041 1041 if nDim == 3:
1042 1042 self.data[i] = self.data[i].reshape((self.data[i].shape[0],self.data[i].shape[1],1))
1043 1043 self.ds[i].resize(self.data[i].shape)
1044 1044 if mode == 2:
1045 1045 self.ds[i].resize(self.data[i].shape)
1046 1046 self.ds[i][:] = self.data[i]
1047 1047 else:
1048 1048
1049 1049 # From second time
1050 1050 # Meteors!
1051 1051 if mode == 2:
1052 1052 dataShape = self.data[i].shape
1053 1053 dsShape = self.ds[i].shape
1054 1054 self.ds[i].resize((self.ds[i].shape[0] + dataShape[0],self.ds[i].shape[1]))
1055 1055 self.ds[i][dsShape[0]:,:] = self.data[i]
1056 1056 # No dimension
1057 1057 elif mode == 0:
1058 1058 self.ds[i].resize((self.ds[i].shape[0], self.ds[i].shape[1] + 1))
1059 1059 self.ds[i][0,-1] = self.data[i]
1060 1060 # One dimension
1061 1061 elif nDim == 1:
1062 1062 self.ds[i].resize((self.ds[i].shape[0] + 1, self.ds[i].shape[1]))
1063 1063 self.ds[i][-1,:] = self.data[i]
1064 1064 # Two dimension
1065 1065 elif nDim == 2:
1066 1066 self.ds[i].resize((self.ds[i].shape[0] + 1,self.ds[i].shape[1]))
1067 1067 self.ds[i][self.blockIndex,:] = self.data[i]
1068 1068 # Three dimensions
1069 1069 elif nDim == 3:
1070 1070 self.ds[i].resize((self.ds[i].shape[0],self.ds[i].shape[1],self.ds[i].shape[2]+1))
1071 1071 self.ds[i][:,:,-1] = self.data[i]
1072 1072
1073 1073 self.firsttime = False
1074 1074 self.blockIndex += 1
1075 1075
1076 1076 #Close to save changes
1077 1077 self.fp.flush()
1078 1078 self.fp.close()
1079 1079 return
1080 1080
1081 1081 def run(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, **kwargs):
1082 1082
1083 1083 if not(self.isConfig):
1084 1084 flagdata = self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
1085 1085 metadataList=metadataList, dataList=dataList, mode=mode, **kwargs)
1086 1086
1087 1087 if not(flagdata):
1088 1088 return
1089 1089
1090 1090 self.isConfig = True
1091 1091 # self.putMetadata()
1092 1092 self.setNextFile()
1093 1093
1094 1094 self.putData()
1095 1095 return
@@ -1,679 +1,698
1 1 '''
2 2 Created on Jul 2, 2014
3 3
4 4 @author: roj-idl71
5 5 '''
6 6 import numpy
7 7
8 8 from jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
9 9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
10 10 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
11 11 from schainpy.model.data.jrodata import Spectra
12 12
13 13 class SpectraReader(JRODataReader, ProcessingUnit):
14
14 15 """
15 16 Esta clase permite leer datos de espectros desde archivos procesados (.pdata). La lectura
16 17 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones)
17 18 son almacenados en tres buffer's para el Self Spectra, el Cross Spectra y el DC Channel.
18 19
19 20 paresCanalesIguales * alturas * perfiles (Self Spectra)
20 21 paresCanalesDiferentes * alturas * perfiles (Cross Spectra)
21 22 canales * alturas (DC Channels)
22 23
24
23 25 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
24 26 RadarControllerHeader y Spectra. Los tres primeros se usan para almacenar informacion de la
25 27 cabecera de datos (metadata), y el cuarto (Spectra) para obtener y almacenar un bloque de
26 28 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
27 29
28 30 Example:
29 31 dpath = "/home/myuser/data"
30 32
31 33 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
32 34
33 35 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
34 36
35 37 readerObj = SpectraReader()
36 38
37 39 readerObj.setup(dpath, startTime, endTime)
38 40
39 41 while(True):
40 42
41 43 readerObj.getData()
42 44
43 45 print readerObj.data_spc
44 46
45 47 print readerObj.data_cspc
46 48
47 49 print readerObj.data_dc
48 50
49 51 if readerObj.flagNoMoreFiles:
50 52 break
51 53
52 54 """
53 55
54 56 pts2read_SelfSpectra = 0
55 57
56 58 pts2read_CrossSpectra = 0
57 59
58 60 pts2read_DCchannels = 0
59 61
60 62 ext = ".pdata"
61 63
62 64 optchar = "P"
63 65
64 66 dataOut = None
65 67
66 68 nRdChannels = None
67 69
68 70 nRdPairs = None
69 71
70 72 rdPairList = []
71 73
72 74 def __init__(self, **kwargs):
73 75 """
74 76 Inicializador de la clase SpectraReader para la lectura de datos de espectros.
75 77
76 78 Inputs:
79
77 80 dataOut : Objeto de la clase Spectra. Este objeto sera utilizado para
78 81 almacenar un perfil de datos cada vez que se haga un requerimiento
79 82 (getData). El perfil sera obtenido a partir del buffer de datos,
80 83 si el buffer esta vacio se hara un nuevo proceso de lectura de un
81 84 bloque de datos.
82 85 Si este parametro no es pasado se creara uno internamente.
83 86
84 Affected:
87
88 Affected:
89
85 90 self.dataOut
86 91
87 92 Return : None
88 93 """
89 94
95
90 96 #Eliminar de la base la herencia
91 97 ProcessingUnit.__init__(self, **kwargs)
92
98
93 99 # self.isConfig = False
94
100
95 101 self.pts2read_SelfSpectra = 0
96
102
97 103 self.pts2read_CrossSpectra = 0
98
104
99 105 self.pts2read_DCchannels = 0
100
106
101 107 self.datablock = None
102
108
103 109 self.utc = None
104
110
105 111 self.ext = ".pdata"
106
112
107 113 self.optchar = "P"
108
114
109 115 self.basicHeaderObj = BasicHeader(LOCALTIME)
110
116
111 117 self.systemHeaderObj = SystemHeader()
112
118
113 119 self.radarControllerHeaderObj = RadarControllerHeader()
114
120
115 121 self.processingHeaderObj = ProcessingHeader()
116
122
117 123 self.online = 0
118
124
119 125 self.fp = None
120
126
121 127 self.idFile = None
122
128
123 129 self.dtype = None
124
130
125 131 self.fileSizeByHeader = None
126
132
127 133 self.filenameList = []
128
134
129 135 self.filename = None
130
136
131 137 self.fileSize = None
132
138
133 139 self.firstHeaderSize = 0
134
140
135 141 self.basicHeaderSize = 24
136
142
137 143 self.pathList = []
138 144
139 145 self.lastUTTime = 0
140
146
141 147 self.maxTimeStep = 30
142
148
143 149 self.flagNoMoreFiles = 0
144
150
145 151 self.set = 0
146
152
147 153 self.path = None
148 154
149 155 self.delay = 60 #seconds
150
156
151 157 self.nTries = 3 #quantity tries
152
158
153 159 self.nFiles = 3 #number of files for searching
154
160
155 161 self.nReadBlocks = 0
156
162
157 163 self.flagIsNewFile = 1
158
164
159 165 self.__isFirstTimeOnline = 1
160
166
161 167 # self.ippSeconds = 0
162
163 self.flagDiscontinuousBlock = 0
164
168
169 self.flagDiscontinuousBlock = 0
170
165 171 self.flagIsNewBlock = 0
166
172
167 173 self.nTotalBlocks = 0
168
174
169 175 self.blocksize = 0
170
176
171 177 self.dataOut = self.createObjByDefault()
172
178
173 179 self.profileIndex = 1 #Always
174 180
175 181
176 182 def createObjByDefault(self):
177
183
178 184 dataObj = Spectra()
179
185
180 186 return dataObj
181
187
182 188 def __hasNotDataInBuffer(self):
183 189 return 1
184 190
185 191
186 192 def getBlockDimension(self):
187 193 """
188 194 Obtiene la cantidad de puntos a leer por cada bloque de datos
189
195
190 196 Affected:
191 197 self.nRdChannels
192 198 self.nRdPairs
193 199 self.pts2read_SelfSpectra
194 200 self.pts2read_CrossSpectra
195 201 self.pts2read_DCchannels
196 202 self.blocksize
197 203 self.dataOut.nChannels
198 204 self.dataOut.nPairs
199 205
200 206 Return:
201 207 None
202 208 """
203 209 self.nRdChannels = 0
204 210 self.nRdPairs = 0
205 211 self.rdPairList = []
206 212
207 213 for i in range(0, self.processingHeaderObj.totalSpectra*2, 2):
208 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 217 else:
211 218 self.nRdPairs = self.nRdPairs + 1 #par de canales diferentes
212 219 self.rdPairList.append((self.processingHeaderObj.spectraComb[i], self.processingHeaderObj.spectraComb[i+1]))
213 220
214 221 pts2read = self.processingHeaderObj.nHeights * self.processingHeaderObj.profilesPerBlock
215
222
216 223 self.pts2read_SelfSpectra = int(self.nRdChannels * pts2read)
217 224 self.blocksize = self.pts2read_SelfSpectra
218
225
219 226 if self.processingHeaderObj.flag_cspc:
220 227 self.pts2read_CrossSpectra = int(self.nRdPairs * pts2read)
221 228 self.blocksize += self.pts2read_CrossSpectra
222
229
223 230 if self.processingHeaderObj.flag_dc:
224 231 self.pts2read_DCchannels = int(self.systemHeaderObj.nChannels * self.processingHeaderObj.nHeights)
225 232 self.blocksize += self.pts2read_DCchannels
226
233
227 234 # self.blocksize = self.pts2read_SelfSpectra + self.pts2read_CrossSpectra + self.pts2read_DCchannels
228 235
229
236
230 237 def readBlock(self):
231 238 """
232 239 Lee el bloque de datos desde la posicion actual del puntero del archivo
233 240 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
234 241 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
235 242 es seteado a 0
236
243
237 244 Return: None
238
245
239 246 Variables afectadas:
247
240 248
241 249 self.flagIsNewFile
242 250 self.flagIsNewBlock
243 251 self.nTotalBlocks
244 252 self.data_spc
245 253 self.data_cspc
246 254 self.data_dc
247 255
248 Exceptions:
256 Exceptions:
249 257 Si un bloque leido no es un bloque valido
250 258 """
259
251 260 blockOk_flag = False
252 261 fpointer = self.fp.tell()
253 262
254 263 spc = numpy.fromfile( self.fp, self.dtype[0], self.pts2read_SelfSpectra )
255 264 spc = spc.reshape( (self.nRdChannels, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
256 265
257 266 if self.processingHeaderObj.flag_cspc:
258 267 cspc = numpy.fromfile( self.fp, self.dtype, self.pts2read_CrossSpectra )
259 268 cspc = cspc.reshape( (self.nRdPairs, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
260
269
261 270 if self.processingHeaderObj.flag_dc:
262 271 dc = numpy.fromfile( self.fp, self.dtype, self.pts2read_DCchannels ) #int(self.processingHeaderObj.nHeights*self.systemHeaderObj.nChannels) )
263 272 dc = dc.reshape( (self.systemHeaderObj.nChannels, self.processingHeaderObj.nHeights) ) #transforma a un arreglo 2D
264
265
273
274
266 275 if not(self.processingHeaderObj.shif_fft):
267 276 #desplaza a la derecha en el eje 2 determinadas posiciones
268 277 shift = int(self.processingHeaderObj.profilesPerBlock/2)
269 278 spc = numpy.roll( spc, shift , axis=2 )
270
279
271 280 if self.processingHeaderObj.flag_cspc:
272 281 #desplaza a la derecha en el eje 2 determinadas posiciones
273 282 cspc = numpy.roll( cspc, shift, axis=2 )
274
283
275 284 #Dimensions : nChannels, nProfiles, nSamples
276 285 spc = numpy.transpose( spc, (0,2,1) )
277 286 self.data_spc = spc
287
288 if self.processingHeaderObj.flag_cspc:
278 289
279 if self.processingHeaderObj.flag_cspc:
280 290 cspc = numpy.transpose( cspc, (0,2,1) )
281 291 self.data_cspc = cspc['real'] + cspc['imag']*1j
282 292 else:
283 293 self.data_cspc = None
294
284 295
285 296 if self.processingHeaderObj.flag_dc:
286 297 self.data_dc = dc['real'] + dc['imag']*1j
287 298 else:
288 299 self.data_dc = None
289 300
290 301 self.flagIsNewFile = 0
291 302 self.flagIsNewBlock = 1
292 303
293 304 self.nTotalBlocks += 1
294 305 self.nReadBlocks += 1
295 306
296 307 return 1
297
308
298 309 def getFirstHeader(self):
299
310
300 311 self.getBasicHeader()
301
312
302 313 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
303
314
304 315 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
305
316
306 317 # self.dataOut.ippSeconds = self.ippSeconds
307
318
308 319 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt * self.processingHeaderObj.nIncohInt * self.processingHeaderObj.profilesPerBlock
309 320
310 321 self.dataOut.dtype = self.dtype
311
322
312 323 # self.dataOut.nPairs = self.nPairs
313
324
314 325 self.dataOut.pairsList = self.rdPairList
315
326
316 327 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
317
328
318 329 self.dataOut.nFFTPoints = self.processingHeaderObj.profilesPerBlock
319
330
320 331 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
321
332
322 333 self.dataOut.nIncohInt = self.processingHeaderObj.nIncohInt
323
334
324 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)
327
337 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight)
338
328 339 self.dataOut.channelList = range(self.systemHeaderObj.nChannels)
329
340
330 341 self.dataOut.flagShiftFFT = True #Data is always shifted
331
342
332 343 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode #asumo q la data no esta decodificada
333
334 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data esta sin flip
335
344
345 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data esta sin flip
346
336 347 def getData(self):
337 348 """
338 349 First method to execute before "RUN" is called.
339
350
340 351 Copia el buffer de lectura a la clase "Spectra",
341 352 con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de
342 353 lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock"
343
354
344 355 Return:
345 356 0 : Si no hay mas archivos disponibles
346 357 1 : Si hizo una buena copia del buffer
347
358
348 359 Affected:
349 360 self.dataOut
350
361
351 362 self.flagDiscontinuousBlock
352 363 self.flagIsNewBlock
353 364 """
354 365
355 366 if self.flagNoMoreFiles:
356 367 self.dataOut.flagNoData = True
357 368 print 'Process finished'
358 369 return 0
359
370
360 371 self.flagDiscontinuousBlock = 0
361 372 self.flagIsNewBlock = 0
362
363 if self.__hasNotDataInBuffer():
373
374 if self.__hasNotDataInBuffer():
364 375
365 376 if not( self.readNextBlock() ):
366 377 self.dataOut.flagNoData = True
367 378 return 0
379
368 380
369 381 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
370 382
371 383 if self.data_spc is None:
372 384 self.dataOut.flagNoData = True
373 385 return 0
374
386
375 387 self.getBasicHeader()
376
388
377 389 self.getFirstHeader()
378 390
379 391 self.dataOut.data_spc = self.data_spc
380
392
381 393 self.dataOut.data_cspc = self.data_cspc
382
394
383 395 self.dataOut.data_dc = self.data_dc
384
396
385 397 self.dataOut.flagNoData = False
386
398
387 399 self.dataOut.realtime = self.online
388
400
389 401 return self.dataOut.data_spc
390 402
391 403 class SpectraWriter(JRODataWriter, Operation):
392
393 """
404
405 """
394 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 410 ext = ".pdata"
399
411
400 412 optchar = "P"
401
413
402 414 shape_spc_Buffer = None
403
415
404 416 shape_cspc_Buffer = None
405
417
406 418 shape_dc_Buffer = None
407
419
408 420 data_spc = None
409
421
410 422 data_cspc = None
411
423
412 424 data_dc = None
413
425
414 426 # dataOut = None
415
416 def __init__(self, **kwargs):
417 """
427
428 def __init__(self):
429 """
418 430 Inicializador de la clase SpectraWriter para la escritura de datos de espectros.
431
432 Affected:
419 433
420 Affected:
421 434 self.dataOut
422 435 self.basicHeaderObj
423 436 self.systemHeaderObj
424 437 self.radarControllerHeaderObj
425 438 self.processingHeaderObj
426 439
427 440 Return: None
428 441 """
429
430 Operation.__init__(self, **kwargs)
431
442
443 Operation.__init__(self)
444
432 445 self.isConfig = False
433
446
434 447 self.nTotalBlocks = 0
435
448
436 449 self.data_spc = None
437
450
438 451 self.data_cspc = None
452
439 453
440 454 self.data_dc = None
441 455
442 456 self.fp = None
443 457
444 458 self.flagIsNewFile = 1
445
446 self.nTotalBlocks = 0
447
459
460 self.nTotalBlocks = 0
461
448 462 self.flagIsNewBlock = 0
449 463
450 464 self.setFile = None
451
465
452 466 self.dtype = None
453
467
454 468 self.path = None
455
469
456 470 self.noMoreFiles = 0
457
471
458 472 self.filename = None
459
473
460 474 self.basicHeaderObj = BasicHeader(LOCALTIME)
461
475
462 476 self.systemHeaderObj = SystemHeader()
463
477
464 478 self.radarControllerHeaderObj = RadarControllerHeader()
465
479
466 480 self.processingHeaderObj = ProcessingHeader()
467 481
468
482
469 483 def hasAllDataInBuffer(self):
470 484 return 1
471 485
486
472 487
473 488 def setBlockDimension(self):
474 489 """
475 490 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
476 491
477 492 Affected:
478 493 self.shape_spc_Buffer
479 494 self.shape_cspc_Buffer
480 495 self.shape_dc_Buffer
481 496
482 497 Return: None
483 498 """
484 499 self.shape_spc_Buffer = (self.dataOut.nChannels,
485 500 self.processingHeaderObj.nHeights,
486 501 self.processingHeaderObj.profilesPerBlock)
487 502
488 503 self.shape_cspc_Buffer = (self.dataOut.nPairs,
489 504 self.processingHeaderObj.nHeights,
490 505 self.processingHeaderObj.profilesPerBlock)
491
506
492 507 self.shape_dc_Buffer = (self.dataOut.nChannels,
493 508 self.processingHeaderObj.nHeights)
494 509
495
510
496 511 def writeBlock(self):
497 512 """
498 513 Escribe el buffer en el file designado
514
499 515
500 516 Affected:
501 517 self.data_spc
502 518 self.data_cspc
503 519 self.data_dc
504 520 self.flagIsNewFile
505 521 self.flagIsNewBlock
506 522 self.nTotalBlocks
507 self.nWriteBlocks
508
523 self.nWriteBlocks
524
509 525 Return: None
510 526 """
511
527
512 528 spc = numpy.transpose( self.data_spc, (0,2,1) )
513 529 if not( self.processingHeaderObj.shif_fft ):
514 530 spc = numpy.roll( spc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
515 531 data = spc.reshape((-1))
516 532 data = data.astype(self.dtype[0])
517 533 data.tofile(self.fp)
518 534
519 535 if self.data_cspc is not None:
520 536 data = numpy.zeros( self.shape_cspc_Buffer, self.dtype )
521 537 cspc = numpy.transpose( self.data_cspc, (0,2,1) )
522 538 if not( self.processingHeaderObj.shif_fft ):
523 539 cspc = numpy.roll( cspc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
524 540 data['real'] = cspc.real
525 541 data['imag'] = cspc.imag
526 542 data = data.reshape((-1))
527 543 data.tofile(self.fp)
544
528 545
529 546 if self.data_dc is not None:
530 547 data = numpy.zeros( self.shape_dc_Buffer, self.dtype )
531 548 dc = self.data_dc
532 549 data['real'] = dc.real
533 550 data['imag'] = dc.imag
534 551 data = data.reshape((-1))
535 552 data.tofile(self.fp)
536 553
537 554 # self.data_spc.fill(0)
538 #
555 #
539 556 # if self.data_dc is not None:
540 557 # self.data_dc.fill(0)
541 #
558 #
542 559 # if self.data_cspc is not None:
543 560 # self.data_cspc.fill(0)
561
544 562
545 563 self.flagIsNewFile = 0
546 564 self.flagIsNewBlock = 1
547 565 self.nTotalBlocks += 1
548 566 self.nWriteBlocks += 1
549 567 self.blockIndex += 1
550
568
551 569 # print "[Writing] Block = %d04" %self.blockIndex
552
570
553 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 576 Affected:
558 577 self.data_spc
559 578 self.data_cspc
560 579 self.data_dc
561 580
562 Return:
563 0 : Si no hay data o no hay mas files que puedan escribirse
581 Return:
582 0 : Si no hay data o no hay mas files que puedan escribirse
564 583 1 : Si se escribio la data de un bloque en un file
565 584 """
566
585
567 586 if self.dataOut.flagNoData:
568 587 return 0
569
588
570 589 self.flagIsNewBlock = 0
571
590
572 591 if self.dataOut.flagDiscontinuousBlock:
573 592 self.data_spc.fill(0)
574 if self.dataOut.data_cspc is not None:
575 self.data_cspc.fill(0)
576 if self.dataOut.data_dc is not None:
577 self.data_dc.fill(0)
593 self.data_cspc.fill(0)
594 self.data_dc.fill(0)
578 595 self.setNextFile()
579
596
580 597 if self.flagIsNewFile == 0:
581 598 self.setBasicHeader()
582
599
583 600 self.data_spc = self.dataOut.data_spc.copy()
584
601
585 602 if self.dataOut.data_cspc is not None:
586 603 self.data_cspc = self.dataOut.data_cspc.copy()
587
604
588 605 if self.dataOut.data_dc is not None:
589 606 self.data_dc = self.dataOut.data_dc.copy()
590
607
591 608 # #self.processingHeaderObj.dataBlocksPerFile)
592 609 if self.hasAllDataInBuffer():
593 610 # self.setFirstHeader()
594 611 self.writeNextBlock()
595
612
596 613 return 1
614
597 615
598 616 def __getBlockSize(self):
599 617 '''
600 618 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Spectra
601 619 '''
602
620
603 621 dtype_width = self.getDtypeWidth()
604
622
605 623 pts2write = self.dataOut.nHeights * self.dataOut.nFFTPoints
606
624
607 625 pts2write_SelfSpectra = int(self.dataOut.nChannels * pts2write)
608 626 blocksize = (pts2write_SelfSpectra*dtype_width)
609
627
610 628 if self.dataOut.data_cspc is not None:
611 629 pts2write_CrossSpectra = int(self.dataOut.nPairs * pts2write)
612 630 blocksize += (pts2write_CrossSpectra*dtype_width*2)
613
631
614 632 if self.dataOut.data_dc is not None:
615 633 pts2write_DCchannels = int(self.dataOut.nChannels * self.dataOut.nHeights)
616 634 blocksize += (pts2write_DCchannels*dtype_width*2)
617
635
618 636 # blocksize = blocksize #* datatypeValue * 2 #CORREGIR ESTO
619 637
620 638 return blocksize
621
639
622 640 def setFirstHeader(self):
623
641
624 642 """
625 643 Obtiene una copia del First Header
626
644
627 645 Affected:
628 646 self.systemHeaderObj
629 647 self.radarControllerHeaderObj
630 648 self.dtype
631 649
632 Return:
650 Return:
633 651 None
634 652 """
635
653
636 654 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
637 655 self.systemHeaderObj.nChannels = self.dataOut.nChannels
638 656 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
639
657
640 658 self.processingHeaderObj.dtype = 1 # Spectra
641 659 self.processingHeaderObj.blockSize = self.__getBlockSize()
642 660 self.processingHeaderObj.profilesPerBlock = self.dataOut.nFFTPoints
643 661 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
644 662 self.processingHeaderObj.nWindows = 1 #podria ser 1 o self.dataOut.processingHeaderObj.nWindows
645 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 665 self.processingHeaderObj.totalSpectra = self.dataOut.nPairs + self.dataOut.nChannels
648 666 self.processingHeaderObj.shif_fft = self.dataOut.flagShiftFFT
667
649 668
650 669 if self.processingHeaderObj.totalSpectra > 0:
651 670 channelList = []
652 671 for channel in range(self.dataOut.nChannels):
653 672 channelList.append(channel)
654 673 channelList.append(channel)
655
674
656 675 pairsList = []
657 676 if self.dataOut.nPairs > 0:
658 677 for pair in self.dataOut.pairsList:
659 678 pairsList.append(pair[0])
660 679 pairsList.append(pair[1])
661
680
662 681 spectraComb = channelList + pairsList
663 682 spectraComb = numpy.array(spectraComb, dtype="u1")
664 683 self.processingHeaderObj.spectraComb = spectraComb
665
684
666 685 if self.dataOut.code is not None:
667 686 self.processingHeaderObj.code = self.dataOut.code
668 687 self.processingHeaderObj.nCode = self.dataOut.nCode
669 688 self.processingHeaderObj.nBaud = self.dataOut.nBaud
670
689
671 690 if self.processingHeaderObj.nWindows != 0:
672 691 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
673 692 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
674 693 self.processingHeaderObj.nHeights = self.dataOut.nHeights
675 694 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
676
695
677 696 self.processingHeaderObj.processFlags = self.getProcessFlags()
678
697
679 698 self.setBasicHeader()
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 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
The requested commit or file is too big and content was truncated. Show full diff
1 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