##// END OF EJS Templates
merge revisado
José Chávez -
r1074:238914c187b3 merge
parent child
Show More
@@ -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,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
@@ -0,0 +1,403
1 '''
2 Created on Oct 24, 2016
3
4 @author: roj- LouVD
5 '''
6
7 import numpy
8 import copy
9 import datetime
10 import time
11 from time import gmtime
12
13 from numpy import transpose
14
15 from jroproc_base import ProcessingUnit, Operation
16 from schainpy.model.data.jrodata import Parameters
17
18
19 class BLTRParametersProc(ProcessingUnit):
20 '''
21 Processing unit for BLTR parameters data (winds)
22
23 Inputs:
24 self.dataOut.nmodes - Number of operation modes
25 self.dataOut.nchannels - Number of channels
26 self.dataOut.nranges - Number of ranges
27
28 self.dataOut.data_SNR - SNR array
29 self.dataOut.data_output - Zonal, Vertical and Meridional velocity array
30 self.dataOut.height - Height array (km)
31 self.dataOut.time - Time array (seconds)
32
33 self.dataOut.fileIndex -Index of the file currently read
34 self.dataOut.lat - Latitude coordinate of BLTR location
35
36 self.dataOut.doy - Experiment doy (number of the day in the current year)
37 self.dataOut.month - Experiment month
38 self.dataOut.day - Experiment day
39 self.dataOut.year - Experiment year
40 '''
41
42 def __init__(self, **kwargs):
43 '''
44 Inputs: None
45 '''
46 ProcessingUnit.__init__(self, **kwargs)
47 self.dataOut = Parameters()
48 self.isConfig = False
49
50 def setup(self, mode):
51 '''
52 '''
53 self.dataOut.mode = mode
54
55 def run(self, mode, snr_threshold=None):
56 '''
57 Inputs:
58 mode = High resolution (0) or Low resolution (1) data
59 snr_threshold = snr filter value
60 '''
61
62 if not self.isConfig:
63 self.setup(mode)
64 self.isConfig = True
65
66 if self.dataIn.type == 'Parameters':
67 self.dataOut.copy(self.dataIn)
68
69 self.dataOut.data_output = self.dataOut.data_output[mode]
70 self.dataOut.heightList = self.dataOut.height[0]
71 self.dataOut.data_SNR = self.dataOut.data_SNR[mode]
72
73 if snr_threshold is not None:
74 SNRavg = numpy.average(self.dataOut.data_SNR, axis=0)
75 SNRavgdB = 10*numpy.log10(SNRavg)
76 for i in range(3):
77 self.dataOut.data_output[i][SNRavgdB <= snr_threshold] = numpy.nan
78
79 # TODO
80 class OutliersFilter(Operation):
81
82 def __init__(self, **kwargs):
83 '''
84 '''
85 Operation.__init__(self, **kwargs)
86
87 def run(self, svalue2, method, factor, filter, npoints=9):
88 '''
89 Inputs:
90 svalue - string to select array velocity
91 svalue2 - string to choose axis filtering
92 method - 0 for SMOOTH or 1 for MEDIAN
93 factor - number used to set threshold
94 filter - 1 for data filtering using the standard deviation criteria else 0
95 npoints - number of points for mask filter
96 '''
97
98 print ' Outliers Filter {} {} / threshold = {}'.format(svalue, svalue, factor)
99
100
101 yaxis = self.dataOut.heightList
102 xaxis = numpy.array([[self.dataOut.utctime]])
103
104 # Zonal
105 value_temp = self.dataOut.data_output[0]
106
107 # Zonal
108 value_temp = self.dataOut.data_output[1]
109
110 # Vertical
111 value_temp = numpy.transpose(self.dataOut.data_output[2])
112
113 htemp = yaxis
114 std = value_temp
115 for h in range(len(htemp)):
116 nvalues_valid = len(numpy.where(numpy.isfinite(value_temp[h]))[0])
117 minvalid = npoints
118
119 #only if valid values greater than the minimum required (10%)
120 if nvalues_valid > minvalid:
121
122 if method == 0:
123 #SMOOTH
124 w = value_temp[h] - self.Smooth(input=value_temp[h], width=npoints, edge_truncate=1)
125
126
127 if method == 1:
128 #MEDIAN
129 w = value_temp[h] - self.Median(input=value_temp[h], width = npoints)
130
131 dw = numpy.std(w[numpy.where(numpy.isfinite(w))],ddof = 1)
132
133 threshold = dw*factor
134 value_temp[numpy.where(w > threshold),h] = numpy.nan
135 value_temp[numpy.where(w < -1*threshold),h] = numpy.nan
136
137
138 #At the end
139 if svalue2 == 'inHeight':
140 value_temp = numpy.transpose(value_temp)
141 output_array[:,m] = value_temp
142
143 if svalue == 'zonal':
144 self.dataOut.data_output[0] = output_array
145
146 elif svalue == 'meridional':
147 self.dataOut.data_output[1] = output_array
148
149 elif svalue == 'vertical':
150 self.dataOut.data_output[2] = output_array
151
152 return self.dataOut.data_output
153
154
155 def Median(self,input,width):
156 '''
157 Inputs:
158 input - Velocity array
159 width - Number of points for mask filter
160
161 '''
162
163 if numpy.mod(width,2) == 1:
164 pc = int((width - 1) / 2)
165 cont = 0
166 output = []
167
168 for i in range(len(input)):
169 if i >= pc and i < len(input) - pc:
170 new2 = input[i-pc:i+pc+1]
171 temp = numpy.where(numpy.isfinite(new2))
172 new = new2[temp]
173 value = numpy.median(new)
174 output.append(value)
175
176 output = numpy.array(output)
177 output = numpy.hstack((input[0:pc],output))
178 output = numpy.hstack((output,input[-pc:len(input)]))
179
180 return output
181
182 def Smooth(self,input,width,edge_truncate = None):
183 '''
184 Inputs:
185 input - Velocity array
186 width - Number of points for mask filter
187 edge_truncate - 1 for truncate the convolution product else
188
189 '''
190
191 if numpy.mod(width,2) == 0:
192 real_width = width + 1
193 nzeros = width / 2
194 else:
195 real_width = width
196 nzeros = (width - 1) / 2
197
198 half_width = int(real_width)/2
199 length = len(input)
200
201 gate = numpy.ones(real_width,dtype='float')
202 norm_of_gate = numpy.sum(gate)
203
204 nan_process = 0
205 nan_id = numpy.where(numpy.isnan(input))
206 if len(nan_id[0]) > 0:
207 nan_process = 1
208 pb = numpy.zeros(len(input))
209 pb[nan_id] = 1.
210 input[nan_id] = 0.
211
212 if edge_truncate == True:
213 output = numpy.convolve(input/norm_of_gate,gate,mode='same')
214 elif edge_truncate == False or edge_truncate == None:
215 output = numpy.convolve(input/norm_of_gate,gate,mode='valid')
216 output = numpy.hstack((input[0:half_width],output))
217 output = numpy.hstack((output,input[len(input)-half_width:len(input)]))
218
219 if nan_process:
220 pb = numpy.convolve(pb/norm_of_gate,gate,mode='valid')
221 pb = numpy.hstack((numpy.zeros(half_width),pb))
222 pb = numpy.hstack((pb,numpy.zeros(half_width)))
223 output[numpy.where(pb > 0.9999)] = numpy.nan
224 input[nan_id] = numpy.nan
225 return output
226
227 def Average(self,aver=0,nhaver=1):
228 '''
229 Inputs:
230 aver - Indicates the time period over which is averaged or consensus data
231 nhaver - Indicates the decimation factor in heights
232
233 '''
234 nhpoints = 48
235
236 lat_piura = -5.17
237 lat_huancayo = -12.04
238 lat_porcuya = -5.8
239
240 if '%2.2f'%self.dataOut.lat == '%2.2f'%lat_piura:
241 hcm = 3.
242 if self.dataOut.year == 2003 :
243 if self.dataOut.doy >= 25 and self.dataOut.doy < 64:
244 nhpoints = 12
245
246 elif '%2.2f'%self.dataOut.lat == '%2.2f'%lat_huancayo:
247 hcm = 3.
248 if self.dataOut.year == 2003 :
249 if self.dataOut.doy >= 25 and self.dataOut.doy < 64:
250 nhpoints = 12
251
252
253 elif '%2.2f'%self.dataOut.lat == '%2.2f'%lat_porcuya:
254 hcm = 5.#2
255
256 pdata = 0.2
257 taver = [1,2,3,4,6,8,12,24]
258 t0 = 0
259 tf = 24
260 ntime =(tf-t0)/taver[aver]
261 ti = numpy.arange(ntime)
262 tf = numpy.arange(ntime) + taver[aver]
263
264
265 old_height = self.dataOut.heightList
266
267 if nhaver > 1:
268 num_hei = len(self.dataOut.heightList)/nhaver/self.dataOut.nmodes
269 deltha = 0.05*nhaver
270 minhvalid = pdata*nhaver
271 for im in range(self.dataOut.nmodes):
272 new_height = numpy.arange(num_hei)*deltha + self.dataOut.height[im,0] + deltha/2.
273
274
275 data_fHeigths_List = []
276 data_fZonal_List = []
277 data_fMeridional_List = []
278 data_fVertical_List = []
279 startDTList = []
280
281
282 for i in range(ntime):
283 height = old_height
284
285 start = datetime.datetime(self.dataOut.year,self.dataOut.month,self.dataOut.day) + datetime.timedelta(hours = int(ti[i])) - datetime.timedelta(hours = 5)
286 stop = datetime.datetime(self.dataOut.year,self.dataOut.month,self.dataOut.day) + datetime.timedelta(hours = int(tf[i])) - datetime.timedelta(hours = 5)
287
288
289 limit_sec1 = time.mktime(start.timetuple())
290 limit_sec2 = time.mktime(stop.timetuple())
291
292 t1 = numpy.where(self.f_timesec >= limit_sec1)
293 t2 = numpy.where(self.f_timesec < limit_sec2)
294 time_select = []
295 for val_sec in t1[0]:
296 if val_sec in t2[0]:
297 time_select.append(val_sec)
298
299
300 time_select = numpy.array(time_select,dtype = 'int')
301 minvalid = numpy.ceil(pdata*nhpoints)
302
303 zon_aver = numpy.zeros([self.dataOut.nranges,self.dataOut.nmodes],dtype='f4') + numpy.nan
304 mer_aver = numpy.zeros([self.dataOut.nranges,self.dataOut.nmodes],dtype='f4') + numpy.nan
305 ver_aver = numpy.zeros([self.dataOut.nranges,self.dataOut.nmodes],dtype='f4') + numpy.nan
306
307 if nhaver > 1:
308 new_zon_aver = numpy.zeros([num_hei,self.dataOut.nmodes],dtype='f4') + numpy.nan
309 new_mer_aver = numpy.zeros([num_hei,self.dataOut.nmodes],dtype='f4') + numpy.nan
310 new_ver_aver = numpy.zeros([num_hei,self.dataOut.nmodes],dtype='f4') + numpy.nan
311
312 if len(time_select) > minvalid:
313 time_average = self.f_timesec[time_select]
314
315 for im in range(self.dataOut.nmodes):
316
317 for ih in range(self.dataOut.nranges):
318 if numpy.sum(numpy.isfinite(self.f_zon[time_select,ih,im])) >= minvalid:
319 zon_aver[ih,im] = numpy.nansum(self.f_zon[time_select,ih,im]) / numpy.sum(numpy.isfinite(self.f_zon[time_select,ih,im]))
320
321 if numpy.sum(numpy.isfinite(self.f_mer[time_select,ih,im])) >= minvalid:
322 mer_aver[ih,im] = numpy.nansum(self.f_mer[time_select,ih,im]) / numpy.sum(numpy.isfinite(self.f_mer[time_select,ih,im]))
323
324 if numpy.sum(numpy.isfinite(self.f_ver[time_select,ih,im])) >= minvalid:
325 ver_aver[ih,im] = numpy.nansum(self.f_ver[time_select,ih,im]) / numpy.sum(numpy.isfinite(self.f_ver[time_select,ih,im]))
326
327 if nhaver > 1:
328 for ih in range(num_hei):
329 hvalid = numpy.arange(nhaver) + nhaver*ih
330
331 if numpy.sum(numpy.isfinite(zon_aver[hvalid,im])) >= minvalid:
332 new_zon_aver[ih,im] = numpy.nansum(zon_aver[hvalid,im]) / numpy.sum(numpy.isfinite(zon_aver[hvalid,im]))
333
334 if numpy.sum(numpy.isfinite(mer_aver[hvalid,im])) >= minvalid:
335 new_mer_aver[ih,im] = numpy.nansum(mer_aver[hvalid,im]) / numpy.sum(numpy.isfinite(mer_aver[hvalid,im]))
336
337 if numpy.sum(numpy.isfinite(ver_aver[hvalid,im])) >= minvalid:
338 new_ver_aver[ih,im] = numpy.nansum(ver_aver[hvalid,im]) / numpy.sum(numpy.isfinite(ver_aver[hvalid,im]))
339 if nhaver > 1:
340 zon_aver = new_zon_aver
341 mer_aver = new_mer_aver
342 ver_aver = new_ver_aver
343 height = new_height
344
345
346 tstart = time_average[0]
347 tend = time_average[-1]
348 startTime = time.gmtime(tstart)
349
350 year = startTime.tm_year
351 month = startTime.tm_mon
352 day = startTime.tm_mday
353 hour = startTime.tm_hour
354 minute = startTime.tm_min
355 second = startTime.tm_sec
356
357 startDTList.append(datetime.datetime(year,month,day,hour,minute,second))
358
359
360 o_height = numpy.array([])
361 o_zon_aver = numpy.array([])
362 o_mer_aver = numpy.array([])
363 o_ver_aver = numpy.array([])
364 if self.dataOut.nmodes > 1:
365 for im in range(self.dataOut.nmodes):
366
367 if im == 0:
368 h_select = numpy.where(numpy.bitwise_and(height[0,:] >=0,height[0,:] <= hcm,numpy.isfinite(height[0,:])))
369 else:
370 h_select = numpy.where(numpy.bitwise_and(height[1,:] > hcm,height[1,:] < 20,numpy.isfinite(height[1,:])))
371
372
373 ht = h_select[0]
374
375 o_height = numpy.hstack((o_height,height[im,ht]))
376 o_zon_aver = numpy.hstack((o_zon_aver,zon_aver[ht,im]))
377 o_mer_aver = numpy.hstack((o_mer_aver,mer_aver[ht,im]))
378 o_ver_aver = numpy.hstack((o_ver_aver,ver_aver[ht,im]))
379
380 data_fHeigths_List.append(o_height)
381 data_fZonal_List.append(o_zon_aver)
382 data_fMeridional_List.append(o_mer_aver)
383 data_fVertical_List.append(o_ver_aver)
384
385
386 else:
387 h_select = numpy.where(numpy.bitwise_and(height[0,:] <= hcm,numpy.isfinite(height[0,:])))
388 ht = h_select[0]
389 o_height = numpy.hstack((o_height,height[im,ht]))
390 o_zon_aver = numpy.hstack((o_zon_aver,zon_aver[ht,im]))
391 o_mer_aver = numpy.hstack((o_mer_aver,mer_aver[ht,im]))
392 o_ver_aver = numpy.hstack((o_ver_aver,ver_aver[ht,im]))
393
394 data_fHeigths_List.append(o_height)
395 data_fZonal_List.append(o_zon_aver)
396 data_fMeridional_List.append(o_mer_aver)
397 data_fVertical_List.append(o_ver_aver)
398
399
400 return startDTList, data_fHeigths_List, data_fZonal_List, data_fMeridional_List, data_fVertical_List
401
402
403 No newline at end of file
@@ -1,7 +1,7
1 '''
1 '''
2 Created on Feb 7, 2012
2 Created on Feb 7, 2012
3
3
4 @author $Author$
4 @author $Author$
5 @version $Id$
5 @version $Id$
6 '''
6 '''
7 __version__ = "2.3"
7 __version__ = '2.3'
@@ -1,1218 +1,1227
1 '''
1 '''
2
2
3 $Author: murco $
3 $Author: murco $
4 $Id: JROData.py 173 2012-11-20 15:06:21Z murco $
4 $Id: JROData.py 173 2012-11-20 15:06:21Z murco $
5 '''
5 '''
6
6
7 import copy
7 import copy
8 import numpy
8 import numpy
9 import datetime
9 import datetime
10
10
11 from jroheaderIO import SystemHeader, RadarControllerHeader
11 from jroheaderIO import SystemHeader, RadarControllerHeader
12 from schainpy import cSchain
12 from schainpy import cSchain
13
13
14
14
15 def getNumpyDtype(dataTypeCode):
15 def getNumpyDtype(dataTypeCode):
16
16
17 if dataTypeCode == 0:
17 if dataTypeCode == 0:
18 numpyDtype = numpy.dtype([('real','<i1'),('imag','<i1')])
18 numpyDtype = numpy.dtype([('real','<i1'),('imag','<i1')])
19 elif dataTypeCode == 1:
19 elif dataTypeCode == 1:
20 numpyDtype = numpy.dtype([('real','<i2'),('imag','<i2')])
20 numpyDtype = numpy.dtype([('real','<i2'),('imag','<i2')])
21 elif dataTypeCode == 2:
21 elif dataTypeCode == 2:
22 numpyDtype = numpy.dtype([('real','<i4'),('imag','<i4')])
22 numpyDtype = numpy.dtype([('real','<i4'),('imag','<i4')])
23 elif dataTypeCode == 3:
23 elif dataTypeCode == 3:
24 numpyDtype = numpy.dtype([('real','<i8'),('imag','<i8')])
24 numpyDtype = numpy.dtype([('real','<i8'),('imag','<i8')])
25 elif dataTypeCode == 4:
25 elif dataTypeCode == 4:
26 numpyDtype = numpy.dtype([('real','<f4'),('imag','<f4')])
26 numpyDtype = numpy.dtype([('real','<f4'),('imag','<f4')])
27 elif dataTypeCode == 5:
27 elif dataTypeCode == 5:
28 numpyDtype = numpy.dtype([('real','<f8'),('imag','<f8')])
28 numpyDtype = numpy.dtype([('real','<f8'),('imag','<f8')])
29 else:
29 else:
30 raise ValueError, 'dataTypeCode was not defined'
30 raise ValueError, 'dataTypeCode was not defined'
31
31
32 return numpyDtype
32 return numpyDtype
33
33
34 def getDataTypeCode(numpyDtype):
34 def getDataTypeCode(numpyDtype):
35
35
36 if numpyDtype == numpy.dtype([('real','<i1'),('imag','<i1')]):
36 if numpyDtype == numpy.dtype([('real','<i1'),('imag','<i1')]):
37 datatype = 0
37 datatype = 0
38 elif numpyDtype == numpy.dtype([('real','<i2'),('imag','<i2')]):
38 elif numpyDtype == numpy.dtype([('real','<i2'),('imag','<i2')]):
39 datatype = 1
39 datatype = 1
40 elif numpyDtype == numpy.dtype([('real','<i4'),('imag','<i4')]):
40 elif numpyDtype == numpy.dtype([('real','<i4'),('imag','<i4')]):
41 datatype = 2
41 datatype = 2
42 elif numpyDtype == numpy.dtype([('real','<i8'),('imag','<i8')]):
42 elif numpyDtype == numpy.dtype([('real','<i8'),('imag','<i8')]):
43 datatype = 3
43 datatype = 3
44 elif numpyDtype == numpy.dtype([('real','<f4'),('imag','<f4')]):
44 elif numpyDtype == numpy.dtype([('real','<f4'),('imag','<f4')]):
45 datatype = 4
45 datatype = 4
46 elif numpyDtype == numpy.dtype([('real','<f8'),('imag','<f8')]):
46 elif numpyDtype == numpy.dtype([('real','<f8'),('imag','<f8')]):
47 datatype = 5
47 datatype = 5
48 else:
48 else:
49 datatype = None
49 datatype = None
50
50
51 return datatype
51 return datatype
52
52
53 def hildebrand_sekhon(data, navg):
53 def hildebrand_sekhon(data, navg):
54 """
54 """
55 This method is for the objective determination of the noise level in Doppler spectra. This
55 This method is for the objective determination of the noise level in Doppler spectra. This
56 implementation technique is based on the fact that the standard deviation of the spectral
56 implementation technique is based on the fact that the standard deviation of the spectral
57 densities is equal to the mean spectral density for white Gaussian noise
57 densities is equal to the mean spectral density for white Gaussian noise
58
58
59 Inputs:
59 Inputs:
60 Data : heights
60 Data : heights
61 navg : numbers of averages
61 navg : numbers of averages
62
62
63 Return:
63 Return:
64 -1 : any error
64 -1 : any error
65 anoise : noise's level
65 anoise : noise's level
66 """
66 """
67
67
68 sortdata = numpy.sort(data, axis=None)
68 sortdata = numpy.sort(data, axis=None)
69 # lenOfData = len(sortdata)
69 # lenOfData = len(sortdata)
70 # nums_min = lenOfData*0.2
70 # nums_min = lenOfData*0.2
71 #
71 #
72 # if nums_min <= 5:
72 # if nums_min <= 5:
73 # nums_min = 5
73 # nums_min = 5
74 #
74 #
75 # sump = 0.
75 # sump = 0.
76 #
76 #
77 # sumq = 0.
77 # sumq = 0.
78 #
78 #
79 # j = 0
79 # j = 0
80 #
80 #
81 # cont = 1
81 # cont = 1
82 #
82 #
83 # while((cont==1)and(j<lenOfData)):
83 # while((cont==1)and(j<lenOfData)):
84 #
84 #
85 # sump += sortdata[j]
85 # sump += sortdata[j]
86 #
86 #
87 # sumq += sortdata[j]**2
87 # sumq += sortdata[j]**2
88 #
88 #
89 # if j > nums_min:
89 # if j > nums_min:
90 # rtest = float(j)/(j-1) + 1.0/navg
90 # rtest = float(j)/(j-1) + 1.0/navg
91 # if ((sumq*j) > (rtest*sump**2)):
91 # if ((sumq*j) > (rtest*sump**2)):
92 # j = j - 1
92 # j = j - 1
93 # sump = sump - sortdata[j]
93 # sump = sump - sortdata[j]
94 # sumq = sumq - sortdata[j]**2
94 # sumq = sumq - sortdata[j]**2
95 # cont = 0
95 # cont = 0
96 #
96 #
97 # j += 1
97 # j += 1
98 #
98 #
99 # lnoise = sump /j
99 # lnoise = sump /j
100 #
100 #
101 # return lnoise
101 # return lnoise
102
102
103 return cSchain.hildebrand_sekhon(sortdata, navg)
103 return cSchain.hildebrand_sekhon(sortdata, navg)
104
104
105
105
106 class Beam:
106 class Beam:
107
107
108 def __init__(self):
108 def __init__(self):
109 self.codeList = []
109 self.codeList = []
110 self.azimuthList = []
110 self.azimuthList = []
111 self.zenithList = []
111 self.zenithList = []
112
112
113 class GenericData(object):
113 class GenericData(object):
114
114
115 flagNoData = True
115 flagNoData = True
116
116
117 def copy(self, inputObj=None):
117 def copy(self, inputObj=None):
118
118
119 if inputObj == None:
119 if inputObj == None:
120 return copy.deepcopy(self)
120 return copy.deepcopy(self)
121
121
122 for key in inputObj.__dict__.keys():
122 for key in inputObj.__dict__.keys():
123
123
124 attribute = inputObj.__dict__[key]
124 attribute = inputObj.__dict__[key]
125
125
126 #If this attribute is a tuple or list
126 #If this attribute is a tuple or list
127 if type(inputObj.__dict__[key]) in (tuple, list):
127 if type(inputObj.__dict__[key]) in (tuple, list):
128 self.__dict__[key] = attribute[:]
128 self.__dict__[key] = attribute[:]
129 continue
129 continue
130
130
131 #If this attribute is another object or instance
131 #If this attribute is another object or instance
132 if hasattr(attribute, '__dict__'):
132 if hasattr(attribute, '__dict__'):
133 self.__dict__[key] = attribute.copy()
133 self.__dict__[key] = attribute.copy()
134 continue
134 continue
135
135
136 self.__dict__[key] = inputObj.__dict__[key]
136 self.__dict__[key] = inputObj.__dict__[key]
137
137
138 def deepcopy(self):
138 def deepcopy(self):
139
139
140 return copy.deepcopy(self)
140 return copy.deepcopy(self)
141
141
142 def isEmpty(self):
142 def isEmpty(self):
143
143
144 return self.flagNoData
144 return self.flagNoData
145
145
146 class JROData(GenericData):
146 class JROData(GenericData):
147
147
148 # m_BasicHeader = BasicHeader()
148 # m_BasicHeader = BasicHeader()
149 # m_ProcessingHeader = ProcessingHeader()
149 # m_ProcessingHeader = ProcessingHeader()
150
150
151 systemHeaderObj = SystemHeader()
151 systemHeaderObj = SystemHeader()
152
152
153 radarControllerHeaderObj = RadarControllerHeader()
153 radarControllerHeaderObj = RadarControllerHeader()
154
154
155 # data = None
155 # data = None
156
156
157 type = None
157 type = None
158
158
159 datatype = None #dtype but in string
159 datatype = None #dtype but in string
160
160
161 # dtype = None
161 # dtype = None
162
162
163 # nChannels = None
163 # nChannels = None
164
164
165 # nHeights = None
165 # nHeights = None
166
166
167 nProfiles = None
167 nProfiles = None
168
168
169 heightList = None
169 heightList = None
170
170
171 channelList = None
171 channelList = None
172
172
173 flagDiscontinuousBlock = False
173 flagDiscontinuousBlock = False
174
174
175 useLocalTime = False
175 useLocalTime = False
176
176
177 utctime = None
177 utctime = None
178
178
179 timeZone = None
179 timeZone = None
180
180
181 dstFlag = None
181 dstFlag = None
182
182
183 errorCount = None
183 errorCount = None
184
184
185 blocksize = None
185 blocksize = None
186
186
187 # nCode = None
187 # nCode = None
188 #
188 #
189 # nBaud = None
189 # nBaud = None
190 #
190 #
191 # code = None
191 # code = None
192
192
193 flagDecodeData = False #asumo q la data no esta decodificada
193 flagDecodeData = False #asumo q la data no esta decodificada
194
194
195 flagDeflipData = False #asumo q la data no esta sin flip
195 flagDeflipData = False #asumo q la data no esta sin flip
196
196
197 flagShiftFFT = False
197 flagShiftFFT = False
198
198
199 # ippSeconds = None
199 # ippSeconds = None
200
200
201 # timeInterval = None
201 # timeInterval = None
202
202
203 nCohInt = None
203 nCohInt = None
204
204
205 # noise = None
205 # noise = None
206
206
207 windowOfFilter = 1
207 windowOfFilter = 1
208
208
209 #Speed of ligth
209 #Speed of ligth
210 C = 3e8
210 C = 3e8
211
211
212 frequency = 49.92e6
212 frequency = 49.92e6
213
213
214 realtime = False
214 realtime = False
215
215
216 beacon_heiIndexList = None
216 beacon_heiIndexList = None
217
217
218 last_block = None
218 last_block = None
219
219
220 blocknow = None
220 blocknow = None
221
221
222 azimuth = None
222 azimuth = None
223
223
224 zenith = None
224 zenith = None
225
225
226 beam = Beam()
226 beam = Beam()
227
227
228 profileIndex = None
228 profileIndex = None
229
229
230 def getNoise(self):
230 def getNoise(self):
231
231
232 raise NotImplementedError
232 raise NotImplementedError
233
233
234 def getNChannels(self):
234 def getNChannels(self):
235
235
236 return len(self.channelList)
236 return len(self.channelList)
237
237
238 def getChannelIndexList(self):
238 def getChannelIndexList(self):
239
239
240 return range(self.nChannels)
240 return range(self.nChannels)
241
241
242 def getNHeights(self):
242 def getNHeights(self):
243
243
244 return len(self.heightList)
244 return len(self.heightList)
245
245
246 def getHeiRange(self, extrapoints=0):
246 def getHeiRange(self, extrapoints=0):
247
247
248 heis = self.heightList
248 heis = self.heightList
249 # deltah = self.heightList[1] - self.heightList[0]
249 # deltah = self.heightList[1] - self.heightList[0]
250 #
250 #
251 # heis.append(self.heightList[-1])
251 # heis.append(self.heightList[-1])
252
252
253 return heis
253 return heis
254
254
255 def getDeltaH(self):
255 def getDeltaH(self):
256
256
257 delta = self.heightList[1] - self.heightList[0]
257 delta = self.heightList[1] - self.heightList[0]
258
258
259 return delta
259 return delta
260
260
261 def getltctime(self):
261 def getltctime(self):
262
262
263 if self.useLocalTime:
263 if self.useLocalTime:
264 return self.utctime - self.timeZone*60
264 return self.utctime - self.timeZone*60
265
265
266 return self.utctime
266 return self.utctime
267
267
268 def getDatatime(self):
268 def getDatatime(self):
269
269
270 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
270 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
271 return datatimeValue
271 return datatimeValue
272
272
273 def getTimeRange(self):
273 def getTimeRange(self):
274
274
275 datatime = []
275 datatime = []
276
276
277 datatime.append(self.ltctime)
277 datatime.append(self.ltctime)
278 datatime.append(self.ltctime + self.timeInterval+1)
278 datatime.append(self.ltctime + self.timeInterval+1)
279
279
280 datatime = numpy.array(datatime)
280 datatime = numpy.array(datatime)
281
281
282 return datatime
282 return datatime
283
283
284 def getFmaxTimeResponse(self):
284 def getFmaxTimeResponse(self):
285
285
286 period = (10**-6)*self.getDeltaH()/(0.15)
286 period = (10**-6)*self.getDeltaH()/(0.15)
287
287
288 PRF = 1./(period * self.nCohInt)
288 PRF = 1./(period * self.nCohInt)
289
289
290 fmax = PRF
290 fmax = PRF
291
291
292 return fmax
292 return fmax
293
293
294 def getFmax(self):
294 def getFmax(self):
295 PRF = 1./(self.ippSeconds * self.nCohInt)
295 PRF = 1./(self.ippSeconds * self.nCohInt)
296
296
297 fmax = PRF
297 fmax = PRF
298 return fmax
298 return fmax
299
299
300 def getVmax(self):
300 def getVmax(self):
301
301
302 _lambda = self.C/self.frequency
302 _lambda = self.C/self.frequency
303
303
304 vmax = self.getFmax() * _lambda/2
304 vmax = self.getFmax() * _lambda/2
305
305
306 return vmax
306 return vmax
307
307
308 def get_ippSeconds(self):
308 def get_ippSeconds(self):
309 '''
309 '''
310 '''
310 '''
311 return self.radarControllerHeaderObj.ippSeconds
311 return self.radarControllerHeaderObj.ippSeconds
312
312
313 def set_ippSeconds(self, ippSeconds):
313 def set_ippSeconds(self, ippSeconds):
314 '''
314 '''
315 '''
315 '''
316
316
317 self.radarControllerHeaderObj.ippSeconds = ippSeconds
317 self.radarControllerHeaderObj.ippSeconds = ippSeconds
318
318
319 return
319 return
320
320
321 def get_dtype(self):
321 def get_dtype(self):
322 '''
322 '''
323 '''
323 '''
324 return getNumpyDtype(self.datatype)
324 return getNumpyDtype(self.datatype)
325
325
326 def set_dtype(self, numpyDtype):
326 def set_dtype(self, numpyDtype):
327 '''
327 '''
328 '''
328 '''
329
329
330 self.datatype = getDataTypeCode(numpyDtype)
330 self.datatype = getDataTypeCode(numpyDtype)
331
331
332 def get_code(self):
332 def get_code(self):
333 '''
333 '''
334 '''
334 '''
335 return self.radarControllerHeaderObj.code
335 return self.radarControllerHeaderObj.code
336
336
337 def set_code(self, code):
337 def set_code(self, code):
338 '''
338 '''
339 '''
339 '''
340 self.radarControllerHeaderObj.code = code
340 self.radarControllerHeaderObj.code = code
341
341
342 return
342 return
343
343
344 def get_ncode(self):
344 def get_ncode(self):
345 '''
345 '''
346 '''
346 '''
347 return self.radarControllerHeaderObj.nCode
347 return self.radarControllerHeaderObj.nCode
348
348
349 def set_ncode(self, nCode):
349 def set_ncode(self, nCode):
350 '''
350 '''
351 '''
351 '''
352 self.radarControllerHeaderObj.nCode = nCode
352 self.radarControllerHeaderObj.nCode = nCode
353
353
354 return
354 return
355
355
356 def get_nbaud(self):
356 def get_nbaud(self):
357 '''
357 '''
358 '''
358 '''
359 return self.radarControllerHeaderObj.nBaud
359 return self.radarControllerHeaderObj.nBaud
360
360
361 def set_nbaud(self, nBaud):
361 def set_nbaud(self, nBaud):
362 '''
362 '''
363 '''
363 '''
364 self.radarControllerHeaderObj.nBaud = nBaud
364 self.radarControllerHeaderObj.nBaud = nBaud
365
365
366 return
366 return
367
367
368 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
368 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
369 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
369 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
370 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
370 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
371 #noise = property(getNoise, "I'm the 'nHeights' property.")
371 #noise = property(getNoise, "I'm the 'nHeights' property.")
372 datatime = property(getDatatime, "I'm the 'datatime' property")
372 datatime = property(getDatatime, "I'm the 'datatime' property")
373 ltctime = property(getltctime, "I'm the 'ltctime' property")
373 ltctime = property(getltctime, "I'm the 'ltctime' property")
374 ippSeconds = property(get_ippSeconds, set_ippSeconds)
374 ippSeconds = property(get_ippSeconds, set_ippSeconds)
375 dtype = property(get_dtype, set_dtype)
375 dtype = property(get_dtype, set_dtype)
376 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
376 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
377 code = property(get_code, set_code)
377 code = property(get_code, set_code)
378 nCode = property(get_ncode, set_ncode)
378 nCode = property(get_ncode, set_ncode)
379 nBaud = property(get_nbaud, set_nbaud)
379 nBaud = property(get_nbaud, set_nbaud)
380
380
381 class Voltage(JROData):
381 class Voltage(JROData):
382
382
383 #data es un numpy array de 2 dmensiones (canales, alturas)
383 #data es un numpy array de 2 dmensiones (canales, alturas)
384 data = None
384 data = None
385
385
386 def __init__(self):
386 def __init__(self):
387 '''
387 '''
388 Constructor
388 Constructor
389 '''
389 '''
390
390
391 self.useLocalTime = True
391 self.useLocalTime = True
392
392
393 self.radarControllerHeaderObj = RadarControllerHeader()
393 self.radarControllerHeaderObj = RadarControllerHeader()
394
394
395 self.systemHeaderObj = SystemHeader()
395 self.systemHeaderObj = SystemHeader()
396
396
397 self.type = "Voltage"
397 self.type = "Voltage"
398
398
399 self.data = None
399 self.data = None
400
400
401 # self.dtype = None
401 # self.dtype = None
402
402
403 # self.nChannels = 0
403 # self.nChannels = 0
404
404
405 # self.nHeights = 0
405 # self.nHeights = 0
406
406
407 self.nProfiles = None
407 self.nProfiles = None
408
408
409 self.heightList = None
409 self.heightList = None
410
410
411 self.channelList = None
411 self.channelList = None
412
412
413 # self.channelIndexList = None
413 # self.channelIndexList = None
414
414
415 self.flagNoData = True
415 self.flagNoData = True
416
416
417 self.flagDiscontinuousBlock = False
417 self.flagDiscontinuousBlock = False
418
418
419 self.utctime = None
419 self.utctime = None
420
420
421 self.timeZone = None
421 self.timeZone = None
422
422
423 self.dstFlag = None
423 self.dstFlag = None
424
424
425 self.errorCount = None
425 self.errorCount = None
426
426
427 self.nCohInt = None
427 self.nCohInt = None
428
428
429 self.blocksize = None
429 self.blocksize = None
430
430
431 self.flagDecodeData = False #asumo q la data no esta decodificada
431 self.flagDecodeData = False #asumo q la data no esta decodificada
432
432
433 self.flagDeflipData = False #asumo q la data no esta sin flip
433 self.flagDeflipData = False #asumo q la data no esta sin flip
434
434
435 self.flagShiftFFT = False
435 self.flagShiftFFT = False
436
436
437 self.flagDataAsBlock = False #Asumo que la data es leida perfil a perfil
437 self.flagDataAsBlock = False #Asumo que la data es leida perfil a perfil
438
438
439 self.profileIndex = 0
439 self.profileIndex = 0
440
440
441 def getNoisebyHildebrand(self, channel = None):
441 def getNoisebyHildebrand(self, channel = None):
442 """
442 """
443 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
443 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
444
444
445 Return:
445 Return:
446 noiselevel
446 noiselevel
447 """
447 """
448
448
449 if channel != None:
449 if channel != None:
450 data = self.data[channel]
450 data = self.data[channel]
451 nChannels = 1
451 nChannels = 1
452 else:
452 else:
453 data = self.data
453 data = self.data
454 nChannels = self.nChannels
454 nChannels = self.nChannels
455
455
456 noise = numpy.zeros(nChannels)
456 noise = numpy.zeros(nChannels)
457 power = data * numpy.conjugate(data)
457 power = data * numpy.conjugate(data)
458
458
459 for thisChannel in range(nChannels):
459 for thisChannel in range(nChannels):
460 if nChannels == 1:
460 if nChannels == 1:
461 daux = power[:].real
461 daux = power[:].real
462 else:
462 else:
463 daux = power[thisChannel,:].real
463 daux = power[thisChannel,:].real
464 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
464 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
465
465
466 return noise
466 return noise
467
467
468 def getNoise(self, type = 1, channel = None):
468 def getNoise(self, type = 1, channel = None):
469
469
470 if type == 1:
470 if type == 1:
471 noise = self.getNoisebyHildebrand(channel)
471 noise = self.getNoisebyHildebrand(channel)
472
472
473 return noise
473 return noise
474
474
475 def getPower(self, channel = None):
475 def getPower(self, channel = None):
476
476
477 if channel != None:
477 if channel != None:
478 data = self.data[channel]
478 data = self.data[channel]
479 else:
479 else:
480 data = self.data
480 data = self.data
481
481
482 power = data * numpy.conjugate(data)
482 power = data * numpy.conjugate(data)
483 powerdB = 10*numpy.log10(power.real)
483 powerdB = 10*numpy.log10(power.real)
484 powerdB = numpy.squeeze(powerdB)
484 powerdB = numpy.squeeze(powerdB)
485
485
486 return powerdB
486 return powerdB
487
487
488 def getTimeInterval(self):
488 def getTimeInterval(self):
489
489
490 timeInterval = self.ippSeconds * self.nCohInt
490 timeInterval = self.ippSeconds * self.nCohInt
491
491
492 return timeInterval
492 return timeInterval
493
493
494 noise = property(getNoise, "I'm the 'nHeights' property.")
494 noise = property(getNoise, "I'm the 'nHeights' property.")
495 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
495 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
496
496
497 class Spectra(JROData):
497 class Spectra(JROData):
498
498
499 #data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
499 #data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
500 data_spc = None
500 data_spc = None
501
501
502 #data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
502 #data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
503 data_cspc = None
503 data_cspc = None
504
504
505 #data dc es un numpy array de 2 dmensiones (canales, alturas)
505 #data dc es un numpy array de 2 dmensiones (canales, alturas)
506 data_dc = None
506 data_dc = None
507
507
508 #data power
508 #data power
509 data_pwr = None
509 data_pwr = None
510
510
511 nFFTPoints = None
511 nFFTPoints = None
512
512
513 # nPairs = None
513 # nPairs = None
514
514
515 pairsList = None
515 pairsList = None
516
516
517 nIncohInt = None
517 nIncohInt = None
518
518
519 wavelength = None #Necesario para cacular el rango de velocidad desde la frecuencia
519 wavelength = None #Necesario para cacular el rango de velocidad desde la frecuencia
520
520
521 nCohInt = None #se requiere para determinar el valor de timeInterval
521 nCohInt = None #se requiere para determinar el valor de timeInterval
522
522
523 ippFactor = None
523 ippFactor = None
524
524
525 profileIndex = 0
525 profileIndex = 0
526
526
527 plotting = "spectra"
527 plotting = "spectra"
528
528
529 def __init__(self):
529 def __init__(self):
530 '''
530 '''
531 Constructor
531 Constructor
532 '''
532 '''
533
533
534 self.useLocalTime = True
534 self.useLocalTime = True
535
535
536 self.radarControllerHeaderObj = RadarControllerHeader()
536 self.radarControllerHeaderObj = RadarControllerHeader()
537
537
538 self.systemHeaderObj = SystemHeader()
538 self.systemHeaderObj = SystemHeader()
539
539
540 self.type = "Spectra"
540 self.type = "Spectra"
541
541
542 # self.data = None
542 # self.data = None
543
543
544 # self.dtype = None
544 # self.dtype = None
545
545
546 # self.nChannels = 0
546 # self.nChannels = 0
547
547
548 # self.nHeights = 0
548 # self.nHeights = 0
549
549
550 self.nProfiles = None
550 self.nProfiles = None
551
551
552 self.heightList = None
552 self.heightList = None
553
553
554 self.channelList = None
554 self.channelList = None
555
555
556 # self.channelIndexList = None
556 # self.channelIndexList = None
557
557
558 self.pairsList = None
558 self.pairsList = None
559
559
560 self.flagNoData = True
560 self.flagNoData = True
561
561
562 self.flagDiscontinuousBlock = False
562 self.flagDiscontinuousBlock = False
563
563
564 self.utctime = None
564 self.utctime = None
565
565
566 self.nCohInt = None
566 self.nCohInt = None
567
567
568 self.nIncohInt = None
568 self.nIncohInt = None
569
569
570 self.blocksize = None
570 self.blocksize = None
571
571
572 self.nFFTPoints = None
572 self.nFFTPoints = None
573
573
574 self.wavelength = None
574 self.wavelength = None
575
575
576 self.flagDecodeData = False #asumo q la data no esta decodificada
576 self.flagDecodeData = False #asumo q la data no esta decodificada
577
577
578 self.flagDeflipData = False #asumo q la data no esta sin flip
578 self.flagDeflipData = False #asumo q la data no esta sin flip
579
579
580 self.flagShiftFFT = False
580 self.flagShiftFFT = False
581
581
582 self.ippFactor = 1
582 self.ippFactor = 1
583
583
584 #self.noise = None
584 #self.noise = None
585
585
586 self.beacon_heiIndexList = []
586 self.beacon_heiIndexList = []
587
587
588 self.noise_estimation = None
588 self.noise_estimation = None
589
589
590
590
591 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
591 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
592 """
592 """
593 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
593 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
594
594
595 Return:
595 Return:
596 noiselevel
596 noiselevel
597 """
597 """
598
598
599 noise = numpy.zeros(self.nChannels)
599 noise = numpy.zeros(self.nChannels)
600
600
601 for channel in range(self.nChannels):
601 for channel in range(self.nChannels):
602 daux = self.data_spc[channel,xmin_index:xmax_index,ymin_index:ymax_index]
602 daux = self.data_spc[channel,xmin_index:xmax_index,ymin_index:ymax_index]
603 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
603 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
604
604
605 return noise
605 return noise
606
606
607 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
607 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
608
608
609 if self.noise_estimation is not None:
609 if self.noise_estimation is not None:
610 return self.noise_estimation #this was estimated by getNoise Operation defined in jroproc_spectra.py
610 return self.noise_estimation #this was estimated by getNoise Operation defined in jroproc_spectra.py
611 else:
611 else:
612 noise = self.getNoisebyHildebrand(xmin_index, xmax_index, ymin_index, ymax_index)
612 noise = self.getNoisebyHildebrand(xmin_index, xmax_index, ymin_index, ymax_index)
613 return noise
613 return noise
614
614
615 def getFreqRangeTimeResponse(self, extrapoints=0):
615 def getFreqRangeTimeResponse(self, extrapoints=0):
616
616
617 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints*self.ippFactor)
617 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints*self.ippFactor)
618 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
618 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
619
619
620 return freqrange
620 return freqrange
621
621
622 def getAcfRange(self, extrapoints=0):
622 def getAcfRange(self, extrapoints=0):
623
623
624 deltafreq = 10./(self.getFmax() / (self.nFFTPoints*self.ippFactor))
624 deltafreq = 10./(self.getFmax() / (self.nFFTPoints*self.ippFactor))
625 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
625 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
626
626
627 return freqrange
627 return freqrange
628
628
629 def getFreqRange(self, extrapoints=0):
629 def getFreqRange(self, extrapoints=0):
630
630
631 deltafreq = self.getFmax() / (self.nFFTPoints*self.ippFactor)
631 deltafreq = self.getFmax() / (self.nFFTPoints*self.ippFactor)
632 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
632 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
633
633
634 return freqrange
634 return freqrange
635
635
636 def getVelRange(self, extrapoints=0):
636 def getVelRange(self, extrapoints=0):
637
637
638 deltav = self.getVmax() / (self.nFFTPoints*self.ippFactor)
638 deltav = self.getVmax() / (self.nFFTPoints*self.ippFactor)
639 velrange = deltav*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) #- deltav/2
639 velrange = deltav*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) #- deltav/2
640
640
641 return velrange
641 return velrange
642
642
643 def getNPairs(self):
643 def getNPairs(self):
644
644
645 return len(self.pairsList)
645 return len(self.pairsList)
646
646
647 def getPairsIndexList(self):
647 def getPairsIndexList(self):
648
648
649 return range(self.nPairs)
649 return range(self.nPairs)
650
650
651 def getNormFactor(self):
651 def getNormFactor(self):
652
652
653 pwcode = 1
653 pwcode = 1
654
654
655 if self.flagDecodeData:
655 if self.flagDecodeData:
656 pwcode = numpy.sum(self.code[0]**2)
656 pwcode = numpy.sum(self.code[0]**2)
657 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
657 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
658 normFactor = self.nProfiles*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
658 normFactor = self.nProfiles*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
659
659
660 return normFactor
660 return normFactor
661
661
662 def getFlagCspc(self):
662 def getFlagCspc(self):
663
663
664 if self.data_cspc is None:
664 if self.data_cspc is None:
665 return True
665 return True
666
666
667 return False
667 return False
668
668
669 def getFlagDc(self):
669 def getFlagDc(self):
670
670
671 if self.data_dc is None:
671 if self.data_dc is None:
672 return True
672 return True
673
673
674 return False
674 return False
675
675
676 def getTimeInterval(self):
676 def getTimeInterval(self):
677
677
678 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles
678 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles
679
679
680 return timeInterval
680 return timeInterval
681
681
682 def getPower(self):
682 def getPower(self):
683
683
684 factor = self.normFactor
684 factor = self.normFactor
685 z = self.data_spc/factor
685 z = self.data_spc/factor
686 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
686 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
687 avg = numpy.average(z, axis=1)
687 avg = numpy.average(z, axis=1)
688
688
689 return 10*numpy.log10(avg)
689 return 10*numpy.log10(avg)
690
690
691 def getCoherence(self, pairsList=None, phase=False):
691 def getCoherence(self, pairsList=None, phase=False):
692
692
693 z = []
693 z = []
694 if pairsList is None:
694 if pairsList is None:
695 pairsIndexList = self.pairsIndexList
695 pairsIndexList = self.pairsIndexList
696 else:
696 else:
697 pairsIndexList = []
697 pairsIndexList = []
698 for pair in pairsList:
698 for pair in pairsList:
699 if pair not in self.pairsList:
699 if pair not in self.pairsList:
700 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
700 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
701 pairsIndexList.append(self.pairsList.index(pair))
701 pairsIndexList.append(self.pairsList.index(pair))
702 for i in range(len(pairsIndexList)):
702 for i in range(len(pairsIndexList)):
703 pair = self.pairsList[pairsIndexList[i]]
703 pair = self.pairsList[pairsIndexList[i]]
704 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
704 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
705 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
705 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
706 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
706 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
707 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
707 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
708 if phase:
708 if phase:
709 data = numpy.arctan2(avgcoherenceComplex.imag,
709 data = numpy.arctan2(avgcoherenceComplex.imag,
710 avgcoherenceComplex.real)*180/numpy.pi
710 avgcoherenceComplex.real)*180/numpy.pi
711 else:
711 else:
712 data = numpy.abs(avgcoherenceComplex)
712 data = numpy.abs(avgcoherenceComplex)
713
713
714 z.append(data)
714 z.append(data)
715
715
716 return numpy.array(z)
716 return numpy.array(z)
717
717
718 def setValue(self, value):
718 def setValue(self, value):
719
719
720 print "This property should not be initialized"
720 print "This property should not be initialized"
721
721
722 return
722 return
723
723
724 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
724 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
725 pairsIndexList = property(getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
725 pairsIndexList = property(getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
726 normFactor = property(getNormFactor, setValue, "I'm the 'getNormFactor' property.")
726 normFactor = property(getNormFactor, setValue, "I'm the 'getNormFactor' property.")
727 flag_cspc = property(getFlagCspc, setValue)
727 flag_cspc = property(getFlagCspc, setValue)
728 flag_dc = property(getFlagDc, setValue)
728 flag_dc = property(getFlagDc, setValue)
729 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
729 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
730 timeInterval = property(getTimeInterval, setValue, "I'm the 'timeInterval' property")
730 timeInterval = property(getTimeInterval, setValue, "I'm the 'timeInterval' property")
731
731
732 class SpectraHeis(Spectra):
732 class SpectraHeis(Spectra):
733
733
734 data_spc = None
734 data_spc = None
735
735
736 data_cspc = None
736 data_cspc = None
737
737
738 data_dc = None
738 data_dc = None
739
739
740 nFFTPoints = None
740 nFFTPoints = None
741
741
742 # nPairs = None
742 # nPairs = None
743
743
744 pairsList = None
744 pairsList = None
745
745
746 nCohInt = None
746 nCohInt = None
747
747
748 nIncohInt = None
748 nIncohInt = None
749
749
750 def __init__(self):
750 def __init__(self):
751
751
752 self.radarControllerHeaderObj = RadarControllerHeader()
752 self.radarControllerHeaderObj = RadarControllerHeader()
753
753
754 self.systemHeaderObj = SystemHeader()
754 self.systemHeaderObj = SystemHeader()
755
755
756 self.type = "SpectraHeis"
756 self.type = "SpectraHeis"
757
757
758 # self.dtype = None
758 # self.dtype = None
759
759
760 # self.nChannels = 0
760 # self.nChannels = 0
761
761
762 # self.nHeights = 0
762 # self.nHeights = 0
763
763
764 self.nProfiles = None
764 self.nProfiles = None
765
765
766 self.heightList = None
766 self.heightList = None
767
767
768 self.channelList = None
768 self.channelList = None
769
769
770 # self.channelIndexList = None
770 # self.channelIndexList = None
771
771
772 self.flagNoData = True
772 self.flagNoData = True
773
773
774 self.flagDiscontinuousBlock = False
774 self.flagDiscontinuousBlock = False
775
775
776 # self.nPairs = 0
776 # self.nPairs = 0
777
777
778 self.utctime = None
778 self.utctime = None
779
779
780 self.blocksize = None
780 self.blocksize = None
781
781
782 self.profileIndex = 0
782 self.profileIndex = 0
783
783
784 self.nCohInt = 1
784 self.nCohInt = 1
785
785
786 self.nIncohInt = 1
786 self.nIncohInt = 1
787
787
788 def getNormFactor(self):
788 def getNormFactor(self):
789 pwcode = 1
789 pwcode = 1
790 if self.flagDecodeData:
790 if self.flagDecodeData:
791 pwcode = numpy.sum(self.code[0]**2)
791 pwcode = numpy.sum(self.code[0]**2)
792
792
793 normFactor = self.nIncohInt*self.nCohInt*pwcode
793 normFactor = self.nIncohInt*self.nCohInt*pwcode
794
794
795 return normFactor
795 return normFactor
796
796
797 def getTimeInterval(self):
797 def getTimeInterval(self):
798
798
799 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
799 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
800
800
801 return timeInterval
801 return timeInterval
802
802
803 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
803 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
804 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
804 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
805
805
806 class Fits(JROData):
806 class Fits(JROData):
807
807
808 heightList = None
808 heightList = None
809
809
810 channelList = None
810 channelList = None
811
811
812 flagNoData = True
812 flagNoData = True
813
813
814 flagDiscontinuousBlock = False
814 flagDiscontinuousBlock = False
815
815
816 useLocalTime = False
816 useLocalTime = False
817
817
818 utctime = None
818 utctime = None
819
819
820 timeZone = None
820 timeZone = None
821
821
822 # ippSeconds = None
822 # ippSeconds = None
823
823
824 # timeInterval = None
824 # timeInterval = None
825
825
826 nCohInt = None
826 nCohInt = None
827
827
828 nIncohInt = None
828 nIncohInt = None
829
829
830 noise = None
830 noise = None
831
831
832 windowOfFilter = 1
832 windowOfFilter = 1
833
833
834 #Speed of ligth
834 #Speed of ligth
835 C = 3e8
835 C = 3e8
836
836
837 frequency = 49.92e6
837 frequency = 49.92e6
838
838
839 realtime = False
839 realtime = False
840
840
841
841
842 def __init__(self):
842 def __init__(self):
843
843
844 self.type = "Fits"
844 self.type = "Fits"
845
845
846 self.nProfiles = None
846 self.nProfiles = None
847
847
848 self.heightList = None
848 self.heightList = None
849
849
850 self.channelList = None
850 self.channelList = None
851
851
852 # self.channelIndexList = None
852 # self.channelIndexList = None
853
853
854 self.flagNoData = True
854 self.flagNoData = True
855
855
856 self.utctime = None
856 self.utctime = None
857
857
858 self.nCohInt = 1
858 self.nCohInt = 1
859
859
860 self.nIncohInt = 1
860 self.nIncohInt = 1
861
861
862 self.useLocalTime = True
862 self.useLocalTime = True
863
863
864 self.profileIndex = 0
864 self.profileIndex = 0
865
865
866 # self.utctime = None
866 # self.utctime = None
867 # self.timeZone = None
867 # self.timeZone = None
868 # self.ltctime = None
868 # self.ltctime = None
869 # self.timeInterval = None
869 # self.timeInterval = None
870 # self.header = None
870 # self.header = None
871 # self.data_header = None
871 # self.data_header = None
872 # self.data = None
872 # self.data = None
873 # self.datatime = None
873 # self.datatime = None
874 # self.flagNoData = False
874 # self.flagNoData = False
875 # self.expName = ''
875 # self.expName = ''
876 # self.nChannels = None
876 # self.nChannels = None
877 # self.nSamples = None
877 # self.nSamples = None
878 # self.dataBlocksPerFile = None
878 # self.dataBlocksPerFile = None
879 # self.comments = ''
879 # self.comments = ''
880 #
880 #
881
881
882
882
883 def getltctime(self):
883 def getltctime(self):
884
884
885 if self.useLocalTime:
885 if self.useLocalTime:
886 return self.utctime - self.timeZone*60
886 return self.utctime - self.timeZone*60
887
887
888 return self.utctime
888 return self.utctime
889
889
890 def getDatatime(self):
890 def getDatatime(self):
891
891
892 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
892 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
893 return datatime
893 return datatime
894
894
895 def getTimeRange(self):
895 def getTimeRange(self):
896
896
897 datatime = []
897 datatime = []
898
898
899 datatime.append(self.ltctime)
899 datatime.append(self.ltctime)
900 datatime.append(self.ltctime + self.timeInterval)
900 datatime.append(self.ltctime + self.timeInterval)
901
901
902 datatime = numpy.array(datatime)
902 datatime = numpy.array(datatime)
903
903
904 return datatime
904 return datatime
905
905
906 def getHeiRange(self):
906 def getHeiRange(self):
907
907
908 heis = self.heightList
908 heis = self.heightList
909
909
910 return heis
910 return heis
911
911
912 def getNHeights(self):
912 def getNHeights(self):
913
913
914 return len(self.heightList)
914 return len(self.heightList)
915
915
916 def getNChannels(self):
916 def getNChannels(self):
917
917
918 return len(self.channelList)
918 return len(self.channelList)
919
919
920 def getChannelIndexList(self):
920 def getChannelIndexList(self):
921
921
922 return range(self.nChannels)
922 return range(self.nChannels)
923
923
924 def getNoise(self, type = 1):
924 def getNoise(self, type = 1):
925
925
926 #noise = numpy.zeros(self.nChannels)
926 #noise = numpy.zeros(self.nChannels)
927
927
928 if type == 1:
928 if type == 1:
929 noise = self.getNoisebyHildebrand()
929 noise = self.getNoisebyHildebrand()
930
930
931 if type == 2:
931 if type == 2:
932 noise = self.getNoisebySort()
932 noise = self.getNoisebySort()
933
933
934 if type == 3:
934 if type == 3:
935 noise = self.getNoisebyWindow()
935 noise = self.getNoisebyWindow()
936
936
937 return noise
937 return noise
938
938
939 def getTimeInterval(self):
939 def getTimeInterval(self):
940
940
941 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
941 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
942
942
943 return timeInterval
943 return timeInterval
944
944
945 datatime = property(getDatatime, "I'm the 'datatime' property")
945 datatime = property(getDatatime, "I'm the 'datatime' property")
946 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
946 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
947 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
947 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
948 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
948 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
949 noise = property(getNoise, "I'm the 'nHeights' property.")
949 noise = property(getNoise, "I'm the 'nHeights' property.")
950
950
951 ltctime = property(getltctime, "I'm the 'ltctime' property")
951 ltctime = property(getltctime, "I'm the 'ltctime' property")
952 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
952 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
953
953
954
954
955 class Correlation(JROData):
955 class Correlation(JROData):
956
956
957 noise = None
957 noise = None
958
958
959 SNR = None
959 SNR = None
960
960
961 #--------------------------------------------------
961 #--------------------------------------------------
962
962
963 mode = None
963 mode = None
964
964
965 split = False
965 split = False
966
966
967 data_cf = None
967 data_cf = None
968
968
969 lags = None
969 lags = None
970
970
971 lagRange = None
971 lagRange = None
972
972
973 pairsList = None
973 pairsList = None
974
974
975 normFactor = None
975 normFactor = None
976
976
977 #--------------------------------------------------
977 #--------------------------------------------------
978
978
979 # calculateVelocity = None
979 # calculateVelocity = None
980
980
981 nLags = None
981 nLags = None
982
982
983 nPairs = None
983 nPairs = None
984
984
985 nAvg = None
985 nAvg = None
986
986
987
987
988 def __init__(self):
988 def __init__(self):
989 '''
989 '''
990 Constructor
990 Constructor
991 '''
991 '''
992 self.radarControllerHeaderObj = RadarControllerHeader()
992 self.radarControllerHeaderObj = RadarControllerHeader()
993
993
994 self.systemHeaderObj = SystemHeader()
994 self.systemHeaderObj = SystemHeader()
995
995
996 self.type = "Correlation"
996 self.type = "Correlation"
997
997
998 self.data = None
998 self.data = None
999
999
1000 self.dtype = None
1000 self.dtype = None
1001
1001
1002 self.nProfiles = None
1002 self.nProfiles = None
1003
1003
1004 self.heightList = None
1004 self.heightList = None
1005
1005
1006 self.channelList = None
1006 self.channelList = None
1007
1007
1008 self.flagNoData = True
1008 self.flagNoData = True
1009
1009
1010 self.flagDiscontinuousBlock = False
1010 self.flagDiscontinuousBlock = False
1011
1011
1012 self.utctime = None
1012 self.utctime = None
1013
1013
1014 self.timeZone = None
1014 self.timeZone = None
1015
1015
1016 self.dstFlag = None
1016 self.dstFlag = None
1017
1017
1018 self.errorCount = None
1018 self.errorCount = None
1019
1019
1020 self.blocksize = None
1020 self.blocksize = None
1021
1021
1022 self.flagDecodeData = False #asumo q la data no esta decodificada
1022 self.flagDecodeData = False #asumo q la data no esta decodificada
1023
1023
1024 self.flagDeflipData = False #asumo q la data no esta sin flip
1024 self.flagDeflipData = False #asumo q la data no esta sin flip
1025
1025
1026 self.pairsList = None
1026 self.pairsList = None
1027
1027
1028 self.nPoints = None
1028 self.nPoints = None
1029
1029
1030 def getPairsList(self):
1030 def getPairsList(self):
1031
1031
1032 return self.pairsList
1032 return self.pairsList
1033
1033
1034 def getNoise(self, mode = 2):
1034 def getNoise(self, mode = 2):
1035
1035
1036 indR = numpy.where(self.lagR == 0)[0][0]
1036 indR = numpy.where(self.lagR == 0)[0][0]
1037 indT = numpy.where(self.lagT == 0)[0][0]
1037 indT = numpy.where(self.lagT == 0)[0][0]
1038
1038
1039 jspectra0 = self.data_corr[:,:,indR,:]
1039 jspectra0 = self.data_corr[:,:,indR,:]
1040 jspectra = copy.copy(jspectra0)
1040 jspectra = copy.copy(jspectra0)
1041
1041
1042 num_chan = jspectra.shape[0]
1042 num_chan = jspectra.shape[0]
1043 num_hei = jspectra.shape[2]
1043 num_hei = jspectra.shape[2]
1044
1044
1045 freq_dc = jspectra.shape[1]/2
1045 freq_dc = jspectra.shape[1]/2
1046 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
1046 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
1047
1047
1048 if ind_vel[0]<0:
1048 if ind_vel[0]<0:
1049 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
1049 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
1050
1050
1051 if mode == 1:
1051 if mode == 1:
1052 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
1052 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
1053
1053
1054 if mode == 2:
1054 if mode == 2:
1055
1055
1056 vel = numpy.array([-2,-1,1,2])
1056 vel = numpy.array([-2,-1,1,2])
1057 xx = numpy.zeros([4,4])
1057 xx = numpy.zeros([4,4])
1058
1058
1059 for fil in range(4):
1059 for fil in range(4):
1060 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
1060 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
1061
1061
1062 xx_inv = numpy.linalg.inv(xx)
1062 xx_inv = numpy.linalg.inv(xx)
1063 xx_aux = xx_inv[0,:]
1063 xx_aux = xx_inv[0,:]
1064
1064
1065 for ich in range(num_chan):
1065 for ich in range(num_chan):
1066 yy = jspectra[ich,ind_vel,:]
1066 yy = jspectra[ich,ind_vel,:]
1067 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
1067 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
1068
1068
1069 junkid = jspectra[ich,freq_dc,:]<=0
1069 junkid = jspectra[ich,freq_dc,:]<=0
1070 cjunkid = sum(junkid)
1070 cjunkid = sum(junkid)
1071
1071
1072 if cjunkid.any():
1072 if cjunkid.any():
1073 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
1073 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
1074
1074
1075 noise = jspectra0[:,freq_dc,:] - jspectra[:,freq_dc,:]
1075 noise = jspectra0[:,freq_dc,:] - jspectra[:,freq_dc,:]
1076
1076
1077 return noise
1077 return noise
1078
1078
1079 def getTimeInterval(self):
1079 def getTimeInterval(self):
1080
1080
1081 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
1081 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
1082
1082
1083 return timeInterval
1083 return timeInterval
1084
1084
1085 def splitFunctions(self):
1085 def splitFunctions(self):
1086
1086
1087 pairsList = self.pairsList
1087 pairsList = self.pairsList
1088 ccf_pairs = []
1088 ccf_pairs = []
1089 acf_pairs = []
1089 acf_pairs = []
1090 ccf_ind = []
1090 ccf_ind = []
1091 acf_ind = []
1091 acf_ind = []
1092 for l in range(len(pairsList)):
1092 for l in range(len(pairsList)):
1093 chan0 = pairsList[l][0]
1093 chan0 = pairsList[l][0]
1094 chan1 = pairsList[l][1]
1094 chan1 = pairsList[l][1]
1095
1095
1096 #Obteniendo pares de Autocorrelacion
1096 #Obteniendo pares de Autocorrelacion
1097 if chan0 == chan1:
1097 if chan0 == chan1:
1098 acf_pairs.append(chan0)
1098 acf_pairs.append(chan0)
1099 acf_ind.append(l)
1099 acf_ind.append(l)
1100 else:
1100 else:
1101 ccf_pairs.append(pairsList[l])
1101 ccf_pairs.append(pairsList[l])
1102 ccf_ind.append(l)
1102 ccf_ind.append(l)
1103
1103
1104 data_acf = self.data_cf[acf_ind]
1104 data_acf = self.data_cf[acf_ind]
1105 data_ccf = self.data_cf[ccf_ind]
1105 data_ccf = self.data_cf[ccf_ind]
1106
1106
1107 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1107 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1108
1108
1109 def getNormFactor(self):
1109 def getNormFactor(self):
1110 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1110 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1111 acf_pairs = numpy.array(acf_pairs)
1111 acf_pairs = numpy.array(acf_pairs)
1112 normFactor = numpy.zeros((self.nPairs,self.nHeights))
1112 normFactor = numpy.zeros((self.nPairs,self.nHeights))
1113
1113
1114 for p in range(self.nPairs):
1114 for p in range(self.nPairs):
1115 pair = self.pairsList[p]
1115 pair = self.pairsList[p]
1116
1116
1117 ch0 = pair[0]
1117 ch0 = pair[0]
1118 ch1 = pair[1]
1118 ch1 = pair[1]
1119
1119
1120 ch0_max = numpy.max(data_acf[acf_pairs==ch0,:,:], axis=1)
1120 ch0_max = numpy.max(data_acf[acf_pairs==ch0,:,:], axis=1)
1121 ch1_max = numpy.max(data_acf[acf_pairs==ch1,:,:], axis=1)
1121 ch1_max = numpy.max(data_acf[acf_pairs==ch1,:,:], axis=1)
1122 normFactor[p,:] = numpy.sqrt(ch0_max*ch1_max)
1122 normFactor[p,:] = numpy.sqrt(ch0_max*ch1_max)
1123
1123
1124 return normFactor
1124 return normFactor
1125
1125
1126 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1126 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1127 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1127 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1128
1128
1129 class Parameters(Spectra):
1129 class Parameters(Spectra):
1130
1130
1131 experimentInfo = None #Information about the experiment
1131 experimentInfo = None #Information about the experiment
1132
1132
1133 #Information from previous data
1133 #Information from previous data
1134
1134
1135 inputUnit = None #Type of data to be processed
1135 inputUnit = None #Type of data to be processed
1136
1136
1137 operation = None #Type of operation to parametrize
1137 operation = None #Type of operation to parametrize
1138
1138
1139 #normFactor = None #Normalization Factor
1139 #normFactor = None #Normalization Factor
1140
1140
1141 groupList = None #List of Pairs, Groups, etc
1141 groupList = None #List of Pairs, Groups, etc
1142
1142
1143 #Parameters
1143 #Parameters
1144
1144
1145 data_param = None #Parameters obtained
1145 data_param = None #Parameters obtained
1146
1146
1147 data_pre = None #Data Pre Parametrization
1147 data_pre = None #Data Pre Parametrization
1148
1148
1149 data_SNR = None #Signal to Noise Ratio
1149 data_SNR = None #Signal to Noise Ratio
1150
1150
1151 # heightRange = None #Heights
1151 # heightRange = None #Heights
1152
1152
1153 abscissaList = None #Abscissa, can be velocities, lags or time
1153 abscissaList = None #Abscissa, can be velocities, lags or time
1154
1154
1155 # noise = None #Noise Potency
1155 # noise = None #Noise Potency
1156
1156
1157 utctimeInit = None #Initial UTC time
1157 utctimeInit = None #Initial UTC time
1158
1158
1159 paramInterval = None #Time interval to calculate Parameters in seconds
1159 paramInterval = None #Time interval to calculate Parameters in seconds
1160
1160
1161 useLocalTime = True
1161 useLocalTime = True
1162
1162
1163 #Fitting
1163 #Fitting
1164
1164
1165 data_error = None #Error of the estimation
1165 data_error = None #Error of the estimation
1166
1166
1167 constants = None
1167 constants = None
1168
1168
1169 library = None
1169 library = None
1170
1170
1171 #Output signal
1171 #Output signal
1172
1172
1173 outputInterval = None #Time interval to calculate output signal in seconds
1173 outputInterval = None #Time interval to calculate output signal in seconds
1174
1174
1175 data_output = None #Out signal
1175 data_output = None #Out signal
1176
1176
1177 nAvg = None
1177 nAvg = None
1178
1178
1179 noise_estimation = None
1179 noise_estimation = None
1180
1181 GauSPC = None #Fit gaussian SPC
1180
1182
1181
1183
1182 def __init__(self):
1184 def __init__(self):
1183 '''
1185 '''
1184 Constructor
1186 Constructor
1185 '''
1187 '''
1186 self.radarControllerHeaderObj = RadarControllerHeader()
1188 self.radarControllerHeaderObj = RadarControllerHeader()
1187
1189
1188 self.systemHeaderObj = SystemHeader()
1190 self.systemHeaderObj = SystemHeader()
1189
1191
1190 self.type = "Parameters"
1192 self.type = "Parameters"
1191
1193
1192 def getTimeRange1(self, interval):
1194 def getTimeRange1(self, interval):
1193
1195
1194 datatime = []
1196 datatime = []
1195
1197
1196 if self.useLocalTime:
1198 if self.useLocalTime:
1197 time1 = self.utctimeInit - self.timeZone*60
1199 time1 = self.utctimeInit - self.timeZone*60
1198 else:
1200 else:
1199 time1 = self.utctimeInit
1201 time1 = self.utctimeInit
1200
1202
1201 datatime.append(time1)
1203 datatime.append(time1)
1202 datatime.append(time1 + interval)
1204 datatime.append(time1 + interval)
1203 datatime = numpy.array(datatime)
1205 datatime = numpy.array(datatime)
1204
1206
1205 return datatime
1207 return datatime
1206
1208
1207 def getTimeInterval(self):
1209 def getTimeInterval(self):
1208
1210
1209 if hasattr(self, 'timeInterval1'):
1211 if hasattr(self, 'timeInterval1'):
1210 return self.timeInterval1
1212 return self.timeInterval1
1211 else:
1213 else:
1212 return self.paramInterval
1214 return self.paramInterval
1213
1215
1216 def setValue(self, value):
1217
1218 print "This property should not be initialized"
1219
1220 return
1221
1214 def getNoise(self):
1222 def getNoise(self):
1215
1223
1216 return self.spc_noise
1224 return self.spc_noise
1217
1225
1218 timeInterval = property(getTimeInterval)
1226 timeInterval = property(getTimeInterval)
1227 noise = property(getNoise, setValue, "I'm the 'Noise' property.")
@@ -1,782 +1,819
1
1
2 import os
2 import os
3 import time
3 import time
4 import glob
4 import glob
5 import datetime
5 import datetime
6 from multiprocessing import Process
6 from multiprocessing import Process
7
7
8 import zmq
8 import zmq
9 import numpy
9 import numpy
10 import matplotlib
10 import matplotlib
11 import matplotlib.pyplot as plt
11 import matplotlib.pyplot as plt
12 from mpl_toolkits.axes_grid1 import make_axes_locatable
12 from mpl_toolkits.axes_grid1 import make_axes_locatable
13 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
13 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
14
14
15 from schainpy.model.proc.jroproc_base import Operation
15 from schainpy.model.proc.jroproc_base import Operation
16 from schainpy.utils import log
16 from schainpy.utils import log
17
17
18 func = lambda x, pos: ('%s') %(datetime.datetime.fromtimestamp(x).strftime('%H:%M'))
18 jet_values = matplotlib.pyplot.get_cmap("jet", 100)(numpy.arange(100))[10:90]
19 blu_values = matplotlib.pyplot.get_cmap("seismic_r", 20)(numpy.arange(20))[10:15]
20 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list("jro", numpy.vstack((blu_values, jet_values)))
21 matplotlib.pyplot.register_cmap(cmap=ncmap)
19
22
20 d1970 = datetime.datetime(1970, 1, 1)
23 func = lambda x, pos: '{}'.format(datetime.datetime.fromtimestamp(x).strftime('%H:%M'))
21
24
25 UT1970 = datetime.datetime(1970, 1, 1) - datetime.timedelta(seconds=time.timezone)
26
27 CMAPS = [plt.get_cmap(s) for s in ('jro', 'jet', 'RdBu_r', 'seismic')]
22
28
23 class PlotData(Operation, Process):
29 class PlotData(Operation, Process):
24 '''
30 '''
25 Base class for Schain plotting operations
31 Base class for Schain plotting operations
26 '''
32 '''
27
33
28 CODE = 'Figure'
34 CODE = 'Figure'
29 colormap = 'jro'
35 colormap = 'jro'
30 bgcolor = 'white'
36 bgcolor = 'white'
31 CONFLATE = False
37 CONFLATE = False
32 __MAXNUMX = 80
38 __MAXNUMX = 80
33 __missing = 1E30
39 __missing = 1E30
34
40
35 def __init__(self, **kwargs):
41 def __init__(self, **kwargs):
36
42
37 Operation.__init__(self, plot=True, **kwargs)
43 Operation.__init__(self, plot=True, **kwargs)
38 Process.__init__(self)
44 Process.__init__(self)
39 self.kwargs['code'] = self.CODE
45 self.kwargs['code'] = self.CODE
40 self.mp = False
46 self.mp = False
41 self.data = None
47 self.data = None
42 self.isConfig = False
48 self.isConfig = False
43 self.figures = []
49 self.figures = []
44 self.axes = []
50 self.axes = []
45 self.cb_axes = []
51 self.cb_axes = []
46 self.localtime = kwargs.pop('localtime', True)
52 self.localtime = kwargs.pop('localtime', True)
47 self.show = kwargs.get('show', True)
53 self.show = kwargs.get('show', True)
48 self.save = kwargs.get('save', False)
54 self.save = kwargs.get('save', False)
49 self.colormap = kwargs.get('colormap', self.colormap)
55 self.colormap = kwargs.get('colormap', self.colormap)
50 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
56 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
51 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
57 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
52 self.colormaps = kwargs.get('colormaps', None)
58 self.colormaps = kwargs.get('colormaps', None)
53 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
59 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
54 self.showprofile = kwargs.get('showprofile', False)
60 self.showprofile = kwargs.get('showprofile', False)
55 self.title = kwargs.get('wintitle', self.CODE.upper())
61 self.title = kwargs.get('wintitle', self.CODE.upper())
56 self.cb_label = kwargs.get('cb_label', None)
62 self.cb_label = kwargs.get('cb_label', None)
57 self.cb_labels = kwargs.get('cb_labels', None)
63 self.cb_labels = kwargs.get('cb_labels', None)
58 self.xaxis = kwargs.get('xaxis', 'frequency')
64 self.xaxis = kwargs.get('xaxis', 'frequency')
59 self.zmin = kwargs.get('zmin', None)
65 self.zmin = kwargs.get('zmin', None)
60 self.zmax = kwargs.get('zmax', None)
66 self.zmax = kwargs.get('zmax', None)
61 self.zlimits = kwargs.get('zlimits', None)
67 self.zlimits = kwargs.get('zlimits', None)
62 self.xmin = kwargs.get('xmin', None)
68 self.xmin = kwargs.get('xmin', None)
63 if self.xmin is not None:
64 self.xmin += 5
65 self.xmax = kwargs.get('xmax', None)
69 self.xmax = kwargs.get('xmax', None)
66 self.xrange = kwargs.get('xrange', 24)
70 self.xrange = kwargs.get('xrange', 24)
67 self.ymin = kwargs.get('ymin', None)
71 self.ymin = kwargs.get('ymin', None)
68 self.ymax = kwargs.get('ymax', None)
72 self.ymax = kwargs.get('ymax', None)
69 self.xlabel = kwargs.get('xlabel', None)
73 self.xlabel = kwargs.get('xlabel', None)
70 self.__MAXNUMY = kwargs.get('decimation', 100)
74 self.__MAXNUMY = kwargs.get('decimation', 100)
71 self.showSNR = kwargs.get('showSNR', False)
75 self.showSNR = kwargs.get('showSNR', False)
72 self.oneFigure = kwargs.get('oneFigure', True)
76 self.oneFigure = kwargs.get('oneFigure', True)
73 self.width = kwargs.get('width', None)
77 self.width = kwargs.get('width', None)
74 self.height = kwargs.get('height', None)
78 self.height = kwargs.get('height', None)
75 self.colorbar = kwargs.get('colorbar', True)
79 self.colorbar = kwargs.get('colorbar', True)
76 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
80 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
77 self.titles = ['' for __ in range(16)]
81 self.titles = ['' for __ in range(16)]
78
82
79 def __setup(self):
83 def __setup(self):
80 '''
84 '''
81 Common setup for all figures, here figures and axes are created
85 Common setup for all figures, here figures and axes are created
82 '''
86 '''
83
87
84 self.setup()
88 self.setup()
85
89
90 self.time_label = 'LT' if self.localtime else 'UTC'
91
86 if self.width is None:
92 if self.width is None:
87 self.width = 8
93 self.width = 8
88
94
89 self.figures = []
95 self.figures = []
90 self.axes = []
96 self.axes = []
91 self.cb_axes = []
97 self.cb_axes = []
92 self.pf_axes = []
98 self.pf_axes = []
93 self.cmaps = []
99 self.cmaps = []
94
100
95 size = '15%' if self.ncols==1 else '30%'
101 size = '15%' if self.ncols==1 else '30%'
96 pad = '4%' if self.ncols==1 else '8%'
102 pad = '4%' if self.ncols==1 else '8%'
97
103
98 if self.oneFigure:
104 if self.oneFigure:
99 if self.height is None:
105 if self.height is None:
100 self.height = 1.4*self.nrows + 1
106 self.height = 1.4*self.nrows + 1
101 fig = plt.figure(figsize=(self.width, self.height),
107 fig = plt.figure(figsize=(self.width, self.height),
102 edgecolor='k',
108 edgecolor='k',
103 facecolor='w')
109 facecolor='w')
104 self.figures.append(fig)
110 self.figures.append(fig)
105 for n in range(self.nplots):
111 for n in range(self.nplots):
106 ax = fig.add_subplot(self.nrows, self.ncols, n+1)
112 ax = fig.add_subplot(self.nrows, self.ncols, n+1)
107 ax.tick_params(labelsize=8)
113 ax.tick_params(labelsize=8)
108 ax.firsttime = True
114 ax.firsttime = True
115 ax.index = 0
109 self.axes.append(ax)
116 self.axes.append(ax)
110 if self.showprofile:
117 if self.showprofile:
111 cax = self.__add_axes(ax, size=size, pad=pad)
118 cax = self.__add_axes(ax, size=size, pad=pad)
112 cax.tick_params(labelsize=8)
119 cax.tick_params(labelsize=8)
113 self.pf_axes.append(cax)
120 self.pf_axes.append(cax)
114 else:
121 else:
115 if self.height is None:
122 if self.height is None:
116 self.height = 3
123 self.height = 3
117 for n in range(self.nplots):
124 for n in range(self.nplots):
118 fig = plt.figure(figsize=(self.width, self.height),
125 fig = plt.figure(figsize=(self.width, self.height),
119 edgecolor='k',
126 edgecolor='k',
120 facecolor='w')
127 facecolor='w')
121 ax = fig.add_subplot(1, 1, 1)
128 ax = fig.add_subplot(1, 1, 1)
122 ax.tick_params(labelsize=8)
129 ax.tick_params(labelsize=8)
123 ax.firsttime = True
130 ax.firsttime = True
131 ax.index = 0
124 self.figures.append(fig)
132 self.figures.append(fig)
125 self.axes.append(ax)
133 self.axes.append(ax)
126 if self.showprofile:
134 if self.showprofile:
127 cax = self.__add_axes(ax, size=size, pad=pad)
135 cax = self.__add_axes(ax, size=size, pad=pad)
128 cax.tick_params(labelsize=8)
136 cax.tick_params(labelsize=8)
129 self.pf_axes.append(cax)
137 self.pf_axes.append(cax)
130
138
131 for n in range(self.nrows):
139 for n in range(self.nrows):
132 if self.colormaps is not None:
140 if self.colormaps is not None:
133 cmap = plt.get_cmap(self.colormaps[n])
141 cmap = plt.get_cmap(self.colormaps[n])
134 else:
142 else:
135 cmap = plt.get_cmap(self.colormap)
143 cmap = plt.get_cmap(self.colormap)
136 cmap.set_bad(self.bgcolor, 1.)
144 cmap.set_bad(self.bgcolor, 1.)
137 self.cmaps.append(cmap)
145 self.cmaps.append(cmap)
138
146
147 for fig in self.figures:
148 fig.canvas.mpl_connect('key_press_event', self.event_key_press)
149
150 def event_key_press(self, event):
151 '''
152 '''
153
154 for ax in self.axes:
155 if ax == event.inaxes:
156 if event.key == 'down':
157 ax.index += 1
158 elif event.key == 'up':
159 ax.index -= 1
160 if ax.index < 0:
161 ax.index = len(CMAPS) - 1
162 elif ax.index == len(CMAPS):
163 ax.index = 0
164 cmap = CMAPS[ax.index]
165 ax.cbar.set_cmap(cmap)
166 ax.cbar.draw_all()
167 ax.plt.set_cmap(cmap)
168 ax.cbar.patch.figure.canvas.draw()
169
139 def __add_axes(self, ax, size='30%', pad='8%'):
170 def __add_axes(self, ax, size='30%', pad='8%'):
140 '''
171 '''
141 Add new axes to the given figure
172 Add new axes to the given figure
142 '''
173 '''
143 divider = make_axes_locatable(ax)
174 divider = make_axes_locatable(ax)
144 nax = divider.new_horizontal(size=size, pad=pad)
175 nax = divider.new_horizontal(size=size, pad=pad)
145 ax.figure.add_axes(nax)
176 ax.figure.add_axes(nax)
146 return nax
177 return nax
147
178
179 self.setup()
148
180
149 def setup(self):
181 def setup(self):
150 '''
182 '''
151 This method should be implemented in the child class, the following
183 This method should be implemented in the child class, the following
152 attributes should be set:
184 attributes should be set:
153
185
154 self.nrows: number of rows
186 self.nrows: number of rows
155 self.ncols: number of cols
187 self.ncols: number of cols
156 self.nplots: number of plots (channels or pairs)
188 self.nplots: number of plots (channels or pairs)
157 self.ylabel: label for Y axes
189 self.ylabel: label for Y axes
158 self.titles: list of axes title
190 self.titles: list of axes title
159
191
160 '''
192 '''
161 raise(NotImplementedError, 'Implement this method in child class')
193 raise(NotImplementedError, 'Implement this method in child class')
162
194
163 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
195 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
164 '''
196 '''
165 Create a masked array for missing data
197 Create a masked array for missing data
166 '''
198 '''
167 if x_buffer.shape[0] < 2:
199 if x_buffer.shape[0] < 2:
168 return x_buffer, y_buffer, z_buffer
200 return x_buffer, y_buffer, z_buffer
169
201
170 deltas = x_buffer[1:] - x_buffer[0:-1]
202 deltas = x_buffer[1:] - x_buffer[0:-1]
171 x_median = numpy.median(deltas)
203 x_median = numpy.median(deltas)
172
204
173 index = numpy.where(deltas > 5*x_median)
205 index = numpy.where(deltas > 5*x_median)
174
206
175 if len(index[0]) != 0:
207 if len(index[0]) != 0:
176 z_buffer[::, index[0], ::] = self.__missing
208 z_buffer[::, index[0], ::] = self.__missing
177 z_buffer = numpy.ma.masked_inside(z_buffer,
209 z_buffer = numpy.ma.masked_inside(z_buffer,
178 0.99*self.__missing,
210 0.99*self.__missing,
179 1.01*self.__missing)
211 1.01*self.__missing)
180
212
181 return x_buffer, y_buffer, z_buffer
213 return x_buffer, y_buffer, z_buffer
182
214
183 def decimate(self):
215 def decimate(self):
184
216
185 # dx = int(len(self.x)/self.__MAXNUMX) + 1
217 # dx = int(len(self.x)/self.__MAXNUMX) + 1
186 dy = int(len(self.y)/self.__MAXNUMY) + 1
218 dy = int(len(self.y)/self.__MAXNUMY) + 1
187
219
188 # x = self.x[::dx]
220 # x = self.x[::dx]
189 x = self.x
221 x = self.x
190 y = self.y[::dy]
222 y = self.y[::dy]
191 z = self.z[::, ::, ::dy]
223 z = self.z[::, ::, ::dy]
192
224
193 return x, y, z
225 return x, y, z
194
226
195 def format(self):
227 def format(self):
196 '''
228 '''
197 Set min and max values, labels, ticks and titles
229 Set min and max values, labels, ticks and titles
198 '''
230 '''
199
231
200 if self.xmin is None:
232 if self.xmin is None:
201 xmin = self.min_time
233 xmin = self.min_time
202 else:
234 else:
203 if self.xaxis is 'time':
235 if self.xaxis is 'time':
204 dt = datetime.datetime.fromtimestamp(self.min_time)
236 dt = datetime.datetime.fromtimestamp(self.min_time)
205 xmin = (datetime.datetime.combine(dt.date(),
237 xmin = (datetime.datetime.combine(dt.date(),
206 datetime.time(int(self.xmin), 0, 0))-d1970).total_seconds()
238 datetime.time(int(self.xmin), 0, 0))-UT1970).total_seconds()
207 else:
239 else:
208 xmin = self.xmin
240 xmin = self.xmin
209
241
210 if self.xmax is None:
242 if self.xmax is None:
211 xmax = xmin+self.xrange*60*60
243 xmax = xmin+self.xrange*60*60
212 else:
244 else:
213 if self.xaxis is 'time':
245 if self.xaxis is 'time':
214 dt = datetime.datetime.fromtimestamp(self.min_time)
246 dt = datetime.datetime.fromtimestamp(self.min_time)
215 xmax = (datetime.datetime.combine(dt.date(),
247 xmax = (datetime.datetime.combine(dt.date(),
216 datetime.time(int(self.xmax), 0, 0))-d1970).total_seconds()
248 datetime.time(int(self.xmax), 0, 0))-UT1970).total_seconds()
217 else:
249 else:
218 xmax = self.xmax
250 xmax = self.xmax
219
251
220 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
252 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
221 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
253 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
222
254
223 ystep = 200 if ymax>= 800 else 100 if ymax>=400 else 50 if ymax>=200 else 20
255 ystep = 200 if ymax>= 800 else 100 if ymax>=400 else 50 if ymax>=200 else 20
224
256
225 for n, ax in enumerate(self.axes):
257 for n, ax in enumerate(self.axes):
226 if ax.firsttime:
258 if ax.firsttime:
227 ax.set_facecolor(self.bgcolor)
259 ax.set_facecolor(self.bgcolor)
228 ax.yaxis.set_major_locator(MultipleLocator(ystep))
260 ax.yaxis.set_major_locator(MultipleLocator(ystep))
229 if self.xaxis is 'time':
261 if self.xaxis is 'time':
230 ax.xaxis.set_major_formatter(FuncFormatter(func))
262 ax.xaxis.set_major_formatter(FuncFormatter(func))
231 ax.xaxis.set_major_locator(LinearLocator(9))
263 ax.xaxis.set_major_locator(LinearLocator(9))
232 if self.xlabel is not None:
264 if self.xlabel is not None:
233 ax.set_xlabel(self.xlabel)
265 ax.set_xlabel(self.xlabel)
234 ax.set_ylabel(self.ylabel)
266 ax.set_ylabel(self.ylabel)
235 ax.firsttime = False
267 ax.firsttime = False
236 if self.showprofile:
268 if self.showprofile:
237 self.pf_axes[n].set_ylim(ymin, ymax)
269 self.pf_axes[n].set_ylim(ymin, ymax)
238 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
270 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
239 self.pf_axes[n].set_xlabel('dB')
271 self.pf_axes[n].set_xlabel('dB')
240 self.pf_axes[n].grid(b=True, axis='x')
272 self.pf_axes[n].grid(b=True, axis='x')
241 [tick.set_visible(False) for tick in self.pf_axes[n].get_yticklabels()]
273 [tick.set_visible(False) for tick in self.pf_axes[n].get_yticklabels()]
242 if self.colorbar:
274 if self.colorbar:
243 cb = plt.colorbar(ax.plt, ax=ax, pad=0.02)
275 ax.cbar = plt.colorbar(ax.plt, ax=ax, pad=0.02, aspect=10)
244 cb.ax.tick_params(labelsize=8)
276 ax.cbar.ax.tick_params(labelsize=8)
245 if self.cb_label:
277 if self.cb_label:
246 cb.set_label(self.cb_label, size=8)
278 ax.cbar.set_label(self.cb_label, size=8)
247 elif self.cb_labels:
279 elif self.cb_labels:
248 cb.set_label(self.cb_labels[n], size=8)
280 ax.cbar.set_label(self.cb_labels[n], size=8)
249
281
250 ax.set_title('{} - {} UTC'.format(
282 ax.set_title('{} - {} {}'.format(
251 self.titles[n],
283 self.titles[n],
252 datetime.datetime.fromtimestamp(self.max_time).strftime('%H:%M:%S')),
284 datetime.datetime.fromtimestamp(self.max_time).strftime('%H:%M:%S'),
285 self.time_label),
253 size=8)
286 size=8)
254 ax.set_xlim(xmin, xmax)
287 ax.set_xlim(xmin, xmax)
255 ax.set_ylim(ymin, ymax)
288 ax.set_ylim(ymin, ymax)
256
257
289
258 def __plot(self):
290 def __plot(self):
259 '''
291 '''
260 '''
292 '''
261 log.success('Plotting', self.name)
293 log.success('Plotting', self.name)
262
294
263 self.plot()
295 self.plot()
264 self.format()
296 self.format()
265
297
266 for n, fig in enumerate(self.figures):
298 for n, fig in enumerate(self.figures):
267 if self.nrows == 0 or self.nplots == 0:
299 if self.nrows == 0 or self.nplots == 0:
268 log.warning('No data', self.name)
300 log.warning('No data', self.name)
269 continue
301 continue
270 if self.show:
302 if self.show:
271 fig.show()
303 fig.show()
272
304
273 fig.tight_layout()
305 fig.tight_layout()
274 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
306 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
275 datetime.datetime.fromtimestamp(self.max_time).strftime('%Y/%m/%d')))
307 datetime.datetime.fromtimestamp(self.max_time).strftime('%Y/%m/%d')))
276 # fig.canvas.draw()
308 # fig.canvas.draw()
277
309
278 if self.save and self.data.ended:
310 if self.save and self.data.ended:
279 channels = range(self.nrows)
311 channels = range(self.nrows)
280 if self.oneFigure:
312 if self.oneFigure:
281 label = ''
313 label = ''
282 else:
314 else:
283 label = '_{}'.format(channels[n])
315 label = '_{}'.format(channels[n])
284 figname = os.path.join(
316 figname = os.path.join(
285 self.save,
317 self.save,
286 '{}{}_{}.png'.format(
318 '{}{}_{}.png'.format(
287 self.CODE,
319 self.CODE,
288 label,
320 label,
289 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')
321 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')
290 )
322 )
291 )
323 )
292 print 'Saving figure: {}'.format(figname)
324 print 'Saving figure: {}'.format(figname)
293 fig.savefig(figname)
325 fig.savefig(figname)
294
326
295 def plot(self):
327 def plot(self):
296 '''
328 '''
297 '''
329 '''
298 raise(NotImplementedError, 'Implement this method in child class')
330 raise(NotImplementedError, 'Implement this method in child class')
299
331
300 def run(self):
332 def run(self):
301
333
302 log.success('Starting', self.name)
334 log.success('Starting', self.name)
303
335
304 context = zmq.Context()
336 context = zmq.Context()
305 receiver = context.socket(zmq.SUB)
337 receiver = context.socket(zmq.SUB)
306 receiver.setsockopt(zmq.SUBSCRIBE, '')
338 receiver.setsockopt(zmq.SUBSCRIBE, '')
307 receiver.setsockopt(zmq.CONFLATE, self.CONFLATE)
339 receiver.setsockopt(zmq.CONFLATE, self.CONFLATE)
308
340
309 if 'server' in self.kwargs['parent']:
341 if 'server' in self.kwargs['parent']:
310 receiver.connect('ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
342 receiver.connect('ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
311 else:
343 else:
312 receiver.connect("ipc:///tmp/zmq.plots")
344 receiver.connect("ipc:///tmp/zmq.plots")
313
345
314 while True:
346 while True:
315 try:
347 try:
316 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
348 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
317
349
318 self.min_time = self.data.times[0]
350 if self.localtime:
319 self.max_time = self.data.times[-1]
351 self.times = self.data.times - time.timezone
352 else:
353 self.times = self.data.times
354
355 self.min_time = self.times[0]
356 self.max_time = self.times[-1]
320
357
321 if self.isConfig is False:
358 if self.isConfig is False:
322 self.__setup()
359 self.__setup()
323 self.isConfig = True
360 self.isConfig = True
324
361
325 self.__plot()
362 self.__plot()
326
363
327 except zmq.Again as e:
364 except zmq.Again as e:
328 log.log('Waiting for data...')
365 log.log('Waiting for data...')
329 if self.data:
366 if self.data:
330 plt.pause(self.data.throttle)
367 plt.pause(self.data.throttle)
331 else:
368 else:
332 time.sleep(2)
369 time.sleep(2)
333
370
334 def close(self):
371 def close(self):
335 if self.data:
372 if self.data:
336 self.__plot()
373 self.__plot()
337
374
338
339 class PlotSpectraData(PlotData):
375 class PlotSpectraData(PlotData):
340 '''
376 '''
341 Plot for Spectra data
377 Plot for Spectra data
342 '''
378 '''
343
379
344 CODE = 'spc'
380 CODE = 'spc'
345 colormap = 'jro'
381 colormap = 'jro'
346
382
347 def setup(self):
383 def setup(self):
348 self.nplots = len(self.data.channels)
384 self.nplots = len(self.data.channels)
349 self.ncols = int(numpy.sqrt(self.nplots)+ 0.9)
385 self.ncols = int(numpy.sqrt(self.nplots)+ 0.9)
350 self.nrows = int((1.0*self.nplots/self.ncols) + 0.9)
386 self.nrows = int((1.0*self.nplots/self.ncols) + 0.9)
351 self.width = 3.4*self.ncols
387 self.width = 3.4*self.ncols
352 self.height = 3*self.nrows
388 self.height = 3*self.nrows
353 self.cb_label = 'dB'
389 self.cb_label = 'dB'
354 if self.showprofile:
390 if self.showprofile:
355 self.width += 0.8*self.ncols
391 self.width += 0.8*self.ncols
356
392
357 self.ylabel = 'Range [Km]'
393 self.ylabel = 'Range [Km]'
358
394
359 def plot(self):
395 def plot(self):
360 if self.xaxis == "frequency":
396 if self.xaxis == "frequency":
361 x = self.data.xrange[0]
397 x = self.data.xrange[0]
362 self.xlabel = "Frequency (kHz)"
398 self.xlabel = "Frequency (kHz)"
363 elif self.xaxis == "time":
399 elif self.xaxis == "time":
364 x = self.data.xrange[1]
400 x = self.data.xrange[1]
365 self.xlabel = "Time (ms)"
401 self.xlabel = "Time (ms)"
366 else:
402 else:
367 x = self.data.xrange[2]
403 x = self.data.xrange[2]
368 self.xlabel = "Velocity (m/s)"
404 self.xlabel = "Velocity (m/s)"
369
405
370 if self.CODE == 'spc_mean':
406 if self.CODE == 'spc_mean':
371 x = self.data.xrange[2]
407 x = self.data.xrange[2]
372 self.xlabel = "Velocity (m/s)"
408 self.xlabel = "Velocity (m/s)"
373
409
374 self.titles = []
410 self.titles = []
375
411
376 y = self.data.heights
412 y = self.data.heights
377 self.y = y
413 self.y = y
378 z = self.data['spc']
414 z = self.data['spc']
379
415
380 for n, ax in enumerate(self.axes):
416 for n, ax in enumerate(self.axes):
381 noise = self.data['noise'][n][-1]
417 noise = self.data['noise'][n][-1]
382 if self.CODE == 'spc_mean':
418 if self.CODE == 'spc_mean':
383 mean = self.data['mean'][n][-1]
419 mean = self.data['mean'][n][-1]
384 if ax.firsttime:
420 if ax.firsttime:
385 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
421 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
386 self.xmin = self.xmin if self.xmin else -self.xmax
422 self.xmin = self.xmin if self.xmin else -self.xmax
387 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
423 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
388 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
424 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
389 ax.plt = ax.pcolormesh(x, y, z[n].T,
425 ax.plt = ax.pcolormesh(x, y, z[n].T,
390 vmin=self.zmin,
426 vmin=self.zmin,
391 vmax=self.zmax,
427 vmax=self.zmax,
392 cmap=plt.get_cmap(self.colormap)
428 cmap=plt.get_cmap(self.colormap)
393 )
429 )
394
430
395 if self.showprofile:
431 if self.showprofile:
396 ax.plt_profile= self.pf_axes[n].plot(self.data['rti'][n][-1], y)[0]
432 ax.plt_profile= self.pf_axes[n].plot(self.data['rti'][n][-1], y)[0]
397 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
433 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
398 color="k", linestyle="dashed", lw=1)[0]
434 color="k", linestyle="dashed", lw=1)[0]
399 if self.CODE == 'spc_mean':
435 if self.CODE == 'spc_mean':
400 ax.plt_mean = ax.plot(mean, y, color='k')[0]
436 ax.plt_mean = ax.plot(mean, y, color='k')[0]
401 else:
437 else:
402 ax.plt.set_array(z[n].T.ravel())
438 ax.plt.set_array(z[n].T.ravel())
403 if self.showprofile:
439 if self.showprofile:
404 ax.plt_profile.set_data(self.data['rti'][n][-1], y)
440 ax.plt_profile.set_data(self.data['rti'][n][-1], y)
405 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
441 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
406 if self.CODE == 'spc_mean':
442 if self.CODE == 'spc_mean':
407 ax.plt_mean.set_data(mean, y)
443 ax.plt_mean.set_data(mean, y)
408
444
409 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
445 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
410 self.saveTime = self.max_time
446 self.saveTime = self.max_time
411
447
412
448
413 class PlotCrossSpectraData(PlotData):
449 class PlotCrossSpectraData(PlotData):
414
450
415 CODE = 'cspc'
451 CODE = 'cspc'
416 zmin_coh = None
452 zmin_coh = None
417 zmax_coh = None
453 zmax_coh = None
418 zmin_phase = None
454 zmin_phase = None
419 zmax_phase = None
455 zmax_phase = None
420
456
421 def setup(self):
457 def setup(self):
422
458
423 self.ncols = 4
459 self.ncols = 4
424 self.nrows = len(self.data.pairs)
460 self.nrows = len(self.data.pairs)
425 self.nplots = self.nrows*4
461 self.nplots = self.nrows*4
426 self.width = 3.4*self.ncols
462 self.width = 3.4*self.ncols
427 self.height = 3*self.nrows
463 self.height = 3*self.nrows
428 self.ylabel = 'Range [Km]'
464 self.ylabel = 'Range [Km]'
429 self.showprofile = False
465 self.showprofile = False
430
466
431 def plot(self):
467 def plot(self):
432
468
433 if self.xaxis == "frequency":
469 if self.xaxis == "frequency":
434 x = self.data.xrange[0]
470 x = self.data.xrange[0]
435 self.xlabel = "Frequency (kHz)"
471 self.xlabel = "Frequency (kHz)"
436 elif self.xaxis == "time":
472 elif self.xaxis == "time":
437 x = self.data.xrange[1]
473 x = self.data.xrange[1]
438 self.xlabel = "Time (ms)"
474 self.xlabel = "Time (ms)"
439 else:
475 else:
440 x = self.data.xrange[2]
476 x = self.data.xrange[2]
441 self.xlabel = "Velocity (m/s)"
477 self.xlabel = "Velocity (m/s)"
442
478
443 self.titles = []
479 self.titles = []
444
480
445 y = self.data.heights
481 y = self.data.heights
446 self.y = y
482 self.y = y
447 spc = self.data['spc']
483 spc = self.data['spc']
448 cspc = self.data['cspc']
484 cspc = self.data['cspc']
449
485
450 for n in range(self.nrows):
486 for n in range(self.nrows):
451 noise = self.data['noise'][n][-1]
487 noise = self.data['noise'][n][-1]
452 pair = self.data.pairs[n]
488 pair = self.data.pairs[n]
453 ax = self.axes[4*n]
489 ax = self.axes[4*n]
454 ax3 = self.axes[4*n+3]
490 ax3 = self.axes[4*n+3]
455 if ax.firsttime:
491 if ax.firsttime:
456 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
492 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
457 self.xmin = self.xmin if self.xmin else -self.xmax
493 self.xmin = self.xmin if self.xmin else -self.xmax
458 self.zmin = self.zmin if self.zmin else numpy.nanmin(spc)
494 self.zmin = self.zmin if self.zmin else numpy.nanmin(spc)
459 self.zmax = self.zmax if self.zmax else numpy.nanmax(spc)
495 self.zmax = self.zmax if self.zmax else numpy.nanmax(spc)
460 ax.plt = ax.pcolormesh(x, y, spc[pair[0]].T,
496 ax.plt = ax.pcolormesh(x, y, spc[pair[0]].T,
461 vmin=self.zmin,
497 vmin=self.zmin,
462 vmax=self.zmax,
498 vmax=self.zmax,
463 cmap=plt.get_cmap(self.colormap)
499 cmap=plt.get_cmap(self.colormap)
464 )
500 )
465 else:
501 else:
466 ax.plt.set_array(spc[pair[0]].T.ravel())
502 ax.plt.set_array(spc[pair[0]].T.ravel())
467 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
503 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
468
504
469 ax = self.axes[4*n+1]
505 ax = self.axes[4*n+1]
470 if ax.firsttime:
506 if ax.firsttime:
471 ax.plt = ax.pcolormesh(x, y, spc[pair[1]].T,
507 ax.plt = ax.pcolormesh(x, y, spc[pair[1]].T,
472 vmin=self.zmin,
508 vmin=self.zmin,
473 vmax=self.zmax,
509 vmax=self.zmax,
474 cmap=plt.get_cmap(self.colormap)
510 cmap=plt.get_cmap(self.colormap)
475 )
511 )
476 else:
512 else:
477 ax.plt.set_array(spc[pair[1]].T.ravel())
513 ax.plt.set_array(spc[pair[1]].T.ravel())
478 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
514 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
479
515
480 out = cspc[n]/numpy.sqrt(spc[pair[0]]*spc[pair[1]])
516 out = cspc[n]/numpy.sqrt(spc[pair[0]]*spc[pair[1]])
481 coh = numpy.abs(out)
517 coh = numpy.abs(out)
482 phase = numpy.arctan2(out.imag, out.real)*180/numpy.pi
518 phase = numpy.arctan2(out.imag, out.real)*180/numpy.pi
483
519
484 ax = self.axes[4*n+2]
520 ax = self.axes[4*n+2]
485 if ax.firsttime:
521 if ax.firsttime:
486 ax.plt = ax.pcolormesh(x, y, coh.T,
522 ax.plt = ax.pcolormesh(x, y, coh.T,
487 vmin=0,
523 vmin=0,
488 vmax=1,
524 vmax=1,
489 cmap=plt.get_cmap(self.colormap_coh)
525 cmap=plt.get_cmap(self.colormap_coh)
490 )
526 )
491 else:
527 else:
492 ax.plt.set_array(coh.T.ravel())
528 ax.plt.set_array(coh.T.ravel())
493 self.titles.append('Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
529 self.titles.append('Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
494
530
495 ax = self.axes[4*n+3]
531 ax = self.axes[4*n+3]
496 if ax.firsttime:
532 if ax.firsttime:
497 ax.plt = ax.pcolormesh(x, y, phase.T,
533 ax.plt = ax.pcolormesh(x, y, phase.T,
498 vmin=-180,
534 vmin=-180,
499 vmax=180,
535 vmax=180,
500 cmap=plt.get_cmap(self.colormap_phase)
536 cmap=plt.get_cmap(self.colormap_phase)
501 )
537 )
502 else:
538 else:
503 ax.plt.set_array(phase.T.ravel())
539 ax.plt.set_array(phase.T.ravel())
504 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
540 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
505
541
506 self.saveTime = self.max_time
542 self.saveTime = self.max_time
507
543
508
544
509 class PlotSpectraMeanData(PlotSpectraData):
545 class PlotSpectraMeanData(PlotSpectraData):
510 '''
546 '''
511 Plot for Spectra and Mean
547 Plot for Spectra and Mean
512 '''
548 '''
513 CODE = 'spc_mean'
549 CODE = 'spc_mean'
514 colormap = 'jro'
550 colormap = 'jro'
515
551
516
552
517 class PlotRTIData(PlotData):
553 class PlotRTIData(PlotData):
518 '''
554 '''
519 Plot for RTI data
555 Plot for RTI data
520 '''
556 '''
521
557
522 CODE = 'rti'
558 CODE = 'rti'
523 colormap = 'jro'
559 colormap = 'jro'
524
560
525 def setup(self):
561 def setup(self):
526 self.xaxis = 'time'
562 self.xaxis = 'time'
527 self.ncols = 1
563 self.ncols = 1
528 self.nrows = len(self.data.channels)
564 self.nrows = len(self.data.channels)
529 self.nplots = len(self.data.channels)
565 self.nplots = len(self.data.channels)
530 self.ylabel = 'Range [Km]'
566 self.ylabel = 'Range [Km]'
531 self.cb_label = 'dB'
567 self.cb_label = 'dB'
532 self.titles = ['{} Channel {}'.format(self.CODE.upper(), x) for x in range(self.nrows)]
568 self.titles = ['{} Channel {}'.format(self.CODE.upper(), x) for x in range(self.nrows)]
533
569
534 def plot(self):
570 def plot(self):
535 self.x = self.data.times
571 self.x = self.times
536 self.y = self.data.heights
572 self.y = self.data.heights
537 self.z = self.data[self.CODE]
573 self.z = self.data[self.CODE]
538 self.z = numpy.ma.masked_invalid(self.z)
574 self.z = numpy.ma.masked_invalid(self.z)
539
575
540 for n, ax in enumerate(self.axes):
576 for n, ax in enumerate(self.axes):
541 x, y, z = self.fill_gaps(*self.decimate())
577 x, y, z = self.fill_gaps(*self.decimate())
542 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
578 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
543 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
579 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
544 if ax.firsttime:
580 if ax.firsttime:
545 ax.plt = ax.pcolormesh(x, y, z[n].T,
581 ax.plt = ax.pcolormesh(x, y, z[n].T,
546 vmin=self.zmin,
582 vmin=self.zmin,
547 vmax=self.zmax,
583 vmax=self.zmax,
548 cmap=plt.get_cmap(self.colormap)
584 cmap=plt.get_cmap(self.colormap)
549 )
585 )
550 if self.showprofile:
586 if self.showprofile:
551 ax.plot_profile= self.pf_axes[n].plot(self.data['rti'][n][-1], self.y)[0]
587 ax.plot_profile= self.pf_axes[n].plot(self.data['rti'][n][-1], self.y)[0]
552 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y,
588 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y,
553 color="k", linestyle="dashed", lw=1)[0]
589 color="k", linestyle="dashed", lw=1)[0]
554 else:
590 else:
555 ax.collections.remove(ax.collections[0])
591 ax.collections.remove(ax.collections[0])
556 ax.plt = ax.pcolormesh(x, y, z[n].T,
592 ax.plt = ax.pcolormesh(x, y, z[n].T,
557 vmin=self.zmin,
593 vmin=self.zmin,
558 vmax=self.zmax,
594 vmax=self.zmax,
559 cmap=plt.get_cmap(self.colormap)
595 cmap=plt.get_cmap(self.colormap)
560 )
596 )
561 if self.showprofile:
597 if self.showprofile:
562 ax.plot_profile.set_data(self.data['rti'][n][-1], self.y)
598 ax.plot_profile.set_data(self.data['rti'][n][-1], self.y)
563 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y)
599 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y)
564
600
565 self.saveTime = self.min_time
601 self.saveTime = self.min_time
566
602
567
603
568 class PlotCOHData(PlotRTIData):
604 class PlotCOHData(PlotRTIData):
569 '''
605 '''
570 Plot for Coherence data
606 Plot for Coherence data
571 '''
607 '''
572
608
573 CODE = 'coh'
609 CODE = 'coh'
574
610
575 def setup(self):
611 def setup(self):
576 self.xaxis = 'time'
612 self.xaxis = 'time'
577 self.ncols = 1
613 self.ncols = 1
578 self.nrows = len(self.data.pairs)
614 self.nrows = len(self.data.pairs)
579 self.nplots = len(self.data.pairs)
615 self.nplots = len(self.data.pairs)
580 self.ylabel = 'Range [Km]'
616 self.ylabel = 'Range [Km]'
581 if self.CODE == 'coh':
617 if self.CODE == 'coh':
582 self.cb_label = ''
618 self.cb_label = ''
583 self.titles = ['Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
619 self.titles = ['Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
584 else:
620 else:
585 self.cb_label = 'Degrees'
621 self.cb_label = 'Degrees'
586 self.titles = ['Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
622 self.titles = ['Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
587
623
588
624
589 class PlotPHASEData(PlotCOHData):
625 class PlotPHASEData(PlotCOHData):
590 '''
626 '''
591 Plot for Phase map data
627 Plot for Phase map data
592 '''
628 '''
593
629
594 CODE = 'phase'
630 CODE = 'phase'
595 colormap = 'seismic'
631 colormap = 'seismic'
596
632
597
633
598 class PlotNoiseData(PlotData):
634 class PlotNoiseData(PlotData):
599 '''
635 '''
600 Plot for noise
636 Plot for noise
601 '''
637 '''
602
638
603 CODE = 'noise'
639 CODE = 'noise'
604
640
605 def setup(self):
641 def setup(self):
606 self.xaxis = 'time'
642 self.xaxis = 'time'
607 self.ncols = 1
643 self.ncols = 1
608 self.nrows = 1
644 self.nrows = 1
609 self.nplots = 1
645 self.nplots = 1
610 self.ylabel = 'Intensity [dB]'
646 self.ylabel = 'Intensity [dB]'
611 self.titles = ['Noise']
647 self.titles = ['Noise']
612 self.colorbar = False
648 self.colorbar = False
613
649
614 def plot(self):
650 def plot(self):
615
651
616 x = self.data.times
652 x = self.times
617 xmin = self.min_time
653 xmin = self.min_time
618 xmax = xmin+self.xrange*60*60
654 xmax = xmin+self.xrange*60*60
619 Y = self.data[self.CODE]
655 Y = self.data[self.CODE]
620
656
621 if self.axes[0].firsttime:
657 if self.axes[0].firsttime:
622 for ch in self.data.channels:
658 for ch in self.data.channels:
623 y = Y[ch]
659 y = Y[ch]
624 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
660 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
625 plt.legend()
661 plt.legend()
626 else:
662 else:
627 for ch in self.data.channels:
663 for ch in self.data.channels:
628 y = Y[ch]
664 y = Y[ch]
629 self.axes[0].lines[ch].set_data(x, y)
665 self.axes[0].lines[ch].set_data(x, y)
630
666
631 self.ymin = numpy.nanmin(Y) - 5
667 self.ymin = numpy.nanmin(Y) - 5
632 self.ymax = numpy.nanmax(Y) + 5
668 self.ymax = numpy.nanmax(Y) + 5
633 self.saveTime = self.min_time
669 self.saveTime = self.min_time
634
670
635
671
636 class PlotSNRData(PlotRTIData):
672 class PlotSNRData(PlotRTIData):
637 '''
673 '''
638 Plot for SNR Data
674 Plot for SNR Data
639 '''
675 '''
640
676
641 CODE = 'snr'
677 CODE = 'snr'
642 colormap = 'jet'
678 colormap = 'jet'
643
679
644
680
645 class PlotDOPData(PlotRTIData):
681 class PlotDOPData(PlotRTIData):
646 '''
682 '''
647 Plot for DOPPLER Data
683 Plot for DOPPLER Data
648 '''
684 '''
649
685
650 CODE = 'dop'
686 CODE = 'dop'
651 colormap = 'jet'
687 colormap = 'jet'
652
688
653
689
654 class PlotSkyMapData(PlotData):
690 class PlotSkyMapData(PlotData):
655 '''
691 '''
656 Plot for meteors detection data
692 Plot for meteors detection data
657 '''
693 '''
658
694
659 CODE = 'met'
695 CODE = 'met'
660
696
661 def setup(self):
697 def setup(self):
662
698
663 self.ncols = 1
699 self.ncols = 1
664 self.nrows = 1
700 self.nrows = 1
665 self.width = 7.2
701 self.width = 7.2
666 self.height = 7.2
702 self.height = 7.2
667
703
668 self.xlabel = 'Zonal Zenith Angle (deg)'
704 self.xlabel = 'Zonal Zenith Angle (deg)'
669 self.ylabel = 'Meridional Zenith Angle (deg)'
705 self.ylabel = 'Meridional Zenith Angle (deg)'
670
706
671 if self.figure is None:
707 if self.figure is None:
672 self.figure = plt.figure(figsize=(self.width, self.height),
708 self.figure = plt.figure(figsize=(self.width, self.height),
673 edgecolor='k',
709 edgecolor='k',
674 facecolor='w')
710 facecolor='w')
675 else:
711 else:
676 self.figure.clf()
712 self.figure.clf()
677
713
678 self.ax = plt.subplot2grid((self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
714 self.ax = plt.subplot2grid((self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
679 self.ax.firsttime = True
715 self.ax.firsttime = True
680
716
681
717
682 def plot(self):
718 def plot(self):
683
719
684 arrayParameters = numpy.concatenate([self.data['param'][t] for t in self.data.times])
720 arrayParameters = numpy.concatenate([self.data['param'][t] for t in self.times])
685 error = arrayParameters[:,-1]
721 error = arrayParameters[:,-1]
686 indValid = numpy.where(error == 0)[0]
722 indValid = numpy.where(error == 0)[0]
687 finalMeteor = arrayParameters[indValid,:]
723 finalMeteor = arrayParameters[indValid,:]
688 finalAzimuth = finalMeteor[:,3]
724 finalAzimuth = finalMeteor[:,3]
689 finalZenith = finalMeteor[:,4]
725 finalZenith = finalMeteor[:,4]
690
726
691 x = finalAzimuth*numpy.pi/180
727 x = finalAzimuth*numpy.pi/180
692 y = finalZenith
728 y = finalZenith
693
729
694 if self.ax.firsttime:
730 if self.ax.firsttime:
695 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
731 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
696 self.ax.set_ylim(0,90)
732 self.ax.set_ylim(0,90)
697 self.ax.set_yticks(numpy.arange(0,90,20))
733 self.ax.set_yticks(numpy.arange(0,90,20))
698 self.ax.set_xlabel(self.xlabel)
734 self.ax.set_xlabel(self.xlabel)
699 self.ax.set_ylabel(self.ylabel)
735 self.ax.set_ylabel(self.ylabel)
700 self.ax.yaxis.labelpad = 40
736 self.ax.yaxis.labelpad = 40
701 self.ax.firsttime = False
737 self.ax.firsttime = False
702 else:
738 else:
703 self.ax.plot.set_data(x, y)
739 self.ax.plot.set_data(x, y)
704
740
705
741
706 dt1 = datetime.datetime.fromtimestamp(self.min_time).strftime('%y/%m/%d %H:%M:%S')
742 dt1 = datetime.datetime.fromtimestamp(self.min_time).strftime('%y/%m/%d %H:%M:%S')
707 dt2 = datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')
743 dt2 = datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')
708 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
744 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
709 dt2,
745 dt2,
710 len(x))
746 len(x))
711 self.ax.set_title(title, size=8)
747 self.ax.set_title(title, size=8)
712
748
713 self.saveTime = self.max_time
749 self.saveTime = self.max_time
714
750
715 class PlotParamData(PlotRTIData):
751 class PlotParamData(PlotRTIData):
716 '''
752 '''
717 Plot for data_param object
753 Plot for data_param object
718 '''
754 '''
719
755
720 CODE = 'param'
756 CODE = 'param'
721 colormap = 'seismic'
757 colormap = 'seismic'
722
758
723 def setup(self):
759 def setup(self):
724 self.xaxis = 'time'
760 self.xaxis = 'time'
725 self.ncols = 1
761 self.ncols = 1
726 self.nrows = self.data.shape(self.CODE)[0]
762 self.nrows = self.data.shape(self.CODE)[0]
727 self.nplots = self.nrows
763 self.nplots = self.nrows
728 if self.showSNR:
764 if self.showSNR:
729 self.nrows += 1
765 self.nrows += 1
766 self.nplots += 1
730
767
731 self.ylabel = 'Height [Km]'
768 self.ylabel = 'Height [Km]'
732 self.titles = self.data.parameters \
769 self.titles = self.data.parameters \
733 if self.data.parameters else ['Param {}'.format(x) for x in xrange(self.nrows)]
770 if self.data.parameters else ['Param {}'.format(x) for x in xrange(self.nrows)]
734 if self.showSNR:
771 if self.showSNR:
735 self.titles.append('SNR')
772 self.titles.append('SNR')
736
773
737 def plot(self):
774 def plot(self):
738 self.data.normalize_heights()
775 self.data.normalize_heights()
739 self.x = self.data.times
776 self.x = self.times
740 self.y = self.data.heights
777 self.y = self.data.heights
741 if self.showSNR:
778 if self.showSNR:
742 self.z = numpy.concatenate(
779 self.z = numpy.concatenate(
743 (self.data[self.CODE], self.data['snr'])
780 (self.data[self.CODE], self.data['snr'])
744 )
781 )
745 else:
782 else:
746 self.z = self.data[self.CODE]
783 self.z = self.data[self.CODE]
747
784
748 self.z = numpy.ma.masked_invalid(self.z)
785 self.z = numpy.ma.masked_invalid(self.z)
749
786
750 for n, ax in enumerate(self.axes):
787 for n, ax in enumerate(self.axes):
751
788
752 x, y, z = self.fill_gaps(*self.decimate())
789 x, y, z = self.fill_gaps(*self.decimate())
753
790
754 if ax.firsttime:
791 if ax.firsttime:
755 if self.zlimits is not None:
792 if self.zlimits is not None:
756 self.zmin, self.zmax = self.zlimits[n]
793 self.zmin, self.zmax = self.zlimits[n]
757 self.zmax = self.zmax if self.zmax is not None else numpy.nanmax(abs(self.z[:-1, :]))
794 self.zmax = self.zmax if self.zmax is not None else numpy.nanmax(abs(self.z[:-1, :]))
758 self.zmin = self.zmin if self.zmin is not None else -self.zmax
795 self.zmin = self.zmin if self.zmin is not None else -self.zmax
759 ax.plt = ax.pcolormesh(x, y, z[n, :, :].T*self.factors[n],
796 ax.plt = ax.pcolormesh(x, y, z[n, :, :].T*self.factors[n],
760 vmin=self.zmin,
797 vmin=self.zmin,
761 vmax=self.zmax,
798 vmax=self.zmax,
762 cmap=self.cmaps[n]
799 cmap=self.cmaps[n]
763 )
800 )
764 else:
801 else:
765 if self.zlimits is not None:
802 if self.zlimits is not None:
766 self.zmin, self.zmax = self.zlimits[n]
803 self.zmin, self.zmax = self.zlimits[n]
767 ax.collections.remove(ax.collections[0])
804 ax.collections.remove(ax.collections[0])
768 ax.plt = ax.pcolormesh(x, y, z[n, :, :].T*self.factors[n],
805 ax.plt = ax.pcolormesh(x, y, z[n, :, :].T*self.factors[n],
769 vmin=self.zmin,
806 vmin=self.zmin,
770 vmax=self.zmax,
807 vmax=self.zmax,
771 cmap=self.cmaps[n]
808 cmap=self.cmaps[n]
772 )
809 )
773
810
774 self.saveTime = self.min_time
811 self.saveTime = self.min_time
775
812
776 class PlotOuputData(PlotParamData):
813 class PlotOuputData(PlotParamData):
777 '''
814 '''
778 Plot data_output object
815 Plot data_output object
779 '''
816 '''
780
817
781 CODE = 'output'
818 CODE = 'output'
782 colormap = 'seismic' No newline at end of file
819 colormap = 'seismic'
@@ -1,1945 +1,2151
1 import os
1 import os
2 import datetime
2 import datetime
3 import numpy
3 import numpy
4 import inspect
4 import inspect
5 from figure import Figure, isRealtime, isTimeInHourRange
5 from figure import Figure, isRealtime, isTimeInHourRange
6 from plotting_codes import *
6 from plotting_codes import *
7
7
8
8
9 class FitGauPlot(Figure):
10
11 isConfig = None
12 __nsubplots = None
13
14 WIDTHPROF = None
15 HEIGHTPROF = None
16 PREFIX = 'fitgau'
17
18 def __init__(self, **kwargs):
19 Figure.__init__(self, **kwargs)
20 self.isConfig = False
21 self.__nsubplots = 1
22
23 self.WIDTH = 250
24 self.HEIGHT = 250
25 self.WIDTHPROF = 120
26 self.HEIGHTPROF = 0
27 self.counter_imagwr = 0
28
29 self.PLOT_CODE = SPEC_CODE
30
31 self.FTP_WEI = None
32 self.EXP_CODE = None
33 self.SUB_EXP_CODE = None
34 self.PLOT_POS = None
35
36 self.__xfilter_ena = False
37 self.__yfilter_ena = False
38
39 def getSubplots(self):
40
41 ncol = int(numpy.sqrt(self.nplots)+0.9)
42 nrow = int(self.nplots*1./ncol + 0.9)
43
44 return nrow, ncol
45
46 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
47
48 self.__showprofile = showprofile
49 self.nplots = nplots
50
51 ncolspan = 1
52 colspan = 1
53 if showprofile:
54 ncolspan = 3
55 colspan = 2
56 self.__nsubplots = 2
57
58 self.createFigure(id = id,
59 wintitle = wintitle,
60 widthplot = self.WIDTH + self.WIDTHPROF,
61 heightplot = self.HEIGHT + self.HEIGHTPROF,
62 show=show)
63
64 nrow, ncol = self.getSubplots()
65
66 counter = 0
67 for y in range(nrow):
68 for x in range(ncol):
69
70 if counter >= self.nplots:
71 break
72
73 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
74
75 if showprofile:
76 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
77
78 counter += 1
79
80 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
81 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
82 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
83 server=None, folder=None, username=None, password=None,
84 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
85 xaxis="frequency", colormap='jet', normFactor=None , GauSelector = 1):
86
87 """
88
89 Input:
90 dataOut :
91 id :
92 wintitle :
93 channelList :
94 showProfile :
95 xmin : None,
96 xmax : None,
97 ymin : None,
98 ymax : None,
99 zmin : None,
100 zmax : None
101 """
102 if realtime:
103 if not(isRealtime(utcdatatime = dataOut.utctime)):
104 print 'Skipping this plot function'
105 return
106
107 if channelList == None:
108 channelIndexList = dataOut.channelIndexList
109 else:
110 channelIndexList = []
111 for channel in channelList:
112 if channel not in dataOut.channelList:
113 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
114 channelIndexList.append(dataOut.channelList.index(channel))
115
116 # if normFactor is None:
117 # factor = dataOut.normFactor
118 # else:
119 # factor = normFactor
120 if xaxis == "frequency":
121 x = dataOut.spc_range[0]
122 xlabel = "Frequency (kHz)"
123
124 elif xaxis == "time":
125 x = dataOut.spc_range[1]
126 xlabel = "Time (ms)"
127
128 else:
129 x = dataOut.spc_range[2]
130 xlabel = "Velocity (m/s)"
131
132 ylabel = "Range (Km)"
133
134 y = dataOut.getHeiRange()
135
136 z = dataOut.GauSPC[:,GauSelector,:,:] #GauSelector] #dataOut.data_spc/factor
137 print 'GausSPC', z[0,32,10:40]
138 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
139 zdB = 10*numpy.log10(z)
140
141 avg = numpy.average(z, axis=1)
142 avgdB = 10*numpy.log10(avg)
143
144 noise = dataOut.spc_noise
145 noisedB = 10*numpy.log10(noise)
146
147 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
148 title = wintitle + " Spectra"
149 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
150 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
151
152 if not self.isConfig:
153
154 nplots = len(channelIndexList)
155
156 self.setup(id=id,
157 nplots=nplots,
158 wintitle=wintitle,
159 showprofile=showprofile,
160 show=show)
161
162 if xmin == None: xmin = numpy.nanmin(x)
163 if xmax == None: xmax = numpy.nanmax(x)
164 if ymin == None: ymin = numpy.nanmin(y)
165 if ymax == None: ymax = numpy.nanmax(y)
166 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
167 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
168
169 self.FTP_WEI = ftp_wei
170 self.EXP_CODE = exp_code
171 self.SUB_EXP_CODE = sub_exp_code
172 self.PLOT_POS = plot_pos
173
174 self.isConfig = True
175
176 self.setWinTitle(title)
177
178 for i in range(self.nplots):
179 index = channelIndexList[i]
180 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
181 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
182 if len(dataOut.beam.codeList) != 0:
183 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
184
185 axes = self.axesList[i*self.__nsubplots]
186 axes.pcolor(x, y, zdB[index,:,:],
187 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
188 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
189 ticksize=9, cblabel='')
190
191 if self.__showprofile:
192 axes = self.axesList[i*self.__nsubplots +1]
193 axes.pline(avgdB[index,:], y,
194 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
195 xlabel='dB', ylabel='', title='',
196 ytick_visible=False,
197 grid='x')
198
199 noiseline = numpy.repeat(noisedB[index], len(y))
200 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
201
202 self.draw()
203
204 if figfile == None:
205 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
206 name = str_datetime
207 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
208 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
209 figfile = self.getFilename(name)
210
211 self.save(figpath=figpath,
212 figfile=figfile,
213 save=save,
214 ftp=ftp,
215 wr_period=wr_period,
216 thisDatetime=thisDatetime)
217
218
219
9 class MomentsPlot(Figure):
220 class MomentsPlot(Figure):
10
221
11 isConfig = None
222 isConfig = None
12 __nsubplots = None
223 __nsubplots = None
13
224
14 WIDTHPROF = None
225 WIDTHPROF = None
15 HEIGHTPROF = None
226 HEIGHTPROF = None
16 PREFIX = 'prm'
227 PREFIX = 'prm'
17 def __init__(self, **kwargs):
228 def __init__(self, **kwargs):
18 Figure.__init__(self, **kwargs)
229 Figure.__init__(self, **kwargs)
19 self.isConfig = False
230 self.isConfig = False
20 self.__nsubplots = 1
231 self.__nsubplots = 1
21
232
22 self.WIDTH = 280
233 self.WIDTH = 280
23 self.HEIGHT = 250
234 self.HEIGHT = 250
24 self.WIDTHPROF = 120
235 self.WIDTHPROF = 120
25 self.HEIGHTPROF = 0
236 self.HEIGHTPROF = 0
26 self.counter_imagwr = 0
237 self.counter_imagwr = 0
27
238
28 self.PLOT_CODE = MOMENTS_CODE
239 self.PLOT_CODE = MOMENTS_CODE
29
240
30 self.FTP_WEI = None
241 self.FTP_WEI = None
31 self.EXP_CODE = None
242 self.EXP_CODE = None
32 self.SUB_EXP_CODE = None
243 self.SUB_EXP_CODE = None
33 self.PLOT_POS = None
244 self.PLOT_POS = None
34
245
35 def getSubplots(self):
246 def getSubplots(self):
36
247
37 ncol = int(numpy.sqrt(self.nplots)+0.9)
248 ncol = int(numpy.sqrt(self.nplots)+0.9)
38 nrow = int(self.nplots*1./ncol + 0.9)
249 nrow = int(self.nplots*1./ncol + 0.9)
39
250
40 return nrow, ncol
251 return nrow, ncol
41
252
42 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
253 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
43
254
44 self.__showprofile = showprofile
255 self.__showprofile = showprofile
45 self.nplots = nplots
256 self.nplots = nplots
46
257
47 ncolspan = 1
258 ncolspan = 1
48 colspan = 1
259 colspan = 1
49 if showprofile:
260 if showprofile:
50 ncolspan = 3
261 ncolspan = 3
51 colspan = 2
262 colspan = 2
52 self.__nsubplots = 2
263 self.__nsubplots = 2
53
264
54 self.createFigure(id = id,
265 self.createFigure(id = id,
55 wintitle = wintitle,
266 wintitle = wintitle,
56 widthplot = self.WIDTH + self.WIDTHPROF,
267 widthplot = self.WIDTH + self.WIDTHPROF,
57 heightplot = self.HEIGHT + self.HEIGHTPROF,
268 heightplot = self.HEIGHT + self.HEIGHTPROF,
58 show=show)
269 show=show)
59
270
60 nrow, ncol = self.getSubplots()
271 nrow, ncol = self.getSubplots()
61
272
62 counter = 0
273 counter = 0
63 for y in range(nrow):
274 for y in range(nrow):
64 for x in range(ncol):
275 for x in range(ncol):
65
276
66 if counter >= self.nplots:
277 if counter >= self.nplots:
67 break
278 break
68
279
69 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
280 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
70
281
71 if showprofile:
282 if showprofile:
72 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
283 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
73
284
74 counter += 1
285 counter += 1
75
286
76 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
287 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
77 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
288 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
78 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
289 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
79 server=None, folder=None, username=None, password=None,
290 server=None, folder=None, username=None, password=None,
80 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
291 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
81
292
82 """
293 """
83
294
84 Input:
295 Input:
85 dataOut :
296 dataOut :
86 id :
297 id :
87 wintitle :
298 wintitle :
88 channelList :
299 channelList :
89 showProfile :
300 showProfile :
90 xmin : None,
301 xmin : None,
91 xmax : None,
302 xmax : None,
92 ymin : None,
303 ymin : None,
93 ymax : None,
304 ymax : None,
94 zmin : None,
305 zmin : None,
95 zmax : None
306 zmax : None
96 """
307 """
97
308
98 if dataOut.flagNoData:
309 if dataOut.flagNoData:
99 return None
310 return None
100
311
101 if realtime:
312 if realtime:
102 if not(isRealtime(utcdatatime = dataOut.utctime)):
313 if not(isRealtime(utcdatatime = dataOut.utctime)):
103 print 'Skipping this plot function'
314 print 'Skipping this plot function'
104 return
315 return
105
316
106 if channelList == None:
317 if channelList == None:
107 channelIndexList = dataOut.channelIndexList
318 channelIndexList = dataOut.channelIndexList
108 else:
319 else:
109 channelIndexList = []
320 channelIndexList = []
110 for channel in channelList:
321 for channel in channelList:
111 if channel not in dataOut.channelList:
322 if channel not in dataOut.channelList:
112 raise ValueError, "Channel %d is not in dataOut.channelList"
323 raise ValueError, "Channel %d is not in dataOut.channelList"
113 channelIndexList.append(dataOut.channelList.index(channel))
324 channelIndexList.append(dataOut.channelList.index(channel))
114
325
115 factor = dataOut.normFactor
326 factor = dataOut.normFactor
116 x = dataOut.abscissaList
327 x = dataOut.abscissaList
117 y = dataOut.heightList
328 y = dataOut.heightList
118
329
119 z = dataOut.data_pre[channelIndexList,:,:]/factor
330 z = dataOut.data_pre[channelIndexList,:,:]/factor
120 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
331 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
121 avg = numpy.average(z, axis=1)
332 avg = numpy.average(z, axis=1)
122 noise = dataOut.noise/factor
333 noise = dataOut.noise/factor
123
334
124 zdB = 10*numpy.log10(z)
335 zdB = 10*numpy.log10(z)
125 avgdB = 10*numpy.log10(avg)
336 avgdB = 10*numpy.log10(avg)
126 noisedB = 10*numpy.log10(noise)
337 noisedB = 10*numpy.log10(noise)
127
338
128 #thisDatetime = dataOut.datatime
339 #thisDatetime = dataOut.datatime
129 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
340 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
130 title = wintitle + " Parameters"
341 title = wintitle + " Parameters"
131 xlabel = "Velocity (m/s)"
342 xlabel = "Velocity (m/s)"
132 ylabel = "Range (Km)"
343 ylabel = "Range (Km)"
133
344
134 update_figfile = False
345 update_figfile = False
135
346
136 if not self.isConfig:
347 if not self.isConfig:
137
348
138 nplots = len(channelIndexList)
349 nplots = len(channelIndexList)
139
350
140 self.setup(id=id,
351 self.setup(id=id,
141 nplots=nplots,
352 nplots=nplots,
142 wintitle=wintitle,
353 wintitle=wintitle,
143 showprofile=showprofile,
354 showprofile=showprofile,
144 show=show)
355 show=show)
145
356
146 if xmin == None: xmin = numpy.nanmin(x)
357 if xmin == None: xmin = numpy.nanmin(x)
147 if xmax == None: xmax = numpy.nanmax(x)
358 if xmax == None: xmax = numpy.nanmax(x)
148 if ymin == None: ymin = numpy.nanmin(y)
359 if ymin == None: ymin = numpy.nanmin(y)
149 if ymax == None: ymax = numpy.nanmax(y)
360 if ymax == None: ymax = numpy.nanmax(y)
150 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
361 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
151 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
362 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
152
363
153 self.FTP_WEI = ftp_wei
364 self.FTP_WEI = ftp_wei
154 self.EXP_CODE = exp_code
365 self.EXP_CODE = exp_code
155 self.SUB_EXP_CODE = sub_exp_code
366 self.SUB_EXP_CODE = sub_exp_code
156 self.PLOT_POS = plot_pos
367 self.PLOT_POS = plot_pos
157
368
158 self.isConfig = True
369 self.isConfig = True
159 update_figfile = True
370 update_figfile = True
160
371
161 self.setWinTitle(title)
372 self.setWinTitle(title)
162
373
163 for i in range(self.nplots):
374 for i in range(self.nplots):
164 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
375 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
165 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
376 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
166 axes = self.axesList[i*self.__nsubplots]
377 axes = self.axesList[i*self.__nsubplots]
167 axes.pcolor(x, y, zdB[i,:,:],
378 axes.pcolor(x, y, zdB[i,:,:],
168 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
379 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
169 xlabel=xlabel, ylabel=ylabel, title=title,
380 xlabel=xlabel, ylabel=ylabel, title=title,
170 ticksize=9, cblabel='')
381 ticksize=9, cblabel='')
171 #Mean Line
382 #Mean Line
172 mean = dataOut.data_param[i, 1, :]
383 mean = dataOut.data_param[i, 1, :]
173 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
384 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
174
385
175 if self.__showprofile:
386 if self.__showprofile:
176 axes = self.axesList[i*self.__nsubplots +1]
387 axes = self.axesList[i*self.__nsubplots +1]
177 axes.pline(avgdB[i], y,
388 axes.pline(avgdB[i], y,
178 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
389 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
179 xlabel='dB', ylabel='', title='',
390 xlabel='dB', ylabel='', title='',
180 ytick_visible=False,
391 ytick_visible=False,
181 grid='x')
392 grid='x')
182
393
183 noiseline = numpy.repeat(noisedB[i], len(y))
394 noiseline = numpy.repeat(noisedB[i], len(y))
184 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
395 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
185
396
186 self.draw()
397 self.draw()
187
398
188 self.save(figpath=figpath,
399 self.save(figpath=figpath,
189 figfile=figfile,
400 figfile=figfile,
190 save=save,
401 save=save,
191 ftp=ftp,
402 ftp=ftp,
192 wr_period=wr_period,
403 wr_period=wr_period,
193 thisDatetime=thisDatetime)
404 thisDatetime=thisDatetime)
194
405
195
406
196
407
197 class SkyMapPlot(Figure):
408 class SkyMapPlot(Figure):
198
409
199 __isConfig = None
410 __isConfig = None
200 __nsubplots = None
411 __nsubplots = None
201
412
202 WIDTHPROF = None
413 WIDTHPROF = None
203 HEIGHTPROF = None
414 HEIGHTPROF = None
204 PREFIX = 'mmap'
415 PREFIX = 'mmap'
205
416
206 def __init__(self, **kwargs):
417 def __init__(self, **kwargs):
207 Figure.__init__(self, **kwargs)
418 Figure.__init__(self, **kwargs)
208 self.isConfig = False
419 self.isConfig = False
209 self.__nsubplots = 1
420 self.__nsubplots = 1
210
421
211 # self.WIDTH = 280
422 # self.WIDTH = 280
212 # self.HEIGHT = 250
423 # self.HEIGHT = 250
213 self.WIDTH = 600
424 self.WIDTH = 600
214 self.HEIGHT = 600
425 self.HEIGHT = 600
215 self.WIDTHPROF = 120
426 self.WIDTHPROF = 120
216 self.HEIGHTPROF = 0
427 self.HEIGHTPROF = 0
217 self.counter_imagwr = 0
428 self.counter_imagwr = 0
218
429
219 self.PLOT_CODE = MSKYMAP_CODE
430 self.PLOT_CODE = MSKYMAP_CODE
220
431
221 self.FTP_WEI = None
432 self.FTP_WEI = None
222 self.EXP_CODE = None
433 self.EXP_CODE = None
223 self.SUB_EXP_CODE = None
434 self.SUB_EXP_CODE = None
224 self.PLOT_POS = None
435 self.PLOT_POS = None
225
436
226 def getSubplots(self):
437 def getSubplots(self):
227
438
228 ncol = int(numpy.sqrt(self.nplots)+0.9)
439 ncol = int(numpy.sqrt(self.nplots)+0.9)
229 nrow = int(self.nplots*1./ncol + 0.9)
440 nrow = int(self.nplots*1./ncol + 0.9)
230
441
231 return nrow, ncol
442 return nrow, ncol
232
443
233 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
444 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
234
445
235 self.__showprofile = showprofile
446 self.__showprofile = showprofile
236 self.nplots = nplots
447 self.nplots = nplots
237
448
238 ncolspan = 1
449 ncolspan = 1
239 colspan = 1
450 colspan = 1
240
451
241 self.createFigure(id = id,
452 self.createFigure(id = id,
242 wintitle = wintitle,
453 wintitle = wintitle,
243 widthplot = self.WIDTH, #+ self.WIDTHPROF,
454 widthplot = self.WIDTH, #+ self.WIDTHPROF,
244 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
455 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
245 show=show)
456 show=show)
246
457
247 nrow, ncol = 1,1
458 nrow, ncol = 1,1
248 counter = 0
459 counter = 0
249 x = 0
460 x = 0
250 y = 0
461 y = 0
251 self.addAxes(1, 1, 0, 0, 1, 1, True)
462 self.addAxes(1, 1, 0, 0, 1, 1, True)
252
463
253 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
464 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
254 tmin=0, tmax=24, timerange=None,
465 tmin=0, tmax=24, timerange=None,
255 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
466 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
256 server=None, folder=None, username=None, password=None,
467 server=None, folder=None, username=None, password=None,
257 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
468 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
258
469
259 """
470 """
260
471
261 Input:
472 Input:
262 dataOut :
473 dataOut :
263 id :
474 id :
264 wintitle :
475 wintitle :
265 channelList :
476 channelList :
266 showProfile :
477 showProfile :
267 xmin : None,
478 xmin : None,
268 xmax : None,
479 xmax : None,
269 ymin : None,
480 ymin : None,
270 ymax : None,
481 ymax : None,
271 zmin : None,
482 zmin : None,
272 zmax : None
483 zmax : None
273 """
484 """
274
485
275 arrayParameters = dataOut.data_param
486 arrayParameters = dataOut.data_param
276 error = arrayParameters[:,-1]
487 error = arrayParameters[:,-1]
277 indValid = numpy.where(error == 0)[0]
488 indValid = numpy.where(error == 0)[0]
278 finalMeteor = arrayParameters[indValid,:]
489 finalMeteor = arrayParameters[indValid,:]
279 finalAzimuth = finalMeteor[:,3]
490 finalAzimuth = finalMeteor[:,3]
280 finalZenith = finalMeteor[:,4]
491 finalZenith = finalMeteor[:,4]
281
492
282 x = finalAzimuth*numpy.pi/180
493 x = finalAzimuth*numpy.pi/180
283 y = finalZenith
494 y = finalZenith
284 x1 = [dataOut.ltctime, dataOut.ltctime]
495 x1 = [dataOut.ltctime, dataOut.ltctime]
285
496
286 #thisDatetime = dataOut.datatime
497 #thisDatetime = dataOut.datatime
287 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
498 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
288 title = wintitle + " Parameters"
499 title = wintitle + " Parameters"
289 xlabel = "Zonal Zenith Angle (deg) "
500 xlabel = "Zonal Zenith Angle (deg) "
290 ylabel = "Meridional Zenith Angle (deg)"
501 ylabel = "Meridional Zenith Angle (deg)"
291 update_figfile = False
502 update_figfile = False
292
503
293 if not self.isConfig:
504 if not self.isConfig:
294
505
295 nplots = 1
506 nplots = 1
296
507
297 self.setup(id=id,
508 self.setup(id=id,
298 nplots=nplots,
509 nplots=nplots,
299 wintitle=wintitle,
510 wintitle=wintitle,
300 showprofile=showprofile,
511 showprofile=showprofile,
301 show=show)
512 show=show)
302
513
303 if self.xmin is None and self.xmax is None:
514 if self.xmin is None and self.xmax is None:
304 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
515 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
305
516
306 if timerange != None:
517 if timerange != None:
307 self.timerange = timerange
518 self.timerange = timerange
308 else:
519 else:
309 self.timerange = self.xmax - self.xmin
520 self.timerange = self.xmax - self.xmin
310
521
311 self.FTP_WEI = ftp_wei
522 self.FTP_WEI = ftp_wei
312 self.EXP_CODE = exp_code
523 self.EXP_CODE = exp_code
313 self.SUB_EXP_CODE = sub_exp_code
524 self.SUB_EXP_CODE = sub_exp_code
314 self.PLOT_POS = plot_pos
525 self.PLOT_POS = plot_pos
315 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
526 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
316 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
527 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
317 self.isConfig = True
528 self.isConfig = True
318 update_figfile = True
529 update_figfile = True
319
530
320 self.setWinTitle(title)
531 self.setWinTitle(title)
321
532
322 i = 0
533 i = 0
323 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
534 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
324
535
325 axes = self.axesList[i*self.__nsubplots]
536 axes = self.axesList[i*self.__nsubplots]
326 nevents = axes.x_buffer.shape[0] + x.shape[0]
537 nevents = axes.x_buffer.shape[0] + x.shape[0]
327 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
538 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
328 axes.polar(x, y,
539 axes.polar(x, y,
329 title=title, xlabel=xlabel, ylabel=ylabel,
540 title=title, xlabel=xlabel, ylabel=ylabel,
330 ticksize=9, cblabel='')
541 ticksize=9, cblabel='')
331
542
332 self.draw()
543 self.draw()
333
544
334 self.save(figpath=figpath,
545 self.save(figpath=figpath,
335 figfile=figfile,
546 figfile=figfile,
336 save=save,
547 save=save,
337 ftp=ftp,
548 ftp=ftp,
338 wr_period=wr_period,
549 wr_period=wr_period,
339 thisDatetime=thisDatetime,
550 thisDatetime=thisDatetime,
340 update_figfile=update_figfile)
551 update_figfile=update_figfile)
341
552
342 if dataOut.ltctime >= self.xmax:
553 if dataOut.ltctime >= self.xmax:
343 self.isConfigmagwr = wr_period
554 self.isConfigmagwr = wr_period
344 self.isConfig = False
555 self.isConfig = False
345 update_figfile = True
556 update_figfile = True
346 axes.__firsttime = True
557 axes.__firsttime = True
347 self.xmin += self.timerange
558 self.xmin += self.timerange
348 self.xmax += self.timerange
559 self.xmax += self.timerange
349
560
350
561
351
562
352
563
353 class WindProfilerPlot(Figure):
564 class WindProfilerPlot(Figure):
354
565
355 __isConfig = None
566 __isConfig = None
356 __nsubplots = None
567 __nsubplots = None
357
568
358 WIDTHPROF = None
569 WIDTHPROF = None
359 HEIGHTPROF = None
570 HEIGHTPROF = None
360 PREFIX = 'wind'
571 PREFIX = 'wind'
361
572
362 def __init__(self, **kwargs):
573 def __init__(self, **kwargs):
363 Figure.__init__(self, **kwargs)
574 Figure.__init__(self, **kwargs)
364 self.timerange = None
575 self.timerange = None
365 self.isConfig = False
576 self.isConfig = False
366 self.__nsubplots = 1
577 self.__nsubplots = 1
367
578
368 self.WIDTH = 800
579 self.WIDTH = 800
369 self.HEIGHT = 300
580 self.HEIGHT = 300
370 self.WIDTHPROF = 120
581 self.WIDTHPROF = 120
371 self.HEIGHTPROF = 0
582 self.HEIGHTPROF = 0
372 self.counter_imagwr = 0
583 self.counter_imagwr = 0
373
584
374 self.PLOT_CODE = WIND_CODE
585 self.PLOT_CODE = WIND_CODE
375
586
376 self.FTP_WEI = None
587 self.FTP_WEI = None
377 self.EXP_CODE = None
588 self.EXP_CODE = None
378 self.SUB_EXP_CODE = None
589 self.SUB_EXP_CODE = None
379 self.PLOT_POS = None
590 self.PLOT_POS = None
380 self.tmin = None
591 self.tmin = None
381 self.tmax = None
592 self.tmax = None
382
593
383 self.xmin = None
594 self.xmin = None
384 self.xmax = None
595 self.xmax = None
385
596
386 self.figfile = None
597 self.figfile = None
387
598
388 def getSubplots(self):
599 def getSubplots(self):
389
600
390 ncol = 1
601 ncol = 1
391 nrow = self.nplots
602 nrow = self.nplots
392
603
393 return nrow, ncol
604 return nrow, ncol
394
605
395 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
606 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
396
607
397 self.__showprofile = showprofile
608 self.__showprofile = showprofile
398 self.nplots = nplots
609 self.nplots = nplots
399
610
400 ncolspan = 1
611 ncolspan = 1
401 colspan = 1
612 colspan = 1
402
613
403 self.createFigure(id = id,
614 self.createFigure(id = id,
404 wintitle = wintitle,
615 wintitle = wintitle,
405 widthplot = self.WIDTH + self.WIDTHPROF,
616 widthplot = self.WIDTH + self.WIDTHPROF,
406 heightplot = self.HEIGHT + self.HEIGHTPROF,
617 heightplot = self.HEIGHT + self.HEIGHTPROF,
407 show=show)
618 show=show)
408
619
409 nrow, ncol = self.getSubplots()
620 nrow, ncol = self.getSubplots()
410
621
411 counter = 0
622 counter = 0
412 for y in range(nrow):
623 for y in range(nrow):
413 if counter >= self.nplots:
624 if counter >= self.nplots:
414 break
625 break
415
626
416 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
627 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
417 counter += 1
628 counter += 1
418
629
419 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
630 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
420 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
631 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
421 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
632 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
422 timerange=None, SNRthresh = None,
633 timerange=None, SNRthresh = None,
423 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
634 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
424 server=None, folder=None, username=None, password=None,
635 server=None, folder=None, username=None, password=None,
425 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
636 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
426 """
637 """
427
638
428 Input:
639 Input:
429 dataOut :
640 dataOut :
430 id :
641 id :
431 wintitle :
642 wintitle :
432 channelList :
643 channelList :
433 showProfile :
644 showProfile :
434 xmin : None,
645 xmin : None,
435 xmax : None,
646 xmax : None,
436 ymin : None,
647 ymin : None,
437 ymax : None,
648 ymax : None,
438 zmin : None,
649 zmin : None,
439 zmax : None
650 zmax : None
440 """
651 """
441
652
442 # if timerange is not None:
653 # if timerange is not None:
443 # self.timerange = timerange
654 # self.timerange = timerange
444 #
655 #
445 # tmin = None
656 # tmin = None
446 # tmax = None
657 # tmax = None
447
658
448
659 x = dataOut.getTimeRange1(dataOut.paramInterval)
449 x = dataOut.getTimeRange1(dataOut.outputInterval)
660 y = dataOut.heightList
450 y = dataOut.heightList
661 z = dataOut.data_output.copy()
451 z = dataOut.data_output.copy()
452 nplots = z.shape[0] #Number of wind dimensions estimated
662 nplots = z.shape[0] #Number of wind dimensions estimated
453 nplotsw = nplots
663 nplotsw = nplots
454
664
455
665
456 #If there is a SNR function defined
666 #If there is a SNR function defined
457 if dataOut.data_SNR is not None:
667 if dataOut.data_SNR is not None:
458 nplots += 1
668 nplots += 1
459 SNR = dataOut.data_SNR
669 SNR = dataOut.data_SNR
460 SNRavg = numpy.average(SNR, axis=0)
670 SNRavg = numpy.average(SNR, axis=0)
461
671
462 SNRdB = 10*numpy.log10(SNR)
672 SNRdB = 10*numpy.log10(SNR)
463 SNRavgdB = 10*numpy.log10(SNRavg)
673 SNRavgdB = 10*numpy.log10(SNRavg)
464
674
465 if SNRthresh == None: SNRthresh = -5.0
675 if SNRthresh == None: SNRthresh = -5.0
466 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
676 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
467
677
468 for i in range(nplotsw):
678 for i in range(nplotsw):
469 z[i,ind] = numpy.nan
679 z[i,ind] = numpy.nan
470
680
471 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
681 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
472 #thisDatetime = datetime.datetime.now()
682 #thisDatetime = datetime.datetime.now()
473 title = wintitle + "Wind"
683 title = wintitle + "Wind"
474 xlabel = ""
684 xlabel = ""
475 ylabel = "Height (km)"
685 ylabel = "Height (km)"
476 update_figfile = False
686 update_figfile = False
477
687
478 if not self.isConfig:
688 if not self.isConfig:
479
689
480 self.setup(id=id,
690 self.setup(id=id,
481 nplots=nplots,
691 nplots=nplots,
482 wintitle=wintitle,
692 wintitle=wintitle,
483 showprofile=showprofile,
693 showprofile=showprofile,
484 show=show)
694 show=show)
485
695
486 if timerange is not None:
696 if timerange is not None:
487 self.timerange = timerange
697 self.timerange = timerange
488
698
489 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
699 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
490
700
491 if ymin == None: ymin = numpy.nanmin(y)
701 if ymin == None: ymin = numpy.nanmin(y)
492 if ymax == None: ymax = numpy.nanmax(y)
702 if ymax == None: ymax = numpy.nanmax(y)
493
703
494 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
704 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
495 #if numpy.isnan(zmax): zmax = 50
705 #if numpy.isnan(zmax): zmax = 50
496 if zmin == None: zmin = -zmax
706 if zmin == None: zmin = -zmax
497
707
498 if nplotsw == 3:
708 if nplotsw == 3:
499 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
709 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
500 if zmin_ver == None: zmin_ver = -zmax_ver
710 if zmin_ver == None: zmin_ver = -zmax_ver
501
711
502 if dataOut.data_SNR is not None:
712 if dataOut.data_SNR is not None:
503 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
713 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
504 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
714 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
505
715
506
716
507 self.FTP_WEI = ftp_wei
717 self.FTP_WEI = ftp_wei
508 self.EXP_CODE = exp_code
718 self.EXP_CODE = exp_code
509 self.SUB_EXP_CODE = sub_exp_code
719 self.SUB_EXP_CODE = sub_exp_code
510 self.PLOT_POS = plot_pos
720 self.PLOT_POS = plot_pos
511
721
512 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
722 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
513 self.isConfig = True
723 self.isConfig = True
514 self.figfile = figfile
724 self.figfile = figfile
515 update_figfile = True
725 update_figfile = True
516
726
517 self.setWinTitle(title)
727 self.setWinTitle(title)
518
728
519 if ((self.xmax - x[1]) < (x[1]-x[0])):
729 if ((self.xmax - x[1]) < (x[1]-x[0])):
520 x[1] = self.xmax
730 x[1] = self.xmax
521
731
522 strWind = ['Zonal', 'Meridional', 'Vertical']
732 strWind = ['Zonal', 'Meridional', 'Vertical']
523 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
733 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
524 zmaxVector = [zmax, zmax, zmax_ver]
734 zmaxVector = [zmax, zmax, zmax_ver]
525 zminVector = [zmin, zmin, zmin_ver]
735 zminVector = [zmin, zmin, zmin_ver]
526 windFactor = [1,1,100]
736 windFactor = [1,1,100]
527
737
528 for i in range(nplotsw):
738 for i in range(nplotsw):
529
739
530 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
740 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
531 axes = self.axesList[i*self.__nsubplots]
741 axes = self.axesList[i*self.__nsubplots]
532
742
533 z1 = z[i,:].reshape((1,-1))*windFactor[i]
743 z1 = z[i,:].reshape((1,-1))*windFactor[i]
534 #z1=numpy.ma.masked_where(z1==0.,z1)
744 #z1=numpy.ma.masked_where(z1==0.,z1)
535
745
536 axes.pcolorbuffer(x, y, z1,
746 axes.pcolorbuffer(x, y, z1,
537 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
747 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
538 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
748 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
539 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
749 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
540
750
541 if dataOut.data_SNR is not None:
751 if dataOut.data_SNR is not None:
542 i += 1
752 i += 1
543 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
753 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
544 axes = self.axesList[i*self.__nsubplots]
754 axes = self.axesList[i*self.__nsubplots]
545 SNRavgdB = SNRavgdB.reshape((1,-1))
755 SNRavgdB = SNRavgdB.reshape((1,-1))
546 axes.pcolorbuffer(x, y, SNRavgdB,
756 axes.pcolorbuffer(x, y, SNRavgdB,
547 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
757 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
548 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
758 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
549 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
759 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
550
760
551 self.draw()
761 self.draw()
552
762
553 self.save(figpath=figpath,
763 self.save(figpath=figpath,
554 figfile=figfile,
764 figfile=figfile,
555 save=save,
765 save=save,
556 ftp=ftp,
766 ftp=ftp,
557 wr_period=wr_period,
767 wr_period=wr_period,
558 thisDatetime=thisDatetime,
768 thisDatetime=thisDatetime,
559 update_figfile=update_figfile)
769 update_figfile=update_figfile)
560
770
561 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
771 if dataOut.ltctime + dataOut.paramInterval >= self.xmax:
562 self.counter_imagwr = wr_period
772 self.counter_imagwr = wr_period
563 self.isConfig = False
773 self.isConfig = False
564 update_figfile = True
774 update_figfile = True
565
775
566
776
567 class ParametersPlot(Figure):
777 class ParametersPlot(Figure):
568
778
569 __isConfig = None
779 __isConfig = None
570 __nsubplots = None
780 __nsubplots = None
571
781
572 WIDTHPROF = None
782 WIDTHPROF = None
573 HEIGHTPROF = None
783 HEIGHTPROF = None
574 PREFIX = 'param'
784 PREFIX = 'param'
575
785
576 nplots = None
786 nplots = None
577 nchan = None
787 nchan = None
578
788
579 def __init__(self, **kwargs):
789 def __init__(self, **kwargs):
580 Figure.__init__(self, **kwargs)
790 Figure.__init__(self, **kwargs)
581 self.timerange = None
791 self.timerange = None
582 self.isConfig = False
792 self.isConfig = False
583 self.__nsubplots = 1
793 self.__nsubplots = 1
584
794
585 self.WIDTH = 800
795 self.WIDTH = 800
586 self.HEIGHT = 180
796 self.HEIGHT = 180
587 self.WIDTHPROF = 120
797 self.WIDTHPROF = 120
588 self.HEIGHTPROF = 0
798 self.HEIGHTPROF = 0
589 self.counter_imagwr = 0
799 self.counter_imagwr = 0
590
800
591 self.PLOT_CODE = RTI_CODE
801 self.PLOT_CODE = RTI_CODE
592
802
593 self.FTP_WEI = None
803 self.FTP_WEI = None
594 self.EXP_CODE = None
804 self.EXP_CODE = None
595 self.SUB_EXP_CODE = None
805 self.SUB_EXP_CODE = None
596 self.PLOT_POS = None
806 self.PLOT_POS = None
597 self.tmin = None
807 self.tmin = None
598 self.tmax = None
808 self.tmax = None
599
809
600 self.xmin = None
810 self.xmin = None
601 self.xmax = None
811 self.xmax = None
602
812
603 self.figfile = None
813 self.figfile = None
604
814
605 def getSubplots(self):
815 def getSubplots(self):
606
816
607 ncol = 1
817 ncol = 1
608 nrow = self.nplots
818 nrow = self.nplots
609
819
610 return nrow, ncol
820 return nrow, ncol
611
821
612 def setup(self, id, nplots, wintitle, show=True):
822 def setup(self, id, nplots, wintitle, show=True):
613
823
614 self.nplots = nplots
824 self.nplots = nplots
615
825
616 ncolspan = 1
826 ncolspan = 1
617 colspan = 1
827 colspan = 1
618
828
619 self.createFigure(id = id,
829 self.createFigure(id = id,
620 wintitle = wintitle,
830 wintitle = wintitle,
621 widthplot = self.WIDTH + self.WIDTHPROF,
831 widthplot = self.WIDTH + self.WIDTHPROF,
622 heightplot = self.HEIGHT + self.HEIGHTPROF,
832 heightplot = self.HEIGHT + self.HEIGHTPROF,
623 show=show)
833 show=show)
624
834
625 nrow, ncol = self.getSubplots()
835 nrow, ncol = self.getSubplots()
626
836
627 counter = 0
837 counter = 0
628 for y in range(nrow):
838 for y in range(nrow):
629 for x in range(ncol):
839 for x in range(ncol):
630
840
631 if counter >= self.nplots:
841 if counter >= self.nplots:
632 break
842 break
633
843
634 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
844 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
635
845
636 counter += 1
846 counter += 1
637
847
638 def run(self, dataOut, id, wintitle="", channelList=None, paramIndex = 0, colormap=True,
848 def run(self, dataOut, id, wintitle="", channelList=None, paramIndex = 0, colormap="jet",
639 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
849 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
640 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
850 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
641 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
851 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
642 server=None, folder=None, username=None, password=None,
852 server=None, folder=None, username=None, password=None,
643 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
853 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, HEIGHT=None):
644 """
854 """
645
855
646 Input:
856 Input:
647 dataOut :
857 dataOut :
648 id :
858 id :
649 wintitle :
859 wintitle :
650 channelList :
860 channelList :
651 showProfile :
861 showProfile :
652 xmin : None,
862 xmin : None,
653 xmax : None,
863 xmax : None,
654 ymin : None,
864 ymin : None,
655 ymax : None,
865 ymax : None,
656 zmin : None,
866 zmin : None,
657 zmax : None
867 zmax : None
658 """
868 """
659
869
660 if colormap:
870 if HEIGHT is not None:
661 colormap="jet"
871 self.HEIGHT = HEIGHT
662 else:
872
663 colormap="RdBu_r"
873
664
665 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
874 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
666 return
875 return
667
876
668 if channelList == None:
877 if channelList == None:
669 channelIndexList = range(dataOut.data_param.shape[0])
878 channelIndexList = range(dataOut.data_param.shape[0])
670 else:
879 else:
671 channelIndexList = []
880 channelIndexList = []
672 for channel in channelList:
881 for channel in channelList:
673 if channel not in dataOut.channelList:
882 if channel not in dataOut.channelList:
674 raise ValueError, "Channel %d is not in dataOut.channelList"
883 raise ValueError, "Channel %d is not in dataOut.channelList"
675 channelIndexList.append(dataOut.channelList.index(channel))
884 channelIndexList.append(dataOut.channelList.index(channel))
676
885
677 x = dataOut.getTimeRange1(dataOut.paramInterval)
886 x = dataOut.getTimeRange1(dataOut.paramInterval)
678 y = dataOut.getHeiRange()
887 y = dataOut.getHeiRange()
679
888
680 if dataOut.data_param.ndim == 3:
889 if dataOut.data_param.ndim == 3:
681 z = dataOut.data_param[channelIndexList,paramIndex,:]
890 z = dataOut.data_param[channelIndexList,paramIndex,:]
682 else:
891 else:
683 z = dataOut.data_param[channelIndexList,:]
892 z = dataOut.data_param[channelIndexList,:]
684
893
685 if showSNR:
894 if showSNR:
686 #SNR data
895 #SNR data
687 SNRarray = dataOut.data_SNR[channelIndexList,:]
896 SNRarray = dataOut.data_SNR[channelIndexList,:]
688 SNRdB = 10*numpy.log10(SNRarray)
897 SNRdB = 10*numpy.log10(SNRarray)
689 ind = numpy.where(SNRdB < SNRthresh)
898 ind = numpy.where(SNRdB < SNRthresh)
690 z[ind] = numpy.nan
899 z[ind] = numpy.nan
691
900
692 thisDatetime = dataOut.datatime
901 thisDatetime = dataOut.datatime
693 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
902 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
694 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
903 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
695 xlabel = ""
904 xlabel = ""
696 ylabel = "Range (Km)"
905 ylabel = "Range (Km)"
697
906
698 update_figfile = False
907 update_figfile = False
699
908
700 if not self.isConfig:
909 if not self.isConfig:
701
910
702 nchan = len(channelIndexList)
911 nchan = len(channelIndexList)
703 self.nchan = nchan
912 self.nchan = nchan
704 self.plotFact = 1
913 self.plotFact = 1
705 nplots = nchan
914 nplots = nchan
706
915
707 if showSNR:
916 if showSNR:
708 nplots = nchan*2
917 nplots = nchan*2
709 self.plotFact = 2
918 self.plotFact = 2
710 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
919 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
711 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
920 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
712
921
713 self.setup(id=id,
922 self.setup(id=id,
714 nplots=nplots,
923 nplots=nplots,
715 wintitle=wintitle,
924 wintitle=wintitle,
716 show=show)
925 show=show)
717
926
718 if timerange != None:
927 if timerange != None:
719 self.timerange = timerange
928 self.timerange = timerange
720
929
721 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
930 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
722
931
723 if ymin == None: ymin = numpy.nanmin(y)
932 if ymin == None: ymin = numpy.nanmin(y)
724 if ymax == None: ymax = numpy.nanmax(y)
933 if ymax == None: ymax = numpy.nanmax(y)
725 if zmin == None: zmin = numpy.nanmin(z)
934 if zmin == None: zmin = numpy.nanmin(z)
726 if zmax == None: zmax = numpy.nanmax(z)
935 if zmax == None: zmax = numpy.nanmax(z)
727
936
728 self.FTP_WEI = ftp_wei
937 self.FTP_WEI = ftp_wei
729 self.EXP_CODE = exp_code
938 self.EXP_CODE = exp_code
730 self.SUB_EXP_CODE = sub_exp_code
939 self.SUB_EXP_CODE = sub_exp_code
731 self.PLOT_POS = plot_pos
940 self.PLOT_POS = plot_pos
732
941
733 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
942 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
734 self.isConfig = True
943 self.isConfig = True
735 self.figfile = figfile
944 self.figfile = figfile
736 update_figfile = True
945 update_figfile = True
737
946
738 self.setWinTitle(title)
947 self.setWinTitle(title)
739
948
740 for i in range(self.nchan):
949 for i in range(self.nchan):
741 index = channelIndexList[i]
950 index = channelIndexList[i]
742 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
951 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
743 axes = self.axesList[i*self.plotFact]
952 axes = self.axesList[i*self.plotFact]
744 z1 = z[i,:].reshape((1,-1))
953 z1 = z[i,:].reshape((1,-1))
745 axes.pcolorbuffer(x, y, z1,
954 axes.pcolorbuffer(x, y, z1,
746 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
955 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
747 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
956 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
748 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
957 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
749
958
750 if showSNR:
959 if showSNR:
751 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
960 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
752 axes = self.axesList[i*self.plotFact + 1]
961 axes = self.axesList[i*self.plotFact + 1]
753 SNRdB1 = SNRdB[i,:].reshape((1,-1))
962 SNRdB1 = SNRdB[i,:].reshape((1,-1))
754 axes.pcolorbuffer(x, y, SNRdB1,
963 axes.pcolorbuffer(x, y, SNRdB1,
755 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
964 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
756 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
965 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
757 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
966 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
758
967
759
968
760 self.draw()
969 self.draw()
761
970
762 if dataOut.ltctime >= self.xmax:
971 if dataOut.ltctime >= self.xmax:
763 self.counter_imagwr = wr_period
972 self.counter_imagwr = wr_period
764 self.isConfig = False
973 self.isConfig = False
765 update_figfile = True
974 update_figfile = True
766
975
767 self.save(figpath=figpath,
976 self.save(figpath=figpath,
768 figfile=figfile,
977 figfile=figfile,
769 save=save,
978 save=save,
770 ftp=ftp,
979 ftp=ftp,
771 wr_period=wr_period,
980 wr_period=wr_period,
772 thisDatetime=thisDatetime,
981 thisDatetime=thisDatetime,
773 update_figfile=update_figfile)
982 update_figfile=update_figfile)
774
983
775
984
776
985
777 class Parameters1Plot(Figure):
986 class Parameters1Plot(Figure):
778
987
779 __isConfig = None
988 __isConfig = None
780 __nsubplots = None
989 __nsubplots = None
781
990
782 WIDTHPROF = None
991 WIDTHPROF = None
783 HEIGHTPROF = None
992 HEIGHTPROF = None
784 PREFIX = 'prm'
993 PREFIX = 'prm'
785
994
786 def __init__(self, **kwargs):
995 def __init__(self, **kwargs):
787 Figure.__init__(self, **kwargs)
996 Figure.__init__(self, **kwargs)
788 self.timerange = 2*60*60
997 self.timerange = 2*60*60
789 self.isConfig = False
998 self.isConfig = False
790 self.__nsubplots = 1
999 self.__nsubplots = 1
791
1000
792 self.WIDTH = 800
1001 self.WIDTH = 800
793 self.HEIGHT = 180
1002 self.HEIGHT = 180
794 self.WIDTHPROF = 120
1003 self.WIDTHPROF = 120
795 self.HEIGHTPROF = 0
1004 self.HEIGHTPROF = 0
796 self.counter_imagwr = 0
1005 self.counter_imagwr = 0
797
1006
798 self.PLOT_CODE = PARMS_CODE
1007 self.PLOT_CODE = PARMS_CODE
799
1008
800 self.FTP_WEI = None
1009 self.FTP_WEI = None
801 self.EXP_CODE = None
1010 self.EXP_CODE = None
802 self.SUB_EXP_CODE = None
1011 self.SUB_EXP_CODE = None
803 self.PLOT_POS = None
1012 self.PLOT_POS = None
804 self.tmin = None
1013 self.tmin = None
805 self.tmax = None
1014 self.tmax = None
806
1015
807 self.xmin = None
1016 self.xmin = None
808 self.xmax = None
1017 self.xmax = None
809
1018
810 self.figfile = None
1019 self.figfile = None
811
1020
812 def getSubplots(self):
1021 def getSubplots(self):
813
1022
814 ncol = 1
1023 ncol = 1
815 nrow = self.nplots
1024 nrow = self.nplots
816
1025
817 return nrow, ncol
1026 return nrow, ncol
818
1027
819 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1028 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
820
1029
821 self.__showprofile = showprofile
1030 self.__showprofile = showprofile
822 self.nplots = nplots
1031 self.nplots = nplots
823
1032
824 ncolspan = 1
1033 ncolspan = 1
825 colspan = 1
1034 colspan = 1
826
1035
827 self.createFigure(id = id,
1036 self.createFigure(id = id,
828 wintitle = wintitle,
1037 wintitle = wintitle,
829 widthplot = self.WIDTH + self.WIDTHPROF,
1038 widthplot = self.WIDTH + self.WIDTHPROF,
830 heightplot = self.HEIGHT + self.HEIGHTPROF,
1039 heightplot = self.HEIGHT + self.HEIGHTPROF,
831 show=show)
1040 show=show)
832
1041
833 nrow, ncol = self.getSubplots()
1042 nrow, ncol = self.getSubplots()
834
1043
835 counter = 0
1044 counter = 0
836 for y in range(nrow):
1045 for y in range(nrow):
837 for x in range(ncol):
1046 for x in range(ncol):
838
1047
839 if counter >= self.nplots:
1048 if counter >= self.nplots:
840 break
1049 break
841
1050
842 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1051 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
843
1052
844 if showprofile:
1053 if showprofile:
845 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1054 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
846
1055
847 counter += 1
1056 counter += 1
848
1057
849 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
1058 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
850 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
1059 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
851 parameterIndex = None, onlyPositive = False,
1060 parameterIndex = None, onlyPositive = False,
852 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
1061 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
853 DOP = True,
1062 DOP = True,
854 zlabel = "", parameterName = "", parameterObject = "data_param",
1063 zlabel = "", parameterName = "", parameterObject = "data_param",
855 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1064 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
856 server=None, folder=None, username=None, password=None,
1065 server=None, folder=None, username=None, password=None,
857 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1066 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
858 #print inspect.getargspec(self.run).args
1067 #print inspect.getargspec(self.run).args
859 """
1068 """
860
1069
861 Input:
1070 Input:
862 dataOut :
1071 dataOut :
863 id :
1072 id :
864 wintitle :
1073 wintitle :
865 channelList :
1074 channelList :
866 showProfile :
1075 showProfile :
867 xmin : None,
1076 xmin : None,
868 xmax : None,
1077 xmax : None,
869 ymin : None,
1078 ymin : None,
870 ymax : None,
1079 ymax : None,
871 zmin : None,
1080 zmin : None,
872 zmax : None
1081 zmax : None
873 """
1082 """
874
1083
875 data_param = getattr(dataOut, parameterObject)
1084 data_param = getattr(dataOut, parameterObject)
876
1085
877 if channelList == None:
1086 if channelList == None:
878 channelIndexList = numpy.arange(data_param.shape[0])
1087 channelIndexList = numpy.arange(data_param.shape[0])
879 else:
1088 else:
880 channelIndexList = numpy.array(channelList)
1089 channelIndexList = numpy.array(channelList)
881
1090
882 nchan = len(channelIndexList) #Number of channels being plotted
1091 nchan = len(channelIndexList) #Number of channels being plotted
883
1092
884 if nchan < 1:
1093 if nchan < 1:
885 return
1094 return
886
1095
887 nGraphsByChannel = 0
1096 nGraphsByChannel = 0
888
1097
889 if SNR:
1098 if SNR:
890 nGraphsByChannel += 1
1099 nGraphsByChannel += 1
891 if DOP:
1100 if DOP:
892 nGraphsByChannel += 1
1101 nGraphsByChannel += 1
893
1102
894 if nGraphsByChannel < 1:
1103 if nGraphsByChannel < 1:
895 return
1104 return
896
1105
897 nplots = nGraphsByChannel*nchan
1106 nplots = nGraphsByChannel*nchan
898
1107
899 if timerange is not None:
1108 if timerange is not None:
900 self.timerange = timerange
1109 self.timerange = timerange
901
1110
902 #tmin = None
1111 #tmin = None
903 #tmax = None
1112 #tmax = None
904 if parameterIndex == None:
1113 if parameterIndex == None:
905 parameterIndex = 1
1114 parameterIndex = 1
906
1115
907 x = dataOut.getTimeRange1(dataOut.paramInterval)
1116 x = dataOut.getTimeRange1(dataOut.paramInterval)
908 y = dataOut.heightList
1117 y = dataOut.heightList
909 z = data_param[channelIndexList,parameterIndex,:].copy()
910
1118
911 zRange = dataOut.abscissaList
1119 if dataOut.data_param.ndim == 3:
912 # nChannels = z.shape[0] #Number of wind dimensions estimated
1120 z = dataOut.data_param[channelIndexList,parameterIndex,:]
913 # thisDatetime = dataOut.datatime
1121 else:
1122 z = dataOut.data_param[channelIndexList,:]
914
1123
915 if dataOut.data_SNR is not None:
1124 if dataOut.data_SNR is not None:
916 SNRarray = dataOut.data_SNR[channelIndexList,:]
1125 if dataOut.data_SNR.ndim == 2:
917 SNRdB = 10*numpy.log10(SNRarray)
1126 SNRavg = numpy.average(dataOut.data_SNR, axis=0)
918 # SNRavgdB = 10*numpy.log10(SNRavg)
1127 else:
919 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
1128 SNRavg = dataOut.data_SNR
920 z[ind] = numpy.nan
1129 SNRdB = 10*numpy.log10(SNRavg)
921
1130
922 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1131 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
923 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
1132 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
924 xlabel = ""
1133 xlabel = ""
925 ylabel = "Range (Km)"
1134 ylabel = "Range (Km)"
926
927 if (SNR and not onlySNR): nplots = 2*nplots
928
1135
929 if onlyPositive:
1136 if onlyPositive:
930 colormap = "jet"
1137 colormap = "jet"
931 zmin = 0
1138 zmin = 0
932 else: colormap = "RdBu_r"
1139 else: colormap = "RdBu_r"
933
1140
934 if not self.isConfig:
1141 if not self.isConfig:
935
1142
936 self.setup(id=id,
1143 self.setup(id=id,
937 nplots=nplots,
1144 nplots=nplots,
938 wintitle=wintitle,
1145 wintitle=wintitle,
939 showprofile=showprofile,
1146 showprofile=showprofile,
940 show=show)
1147 show=show)
941
1148
942 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1149 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
943
1150
944 if ymin == None: ymin = numpy.nanmin(y)
1151 if ymin == None: ymin = numpy.nanmin(y)
945 if ymax == None: ymax = numpy.nanmax(y)
1152 if ymax == None: ymax = numpy.nanmax(y)
946 if zmin == None: zmin = numpy.nanmin(zRange)
1153 if zmin == None: zmin = numpy.nanmin(z)
947 if zmax == None: zmax = numpy.nanmax(zRange)
1154 if zmax == None: zmax = numpy.nanmax(z)
948
1155
949 if SNR:
1156 if SNR:
950 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
1157 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
951 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
1158 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
952
1159
953 self.FTP_WEI = ftp_wei
1160 self.FTP_WEI = ftp_wei
954 self.EXP_CODE = exp_code
1161 self.EXP_CODE = exp_code
955 self.SUB_EXP_CODE = sub_exp_code
1162 self.SUB_EXP_CODE = sub_exp_code
956 self.PLOT_POS = plot_pos
1163 self.PLOT_POS = plot_pos
957
1164
958 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1165 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
959 self.isConfig = True
1166 self.isConfig = True
960 self.figfile = figfile
1167 self.figfile = figfile
961
1168
962 self.setWinTitle(title)
1169 self.setWinTitle(title)
963
1170
964 if ((self.xmax - x[1]) < (x[1]-x[0])):
1171 if ((self.xmax - x[1]) < (x[1]-x[0])):
965 x[1] = self.xmax
1172 x[1] = self.xmax
966
1173
967 for i in range(nchan):
1174 for i in range(nchan):
968
1175
969 if (SNR and not onlySNR): j = 2*i
1176 if (SNR and not onlySNR): j = 2*i
970 else: j = i
1177 else: j = i
971
1178
972 j = nGraphsByChannel*i
1179 j = nGraphsByChannel*i
973
1180
974 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1181 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
975 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
1182 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
976
1183
977 if not onlySNR:
1184 if not onlySNR:
978 axes = self.axesList[j*self.__nsubplots]
1185 axes = self.axesList[j*self.__nsubplots]
979 z1 = z[i,:].reshape((1,-1))
1186 z1 = z[i,:].reshape((1,-1))
980 axes.pcolorbuffer(x, y, z1,
1187 axes.pcolorbuffer(x, y, z1,
981 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
1188 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
982 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
1189 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
983 ticksize=9, cblabel=zlabel, cbsize="1%")
1190 ticksize=9, cblabel=zlabel, cbsize="1%")
984
1191
985 if DOP:
1192 if DOP:
986 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1193 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
987
1194
988 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1195 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
989 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
1196 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
990 axes = self.axesList[j]
1197 axes = self.axesList[j]
991 z1 = z[i,:].reshape((1,-1))
1198 z1 = z[i,:].reshape((1,-1))
992 axes.pcolorbuffer(x, y, z1,
1199 axes.pcolorbuffer(x, y, z1,
993 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
1200 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
994 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
1201 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
995 ticksize=9, cblabel=zlabel, cbsize="1%")
1202 ticksize=9, cblabel=zlabel, cbsize="1%")
996
1203
997 if SNR:
1204 if SNR:
998 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1205 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
999 axes = self.axesList[(j)*self.__nsubplots]
1206 axes = self.axesList[(j)*self.__nsubplots]
1000 if not onlySNR:
1207 if not onlySNR:
1001 axes = self.axesList[(j + 1)*self.__nsubplots]
1208 axes = self.axesList[(j + 1)*self.__nsubplots]
1002
1003 axes = self.axesList[(j + nGraphsByChannel-1)]
1004
1209
1005 z1 = SNRdB[i,:].reshape((1,-1))
1210 axes = self.axesList[(j + nGraphsByChannel-1)]
1006 axes.pcolorbuffer(x, y, z1,
1211 z1 = SNRdB.reshape((1,-1))
1007 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1212 axes.pcolorbuffer(x, y, z1,
1008 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1213 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1009 ticksize=9, cblabel=zlabel, cbsize="1%")
1214 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1215 ticksize=9, cblabel=zlabel, cbsize="1%")
1010
1216
1011
1217
1012
1218
1013 self.draw()
1219 self.draw()
1014
1220
1015 if x[1] >= self.axesList[0].xmax:
1221 if x[1] >= self.axesList[0].xmax:
1016 self.counter_imagwr = wr_period
1222 self.counter_imagwr = wr_period
1017 self.isConfig = False
1223 self.isConfig = False
1018 self.figfile = None
1224 self.figfile = None
1019
1225
1020 self.save(figpath=figpath,
1226 self.save(figpath=figpath,
1021 figfile=figfile,
1227 figfile=figfile,
1022 save=save,
1228 save=save,
1023 ftp=ftp,
1229 ftp=ftp,
1024 wr_period=wr_period,
1230 wr_period=wr_period,
1025 thisDatetime=thisDatetime,
1231 thisDatetime=thisDatetime,
1026 update_figfile=False)
1232 update_figfile=False)
1027
1233
1028 class SpectralFittingPlot(Figure):
1234 class SpectralFittingPlot(Figure):
1029
1235
1030 __isConfig = None
1236 __isConfig = None
1031 __nsubplots = None
1237 __nsubplots = None
1032
1238
1033 WIDTHPROF = None
1239 WIDTHPROF = None
1034 HEIGHTPROF = None
1240 HEIGHTPROF = None
1035 PREFIX = 'prm'
1241 PREFIX = 'prm'
1036
1242
1037
1243
1038 N = None
1244 N = None
1039 ippSeconds = None
1245 ippSeconds = None
1040
1246
1041 def __init__(self, **kwargs):
1247 def __init__(self, **kwargs):
1042 Figure.__init__(self, **kwargs)
1248 Figure.__init__(self, **kwargs)
1043 self.isConfig = False
1249 self.isConfig = False
1044 self.__nsubplots = 1
1250 self.__nsubplots = 1
1045
1251
1046 self.PLOT_CODE = SPECFIT_CODE
1252 self.PLOT_CODE = SPECFIT_CODE
1047
1253
1048 self.WIDTH = 450
1254 self.WIDTH = 450
1049 self.HEIGHT = 250
1255 self.HEIGHT = 250
1050 self.WIDTHPROF = 0
1256 self.WIDTHPROF = 0
1051 self.HEIGHTPROF = 0
1257 self.HEIGHTPROF = 0
1052
1258
1053 def getSubplots(self):
1259 def getSubplots(self):
1054
1260
1055 ncol = int(numpy.sqrt(self.nplots)+0.9)
1261 ncol = int(numpy.sqrt(self.nplots)+0.9)
1056 nrow = int(self.nplots*1./ncol + 0.9)
1262 nrow = int(self.nplots*1./ncol + 0.9)
1057
1263
1058 return nrow, ncol
1264 return nrow, ncol
1059
1265
1060 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1266 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1061
1267
1062 showprofile = False
1268 showprofile = False
1063 self.__showprofile = showprofile
1269 self.__showprofile = showprofile
1064 self.nplots = nplots
1270 self.nplots = nplots
1065
1271
1066 ncolspan = 5
1272 ncolspan = 5
1067 colspan = 4
1273 colspan = 4
1068 if showprofile:
1274 if showprofile:
1069 ncolspan = 5
1275 ncolspan = 5
1070 colspan = 4
1276 colspan = 4
1071 self.__nsubplots = 2
1277 self.__nsubplots = 2
1072
1278
1073 self.createFigure(id = id,
1279 self.createFigure(id = id,
1074 wintitle = wintitle,
1280 wintitle = wintitle,
1075 widthplot = self.WIDTH + self.WIDTHPROF,
1281 widthplot = self.WIDTH + self.WIDTHPROF,
1076 heightplot = self.HEIGHT + self.HEIGHTPROF,
1282 heightplot = self.HEIGHT + self.HEIGHTPROF,
1077 show=show)
1283 show=show)
1078
1284
1079 nrow, ncol = self.getSubplots()
1285 nrow, ncol = self.getSubplots()
1080
1286
1081 counter = 0
1287 counter = 0
1082 for y in range(nrow):
1288 for y in range(nrow):
1083 for x in range(ncol):
1289 for x in range(ncol):
1084
1290
1085 if counter >= self.nplots:
1291 if counter >= self.nplots:
1086 break
1292 break
1087
1293
1088 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1294 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1089
1295
1090 if showprofile:
1296 if showprofile:
1091 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1297 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1092
1298
1093 counter += 1
1299 counter += 1
1094
1300
1095 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1301 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1096 xmin=None, xmax=None, ymin=None, ymax=None,
1302 xmin=None, xmax=None, ymin=None, ymax=None,
1097 save=False, figpath='./', figfile=None, show=True):
1303 save=False, figpath='./', figfile=None, show=True):
1098
1304
1099 """
1305 """
1100
1306
1101 Input:
1307 Input:
1102 dataOut :
1308 dataOut :
1103 id :
1309 id :
1104 wintitle :
1310 wintitle :
1105 channelList :
1311 channelList :
1106 showProfile :
1312 showProfile :
1107 xmin : None,
1313 xmin : None,
1108 xmax : None,
1314 xmax : None,
1109 zmin : None,
1315 zmin : None,
1110 zmax : None
1316 zmax : None
1111 """
1317 """
1112
1318
1113 if cutHeight==None:
1319 if cutHeight==None:
1114 h=270
1320 h=270
1115 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1321 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1116 cutHeight = dataOut.heightList[heightindex]
1322 cutHeight = dataOut.heightList[heightindex]
1117
1323
1118 factor = dataOut.normFactor
1324 factor = dataOut.normFactor
1119 x = dataOut.abscissaList[:-1]
1325 x = dataOut.abscissaList[:-1]
1120 #y = dataOut.getHeiRange()
1326 #y = dataOut.getHeiRange()
1121
1327
1122 z = dataOut.data_pre[:,:,heightindex]/factor
1328 z = dataOut.data_pre[:,:,heightindex]/factor
1123 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1329 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1124 avg = numpy.average(z, axis=1)
1330 avg = numpy.average(z, axis=1)
1125 listChannels = z.shape[0]
1331 listChannels = z.shape[0]
1126
1332
1127 #Reconstruct Function
1333 #Reconstruct Function
1128 if fit==True:
1334 if fit==True:
1129 groupArray = dataOut.groupList
1335 groupArray = dataOut.groupList
1130 listChannels = groupArray.reshape((groupArray.size))
1336 listChannels = groupArray.reshape((groupArray.size))
1131 listChannels.sort()
1337 listChannels.sort()
1132 spcFitLine = numpy.zeros(z.shape)
1338 spcFitLine = numpy.zeros(z.shape)
1133 constants = dataOut.constants
1339 constants = dataOut.constants
1134
1340
1135 nGroups = groupArray.shape[0]
1341 nGroups = groupArray.shape[0]
1136 nChannels = groupArray.shape[1]
1342 nChannels = groupArray.shape[1]
1137 nProfiles = z.shape[1]
1343 nProfiles = z.shape[1]
1138
1344
1139 for f in range(nGroups):
1345 for f in range(nGroups):
1140 groupChann = groupArray[f,:]
1346 groupChann = groupArray[f,:]
1141 p = dataOut.data_param[f,:,heightindex]
1347 p = dataOut.data_param[f,:,heightindex]
1142 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1348 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1143 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1349 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1144 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1350 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1145 spcFitLine[groupChann,:] = fitLineAux
1351 spcFitLine[groupChann,:] = fitLineAux
1146 # spcFitLine = spcFitLine/factor
1352 # spcFitLine = spcFitLine/factor
1147
1353
1148 z = z[listChannels,:]
1354 z = z[listChannels,:]
1149 spcFitLine = spcFitLine[listChannels,:]
1355 spcFitLine = spcFitLine[listChannels,:]
1150 spcFitLinedB = 10*numpy.log10(spcFitLine)
1356 spcFitLinedB = 10*numpy.log10(spcFitLine)
1151
1357
1152 zdB = 10*numpy.log10(z)
1358 zdB = 10*numpy.log10(z)
1153 #thisDatetime = dataOut.datatime
1359 #thisDatetime = dataOut.datatime
1154 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1360 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1155 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1361 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1156 xlabel = "Velocity (m/s)"
1362 xlabel = "Velocity (m/s)"
1157 ylabel = "Spectrum"
1363 ylabel = "Spectrum"
1158
1364
1159 if not self.isConfig:
1365 if not self.isConfig:
1160
1366
1161 nplots = listChannels.size
1367 nplots = listChannels.size
1162
1368
1163 self.setup(id=id,
1369 self.setup(id=id,
1164 nplots=nplots,
1370 nplots=nplots,
1165 wintitle=wintitle,
1371 wintitle=wintitle,
1166 showprofile=showprofile,
1372 showprofile=showprofile,
1167 show=show)
1373 show=show)
1168
1374
1169 if xmin == None: xmin = numpy.nanmin(x)
1375 if xmin == None: xmin = numpy.nanmin(x)
1170 if xmax == None: xmax = numpy.nanmax(x)
1376 if xmax == None: xmax = numpy.nanmax(x)
1171 if ymin == None: ymin = numpy.nanmin(zdB)
1377 if ymin == None: ymin = numpy.nanmin(zdB)
1172 if ymax == None: ymax = numpy.nanmax(zdB)+2
1378 if ymax == None: ymax = numpy.nanmax(zdB)+2
1173
1379
1174 self.isConfig = True
1380 self.isConfig = True
1175
1381
1176 self.setWinTitle(title)
1382 self.setWinTitle(title)
1177 for i in range(self.nplots):
1383 for i in range(self.nplots):
1178 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1384 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1179 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1385 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1180 axes = self.axesList[i*self.__nsubplots]
1386 axes = self.axesList[i*self.__nsubplots]
1181 if fit == False:
1387 if fit == False:
1182 axes.pline(x, zdB[i,:],
1388 axes.pline(x, zdB[i,:],
1183 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1389 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1184 xlabel=xlabel, ylabel=ylabel, title=title
1390 xlabel=xlabel, ylabel=ylabel, title=title
1185 )
1391 )
1186 if fit == True:
1392 if fit == True:
1187 fitline=spcFitLinedB[i,:]
1393 fitline=spcFitLinedB[i,:]
1188 y=numpy.vstack([zdB[i,:],fitline] )
1394 y=numpy.vstack([zdB[i,:],fitline] )
1189 legendlabels=['Data','Fitting']
1395 legendlabels=['Data','Fitting']
1190 axes.pmultilineyaxis(x, y,
1396 axes.pmultilineyaxis(x, y,
1191 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1397 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1192 xlabel=xlabel, ylabel=ylabel, title=title,
1398 xlabel=xlabel, ylabel=ylabel, title=title,
1193 legendlabels=legendlabels, marker=None,
1399 legendlabels=legendlabels, marker=None,
1194 linestyle='solid', grid='both')
1400 linestyle='solid', grid='both')
1195
1401
1196 self.draw()
1402 self.draw()
1197
1403
1198 self.save(figpath=figpath,
1404 self.save(figpath=figpath,
1199 figfile=figfile,
1405 figfile=figfile,
1200 save=save,
1406 save=save,
1201 ftp=ftp,
1407 ftp=ftp,
1202 wr_period=wr_period,
1408 wr_period=wr_period,
1203 thisDatetime=thisDatetime)
1409 thisDatetime=thisDatetime)
1204
1410
1205
1411
1206 class EWDriftsPlot(Figure):
1412 class EWDriftsPlot(Figure):
1207
1413
1208 __isConfig = None
1414 __isConfig = None
1209 __nsubplots = None
1415 __nsubplots = None
1210
1416
1211 WIDTHPROF = None
1417 WIDTHPROF = None
1212 HEIGHTPROF = None
1418 HEIGHTPROF = None
1213 PREFIX = 'drift'
1419 PREFIX = 'drift'
1214
1420
1215 def __init__(self, **kwargs):
1421 def __init__(self, **kwargs):
1216 Figure.__init__(self, **kwargs)
1422 Figure.__init__(self, **kwargs)
1217 self.timerange = 2*60*60
1423 self.timerange = 2*60*60
1218 self.isConfig = False
1424 self.isConfig = False
1219 self.__nsubplots = 1
1425 self.__nsubplots = 1
1220
1426
1221 self.WIDTH = 800
1427 self.WIDTH = 800
1222 self.HEIGHT = 150
1428 self.HEIGHT = 150
1223 self.WIDTHPROF = 120
1429 self.WIDTHPROF = 120
1224 self.HEIGHTPROF = 0
1430 self.HEIGHTPROF = 0
1225 self.counter_imagwr = 0
1431 self.counter_imagwr = 0
1226
1432
1227 self.PLOT_CODE = EWDRIFT_CODE
1433 self.PLOT_CODE = EWDRIFT_CODE
1228
1434
1229 self.FTP_WEI = None
1435 self.FTP_WEI = None
1230 self.EXP_CODE = None
1436 self.EXP_CODE = None
1231 self.SUB_EXP_CODE = None
1437 self.SUB_EXP_CODE = None
1232 self.PLOT_POS = None
1438 self.PLOT_POS = None
1233 self.tmin = None
1439 self.tmin = None
1234 self.tmax = None
1440 self.tmax = None
1235
1441
1236 self.xmin = None
1442 self.xmin = None
1237 self.xmax = None
1443 self.xmax = None
1238
1444
1239 self.figfile = None
1445 self.figfile = None
1240
1446
1241 def getSubplots(self):
1447 def getSubplots(self):
1242
1448
1243 ncol = 1
1449 ncol = 1
1244 nrow = self.nplots
1450 nrow = self.nplots
1245
1451
1246 return nrow, ncol
1452 return nrow, ncol
1247
1453
1248 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1454 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1249
1455
1250 self.__showprofile = showprofile
1456 self.__showprofile = showprofile
1251 self.nplots = nplots
1457 self.nplots = nplots
1252
1458
1253 ncolspan = 1
1459 ncolspan = 1
1254 colspan = 1
1460 colspan = 1
1255
1461
1256 self.createFigure(id = id,
1462 self.createFigure(id = id,
1257 wintitle = wintitle,
1463 wintitle = wintitle,
1258 widthplot = self.WIDTH + self.WIDTHPROF,
1464 widthplot = self.WIDTH + self.WIDTHPROF,
1259 heightplot = self.HEIGHT + self.HEIGHTPROF,
1465 heightplot = self.HEIGHT + self.HEIGHTPROF,
1260 show=show)
1466 show=show)
1261
1467
1262 nrow, ncol = self.getSubplots()
1468 nrow, ncol = self.getSubplots()
1263
1469
1264 counter = 0
1470 counter = 0
1265 for y in range(nrow):
1471 for y in range(nrow):
1266 if counter >= self.nplots:
1472 if counter >= self.nplots:
1267 break
1473 break
1268
1474
1269 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1475 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1270 counter += 1
1476 counter += 1
1271
1477
1272 def run(self, dataOut, id, wintitle="", channelList=None,
1478 def run(self, dataOut, id, wintitle="", channelList=None,
1273 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1479 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1274 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1480 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1275 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1481 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1276 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1482 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1277 server=None, folder=None, username=None, password=None,
1483 server=None, folder=None, username=None, password=None,
1278 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1484 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1279 """
1485 """
1280
1486
1281 Input:
1487 Input:
1282 dataOut :
1488 dataOut :
1283 id :
1489 id :
1284 wintitle :
1490 wintitle :
1285 channelList :
1491 channelList :
1286 showProfile :
1492 showProfile :
1287 xmin : None,
1493 xmin : None,
1288 xmax : None,
1494 xmax : None,
1289 ymin : None,
1495 ymin : None,
1290 ymax : None,
1496 ymax : None,
1291 zmin : None,
1497 zmin : None,
1292 zmax : None
1498 zmax : None
1293 """
1499 """
1294
1500
1295 if timerange is not None:
1501 if timerange is not None:
1296 self.timerange = timerange
1502 self.timerange = timerange
1297
1503
1298 tmin = None
1504 tmin = None
1299 tmax = None
1505 tmax = None
1300
1506
1301 x = dataOut.getTimeRange1(dataOut.outputInterval)
1507 x = dataOut.getTimeRange1(dataOut.outputInterval)
1302 # y = dataOut.heightList
1508 # y = dataOut.heightList
1303 y = dataOut.heightList
1509 y = dataOut.heightList
1304
1510
1305 z = dataOut.data_output
1511 z = dataOut.data_output
1306 nplots = z.shape[0] #Number of wind dimensions estimated
1512 nplots = z.shape[0] #Number of wind dimensions estimated
1307 nplotsw = nplots
1513 nplotsw = nplots
1308
1514
1309 #If there is a SNR function defined
1515 #If there is a SNR function defined
1310 if dataOut.data_SNR is not None:
1516 if dataOut.data_SNR is not None:
1311 nplots += 1
1517 nplots += 1
1312 SNR = dataOut.data_SNR
1518 SNR = dataOut.data_SNR
1313
1519
1314 if SNR_1:
1520 if SNR_1:
1315 SNR += 1
1521 SNR += 1
1316
1522
1317 SNRavg = numpy.average(SNR, axis=0)
1523 SNRavg = numpy.average(SNR, axis=0)
1318
1524
1319 SNRdB = 10*numpy.log10(SNR)
1525 SNRdB = 10*numpy.log10(SNR)
1320 SNRavgdB = 10*numpy.log10(SNRavg)
1526 SNRavgdB = 10*numpy.log10(SNRavg)
1321
1527
1322 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1528 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1323
1529
1324 for i in range(nplotsw):
1530 for i in range(nplotsw):
1325 z[i,ind] = numpy.nan
1531 z[i,ind] = numpy.nan
1326
1532
1327
1533
1328 showprofile = False
1534 showprofile = False
1329 # thisDatetime = dataOut.datatime
1535 # thisDatetime = dataOut.datatime
1330 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1536 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1331 title = wintitle + " EW Drifts"
1537 title = wintitle + " EW Drifts"
1332 xlabel = ""
1538 xlabel = ""
1333 ylabel = "Height (Km)"
1539 ylabel = "Height (Km)"
1334
1540
1335 if not self.isConfig:
1541 if not self.isConfig:
1336
1542
1337 self.setup(id=id,
1543 self.setup(id=id,
1338 nplots=nplots,
1544 nplots=nplots,
1339 wintitle=wintitle,
1545 wintitle=wintitle,
1340 showprofile=showprofile,
1546 showprofile=showprofile,
1341 show=show)
1547 show=show)
1342
1548
1343 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1549 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1344
1550
1345 if ymin == None: ymin = numpy.nanmin(y)
1551 if ymin == None: ymin = numpy.nanmin(y)
1346 if ymax == None: ymax = numpy.nanmax(y)
1552 if ymax == None: ymax = numpy.nanmax(y)
1347
1553
1348 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1554 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1349 if zminZonal == None: zminZonal = -zmaxZonal
1555 if zminZonal == None: zminZonal = -zmaxZonal
1350 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1556 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1351 if zminVertical == None: zminVertical = -zmaxVertical
1557 if zminVertical == None: zminVertical = -zmaxVertical
1352
1558
1353 if dataOut.data_SNR is not None:
1559 if dataOut.data_SNR is not None:
1354 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1560 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1355 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1561 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1356
1562
1357 self.FTP_WEI = ftp_wei
1563 self.FTP_WEI = ftp_wei
1358 self.EXP_CODE = exp_code
1564 self.EXP_CODE = exp_code
1359 self.SUB_EXP_CODE = sub_exp_code
1565 self.SUB_EXP_CODE = sub_exp_code
1360 self.PLOT_POS = plot_pos
1566 self.PLOT_POS = plot_pos
1361
1567
1362 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1568 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1363 self.isConfig = True
1569 self.isConfig = True
1364
1570
1365
1571
1366 self.setWinTitle(title)
1572 self.setWinTitle(title)
1367
1573
1368 if ((self.xmax - x[1]) < (x[1]-x[0])):
1574 if ((self.xmax - x[1]) < (x[1]-x[0])):
1369 x[1] = self.xmax
1575 x[1] = self.xmax
1370
1576
1371 strWind = ['Zonal','Vertical']
1577 strWind = ['Zonal','Vertical']
1372 strCb = 'Velocity (m/s)'
1578 strCb = 'Velocity (m/s)'
1373 zmaxVector = [zmaxZonal, zmaxVertical]
1579 zmaxVector = [zmaxZonal, zmaxVertical]
1374 zminVector = [zminZonal, zminVertical]
1580 zminVector = [zminZonal, zminVertical]
1375
1581
1376 for i in range(nplotsw):
1582 for i in range(nplotsw):
1377
1583
1378 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1584 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1379 axes = self.axesList[i*self.__nsubplots]
1585 axes = self.axesList[i*self.__nsubplots]
1380
1586
1381 z1 = z[i,:].reshape((1,-1))
1587 z1 = z[i,:].reshape((1,-1))
1382
1588
1383 axes.pcolorbuffer(x, y, z1,
1589 axes.pcolorbuffer(x, y, z1,
1384 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1590 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1385 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1591 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1386 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1592 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1387
1593
1388 if dataOut.data_SNR is not None:
1594 if dataOut.data_SNR is not None:
1389 i += 1
1595 i += 1
1390 if SNR_1:
1596 if SNR_1:
1391 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1597 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1392 else:
1598 else:
1393 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1599 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1394 axes = self.axesList[i*self.__nsubplots]
1600 axes = self.axesList[i*self.__nsubplots]
1395 SNRavgdB = SNRavgdB.reshape((1,-1))
1601 SNRavgdB = SNRavgdB.reshape((1,-1))
1396
1602
1397 axes.pcolorbuffer(x, y, SNRavgdB,
1603 axes.pcolorbuffer(x, y, SNRavgdB,
1398 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1604 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1399 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1605 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1400 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1606 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1401
1607
1402 self.draw()
1608 self.draw()
1403
1609
1404 if x[1] >= self.axesList[0].xmax:
1610 if x[1] >= self.axesList[0].xmax:
1405 self.counter_imagwr = wr_period
1611 self.counter_imagwr = wr_period
1406 self.isConfig = False
1612 self.isConfig = False
1407 self.figfile = None
1613 self.figfile = None
1408
1614
1409
1615
1410
1616
1411
1617
1412 class PhasePlot(Figure):
1618 class PhasePlot(Figure):
1413
1619
1414 __isConfig = None
1620 __isConfig = None
1415 __nsubplots = None
1621 __nsubplots = None
1416
1622
1417 PREFIX = 'mphase'
1623 PREFIX = 'mphase'
1418
1624
1419
1625
1420 def __init__(self, **kwargs):
1626 def __init__(self, **kwargs):
1421 Figure.__init__(self, **kwargs)
1627 Figure.__init__(self, **kwargs)
1422 self.timerange = 24*60*60
1628 self.timerange = 24*60*60
1423 self.isConfig = False
1629 self.isConfig = False
1424 self.__nsubplots = 1
1630 self.__nsubplots = 1
1425 self.counter_imagwr = 0
1631 self.counter_imagwr = 0
1426 self.WIDTH = 600
1632 self.WIDTH = 600
1427 self.HEIGHT = 300
1633 self.HEIGHT = 300
1428 self.WIDTHPROF = 120
1634 self.WIDTHPROF = 120
1429 self.HEIGHTPROF = 0
1635 self.HEIGHTPROF = 0
1430 self.xdata = None
1636 self.xdata = None
1431 self.ydata = None
1637 self.ydata = None
1432
1638
1433 self.PLOT_CODE = MPHASE_CODE
1639 self.PLOT_CODE = MPHASE_CODE
1434
1640
1435 self.FTP_WEI = None
1641 self.FTP_WEI = None
1436 self.EXP_CODE = None
1642 self.EXP_CODE = None
1437 self.SUB_EXP_CODE = None
1643 self.SUB_EXP_CODE = None
1438 self.PLOT_POS = None
1644 self.PLOT_POS = None
1439
1645
1440
1646
1441 self.filename_phase = None
1647 self.filename_phase = None
1442
1648
1443 self.figfile = None
1649 self.figfile = None
1444
1650
1445 def getSubplots(self):
1651 def getSubplots(self):
1446
1652
1447 ncol = 1
1653 ncol = 1
1448 nrow = 1
1654 nrow = 1
1449
1655
1450 return nrow, ncol
1656 return nrow, ncol
1451
1657
1452 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1658 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1453
1659
1454 self.__showprofile = showprofile
1660 self.__showprofile = showprofile
1455 self.nplots = nplots
1661 self.nplots = nplots
1456
1662
1457 ncolspan = 7
1663 ncolspan = 7
1458 colspan = 6
1664 colspan = 6
1459 self.__nsubplots = 2
1665 self.__nsubplots = 2
1460
1666
1461 self.createFigure(id = id,
1667 self.createFigure(id = id,
1462 wintitle = wintitle,
1668 wintitle = wintitle,
1463 widthplot = self.WIDTH+self.WIDTHPROF,
1669 widthplot = self.WIDTH+self.WIDTHPROF,
1464 heightplot = self.HEIGHT+self.HEIGHTPROF,
1670 heightplot = self.HEIGHT+self.HEIGHTPROF,
1465 show=show)
1671 show=show)
1466
1672
1467 nrow, ncol = self.getSubplots()
1673 nrow, ncol = self.getSubplots()
1468
1674
1469 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1675 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1470
1676
1471
1677
1472 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1678 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1473 xmin=None, xmax=None, ymin=None, ymax=None,
1679 xmin=None, xmax=None, ymin=None, ymax=None,
1474 timerange=None,
1680 timerange=None,
1475 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1681 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1476 server=None, folder=None, username=None, password=None,
1682 server=None, folder=None, username=None, password=None,
1477 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1683 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1478
1684
1479
1685
1480 tmin = None
1686 tmin = None
1481 tmax = None
1687 tmax = None
1482 x = dataOut.getTimeRange1(dataOut.outputInterval)
1688 x = dataOut.getTimeRange1(dataOut.outputInterval)
1483 y = dataOut.getHeiRange()
1689 y = dataOut.getHeiRange()
1484
1690
1485
1691
1486 #thisDatetime = dataOut.datatime
1692 #thisDatetime = dataOut.datatime
1487 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1693 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1488 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1694 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1489 xlabel = "Local Time"
1695 xlabel = "Local Time"
1490 ylabel = "Phase"
1696 ylabel = "Phase"
1491
1697
1492
1698
1493 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1699 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1494 phase_beacon = dataOut.data_output
1700 phase_beacon = dataOut.data_output
1495 update_figfile = False
1701 update_figfile = False
1496
1702
1497 if not self.isConfig:
1703 if not self.isConfig:
1498
1704
1499 self.nplots = phase_beacon.size
1705 self.nplots = phase_beacon.size
1500
1706
1501 self.setup(id=id,
1707 self.setup(id=id,
1502 nplots=self.nplots,
1708 nplots=self.nplots,
1503 wintitle=wintitle,
1709 wintitle=wintitle,
1504 showprofile=showprofile,
1710 showprofile=showprofile,
1505 show=show)
1711 show=show)
1506
1712
1507 if timerange is not None:
1713 if timerange is not None:
1508 self.timerange = timerange
1714 self.timerange = timerange
1509
1715
1510 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1716 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1511
1717
1512 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1718 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1513 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1719 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1514
1720
1515 self.FTP_WEI = ftp_wei
1721 self.FTP_WEI = ftp_wei
1516 self.EXP_CODE = exp_code
1722 self.EXP_CODE = exp_code
1517 self.SUB_EXP_CODE = sub_exp_code
1723 self.SUB_EXP_CODE = sub_exp_code
1518 self.PLOT_POS = plot_pos
1724 self.PLOT_POS = plot_pos
1519
1725
1520 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1726 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1521 self.isConfig = True
1727 self.isConfig = True
1522 self.figfile = figfile
1728 self.figfile = figfile
1523 self.xdata = numpy.array([])
1729 self.xdata = numpy.array([])
1524 self.ydata = numpy.array([])
1730 self.ydata = numpy.array([])
1525
1731
1526 #open file beacon phase
1732 #open file beacon phase
1527 path = '%s%03d' %(self.PREFIX, self.id)
1733 path = '%s%03d' %(self.PREFIX, self.id)
1528 beacon_file = os.path.join(path,'%s.txt'%self.name)
1734 beacon_file = os.path.join(path,'%s.txt'%self.name)
1529 self.filename_phase = os.path.join(figpath,beacon_file)
1735 self.filename_phase = os.path.join(figpath,beacon_file)
1530 update_figfile = True
1736 update_figfile = True
1531
1737
1532
1738
1533 #store data beacon phase
1739 #store data beacon phase
1534 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1740 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1535
1741
1536 self.setWinTitle(title)
1742 self.setWinTitle(title)
1537
1743
1538
1744
1539 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1745 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1540
1746
1541 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1747 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1542
1748
1543 axes = self.axesList[0]
1749 axes = self.axesList[0]
1544
1750
1545 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1751 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1546
1752
1547 if len(self.ydata)==0:
1753 if len(self.ydata)==0:
1548 self.ydata = phase_beacon.reshape(-1,1)
1754 self.ydata = phase_beacon.reshape(-1,1)
1549 else:
1755 else:
1550 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1756 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1551
1757
1552
1758
1553 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1759 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1554 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1760 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1555 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1761 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1556 XAxisAsTime=True, grid='both'
1762 XAxisAsTime=True, grid='both'
1557 )
1763 )
1558
1764
1559 self.draw()
1765 self.draw()
1560
1766
1561 self.save(figpath=figpath,
1767 self.save(figpath=figpath,
1562 figfile=figfile,
1768 figfile=figfile,
1563 save=save,
1769 save=save,
1564 ftp=ftp,
1770 ftp=ftp,
1565 wr_period=wr_period,
1771 wr_period=wr_period,
1566 thisDatetime=thisDatetime,
1772 thisDatetime=thisDatetime,
1567 update_figfile=update_figfile)
1773 update_figfile=update_figfile)
1568
1774
1569 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1775 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1570 self.counter_imagwr = wr_period
1776 self.counter_imagwr = wr_period
1571 self.isConfig = False
1777 self.isConfig = False
1572 update_figfile = True
1778 update_figfile = True
1573
1779
1574
1780
1575
1781
1576 class NSMeteorDetection1Plot(Figure):
1782 class NSMeteorDetection1Plot(Figure):
1577
1783
1578 isConfig = None
1784 isConfig = None
1579 __nsubplots = None
1785 __nsubplots = None
1580
1786
1581 WIDTHPROF = None
1787 WIDTHPROF = None
1582 HEIGHTPROF = None
1788 HEIGHTPROF = None
1583 PREFIX = 'nsm'
1789 PREFIX = 'nsm'
1584
1790
1585 zminList = None
1791 zminList = None
1586 zmaxList = None
1792 zmaxList = None
1587 cmapList = None
1793 cmapList = None
1588 titleList = None
1794 titleList = None
1589 nPairs = None
1795 nPairs = None
1590 nChannels = None
1796 nChannels = None
1591 nParam = None
1797 nParam = None
1592
1798
1593 def __init__(self, **kwargs):
1799 def __init__(self, **kwargs):
1594 Figure.__init__(self, **kwargs)
1800 Figure.__init__(self, **kwargs)
1595 self.isConfig = False
1801 self.isConfig = False
1596 self.__nsubplots = 1
1802 self.__nsubplots = 1
1597
1803
1598 self.WIDTH = 750
1804 self.WIDTH = 750
1599 self.HEIGHT = 250
1805 self.HEIGHT = 250
1600 self.WIDTHPROF = 120
1806 self.WIDTHPROF = 120
1601 self.HEIGHTPROF = 0
1807 self.HEIGHTPROF = 0
1602 self.counter_imagwr = 0
1808 self.counter_imagwr = 0
1603
1809
1604 self.PLOT_CODE = SPEC_CODE
1810 self.PLOT_CODE = SPEC_CODE
1605
1811
1606 self.FTP_WEI = None
1812 self.FTP_WEI = None
1607 self.EXP_CODE = None
1813 self.EXP_CODE = None
1608 self.SUB_EXP_CODE = None
1814 self.SUB_EXP_CODE = None
1609 self.PLOT_POS = None
1815 self.PLOT_POS = None
1610
1816
1611 self.__xfilter_ena = False
1817 self.__xfilter_ena = False
1612 self.__yfilter_ena = False
1818 self.__yfilter_ena = False
1613
1819
1614 def getSubplots(self):
1820 def getSubplots(self):
1615
1821
1616 ncol = 3
1822 ncol = 3
1617 nrow = int(numpy.ceil(self.nplots/3.0))
1823 nrow = int(numpy.ceil(self.nplots/3.0))
1618
1824
1619 return nrow, ncol
1825 return nrow, ncol
1620
1826
1621 def setup(self, id, nplots, wintitle, show=True):
1827 def setup(self, id, nplots, wintitle, show=True):
1622
1828
1623 self.nplots = nplots
1829 self.nplots = nplots
1624
1830
1625 ncolspan = 1
1831 ncolspan = 1
1626 colspan = 1
1832 colspan = 1
1627
1833
1628 self.createFigure(id = id,
1834 self.createFigure(id = id,
1629 wintitle = wintitle,
1835 wintitle = wintitle,
1630 widthplot = self.WIDTH + self.WIDTHPROF,
1836 widthplot = self.WIDTH + self.WIDTHPROF,
1631 heightplot = self.HEIGHT + self.HEIGHTPROF,
1837 heightplot = self.HEIGHT + self.HEIGHTPROF,
1632 show=show)
1838 show=show)
1633
1839
1634 nrow, ncol = self.getSubplots()
1840 nrow, ncol = self.getSubplots()
1635
1841
1636 counter = 0
1842 counter = 0
1637 for y in range(nrow):
1843 for y in range(nrow):
1638 for x in range(ncol):
1844 for x in range(ncol):
1639
1845
1640 if counter >= self.nplots:
1846 if counter >= self.nplots:
1641 break
1847 break
1642
1848
1643 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1849 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1644
1850
1645 counter += 1
1851 counter += 1
1646
1852
1647 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1853 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1648 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1854 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1649 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1855 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1650 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1856 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1651 server=None, folder=None, username=None, password=None,
1857 server=None, folder=None, username=None, password=None,
1652 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1858 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1653 xaxis="frequency"):
1859 xaxis="frequency"):
1654
1860
1655 """
1861 """
1656
1862
1657 Input:
1863 Input:
1658 dataOut :
1864 dataOut :
1659 id :
1865 id :
1660 wintitle :
1866 wintitle :
1661 channelList :
1867 channelList :
1662 showProfile :
1868 showProfile :
1663 xmin : None,
1869 xmin : None,
1664 xmax : None,
1870 xmax : None,
1665 ymin : None,
1871 ymin : None,
1666 ymax : None,
1872 ymax : None,
1667 zmin : None,
1873 zmin : None,
1668 zmax : None
1874 zmax : None
1669 """
1875 """
1670 #SEPARAR EN DOS PLOTS
1876 #SEPARAR EN DOS PLOTS
1671 nParam = dataOut.data_param.shape[1] - 3
1877 nParam = dataOut.data_param.shape[1] - 3
1672
1878
1673 utctime = dataOut.data_param[0,0]
1879 utctime = dataOut.data_param[0,0]
1674 tmet = dataOut.data_param[:,1].astype(int)
1880 tmet = dataOut.data_param[:,1].astype(int)
1675 hmet = dataOut.data_param[:,2].astype(int)
1881 hmet = dataOut.data_param[:,2].astype(int)
1676
1882
1677 x = dataOut.abscissaList
1883 x = dataOut.abscissaList
1678 y = dataOut.heightList
1884 y = dataOut.heightList
1679
1885
1680 z = numpy.zeros((nParam, y.size, x.size - 1))
1886 z = numpy.zeros((nParam, y.size, x.size - 1))
1681 z[:,:] = numpy.nan
1887 z[:,:] = numpy.nan
1682 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1888 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1683 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1889 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1684
1890
1685 xlabel = "Time (s)"
1891 xlabel = "Time (s)"
1686 ylabel = "Range (km)"
1892 ylabel = "Range (km)"
1687
1893
1688 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1894 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1689
1895
1690 if not self.isConfig:
1896 if not self.isConfig:
1691
1897
1692 nplots = nParam
1898 nplots = nParam
1693
1899
1694 self.setup(id=id,
1900 self.setup(id=id,
1695 nplots=nplots,
1901 nplots=nplots,
1696 wintitle=wintitle,
1902 wintitle=wintitle,
1697 show=show)
1903 show=show)
1698
1904
1699 if xmin is None: xmin = numpy.nanmin(x)
1905 if xmin is None: xmin = numpy.nanmin(x)
1700 if xmax is None: xmax = numpy.nanmax(x)
1906 if xmax is None: xmax = numpy.nanmax(x)
1701 if ymin is None: ymin = numpy.nanmin(y)
1907 if ymin is None: ymin = numpy.nanmin(y)
1702 if ymax is None: ymax = numpy.nanmax(y)
1908 if ymax is None: ymax = numpy.nanmax(y)
1703 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1909 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1704 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1910 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1705 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1911 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1706 if vmin is None: vmin = -vmax
1912 if vmin is None: vmin = -vmax
1707 if wmin is None: wmin = 0
1913 if wmin is None: wmin = 0
1708 if wmax is None: wmax = 50
1914 if wmax is None: wmax = 50
1709
1915
1710 pairsList = dataOut.groupList
1916 pairsList = dataOut.groupList
1711 self.nPairs = len(dataOut.groupList)
1917 self.nPairs = len(dataOut.groupList)
1712
1918
1713 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1919 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1714 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1920 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1715 titleList = ["SNR","Radial Velocity","Coherence"]
1921 titleList = ["SNR","Radial Velocity","Coherence"]
1716 cmapList = ["jet","RdBu_r","jet"]
1922 cmapList = ["jet","RdBu_r","jet"]
1717
1923
1718 for i in range(self.nPairs):
1924 for i in range(self.nPairs):
1719 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1925 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1720 titleList = titleList + [strAux1]
1926 titleList = titleList + [strAux1]
1721 cmapList = cmapList + ["RdBu_r"]
1927 cmapList = cmapList + ["RdBu_r"]
1722
1928
1723 self.zminList = zminList
1929 self.zminList = zminList
1724 self.zmaxList = zmaxList
1930 self.zmaxList = zmaxList
1725 self.cmapList = cmapList
1931 self.cmapList = cmapList
1726 self.titleList = titleList
1932 self.titleList = titleList
1727
1933
1728 self.FTP_WEI = ftp_wei
1934 self.FTP_WEI = ftp_wei
1729 self.EXP_CODE = exp_code
1935 self.EXP_CODE = exp_code
1730 self.SUB_EXP_CODE = sub_exp_code
1936 self.SUB_EXP_CODE = sub_exp_code
1731 self.PLOT_POS = plot_pos
1937 self.PLOT_POS = plot_pos
1732
1938
1733 self.isConfig = True
1939 self.isConfig = True
1734
1940
1735 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1941 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1736
1942
1737 for i in range(nParam):
1943 for i in range(nParam):
1738 title = self.titleList[i] + ": " +str_datetime
1944 title = self.titleList[i] + ": " +str_datetime
1739 axes = self.axesList[i]
1945 axes = self.axesList[i]
1740 axes.pcolor(x, y, z[i,:].T,
1946 axes.pcolor(x, y, z[i,:].T,
1741 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1947 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1742 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1948 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1743 self.draw()
1949 self.draw()
1744
1950
1745 if figfile == None:
1951 if figfile == None:
1746 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1952 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1747 name = str_datetime
1953 name = str_datetime
1748 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1954 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1749 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1955 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1750 figfile = self.getFilename(name)
1956 figfile = self.getFilename(name)
1751
1957
1752 self.save(figpath=figpath,
1958 self.save(figpath=figpath,
1753 figfile=figfile,
1959 figfile=figfile,
1754 save=save,
1960 save=save,
1755 ftp=ftp,
1961 ftp=ftp,
1756 wr_period=wr_period,
1962 wr_period=wr_period,
1757 thisDatetime=thisDatetime)
1963 thisDatetime=thisDatetime)
1758
1964
1759
1965
1760 class NSMeteorDetection2Plot(Figure):
1966 class NSMeteorDetection2Plot(Figure):
1761
1967
1762 isConfig = None
1968 isConfig = None
1763 __nsubplots = None
1969 __nsubplots = None
1764
1970
1765 WIDTHPROF = None
1971 WIDTHPROF = None
1766 HEIGHTPROF = None
1972 HEIGHTPROF = None
1767 PREFIX = 'nsm'
1973 PREFIX = 'nsm'
1768
1974
1769 zminList = None
1975 zminList = None
1770 zmaxList = None
1976 zmaxList = None
1771 cmapList = None
1977 cmapList = None
1772 titleList = None
1978 titleList = None
1773 nPairs = None
1979 nPairs = None
1774 nChannels = None
1980 nChannels = None
1775 nParam = None
1981 nParam = None
1776
1982
1777 def __init__(self, **kwargs):
1983 def __init__(self, **kwargs):
1778 Figure.__init__(self, **kwargs)
1984 Figure.__init__(self, **kwargs)
1779 self.isConfig = False
1985 self.isConfig = False
1780 self.__nsubplots = 1
1986 self.__nsubplots = 1
1781
1987
1782 self.WIDTH = 750
1988 self.WIDTH = 750
1783 self.HEIGHT = 250
1989 self.HEIGHT = 250
1784 self.WIDTHPROF = 120
1990 self.WIDTHPROF = 120
1785 self.HEIGHTPROF = 0
1991 self.HEIGHTPROF = 0
1786 self.counter_imagwr = 0
1992 self.counter_imagwr = 0
1787
1993
1788 self.PLOT_CODE = SPEC_CODE
1994 self.PLOT_CODE = SPEC_CODE
1789
1995
1790 self.FTP_WEI = None
1996 self.FTP_WEI = None
1791 self.EXP_CODE = None
1997 self.EXP_CODE = None
1792 self.SUB_EXP_CODE = None
1998 self.SUB_EXP_CODE = None
1793 self.PLOT_POS = None
1999 self.PLOT_POS = None
1794
2000
1795 self.__xfilter_ena = False
2001 self.__xfilter_ena = False
1796 self.__yfilter_ena = False
2002 self.__yfilter_ena = False
1797
2003
1798 def getSubplots(self):
2004 def getSubplots(self):
1799
2005
1800 ncol = 3
2006 ncol = 3
1801 nrow = int(numpy.ceil(self.nplots/3.0))
2007 nrow = int(numpy.ceil(self.nplots/3.0))
1802
2008
1803 return nrow, ncol
2009 return nrow, ncol
1804
2010
1805 def setup(self, id, nplots, wintitle, show=True):
2011 def setup(self, id, nplots, wintitle, show=True):
1806
2012
1807 self.nplots = nplots
2013 self.nplots = nplots
1808
2014
1809 ncolspan = 1
2015 ncolspan = 1
1810 colspan = 1
2016 colspan = 1
1811
2017
1812 self.createFigure(id = id,
2018 self.createFigure(id = id,
1813 wintitle = wintitle,
2019 wintitle = wintitle,
1814 widthplot = self.WIDTH + self.WIDTHPROF,
2020 widthplot = self.WIDTH + self.WIDTHPROF,
1815 heightplot = self.HEIGHT + self.HEIGHTPROF,
2021 heightplot = self.HEIGHT + self.HEIGHTPROF,
1816 show=show)
2022 show=show)
1817
2023
1818 nrow, ncol = self.getSubplots()
2024 nrow, ncol = self.getSubplots()
1819
2025
1820 counter = 0
2026 counter = 0
1821 for y in range(nrow):
2027 for y in range(nrow):
1822 for x in range(ncol):
2028 for x in range(ncol):
1823
2029
1824 if counter >= self.nplots:
2030 if counter >= self.nplots:
1825 break
2031 break
1826
2032
1827 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
2033 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1828
2034
1829 counter += 1
2035 counter += 1
1830
2036
1831 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
2037 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1832 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
2038 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1833 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
2039 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1834 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
2040 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1835 server=None, folder=None, username=None, password=None,
2041 server=None, folder=None, username=None, password=None,
1836 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
2042 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1837 xaxis="frequency"):
2043 xaxis="frequency"):
1838
2044
1839 """
2045 """
1840
2046
1841 Input:
2047 Input:
1842 dataOut :
2048 dataOut :
1843 id :
2049 id :
1844 wintitle :
2050 wintitle :
1845 channelList :
2051 channelList :
1846 showProfile :
2052 showProfile :
1847 xmin : None,
2053 xmin : None,
1848 xmax : None,
2054 xmax : None,
1849 ymin : None,
2055 ymin : None,
1850 ymax : None,
2056 ymax : None,
1851 zmin : None,
2057 zmin : None,
1852 zmax : None
2058 zmax : None
1853 """
2059 """
1854 #Rebuild matrix
2060 #Rebuild matrix
1855 utctime = dataOut.data_param[0,0]
2061 utctime = dataOut.data_param[0,0]
1856 cmet = dataOut.data_param[:,1].astype(int)
2062 cmet = dataOut.data_param[:,1].astype(int)
1857 tmet = dataOut.data_param[:,2].astype(int)
2063 tmet = dataOut.data_param[:,2].astype(int)
1858 hmet = dataOut.data_param[:,3].astype(int)
2064 hmet = dataOut.data_param[:,3].astype(int)
1859
2065
1860 nParam = 3
2066 nParam = 3
1861 nChan = len(dataOut.groupList)
2067 nChan = len(dataOut.groupList)
1862 x = dataOut.abscissaList
2068 x = dataOut.abscissaList
1863 y = dataOut.heightList
2069 y = dataOut.heightList
1864
2070
1865 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
2071 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
1866 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
2072 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
1867 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
2073 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
1868 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
2074 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
1869
2075
1870 xlabel = "Time (s)"
2076 xlabel = "Time (s)"
1871 ylabel = "Range (km)"
2077 ylabel = "Range (km)"
1872
2078
1873 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
2079 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1874
2080
1875 if not self.isConfig:
2081 if not self.isConfig:
1876
2082
1877 nplots = nParam*nChan
2083 nplots = nParam*nChan
1878
2084
1879 self.setup(id=id,
2085 self.setup(id=id,
1880 nplots=nplots,
2086 nplots=nplots,
1881 wintitle=wintitle,
2087 wintitle=wintitle,
1882 show=show)
2088 show=show)
1883
2089
1884 if xmin is None: xmin = numpy.nanmin(x)
2090 if xmin is None: xmin = numpy.nanmin(x)
1885 if xmax is None: xmax = numpy.nanmax(x)
2091 if xmax is None: xmax = numpy.nanmax(x)
1886 if ymin is None: ymin = numpy.nanmin(y)
2092 if ymin is None: ymin = numpy.nanmin(y)
1887 if ymax is None: ymax = numpy.nanmax(y)
2093 if ymax is None: ymax = numpy.nanmax(y)
1888 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
2094 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1889 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
2095 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1890 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
2096 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1891 if vmin is None: vmin = -vmax
2097 if vmin is None: vmin = -vmax
1892 if wmin is None: wmin = 0
2098 if wmin is None: wmin = 0
1893 if wmax is None: wmax = 50
2099 if wmax is None: wmax = 50
1894
2100
1895 self.nChannels = nChan
2101 self.nChannels = nChan
1896
2102
1897 zminList = []
2103 zminList = []
1898 zmaxList = []
2104 zmaxList = []
1899 titleList = []
2105 titleList = []
1900 cmapList = []
2106 cmapList = []
1901 for i in range(self.nChannels):
2107 for i in range(self.nChannels):
1902 strAux1 = "SNR Channel "+ str(i)
2108 strAux1 = "SNR Channel "+ str(i)
1903 strAux2 = "Radial Velocity Channel "+ str(i)
2109 strAux2 = "Radial Velocity Channel "+ str(i)
1904 strAux3 = "Spectral Width Channel "+ str(i)
2110 strAux3 = "Spectral Width Channel "+ str(i)
1905
2111
1906 titleList = titleList + [strAux1,strAux2,strAux3]
2112 titleList = titleList + [strAux1,strAux2,strAux3]
1907 cmapList = cmapList + ["jet","RdBu_r","jet"]
2113 cmapList = cmapList + ["jet","RdBu_r","jet"]
1908 zminList = zminList + [SNRmin,vmin,wmin]
2114 zminList = zminList + [SNRmin,vmin,wmin]
1909 zmaxList = zmaxList + [SNRmax,vmax,wmax]
2115 zmaxList = zmaxList + [SNRmax,vmax,wmax]
1910
2116
1911 self.zminList = zminList
2117 self.zminList = zminList
1912 self.zmaxList = zmaxList
2118 self.zmaxList = zmaxList
1913 self.cmapList = cmapList
2119 self.cmapList = cmapList
1914 self.titleList = titleList
2120 self.titleList = titleList
1915
2121
1916 self.FTP_WEI = ftp_wei
2122 self.FTP_WEI = ftp_wei
1917 self.EXP_CODE = exp_code
2123 self.EXP_CODE = exp_code
1918 self.SUB_EXP_CODE = sub_exp_code
2124 self.SUB_EXP_CODE = sub_exp_code
1919 self.PLOT_POS = plot_pos
2125 self.PLOT_POS = plot_pos
1920
2126
1921 self.isConfig = True
2127 self.isConfig = True
1922
2128
1923 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
2129 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1924
2130
1925 for i in range(self.nplots):
2131 for i in range(self.nplots):
1926 title = self.titleList[i] + ": " +str_datetime
2132 title = self.titleList[i] + ": " +str_datetime
1927 axes = self.axesList[i]
2133 axes = self.axesList[i]
1928 axes.pcolor(x, y, z[i,:].T,
2134 axes.pcolor(x, y, z[i,:].T,
1929 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
2135 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1930 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
2136 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1931 self.draw()
2137 self.draw()
1932
2138
1933 if figfile == None:
2139 if figfile == None:
1934 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
2140 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1935 name = str_datetime
2141 name = str_datetime
1936 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
2142 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1937 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
2143 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1938 figfile = self.getFilename(name)
2144 figfile = self.getFilename(name)
1939
2145
1940 self.save(figpath=figpath,
2146 self.save(figpath=figpath,
1941 figfile=figfile,
2147 figfile=figfile,
1942 save=save,
2148 save=save,
1943 ftp=ftp,
2149 ftp=ftp,
1944 wr_period=wr_period,
2150 wr_period=wr_period,
1945 thisDatetime=thisDatetime)
2151 thisDatetime=thisDatetime)
@@ -1,1535 +1,1542
1 '''
1 '''
2 Created on Jul 9, 2014
2 Created on Jul 9, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import datetime
7 import datetime
8 import numpy
8 import numpy
9
9
10 from figure import Figure, isRealtime, isTimeInHourRange
10 from figure import Figure, isRealtime, isTimeInHourRange
11 from plotting_codes import *
11 from plotting_codes import *
12
12
13
13
14 class SpectraPlot(Figure):
14 class SpectraPlot(Figure):
15
15
16 isConfig = None
16 isConfig = None
17 __nsubplots = None
17 __nsubplots = None
18
18
19 WIDTHPROF = None
19 WIDTHPROF = None
20 HEIGHTPROF = None
20 HEIGHTPROF = None
21 PREFIX = 'spc'
21 PREFIX = 'spc'
22
22
23 def __init__(self, **kwargs):
23 def __init__(self, **kwargs):
24 Figure.__init__(self, **kwargs)
24 Figure.__init__(self, **kwargs)
25 self.isConfig = False
25 self.isConfig = False
26 self.__nsubplots = 1
26 self.__nsubplots = 1
27
27
28 self.WIDTH = 1000
28 self.WIDTH = 1000
29 self.HEIGHT = 1000
29 self.HEIGHT = 1000
30 self.WIDTHPROF = 120
30 self.WIDTHPROF = 120
31 self.HEIGHTPROF = 0
31 self.HEIGHTPROF = 0
32 self.counter_imagwr = 0
32 self.counter_imagwr = 0
33
33
34 self.PLOT_CODE = SPEC_CODE
34 self.PLOT_CODE = SPEC_CODE
35
35
36 self.FTP_WEI = None
36 self.FTP_WEI = None
37 self.EXP_CODE = None
37 self.EXP_CODE = None
38 self.SUB_EXP_CODE = None
38 self.SUB_EXP_CODE = None
39 self.PLOT_POS = None
39 self.PLOT_POS = None
40
40
41 self.__xfilter_ena = False
41 self.__xfilter_ena = False
42 self.__yfilter_ena = False
42 self.__yfilter_ena = False
43
43
44 def getSubplots(self):
44 def getSubplots(self):
45
45
46 ncol = int(numpy.sqrt(self.nplots)+0.9)
46 ncol = int(numpy.sqrt(self.nplots)+0.9)
47 nrow = int(self.nplots*1./ncol + 0.9)
47 nrow = int(self.nplots*1./ncol + 0.9)
48
48
49 return nrow, ncol
49 return nrow, ncol
50
50
51 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
51 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
52
52
53 self.__showprofile = showprofile
53 self.__showprofile = showprofile
54 self.nplots = nplots
54 self.nplots = nplots
55
55
56 ncolspan = 1
56 ncolspan = 1
57 colspan = 1
57 colspan = 1
58 if showprofile:
58 if showprofile:
59 ncolspan = 3
59 ncolspan = 3
60 colspan = 2
60 colspan = 2
61 self.__nsubplots = 2
61 self.__nsubplots = 2
62
62
63 self.createFigure(id = id,
63 self.createFigure(id = id,
64 wintitle = wintitle,
64 wintitle = wintitle,
65 widthplot = self.WIDTH + self.WIDTHPROF,
65 widthplot = self.WIDTH + self.WIDTHPROF,
66 heightplot = self.HEIGHT + self.HEIGHTPROF,
66 heightplot = self.HEIGHT + self.HEIGHTPROF,
67 show=show)
67 show=show)
68
68
69 nrow, ncol = self.getSubplots()
69 nrow, ncol = self.getSubplots()
70
70
71 counter = 0
71 counter = 0
72 for y in range(nrow):
72 for y in range(nrow):
73 for x in range(ncol):
73 for x in range(ncol):
74
74
75 if counter >= self.nplots:
75 if counter >= self.nplots:
76 break
76 break
77
77
78 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
78 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
79
79
80 if showprofile:
80 if showprofile:
81 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
81 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
82
82
83 counter += 1
83 counter += 1
84
84
85 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
85 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
86 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
86 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
87 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
87 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
88 server=None, folder=None, username=None, password=None,
88 server=None, folder=None, username=None, password=None,
89 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
89 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
90 xaxis="velocity", **kwargs):
90 xaxis="frequency", colormap='jet', normFactor=None):
91
91
92 """
92 """
93
93
94 Input:
94 Input:
95 dataOut :
95 dataOut :
96 id :
96 id :
97 wintitle :
97 wintitle :
98 channelList :
98 channelList :
99 showProfile :
99 showProfile :
100 xmin : None,
100 xmin : None,
101 xmax : None,
101 xmax : None,
102 ymin : None,
102 ymin : None,
103 ymax : None,
103 ymax : None,
104 zmin : None,
104 zmin : None,
105 zmax : None
105 zmax : None
106 """
106 """
107
108 colormap = kwargs.get('colormap','jet')
109
110 if realtime:
107 if realtime:
111 if not(isRealtime(utcdatatime = dataOut.utctime)):
108 if not(isRealtime(utcdatatime = dataOut.utctime)):
112 print 'Skipping this plot function'
109 print 'Skipping this plot function'
113 return
110 return
114
111
115 if channelList == None:
112 if channelList == None:
116 channelIndexList = dataOut.channelIndexList
113 channelIndexList = dataOut.channelIndexList
117 else:
114 else:
118 channelIndexList = []
115 channelIndexList = []
119 for channel in channelList:
116 for channel in channelList:
120 if channel not in dataOut.channelList:
117 if channel not in dataOut.channelList:
121 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
118 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
122 channelIndexList.append(dataOut.channelList.index(channel))
119 channelIndexList.append(dataOut.channelList.index(channel))
123
120
124 factor = dataOut.normFactor
121 if normFactor is None:
125
122 factor = dataOut.normFactor
123 else:
124 factor = normFactor
126 if xaxis == "frequency":
125 if xaxis == "frequency":
127 x = dataOut.getFreqRange(1)/1000.
126 x = dataOut.getFreqRange(1)/1000.
128 xlabel = "Frequency (kHz)"
127 xlabel = "Frequency (kHz)"
129
128
130 elif xaxis == "time":
129 elif xaxis == "time":
131 x = dataOut.getAcfRange(1)
130 x = dataOut.getAcfRange(1)
132 xlabel = "Time (ms)"
131 xlabel = "Time (ms)"
133
132
134 else:
133 else:
135 x = dataOut.getVelRange(1)
134 x = dataOut.getVelRange(1)
136 xlabel = "Velocity (m/s)"
135 xlabel = "Velocity (m/s)"
137
136
138 ylabel = "Range (Km)"
137 ylabel = "Range (Km)"
139
138
140 y = dataOut.getHeiRange()
139 y = dataOut.getHeiRange()
141
140
142 z = dataOut.data_spc/factor
141 z = dataOut.data_spc/factor
143 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
142 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
144 zdB = 10*numpy.log10(z)
143 zdB = 10*numpy.log10(z)
145
144
146 avg = numpy.average(z, axis=1)
145 avg = numpy.average(z, axis=1)
147 avgdB = 10*numpy.log10(avg)
146 avgdB = 10*numpy.log10(avg)
148
147
149 noise = dataOut.getNoise()/factor
148 noise = dataOut.getNoise()/factor
150 noisedB = 10*numpy.log10(noise)
149 noisedB = 10*numpy.log10(noise)
151
150
152 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
151 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
153 title = wintitle + " Spectra"
152 title = wintitle + " Spectra"
154 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
153 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
155 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
154 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
156
155
157 if not self.isConfig:
156 if not self.isConfig:
158
157
159 nplots = len(channelIndexList)
158 nplots = len(channelIndexList)
160
159
161 self.setup(id=id,
160 self.setup(id=id,
162 nplots=nplots,
161 nplots=nplots,
163 wintitle=wintitle,
162 wintitle=wintitle,
164 showprofile=showprofile,
163 showprofile=showprofile,
165 show=show)
164 show=show)
166
165
167 if xmin == None: xmin = numpy.nanmin(x)
166 if xmin == None: xmin = numpy.nanmin(x)
168 if xmax == None: xmax = numpy.nanmax(x)
167 if xmax == None: xmax = numpy.nanmax(x)
169 if ymin == None: ymin = numpy.nanmin(y)
168 if ymin == None: ymin = numpy.nanmin(y)
170 if ymax == None: ymax = numpy.nanmax(y)
169 if ymax == None: ymax = numpy.nanmax(y)
171 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
170 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
172 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
171 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
173
172
174 self.FTP_WEI = ftp_wei
173 self.FTP_WEI = ftp_wei
175 self.EXP_CODE = exp_code
174 self.EXP_CODE = exp_code
176 self.SUB_EXP_CODE = sub_exp_code
175 self.SUB_EXP_CODE = sub_exp_code
177 self.PLOT_POS = plot_pos
176 self.PLOT_POS = plot_pos
178
177
179 self.isConfig = True
178 self.isConfig = True
180
179
181 self.setWinTitle(title)
180 self.setWinTitle(title)
182
181
183 for i in range(self.nplots):
182 for i in range(self.nplots):
184 index = channelIndexList[i]
183 index = channelIndexList[i]
185 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
184 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
186 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
185 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
187 if len(dataOut.beam.codeList) != 0:
186 if len(dataOut.beam.codeList) != 0:
188 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
187 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
189
188
190 axes = self.axesList[i*self.__nsubplots]
189 axes = self.axesList[i*self.__nsubplots]
191 axes.pcolor(x, y, zdB[index,:,:],
190 axes.pcolor(x, y, zdB[index,:,:],
192 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
191 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
193 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
192 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
194 ticksize=9, cblabel='')
193 ticksize=9, cblabel='')
195
194
196 if self.__showprofile:
195 if self.__showprofile:
197 axes = self.axesList[i*self.__nsubplots +1]
196 axes = self.axesList[i*self.__nsubplots +1]
198 axes.pline(avgdB[index,:], y,
197 axes.pline(avgdB[index,:], y,
199 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
198 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
200 xlabel='dB', ylabel='', title='',
199 xlabel='dB', ylabel='', title='',
201 ytick_visible=False,
200 ytick_visible=False,
202 grid='x')
201 grid='x')
203
202
204 noiseline = numpy.repeat(noisedB[index], len(y))
203 noiseline = numpy.repeat(noisedB[index], len(y))
205 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
204 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
206
205
207 self.draw()
206 self.draw()
208
207
209 if figfile == None:
208 if figfile == None:
210 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
209 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
211 name = str_datetime
210 name = str_datetime
212 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
211 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
213 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
212 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
214 figfile = self.getFilename(name)
213 figfile = self.getFilename(name)
215
214
216 self.save(figpath=figpath,
215 self.save(figpath=figpath,
217 figfile=figfile,
216 figfile=figfile,
218 save=save,
217 save=save,
219 ftp=ftp,
218 ftp=ftp,
220 wr_period=wr_period,
219 wr_period=wr_period,
221 thisDatetime=thisDatetime)
220 thisDatetime=thisDatetime)
222
221
223 class CrossSpectraPlot(Figure):
222 class CrossSpectraPlot(Figure):
224
223
225 isConfig = None
224 isConfig = None
226 __nsubplots = None
225 __nsubplots = None
227
226
228 WIDTH = None
227 WIDTH = None
229 HEIGHT = None
228 HEIGHT = None
230 WIDTHPROF = None
229 WIDTHPROF = None
231 HEIGHTPROF = None
230 HEIGHTPROF = None
232 PREFIX = 'cspc'
231 PREFIX = 'cspc'
233
232
234 def __init__(self, **kwargs):
233 def __init__(self, **kwargs):
235 Figure.__init__(self, **kwargs)
234 Figure.__init__(self, **kwargs)
236 self.isConfig = False
235 self.isConfig = False
237 self.__nsubplots = 4
236 self.__nsubplots = 4
238 self.counter_imagwr = 0
237 self.counter_imagwr = 0
239 self.WIDTH = 250
238 self.WIDTH = 250
240 self.HEIGHT = 250
239 self.HEIGHT = 250
241 self.WIDTHPROF = 0
240 self.WIDTHPROF = 0
242 self.HEIGHTPROF = 0
241 self.HEIGHTPROF = 0
243
242
244 self.PLOT_CODE = CROSS_CODE
243 self.PLOT_CODE = CROSS_CODE
245 self.FTP_WEI = None
244 self.FTP_WEI = None
246 self.EXP_CODE = None
245 self.EXP_CODE = None
247 self.SUB_EXP_CODE = None
246 self.SUB_EXP_CODE = None
248 self.PLOT_POS = None
247 self.PLOT_POS = None
249
248
250 def getSubplots(self):
249 def getSubplots(self):
251
250
252 ncol = 4
251 ncol = 4
253 nrow = self.nplots
252 nrow = self.nplots
254
253
255 return nrow, ncol
254 return nrow, ncol
256
255
257 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
256 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
258
257
259 self.__showprofile = showprofile
258 self.__showprofile = showprofile
260 self.nplots = nplots
259 self.nplots = nplots
261
260
262 ncolspan = 1
261 ncolspan = 1
263 colspan = 1
262 colspan = 1
264
263
265 self.createFigure(id = id,
264 self.createFigure(id = id,
266 wintitle = wintitle,
265 wintitle = wintitle,
267 widthplot = self.WIDTH + self.WIDTHPROF,
266 widthplot = self.WIDTH + self.WIDTHPROF,
268 heightplot = self.HEIGHT + self.HEIGHTPROF,
267 heightplot = self.HEIGHT + self.HEIGHTPROF,
269 show=True)
268 show=True)
270
269
271 nrow, ncol = self.getSubplots()
270 nrow, ncol = self.getSubplots()
272
271
273 counter = 0
272 counter = 0
274 for y in range(nrow):
273 for y in range(nrow):
275 for x in range(ncol):
274 for x in range(ncol):
276 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
275 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
277
276
278 counter += 1
277 counter += 1
279
278
280 def run(self, dataOut, id, wintitle="", pairsList=None,
279 def run(self, dataOut, id, wintitle="", pairsList=None,
281 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
280 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
282 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
281 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
283 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
282 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
284 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
283 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
285 server=None, folder=None, username=None, password=None,
284 server=None, folder=None, username=None, password=None,
286 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0,
285 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None,
287 xaxis='frequency'):
286 xaxis='frequency'):
288
287
289 """
288 """
290
289
291 Input:
290 Input:
292 dataOut :
291 dataOut :
293 id :
292 id :
294 wintitle :
293 wintitle :
295 channelList :
294 channelList :
296 showProfile :
295 showProfile :
297 xmin : None,
296 xmin : None,
298 xmax : None,
297 xmax : None,
299 ymin : None,
298 ymin : None,
300 ymax : None,
299 ymax : None,
301 zmin : None,
300 zmin : None,
302 zmax : None
301 zmax : None
303 """
302 """
304
303
305 if pairsList == None:
304 if pairsList == None:
306 pairsIndexList = dataOut.pairsIndexList
305 pairsIndexList = dataOut.pairsIndexList
307 else:
306 else:
308 pairsIndexList = []
307 pairsIndexList = []
309 for pair in pairsList:
308 for pair in pairsList:
310 if pair not in dataOut.pairsList:
309 if pair not in dataOut.pairsList:
311 raise ValueError, "Pair %s is not in dataOut.pairsList" %str(pair)
310 raise ValueError, "Pair %s is not in dataOut.pairsList" %str(pair)
312 pairsIndexList.append(dataOut.pairsList.index(pair))
311 pairsIndexList.append(dataOut.pairsList.index(pair))
313
312
314 if not pairsIndexList:
313 if not pairsIndexList:
315 return
314 return
316
315
317 if len(pairsIndexList) > 4:
316 if len(pairsIndexList) > 4:
318 pairsIndexList = pairsIndexList[0:4]
317 pairsIndexList = pairsIndexList[0:4]
319
318
320 factor = dataOut.normFactor
319 if normFactor is None:
320 factor = dataOut.normFactor
321 else:
322 factor = normFactor
321 x = dataOut.getVelRange(1)
323 x = dataOut.getVelRange(1)
322 y = dataOut.getHeiRange()
324 y = dataOut.getHeiRange()
323 z = dataOut.data_spc[:,:,:]/factor
325 z = dataOut.data_spc[:,:,:]/factor
324 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
326 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
325
327
326 noise = dataOut.noise/factor
328 noise = dataOut.noise/factor
327
329
328 zdB = 10*numpy.log10(z)
330 zdB = 10*numpy.log10(z)
329 noisedB = 10*numpy.log10(noise)
331 noisedB = 10*numpy.log10(noise)
330
332
331 if coh_min == None:
333 if coh_min == None:
332 coh_min = 0.0
334 coh_min = 0.0
333 if coh_max == None:
335 if coh_max == None:
334 coh_max = 1.0
336 coh_max = 1.0
335
337
336 if phase_min == None:
338 if phase_min == None:
337 phase_min = -180
339 phase_min = -180
338 if phase_max == None:
340 if phase_max == None:
339 phase_max = 180
341 phase_max = 180
340
342
341 #thisDatetime = dataOut.datatime
343 #thisDatetime = dataOut.datatime
342 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
344 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
343 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
345 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
344 # xlabel = "Velocity (m/s)"
346 # xlabel = "Velocity (m/s)"
345 ylabel = "Range (Km)"
347 ylabel = "Range (Km)"
346
348
347 if xaxis == "frequency":
349 if xaxis == "frequency":
348 x = dataOut.getFreqRange(1)/1000.
350 x = dataOut.getFreqRange(1)/1000.
349 xlabel = "Frequency (kHz)"
351 xlabel = "Frequency (kHz)"
350
352
351 elif xaxis == "time":
353 elif xaxis == "time":
352 x = dataOut.getAcfRange(1)
354 x = dataOut.getAcfRange(1)
353 xlabel = "Time (ms)"
355 xlabel = "Time (ms)"
354
356
355 else:
357 else:
356 x = dataOut.getVelRange(1)
358 x = dataOut.getVelRange(1)
357 xlabel = "Velocity (m/s)"
359 xlabel = "Velocity (m/s)"
358
360
359 if not self.isConfig:
361 if not self.isConfig:
360
362
361 nplots = len(pairsIndexList)
363 nplots = len(pairsIndexList)
362
364
363 self.setup(id=id,
365 self.setup(id=id,
364 nplots=nplots,
366 nplots=nplots,
365 wintitle=wintitle,
367 wintitle=wintitle,
366 showprofile=False,
368 showprofile=False,
367 show=show)
369 show=show)
368
370
369 avg = numpy.abs(numpy.average(z, axis=1))
371 avg = numpy.abs(numpy.average(z, axis=1))
370 avgdB = 10*numpy.log10(avg)
372 avgdB = 10*numpy.log10(avg)
371
373
372 if xmin == None: xmin = numpy.nanmin(x)
374 if xmin == None: xmin = numpy.nanmin(x)
373 if xmax == None: xmax = numpy.nanmax(x)
375 if xmax == None: xmax = numpy.nanmax(x)
374 if ymin == None: ymin = numpy.nanmin(y)
376 if ymin == None: ymin = numpy.nanmin(y)
375 if ymax == None: ymax = numpy.nanmax(y)
377 if ymax == None: ymax = numpy.nanmax(y)
376 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
378 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
377 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
379 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
378
380
379 self.FTP_WEI = ftp_wei
381 self.FTP_WEI = ftp_wei
380 self.EXP_CODE = exp_code
382 self.EXP_CODE = exp_code
381 self.SUB_EXP_CODE = sub_exp_code
383 self.SUB_EXP_CODE = sub_exp_code
382 self.PLOT_POS = plot_pos
384 self.PLOT_POS = plot_pos
383
385
384 self.isConfig = True
386 self.isConfig = True
385
387
386 self.setWinTitle(title)
388 self.setWinTitle(title)
387
389
388 for i in range(self.nplots):
390 for i in range(self.nplots):
389 pair = dataOut.pairsList[pairsIndexList[i]]
391 pair = dataOut.pairsList[pairsIndexList[i]]
390
392
391 chan_index0 = dataOut.channelList.index(pair[0])
393 chan_index0 = dataOut.channelList.index(pair[0])
392 chan_index1 = dataOut.channelList.index(pair[1])
394 chan_index1 = dataOut.channelList.index(pair[1])
393
395
394 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
396 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
395 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
397 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
396 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
398 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
397 axes0 = self.axesList[i*self.__nsubplots]
399 axes0 = self.axesList[i*self.__nsubplots]
398 axes0.pcolor(x, y, zdB,
400 axes0.pcolor(x, y, zdB,
399 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
401 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
400 xlabel=xlabel, ylabel=ylabel, title=title,
402 xlabel=xlabel, ylabel=ylabel, title=title,
401 ticksize=9, colormap=power_cmap, cblabel='')
403 ticksize=9, colormap=power_cmap, cblabel='')
402
404
403 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
405 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
404 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
406 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
405 axes0 = self.axesList[i*self.__nsubplots+1]
407 axes0 = self.axesList[i*self.__nsubplots+1]
406 axes0.pcolor(x, y, zdB,
408 axes0.pcolor(x, y, zdB,
407 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
409 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
408 xlabel=xlabel, ylabel=ylabel, title=title,
410 xlabel=xlabel, ylabel=ylabel, title=title,
409 ticksize=9, colormap=power_cmap, cblabel='')
411 ticksize=9, colormap=power_cmap, cblabel='')
410
412
411 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:])
413 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:])
412 coherence = numpy.abs(coherenceComplex)
414 coherence = numpy.abs(coherenceComplex)
413 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
415 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
414 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
416 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
415
417
416 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
418 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
417 axes0 = self.axesList[i*self.__nsubplots+2]
419 axes0 = self.axesList[i*self.__nsubplots+2]
418 axes0.pcolor(x, y, coherence,
420 axes0.pcolor(x, y, coherence,
419 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
421 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
420 xlabel=xlabel, ylabel=ylabel, title=title,
422 xlabel=xlabel, ylabel=ylabel, title=title,
421 ticksize=9, colormap=coherence_cmap, cblabel='')
423 ticksize=9, colormap=coherence_cmap, cblabel='')
422
424
423 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
425 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
424 axes0 = self.axesList[i*self.__nsubplots+3]
426 axes0 = self.axesList[i*self.__nsubplots+3]
425 axes0.pcolor(x, y, phase,
427 axes0.pcolor(x, y, phase,
426 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
428 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
427 xlabel=xlabel, ylabel=ylabel, title=title,
429 xlabel=xlabel, ylabel=ylabel, title=title,
428 ticksize=9, colormap=phase_cmap, cblabel='')
430 ticksize=9, colormap=phase_cmap, cblabel='')
429
431
430
432
431
433
432 self.draw()
434 self.draw()
433
435
434 self.save(figpath=figpath,
436 self.save(figpath=figpath,
435 figfile=figfile,
437 figfile=figfile,
436 save=save,
438 save=save,
437 ftp=ftp,
439 ftp=ftp,
438 wr_period=wr_period,
440 wr_period=wr_period,
439 thisDatetime=thisDatetime)
441 thisDatetime=thisDatetime)
440
442
441
443
442 class RTIPlot(Figure):
444 class RTIPlot(Figure):
443
445
444 __isConfig = None
446 __isConfig = None
445 __nsubplots = None
447 __nsubplots = None
446
448
447 WIDTHPROF = None
449 WIDTHPROF = None
448 HEIGHTPROF = None
450 HEIGHTPROF = None
449 PREFIX = 'rti'
451 PREFIX = 'rti'
450
452
451 def __init__(self, **kwargs):
453 def __init__(self, **kwargs):
452
454
453 Figure.__init__(self, **kwargs)
455 Figure.__init__(self, **kwargs)
454 self.timerange = None
456 self.timerange = None
455 self.isConfig = False
457 self.isConfig = False
456 self.__nsubplots = 1
458 self.__nsubplots = 1
457
459
458 self.WIDTH = 800
460 self.WIDTH = 800
459 self.HEIGHT = 180
461 self.HEIGHT = 180
460 self.WIDTHPROF = 120
462 self.WIDTHPROF = 120
461 self.HEIGHTPROF = 0
463 self.HEIGHTPROF = 0
462 self.counter_imagwr = 0
464 self.counter_imagwr = 0
463
465
464 self.PLOT_CODE = RTI_CODE
466 self.PLOT_CODE = RTI_CODE
465
467
466 self.FTP_WEI = None
468 self.FTP_WEI = None
467 self.EXP_CODE = None
469 self.EXP_CODE = None
468 self.SUB_EXP_CODE = None
470 self.SUB_EXP_CODE = None
469 self.PLOT_POS = None
471 self.PLOT_POS = None
470 self.tmin = None
472 self.tmin = None
471 self.tmax = None
473 self.tmax = None
472
474
473 self.xmin = None
475 self.xmin = None
474 self.xmax = None
476 self.xmax = None
475
477
476 self.figfile = None
478 self.figfile = None
477
479
478 def getSubplots(self):
480 def getSubplots(self):
479
481
480 ncol = 1
482 ncol = 1
481 nrow = self.nplots
483 nrow = self.nplots
482
484
483 return nrow, ncol
485 return nrow, ncol
484
486
485 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
487 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
486
488
487 self.__showprofile = showprofile
489 self.__showprofile = showprofile
488 self.nplots = nplots
490 self.nplots = nplots
489
491
490 ncolspan = 1
492 ncolspan = 1
491 colspan = 1
493 colspan = 1
492 if showprofile:
494 if showprofile:
493 ncolspan = 7
495 ncolspan = 7
494 colspan = 6
496 colspan = 6
495 self.__nsubplots = 2
497 self.__nsubplots = 2
496
498
497 self.createFigure(id = id,
499 self.createFigure(id = id,
498 wintitle = wintitle,
500 wintitle = wintitle,
499 widthplot = self.WIDTH + self.WIDTHPROF,
501 widthplot = self.WIDTH + self.WIDTHPROF,
500 heightplot = self.HEIGHT + self.HEIGHTPROF,
502 heightplot = self.HEIGHT + self.HEIGHTPROF,
501 show=show)
503 show=show)
502
504
503 nrow, ncol = self.getSubplots()
505 nrow, ncol = self.getSubplots()
504
506
505 counter = 0
507 counter = 0
506 for y in range(nrow):
508 for y in range(nrow):
507 for x in range(ncol):
509 for x in range(ncol):
508
510
509 if counter >= self.nplots:
511 if counter >= self.nplots:
510 break
512 break
511
513
512 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
514 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
513
515
514 if showprofile:
516 if showprofile:
515 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
517 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
516
518
517 counter += 1
519 counter += 1
518
520
519 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
521 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
520 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
522 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
521 timerange=None,
523 timerange=None, colormap='jet',
522 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
524 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
523 server=None, folder=None, username=None, password=None,
525 server=None, folder=None, username=None, password=None,
524 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, **kwargs):
526 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None, HEIGHT=None):
525
527
526 """
528 """
527
529
528 Input:
530 Input:
529 dataOut :
531 dataOut :
530 id :
532 id :
531 wintitle :
533 wintitle :
532 channelList :
534 channelList :
533 showProfile :
535 showProfile :
534 xmin : None,
536 xmin : None,
535 xmax : None,
537 xmax : None,
536 ymin : None,
538 ymin : None,
537 ymax : None,
539 ymax : None,
538 zmin : None,
540 zmin : None,
539 zmax : None
541 zmax : None
540 """
542 """
541
543
542 colormap = kwargs.get('colormap', 'jet')
544 #colormap = kwargs.get('colormap', 'jet')
545 if HEIGHT is not None:
546 self.HEIGHT = HEIGHT
547
543 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
548 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
544 return
549 return
545
550
546 if channelList == None:
551 if channelList == None:
547 channelIndexList = dataOut.channelIndexList
552 channelIndexList = dataOut.channelIndexList
548 else:
553 else:
549 channelIndexList = []
554 channelIndexList = []
550 for channel in channelList:
555 for channel in channelList:
551 if channel not in dataOut.channelList:
556 if channel not in dataOut.channelList:
552 raise ValueError, "Channel %d is not in dataOut.channelList"
557 raise ValueError, "Channel %d is not in dataOut.channelList"
553 channelIndexList.append(dataOut.channelList.index(channel))
558 channelIndexList.append(dataOut.channelList.index(channel))
554
559
555 if hasattr(dataOut, 'normFactor'):
560 if normFactor is None:
556 factor = dataOut.normFactor
561 factor = dataOut.normFactor
557 else:
562 else:
558 factor = 1
563 factor = normFactor
559
564
560 # factor = dataOut.normFactor
565 # factor = dataOut.normFactor
561 x = dataOut.getTimeRange()
566 x = dataOut.getTimeRange()
562 y = dataOut.getHeiRange()
567 y = dataOut.getHeiRange()
563
568
564 # z = dataOut.data_spc/factor
569 z = dataOut.data_spc/factor
565 # z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
570 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
566 # avg = numpy.average(z, axis=1)
571 avg = numpy.average(z, axis=1)
567 # avgdB = 10.*numpy.log10(avg)
572 avgdB = 10.*numpy.log10(avg)
568 avgdB = dataOut.getPower()
573 # avgdB = dataOut.getPower()
574
569
575
570 thisDatetime = dataOut.datatime
576 thisDatetime = dataOut.datatime
571 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
577 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
572 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
578 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
573 xlabel = ""
579 xlabel = ""
574 ylabel = "Range (Km)"
580 ylabel = "Range (Km)"
575
581
576 update_figfile = False
582 update_figfile = False
577
583
578 if dataOut.ltctime >= self.xmax:
584 if dataOut.ltctime >= self.xmax:
579 self.counter_imagwr = wr_period
585 self.counter_imagwr = wr_period
580 self.isConfig = False
586 self.isConfig = False
581 update_figfile = True
587 update_figfile = True
582
588
583 if not self.isConfig:
589 if not self.isConfig:
584
590
585 nplots = len(channelIndexList)
591 nplots = len(channelIndexList)
586
592
587 self.setup(id=id,
593 self.setup(id=id,
588 nplots=nplots,
594 nplots=nplots,
589 wintitle=wintitle,
595 wintitle=wintitle,
590 showprofile=showprofile,
596 showprofile=showprofile,
591 show=show)
597 show=show)
592
598
593 if timerange != None:
599 if timerange != None:
594 self.timerange = timerange
600 self.timerange = timerange
595
601
596 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
602 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
597
603
598 noise = dataOut.noise/factor
604 noise = dataOut.noise/factor
599 noisedB = 10*numpy.log10(noise)
605 noisedB = 10*numpy.log10(noise)
600
606
601 if ymin == None: ymin = numpy.nanmin(y)
607 if ymin == None: ymin = numpy.nanmin(y)
602 if ymax == None: ymax = numpy.nanmax(y)
608 if ymax == None: ymax = numpy.nanmax(y)
603 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
609 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
604 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
610 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
605
611
606 self.FTP_WEI = ftp_wei
612 self.FTP_WEI = ftp_wei
607 self.EXP_CODE = exp_code
613 self.EXP_CODE = exp_code
608 self.SUB_EXP_CODE = sub_exp_code
614 self.SUB_EXP_CODE = sub_exp_code
609 self.PLOT_POS = plot_pos
615 self.PLOT_POS = plot_pos
610
616
611 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
617 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
612 self.isConfig = True
618 self.isConfig = True
613 self.figfile = figfile
619 self.figfile = figfile
614 update_figfile = True
620 update_figfile = True
615
621
616 self.setWinTitle(title)
622 self.setWinTitle(title)
617
623
618 for i in range(self.nplots):
624 for i in range(self.nplots):
619 index = channelIndexList[i]
625 index = channelIndexList[i]
620 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
626 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
621 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
627 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
622 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
628 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
623 axes = self.axesList[i*self.__nsubplots]
629 axes = self.axesList[i*self.__nsubplots]
624 zdB = avgdB[index].reshape((1,-1))
630 zdB = avgdB[index].reshape((1,-1))
625 axes.pcolorbuffer(x, y, zdB,
631 axes.pcolorbuffer(x, y, zdB,
626 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
632 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
627 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
633 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
628 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
634 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
629
635
630 if self.__showprofile:
636 if self.__showprofile:
631 axes = self.axesList[i*self.__nsubplots +1]
637 axes = self.axesList[i*self.__nsubplots +1]
632 axes.pline(avgdB[index], y,
638 axes.pline(avgdB[index], y,
633 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
639 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
634 xlabel='dB', ylabel='', title='',
640 xlabel='dB', ylabel='', title='',
635 ytick_visible=False,
641 ytick_visible=False,
636 grid='x')
642 grid='x')
637
643
638 self.draw()
644 self.draw()
639
645
640 self.save(figpath=figpath,
646 self.save(figpath=figpath,
641 figfile=figfile,
647 figfile=figfile,
642 save=save,
648 save=save,
643 ftp=ftp,
649 ftp=ftp,
644 wr_period=wr_period,
650 wr_period=wr_period,
645 thisDatetime=thisDatetime,
651 thisDatetime=thisDatetime,
646 update_figfile=update_figfile)
652 update_figfile=update_figfile)
647
653
648 class CoherenceMap(Figure):
654 class CoherenceMap(Figure):
649 isConfig = None
655 isConfig = None
650 __nsubplots = None
656 __nsubplots = None
651
657
652 WIDTHPROF = None
658 WIDTHPROF = None
653 HEIGHTPROF = None
659 HEIGHTPROF = None
654 PREFIX = 'cmap'
660 PREFIX = 'cmap'
655
661
656 def __init__(self, **kwargs):
662 def __init__(self, **kwargs):
657 Figure.__init__(self, **kwargs)
663 Figure.__init__(self, **kwargs)
658 self.timerange = 2*60*60
664 self.timerange = 2*60*60
659 self.isConfig = False
665 self.isConfig = False
660 self.__nsubplots = 1
666 self.__nsubplots = 1
661
667
662 self.WIDTH = 800
668 self.WIDTH = 800
663 self.HEIGHT = 180
669 self.HEIGHT = 180
664 self.WIDTHPROF = 120
670 self.WIDTHPROF = 120
665 self.HEIGHTPROF = 0
671 self.HEIGHTPROF = 0
666 self.counter_imagwr = 0
672 self.counter_imagwr = 0
667
673
668 self.PLOT_CODE = COH_CODE
674 self.PLOT_CODE = COH_CODE
669
675
670 self.FTP_WEI = None
676 self.FTP_WEI = None
671 self.EXP_CODE = None
677 self.EXP_CODE = None
672 self.SUB_EXP_CODE = None
678 self.SUB_EXP_CODE = None
673 self.PLOT_POS = None
679 self.PLOT_POS = None
674 self.counter_imagwr = 0
680 self.counter_imagwr = 0
675
681
676 self.xmin = None
682 self.xmin = None
677 self.xmax = None
683 self.xmax = None
678
684
679 def getSubplots(self):
685 def getSubplots(self):
680 ncol = 1
686 ncol = 1
681 nrow = self.nplots*2
687 nrow = self.nplots*2
682
688
683 return nrow, ncol
689 return nrow, ncol
684
690
685 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
691 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
686 self.__showprofile = showprofile
692 self.__showprofile = showprofile
687 self.nplots = nplots
693 self.nplots = nplots
688
694
689 ncolspan = 1
695 ncolspan = 1
690 colspan = 1
696 colspan = 1
691 if showprofile:
697 if showprofile:
692 ncolspan = 7
698 ncolspan = 7
693 colspan = 6
699 colspan = 6
694 self.__nsubplots = 2
700 self.__nsubplots = 2
695
701
696 self.createFigure(id = id,
702 self.createFigure(id = id,
697 wintitle = wintitle,
703 wintitle = wintitle,
698 widthplot = self.WIDTH + self.WIDTHPROF,
704 widthplot = self.WIDTH + self.WIDTHPROF,
699 heightplot = self.HEIGHT + self.HEIGHTPROF,
705 heightplot = self.HEIGHT + self.HEIGHTPROF,
700 show=True)
706 show=True)
701
707
702 nrow, ncol = self.getSubplots()
708 nrow, ncol = self.getSubplots()
703
709
704 for y in range(nrow):
710 for y in range(nrow):
705 for x in range(ncol):
711 for x in range(ncol):
706
712
707 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
713 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
708
714
709 if showprofile:
715 if showprofile:
710 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
716 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
711
717
712 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
718 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
713 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
719 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
714 timerange=None, phase_min=None, phase_max=None,
720 timerange=None, phase_min=None, phase_max=None,
715 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
721 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
716 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
722 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
717 server=None, folder=None, username=None, password=None,
723 server=None, folder=None, username=None, password=None,
718 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
724 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
719
725
720 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
726 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
721 return
727 return
722
728
723 if pairsList == None:
729 if pairsList == None:
724 pairsIndexList = dataOut.pairsIndexList
730 pairsIndexList = dataOut.pairsIndexList
725 else:
731 else:
726 pairsIndexList = []
732 pairsIndexList = []
727 for pair in pairsList:
733 for pair in pairsList:
728 if pair not in dataOut.pairsList:
734 if pair not in dataOut.pairsList:
729 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
735 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
730 pairsIndexList.append(dataOut.pairsList.index(pair))
736 pairsIndexList.append(dataOut.pairsList.index(pair))
731
737
732 if pairsIndexList == []:
738 if pairsIndexList == []:
733 return
739 return
734
740
735 if len(pairsIndexList) > 4:
741 if len(pairsIndexList) > 4:
736 pairsIndexList = pairsIndexList[0:4]
742 pairsIndexList = pairsIndexList[0:4]
737
743
738 if phase_min == None:
744 if phase_min == None:
739 phase_min = -180
745 phase_min = -180
740 if phase_max == None:
746 if phase_max == None:
741 phase_max = 180
747 phase_max = 180
742
748
743 x = dataOut.getTimeRange()
749 x = dataOut.getTimeRange()
744 y = dataOut.getHeiRange()
750 y = dataOut.getHeiRange()
745
751
746 thisDatetime = dataOut.datatime
752 thisDatetime = dataOut.datatime
747
753
748 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
754 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
749 xlabel = ""
755 xlabel = ""
750 ylabel = "Range (Km)"
756 ylabel = "Range (Km)"
751 update_figfile = False
757 update_figfile = False
752
758
753 if not self.isConfig:
759 if not self.isConfig:
754 nplots = len(pairsIndexList)
760 nplots = len(pairsIndexList)
755 self.setup(id=id,
761 self.setup(id=id,
756 nplots=nplots,
762 nplots=nplots,
757 wintitle=wintitle,
763 wintitle=wintitle,
758 showprofile=showprofile,
764 showprofile=showprofile,
759 show=show)
765 show=show)
760
766
761 if timerange != None:
767 if timerange != None:
762 self.timerange = timerange
768 self.timerange = timerange
763
769
764 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
770 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
765
771
766 if ymin == None: ymin = numpy.nanmin(y)
772 if ymin == None: ymin = numpy.nanmin(y)
767 if ymax == None: ymax = numpy.nanmax(y)
773 if ymax == None: ymax = numpy.nanmax(y)
768 if zmin == None: zmin = 0.
774 if zmin == None: zmin = 0.
769 if zmax == None: zmax = 1.
775 if zmax == None: zmax = 1.
770
776
771 self.FTP_WEI = ftp_wei
777 self.FTP_WEI = ftp_wei
772 self.EXP_CODE = exp_code
778 self.EXP_CODE = exp_code
773 self.SUB_EXP_CODE = sub_exp_code
779 self.SUB_EXP_CODE = sub_exp_code
774 self.PLOT_POS = plot_pos
780 self.PLOT_POS = plot_pos
775
781
776 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
782 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
777
783
778 self.isConfig = True
784 self.isConfig = True
779 update_figfile = True
785 update_figfile = True
780
786
781 self.setWinTitle(title)
787 self.setWinTitle(title)
782
788
783 for i in range(self.nplots):
789 for i in range(self.nplots):
784
790
785 pair = dataOut.pairsList[pairsIndexList[i]]
791 pair = dataOut.pairsList[pairsIndexList[i]]
786
792
787 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
793 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
788 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
794 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
789 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
795 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
790
796
791
797
792 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
798 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
793 coherence = numpy.abs(avgcoherenceComplex)
799 coherence = numpy.abs(avgcoherenceComplex)
794
800
795 z = coherence.reshape((1,-1))
801 z = coherence.reshape((1,-1))
796
802
797 counter = 0
803 counter = 0
798
804
799 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
805 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
800 axes = self.axesList[i*self.__nsubplots*2]
806 axes = self.axesList[i*self.__nsubplots*2]
801 axes.pcolorbuffer(x, y, z,
807 axes.pcolorbuffer(x, y, z,
802 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
808 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
803 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
809 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
804 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
810 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
805
811
806 if self.__showprofile:
812 if self.__showprofile:
807 counter += 1
813 counter += 1
808 axes = self.axesList[i*self.__nsubplots*2 + counter]
814 axes = self.axesList[i*self.__nsubplots*2 + counter]
809 axes.pline(coherence, y,
815 axes.pline(coherence, y,
810 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
816 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
811 xlabel='', ylabel='', title='', ticksize=7,
817 xlabel='', ylabel='', title='', ticksize=7,
812 ytick_visible=False, nxticks=5,
818 ytick_visible=False, nxticks=5,
813 grid='x')
819 grid='x')
814
820
815 counter += 1
821 counter += 1
816
822
817 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
823 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
818
824
819 z = phase.reshape((1,-1))
825 z = phase.reshape((1,-1))
820
826
821 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
827 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
822 axes = self.axesList[i*self.__nsubplots*2 + counter]
828 axes = self.axesList[i*self.__nsubplots*2 + counter]
823 axes.pcolorbuffer(x, y, z,
829 axes.pcolorbuffer(x, y, z,
824 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
830 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
825 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
831 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
826 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
832 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
827
833
828 if self.__showprofile:
834 if self.__showprofile:
829 counter += 1
835 counter += 1
830 axes = self.axesList[i*self.__nsubplots*2 + counter]
836 axes = self.axesList[i*self.__nsubplots*2 + counter]
831 axes.pline(phase, y,
837 axes.pline(phase, y,
832 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
838 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
833 xlabel='', ylabel='', title='', ticksize=7,
839 xlabel='', ylabel='', title='', ticksize=7,
834 ytick_visible=False, nxticks=4,
840 ytick_visible=False, nxticks=4,
835 grid='x')
841 grid='x')
836
842
837 self.draw()
843 self.draw()
838
844
839 if dataOut.ltctime >= self.xmax:
845 if dataOut.ltctime >= self.xmax:
840 self.counter_imagwr = wr_period
846 self.counter_imagwr = wr_period
841 self.isConfig = False
847 self.isConfig = False
842 update_figfile = True
848 update_figfile = True
843
849
844 self.save(figpath=figpath,
850 self.save(figpath=figpath,
845 figfile=figfile,
851 figfile=figfile,
846 save=save,
852 save=save,
847 ftp=ftp,
853 ftp=ftp,
848 wr_period=wr_period,
854 wr_period=wr_period,
849 thisDatetime=thisDatetime,
855 thisDatetime=thisDatetime,
850 update_figfile=update_figfile)
856 update_figfile=update_figfile)
851
857
852 class PowerProfilePlot(Figure):
858 class PowerProfilePlot(Figure):
853
859
854 isConfig = None
860 isConfig = None
855 __nsubplots = None
861 __nsubplots = None
856
862
857 WIDTHPROF = None
863 WIDTHPROF = None
858 HEIGHTPROF = None
864 HEIGHTPROF = None
859 PREFIX = 'spcprofile'
865 PREFIX = 'spcprofile'
860
866
861 def __init__(self, **kwargs):
867 def __init__(self, **kwargs):
862 Figure.__init__(self, **kwargs)
868 Figure.__init__(self, **kwargs)
863 self.isConfig = False
869 self.isConfig = False
864 self.__nsubplots = 1
870 self.__nsubplots = 1
865
871
866 self.PLOT_CODE = POWER_CODE
872 self.PLOT_CODE = POWER_CODE
867
873
868 self.WIDTH = 300
874 self.WIDTH = 300
869 self.HEIGHT = 500
875 self.HEIGHT = 500
870 self.counter_imagwr = 0
876 self.counter_imagwr = 0
871
877
872 def getSubplots(self):
878 def getSubplots(self):
873 ncol = 1
879 ncol = 1
874 nrow = 1
880 nrow = 1
875
881
876 return nrow, ncol
882 return nrow, ncol
877
883
878 def setup(self, id, nplots, wintitle, show):
884 def setup(self, id, nplots, wintitle, show):
879
885
880 self.nplots = nplots
886 self.nplots = nplots
881
887
882 ncolspan = 1
888 ncolspan = 1
883 colspan = 1
889 colspan = 1
884
890
885 self.createFigure(id = id,
891 self.createFigure(id = id,
886 wintitle = wintitle,
892 wintitle = wintitle,
887 widthplot = self.WIDTH,
893 widthplot = self.WIDTH,
888 heightplot = self.HEIGHT,
894 heightplot = self.HEIGHT,
889 show=show)
895 show=show)
890
896
891 nrow, ncol = self.getSubplots()
897 nrow, ncol = self.getSubplots()
892
898
893 counter = 0
899 counter = 0
894 for y in range(nrow):
900 for y in range(nrow):
895 for x in range(ncol):
901 for x in range(ncol):
896 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
902 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
897
903
898 def run(self, dataOut, id, wintitle="", channelList=None,
904 def run(self, dataOut, id, wintitle="", channelList=None,
899 xmin=None, xmax=None, ymin=None, ymax=None,
905 xmin=None, xmax=None, ymin=None, ymax=None,
900 save=False, figpath='./', figfile=None, show=True,
906 save=False, figpath='./', figfile=None, show=True,
901 ftp=False, wr_period=1, server=None,
907 ftp=False, wr_period=1, server=None,
902 folder=None, username=None, password=None):
908 folder=None, username=None, password=None):
903
909
904
910
905 if channelList == None:
911 if channelList == None:
906 channelIndexList = dataOut.channelIndexList
912 channelIndexList = dataOut.channelIndexList
907 channelList = dataOut.channelList
913 channelList = dataOut.channelList
908 else:
914 else:
909 channelIndexList = []
915 channelIndexList = []
910 for channel in channelList:
916 for channel in channelList:
911 if channel not in dataOut.channelList:
917 if channel not in dataOut.channelList:
912 raise ValueError, "Channel %d is not in dataOut.channelList"
918 raise ValueError, "Channel %d is not in dataOut.channelList"
913 channelIndexList.append(dataOut.channelList.index(channel))
919 channelIndexList.append(dataOut.channelList.index(channel))
914
920
915 factor = dataOut.normFactor
921 factor = dataOut.normFactor
916
922
917 y = dataOut.getHeiRange()
923 y = dataOut.getHeiRange()
918
924
919 #for voltage
925 #for voltage
920 if dataOut.type == 'Voltage':
926 if dataOut.type == 'Voltage':
921 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
927 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
922 x = x.real
928 x = x.real
923 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
929 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
924
930
925 #for spectra
931 #for spectra
926 if dataOut.type == 'Spectra':
932 if dataOut.type == 'Spectra':
927 x = dataOut.data_spc[channelIndexList,:,:]/factor
933 x = dataOut.data_spc[channelIndexList,:,:]/factor
928 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
934 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
929 x = numpy.average(x, axis=1)
935 x = numpy.average(x, axis=1)
930
936
931
937
932 xdB = 10*numpy.log10(x)
938 xdB = 10*numpy.log10(x)
933
939
934 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
940 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
935 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
941 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
936 xlabel = "dB"
942 xlabel = "dB"
937 ylabel = "Range (Km)"
943 ylabel = "Range (Km)"
938
944
939 if not self.isConfig:
945 if not self.isConfig:
940
946
941 nplots = 1
947 nplots = 1
942
948
943 self.setup(id=id,
949 self.setup(id=id,
944 nplots=nplots,
950 nplots=nplots,
945 wintitle=wintitle,
951 wintitle=wintitle,
946 show=show)
952 show=show)
947
953
948 if ymin == None: ymin = numpy.nanmin(y)
954 if ymin == None: ymin = numpy.nanmin(y)
949 if ymax == None: ymax = numpy.nanmax(y)
955 if ymax == None: ymax = numpy.nanmax(y)
950 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
956 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
951 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
957 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
952
958
953 self.isConfig = True
959 self.isConfig = True
954
960
955 self.setWinTitle(title)
961 self.setWinTitle(title)
956
962
957 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
963 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
958 axes = self.axesList[0]
964 axes = self.axesList[0]
959
965
960 legendlabels = ["channel %d"%x for x in channelList]
966 legendlabels = ["channel %d"%x for x in channelList]
961 axes.pmultiline(xdB, y,
967 axes.pmultiline(xdB, y,
962 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
968 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
963 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
969 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
964 ytick_visible=True, nxticks=5,
970 ytick_visible=True, nxticks=5,
965 grid='x')
971 grid='x')
966
972
967 self.draw()
973 self.draw()
968
974
969 self.save(figpath=figpath,
975 self.save(figpath=figpath,
970 figfile=figfile,
976 figfile=figfile,
971 save=save,
977 save=save,
972 ftp=ftp,
978 ftp=ftp,
973 wr_period=wr_period,
979 wr_period=wr_period,
974 thisDatetime=thisDatetime)
980 thisDatetime=thisDatetime)
975
981
976 class SpectraCutPlot(Figure):
982 class SpectraCutPlot(Figure):
977
983
978 isConfig = None
984 isConfig = None
979 __nsubplots = None
985 __nsubplots = None
980
986
981 WIDTHPROF = None
987 WIDTHPROF = None
982 HEIGHTPROF = None
988 HEIGHTPROF = None
983 PREFIX = 'spc_cut'
989 PREFIX = 'spc_cut'
984
990
985 def __init__(self, **kwargs):
991 def __init__(self, **kwargs):
986 Figure.__init__(self, **kwargs)
992 Figure.__init__(self, **kwargs)
987 self.isConfig = False
993 self.isConfig = False
988 self.__nsubplots = 1
994 self.__nsubplots = 1
989
995
990 self.PLOT_CODE = POWER_CODE
996 self.PLOT_CODE = POWER_CODE
991
997
992 self.WIDTH = 700
998 self.WIDTH = 700
993 self.HEIGHT = 500
999 self.HEIGHT = 500
994 self.counter_imagwr = 0
1000 self.counter_imagwr = 0
995
1001
996 def getSubplots(self):
1002 def getSubplots(self):
997 ncol = 1
1003 ncol = 1
998 nrow = 1
1004 nrow = 1
999
1005
1000 return nrow, ncol
1006 return nrow, ncol
1001
1007
1002 def setup(self, id, nplots, wintitle, show):
1008 def setup(self, id, nplots, wintitle, show):
1003
1009
1004 self.nplots = nplots
1010 self.nplots = nplots
1005
1011
1006 ncolspan = 1
1012 ncolspan = 1
1007 colspan = 1
1013 colspan = 1
1008
1014
1009 self.createFigure(id = id,
1015 self.createFigure(id = id,
1010 wintitle = wintitle,
1016 wintitle = wintitle,
1011 widthplot = self.WIDTH,
1017 widthplot = self.WIDTH,
1012 heightplot = self.HEIGHT,
1018 heightplot = self.HEIGHT,
1013 show=show)
1019 show=show)
1014
1020
1015 nrow, ncol = self.getSubplots()
1021 nrow, ncol = self.getSubplots()
1016
1022
1017 counter = 0
1023 counter = 0
1018 for y in range(nrow):
1024 for y in range(nrow):
1019 for x in range(ncol):
1025 for x in range(ncol):
1020 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1026 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1021
1027
1022 def run(self, dataOut, id, wintitle="", channelList=None,
1028 def run(self, dataOut, id, wintitle="", channelList=None,
1023 xmin=None, xmax=None, ymin=None, ymax=None,
1029 xmin=None, xmax=None, ymin=None, ymax=None,
1024 save=False, figpath='./', figfile=None, show=True,
1030 save=False, figpath='./', figfile=None, show=True,
1025 ftp=False, wr_period=1, server=None,
1031 ftp=False, wr_period=1, server=None,
1026 folder=None, username=None, password=None,
1032 folder=None, username=None, password=None,
1027 xaxis="frequency"):
1033 xaxis="frequency"):
1028
1034
1029
1035
1030 if channelList == None:
1036 if channelList == None:
1031 channelIndexList = dataOut.channelIndexList
1037 channelIndexList = dataOut.channelIndexList
1032 channelList = dataOut.channelList
1038 channelList = dataOut.channelList
1033 else:
1039 else:
1034 channelIndexList = []
1040 channelIndexList = []
1035 for channel in channelList:
1041 for channel in channelList:
1036 if channel not in dataOut.channelList:
1042 if channel not in dataOut.channelList:
1037 raise ValueError, "Channel %d is not in dataOut.channelList"
1043 raise ValueError, "Channel %d is not in dataOut.channelList"
1038 channelIndexList.append(dataOut.channelList.index(channel))
1044 channelIndexList.append(dataOut.channelList.index(channel))
1039
1045
1040 factor = dataOut.normFactor
1046 factor = dataOut.normFactor
1041
1047
1042 y = dataOut.getHeiRange()
1048 y = dataOut.getHeiRange()
1043
1049
1044 z = dataOut.data_spc/factor
1050 z = dataOut.data_spc/factor
1045 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1051 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1046
1052
1047 hei_index = numpy.arange(25)*3 + 20
1053 hei_index = numpy.arange(25)*3 + 20
1048
1054
1049 if xaxis == "frequency":
1055 if xaxis == "frequency":
1050 x = dataOut.getFreqRange()/1000.
1056 x = dataOut.getFreqRange()/1000.
1051 zdB = 10*numpy.log10(z[0,:,hei_index])
1057 zdB = 10*numpy.log10(z[0,:,hei_index])
1052 xlabel = "Frequency (kHz)"
1058 xlabel = "Frequency (kHz)"
1053 ylabel = "Power (dB)"
1059 ylabel = "Power (dB)"
1054
1060
1055 elif xaxis == "time":
1061 elif xaxis == "time":
1056 x = dataOut.getAcfRange()
1062 x = dataOut.getAcfRange()
1057 zdB = z[0,:,hei_index]
1063 zdB = z[0,:,hei_index]
1058 xlabel = "Time (ms)"
1064 xlabel = "Time (ms)"
1059 ylabel = "ACF"
1065 ylabel = "ACF"
1060
1066
1061 else:
1067 else:
1062 x = dataOut.getVelRange()
1068 x = dataOut.getVelRange()
1063 zdB = 10*numpy.log10(z[0,:,hei_index])
1069 zdB = 10*numpy.log10(z[0,:,hei_index])
1064 xlabel = "Velocity (m/s)"
1070 xlabel = "Velocity (m/s)"
1065 ylabel = "Power (dB)"
1071 ylabel = "Power (dB)"
1066
1072
1067 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1073 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1068 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1074 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1069
1075
1070 if not self.isConfig:
1076 if not self.isConfig:
1071
1077
1072 nplots = 1
1078 nplots = 1
1073
1079
1074 self.setup(id=id,
1080 self.setup(id=id,
1075 nplots=nplots,
1081 nplots=nplots,
1076 wintitle=wintitle,
1082 wintitle=wintitle,
1077 show=show)
1083 show=show)
1078
1084
1079 if xmin == None: xmin = numpy.nanmin(x)*0.9
1085 if xmin == None: xmin = numpy.nanmin(x)*0.9
1080 if xmax == None: xmax = numpy.nanmax(x)*1.1
1086 if xmax == None: xmax = numpy.nanmax(x)*1.1
1081 if ymin == None: ymin = numpy.nanmin(zdB)
1087 if ymin == None: ymin = numpy.nanmin(zdB)
1082 if ymax == None: ymax = numpy.nanmax(zdB)
1088 if ymax == None: ymax = numpy.nanmax(zdB)
1083
1089
1084 self.isConfig = True
1090 self.isConfig = True
1085
1091
1086 self.setWinTitle(title)
1092 self.setWinTitle(title)
1087
1093
1088 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1094 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1089 axes = self.axesList[0]
1095 axes = self.axesList[0]
1090
1096
1091 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1097 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1092
1098
1093 axes.pmultilineyaxis( x, zdB,
1099 axes.pmultilineyaxis( x, zdB,
1094 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1100 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1095 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1101 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1096 ytick_visible=True, nxticks=5,
1102 ytick_visible=True, nxticks=5,
1097 grid='x')
1103 grid='x')
1098
1104
1099 self.draw()
1105 self.draw()
1100
1106
1101 self.save(figpath=figpath,
1107 self.save(figpath=figpath,
1102 figfile=figfile,
1108 figfile=figfile,
1103 save=save,
1109 save=save,
1104 ftp=ftp,
1110 ftp=ftp,
1105 wr_period=wr_period,
1111 wr_period=wr_period,
1106 thisDatetime=thisDatetime)
1112 thisDatetime=thisDatetime)
1107
1113
1108 class Noise(Figure):
1114 class Noise(Figure):
1109
1115
1110 isConfig = None
1116 isConfig = None
1111 __nsubplots = None
1117 __nsubplots = None
1112
1118
1113 PREFIX = 'noise'
1119 PREFIX = 'noise'
1114
1120
1121
1115 def __init__(self, **kwargs):
1122 def __init__(self, **kwargs):
1116 Figure.__init__(self, **kwargs)
1123 Figure.__init__(self, **kwargs)
1117 self.timerange = 24*60*60
1124 self.timerange = 24*60*60
1118 self.isConfig = False
1125 self.isConfig = False
1119 self.__nsubplots = 1
1126 self.__nsubplots = 1
1120 self.counter_imagwr = 0
1127 self.counter_imagwr = 0
1121 self.WIDTH = 800
1128 self.WIDTH = 800
1122 self.HEIGHT = 400
1129 self.HEIGHT = 400
1123 self.WIDTHPROF = 120
1130 self.WIDTHPROF = 120
1124 self.HEIGHTPROF = 0
1131 self.HEIGHTPROF = 0
1125 self.xdata = None
1132 self.xdata = None
1126 self.ydata = None
1133 self.ydata = None
1127
1134
1128 self.PLOT_CODE = NOISE_CODE
1135 self.PLOT_CODE = NOISE_CODE
1129
1136
1130 self.FTP_WEI = None
1137 self.FTP_WEI = None
1131 self.EXP_CODE = None
1138 self.EXP_CODE = None
1132 self.SUB_EXP_CODE = None
1139 self.SUB_EXP_CODE = None
1133 self.PLOT_POS = None
1140 self.PLOT_POS = None
1134 self.figfile = None
1141 self.figfile = None
1135
1142
1136 self.xmin = None
1143 self.xmin = None
1137 self.xmax = None
1144 self.xmax = None
1138
1145
1139 def getSubplots(self):
1146 def getSubplots(self):
1140
1147
1141 ncol = 1
1148 ncol = 1
1142 nrow = 1
1149 nrow = 1
1143
1150
1144 return nrow, ncol
1151 return nrow, ncol
1145
1152
1146 def openfile(self, filename):
1153 def openfile(self, filename):
1147 dirname = os.path.dirname(filename)
1154 dirname = os.path.dirname(filename)
1148
1155
1149 if not os.path.exists(dirname):
1156 if not os.path.exists(dirname):
1150 os.mkdir(dirname)
1157 os.mkdir(dirname)
1151
1158
1152 f = open(filename,'w+')
1159 f = open(filename,'w+')
1153 f.write('\n\n')
1160 f.write('\n\n')
1154 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1161 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1155 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1162 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1156 f.close()
1163 f.close()
1157
1164
1158 def save_data(self, filename_phase, data, data_datetime):
1165 def save_data(self, filename_phase, data, data_datetime):
1159
1166
1160 f=open(filename_phase,'a')
1167 f=open(filename_phase,'a')
1161
1168
1162 timetuple_data = data_datetime.timetuple()
1169 timetuple_data = data_datetime.timetuple()
1163 day = str(timetuple_data.tm_mday)
1170 day = str(timetuple_data.tm_mday)
1164 month = str(timetuple_data.tm_mon)
1171 month = str(timetuple_data.tm_mon)
1165 year = str(timetuple_data.tm_year)
1172 year = str(timetuple_data.tm_year)
1166 hour = str(timetuple_data.tm_hour)
1173 hour = str(timetuple_data.tm_hour)
1167 minute = str(timetuple_data.tm_min)
1174 minute = str(timetuple_data.tm_min)
1168 second = str(timetuple_data.tm_sec)
1175 second = str(timetuple_data.tm_sec)
1169
1176
1170 data_msg = ''
1177 data_msg = ''
1171 for i in range(len(data)):
1178 for i in range(len(data)):
1172 data_msg += str(data[i]) + ' '
1179 data_msg += str(data[i]) + ' '
1173
1180
1174 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1181 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1175 f.close()
1182 f.close()
1176
1183
1177
1184
1178 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1185 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1179
1186
1180 self.__showprofile = showprofile
1187 self.__showprofile = showprofile
1181 self.nplots = nplots
1188 self.nplots = nplots
1182
1189
1183 ncolspan = 7
1190 ncolspan = 7
1184 colspan = 6
1191 colspan = 6
1185 self.__nsubplots = 2
1192 self.__nsubplots = 2
1186
1193
1187 self.createFigure(id = id,
1194 self.createFigure(id = id,
1188 wintitle = wintitle,
1195 wintitle = wintitle,
1189 widthplot = self.WIDTH+self.WIDTHPROF,
1196 widthplot = self.WIDTH+self.WIDTHPROF,
1190 heightplot = self.HEIGHT+self.HEIGHTPROF,
1197 heightplot = self.HEIGHT+self.HEIGHTPROF,
1191 show=show)
1198 show=show)
1192
1199
1193 nrow, ncol = self.getSubplots()
1200 nrow, ncol = self.getSubplots()
1194
1201
1195 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1202 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1196
1203
1197
1204
1198 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1205 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1199 xmin=None, xmax=None, ymin=None, ymax=None,
1206 xmin=None, xmax=None, ymin=None, ymax=None,
1200 timerange=None,
1207 timerange=None,
1201 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1208 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1202 server=None, folder=None, username=None, password=None,
1209 server=None, folder=None, username=None, password=None,
1203 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1210 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1204
1211
1205 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1212 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1206 return
1213 return
1207
1214
1208 if channelList == None:
1215 if channelList == None:
1209 channelIndexList = dataOut.channelIndexList
1216 channelIndexList = dataOut.channelIndexList
1210 channelList = dataOut.channelList
1217 channelList = dataOut.channelList
1211 else:
1218 else:
1212 channelIndexList = []
1219 channelIndexList = []
1213 for channel in channelList:
1220 for channel in channelList:
1214 if channel not in dataOut.channelList:
1221 if channel not in dataOut.channelList:
1215 raise ValueError, "Channel %d is not in dataOut.channelList"
1222 raise ValueError, "Channel %d is not in dataOut.channelList"
1216 channelIndexList.append(dataOut.channelList.index(channel))
1223 channelIndexList.append(dataOut.channelList.index(channel))
1217
1224
1218 x = dataOut.getTimeRange()
1225 x = dataOut.getTimeRange()
1219 #y = dataOut.getHeiRange()
1226 #y = dataOut.getHeiRange()
1220 factor = dataOut.normFactor
1227 factor = dataOut.normFactor
1221 noise = dataOut.noise[channelIndexList]/factor
1228 noise = dataOut.noise[channelIndexList]/factor
1222 noisedB = 10*numpy.log10(noise)
1229 noisedB = 10*numpy.log10(noise)
1223
1230
1224 thisDatetime = dataOut.datatime
1231 thisDatetime = dataOut.datatime
1225
1232
1226 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1233 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1227 xlabel = ""
1234 xlabel = ""
1228 ylabel = "Intensity (dB)"
1235 ylabel = "Intensity (dB)"
1229 update_figfile = False
1236 update_figfile = False
1230
1237
1231 if not self.isConfig:
1238 if not self.isConfig:
1232
1239
1233 nplots = 1
1240 nplots = 1
1234
1241
1235 self.setup(id=id,
1242 self.setup(id=id,
1236 nplots=nplots,
1243 nplots=nplots,
1237 wintitle=wintitle,
1244 wintitle=wintitle,
1238 showprofile=showprofile,
1245 showprofile=showprofile,
1239 show=show)
1246 show=show)
1240
1247
1241 if timerange != None:
1248 if timerange != None:
1242 self.timerange = timerange
1249 self.timerange = timerange
1243
1250
1244 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1251 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1245
1252
1246 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1253 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1247 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1254 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1248
1255
1249 self.FTP_WEI = ftp_wei
1256 self.FTP_WEI = ftp_wei
1250 self.EXP_CODE = exp_code
1257 self.EXP_CODE = exp_code
1251 self.SUB_EXP_CODE = sub_exp_code
1258 self.SUB_EXP_CODE = sub_exp_code
1252 self.PLOT_POS = plot_pos
1259 self.PLOT_POS = plot_pos
1253
1260
1254
1261
1255 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1262 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1256 self.isConfig = True
1263 self.isConfig = True
1257 self.figfile = figfile
1264 self.figfile = figfile
1258 self.xdata = numpy.array([])
1265 self.xdata = numpy.array([])
1259 self.ydata = numpy.array([])
1266 self.ydata = numpy.array([])
1260
1267
1261 update_figfile = True
1268 update_figfile = True
1262
1269
1263 #open file beacon phase
1270 #open file beacon phase
1264 path = '%s%03d' %(self.PREFIX, self.id)
1271 path = '%s%03d' %(self.PREFIX, self.id)
1265 noise_file = os.path.join(path,'%s.txt'%self.name)
1272 noise_file = os.path.join(path,'%s.txt'%self.name)
1266 self.filename_noise = os.path.join(figpath,noise_file)
1273 self.filename_noise = os.path.join(figpath,noise_file)
1267
1274
1268 self.setWinTitle(title)
1275 self.setWinTitle(title)
1269
1276
1270 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1277 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1271
1278
1272 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1279 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1273 axes = self.axesList[0]
1280 axes = self.axesList[0]
1274
1281
1275 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1282 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1276
1283
1277 if len(self.ydata)==0:
1284 if len(self.ydata)==0:
1278 self.ydata = noisedB.reshape(-1,1)
1285 self.ydata = noisedB.reshape(-1,1)
1279 else:
1286 else:
1280 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1287 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1281
1288
1282
1289
1283 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1290 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1284 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1291 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1285 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1292 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1286 XAxisAsTime=True, grid='both'
1293 XAxisAsTime=True, grid='both'
1287 )
1294 )
1288
1295
1289 self.draw()
1296 self.draw()
1290
1297
1291 if dataOut.ltctime >= self.xmax:
1298 if dataOut.ltctime >= self.xmax:
1292 self.counter_imagwr = wr_period
1299 self.counter_imagwr = wr_period
1293 self.isConfig = False
1300 self.isConfig = False
1294 update_figfile = True
1301 update_figfile = True
1295
1302
1296 self.save(figpath=figpath,
1303 self.save(figpath=figpath,
1297 figfile=figfile,
1304 figfile=figfile,
1298 save=save,
1305 save=save,
1299 ftp=ftp,
1306 ftp=ftp,
1300 wr_period=wr_period,
1307 wr_period=wr_period,
1301 thisDatetime=thisDatetime,
1308 thisDatetime=thisDatetime,
1302 update_figfile=update_figfile)
1309 update_figfile=update_figfile)
1303
1310
1304 #store data beacon phase
1311 #store data beacon phase
1305 if save:
1312 if save:
1306 self.save_data(self.filename_noise, noisedB, thisDatetime)
1313 self.save_data(self.filename_noise, noisedB, thisDatetime)
1307
1314
1308 class BeaconPhase(Figure):
1315 class BeaconPhase(Figure):
1309
1316
1310 __isConfig = None
1317 __isConfig = None
1311 __nsubplots = None
1318 __nsubplots = None
1312
1319
1313 PREFIX = 'beacon_phase'
1320 PREFIX = 'beacon_phase'
1314
1321
1315 def __init__(self, **kwargs):
1322 def __init__(self, **kwargs):
1316 Figure.__init__(self, **kwargs)
1323 Figure.__init__(self, **kwargs)
1317 self.timerange = 24*60*60
1324 self.timerange = 24*60*60
1318 self.isConfig = False
1325 self.isConfig = False
1319 self.__nsubplots = 1
1326 self.__nsubplots = 1
1320 self.counter_imagwr = 0
1327 self.counter_imagwr = 0
1321 self.WIDTH = 800
1328 self.WIDTH = 800
1322 self.HEIGHT = 400
1329 self.HEIGHT = 400
1323 self.WIDTHPROF = 120
1330 self.WIDTHPROF = 120
1324 self.HEIGHTPROF = 0
1331 self.HEIGHTPROF = 0
1325 self.xdata = None
1332 self.xdata = None
1326 self.ydata = None
1333 self.ydata = None
1327
1334
1328 self.PLOT_CODE = BEACON_CODE
1335 self.PLOT_CODE = BEACON_CODE
1329
1336
1330 self.FTP_WEI = None
1337 self.FTP_WEI = None
1331 self.EXP_CODE = None
1338 self.EXP_CODE = None
1332 self.SUB_EXP_CODE = None
1339 self.SUB_EXP_CODE = None
1333 self.PLOT_POS = None
1340 self.PLOT_POS = None
1334
1341
1335 self.filename_phase = None
1342 self.filename_phase = None
1336
1343
1337 self.figfile = None
1344 self.figfile = None
1338
1345
1339 self.xmin = None
1346 self.xmin = None
1340 self.xmax = None
1347 self.xmax = None
1341
1348
1342 def getSubplots(self):
1349 def getSubplots(self):
1343
1350
1344 ncol = 1
1351 ncol = 1
1345 nrow = 1
1352 nrow = 1
1346
1353
1347 return nrow, ncol
1354 return nrow, ncol
1348
1355
1349 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1356 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1350
1357
1351 self.__showprofile = showprofile
1358 self.__showprofile = showprofile
1352 self.nplots = nplots
1359 self.nplots = nplots
1353
1360
1354 ncolspan = 7
1361 ncolspan = 7
1355 colspan = 6
1362 colspan = 6
1356 self.__nsubplots = 2
1363 self.__nsubplots = 2
1357
1364
1358 self.createFigure(id = id,
1365 self.createFigure(id = id,
1359 wintitle = wintitle,
1366 wintitle = wintitle,
1360 widthplot = self.WIDTH+self.WIDTHPROF,
1367 widthplot = self.WIDTH+self.WIDTHPROF,
1361 heightplot = self.HEIGHT+self.HEIGHTPROF,
1368 heightplot = self.HEIGHT+self.HEIGHTPROF,
1362 show=show)
1369 show=show)
1363
1370
1364 nrow, ncol = self.getSubplots()
1371 nrow, ncol = self.getSubplots()
1365
1372
1366 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1373 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1367
1374
1368 def save_phase(self, filename_phase):
1375 def save_phase(self, filename_phase):
1369 f = open(filename_phase,'w+')
1376 f = open(filename_phase,'w+')
1370 f.write('\n\n')
1377 f.write('\n\n')
1371 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1378 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1372 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1379 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1373 f.close()
1380 f.close()
1374
1381
1375 def save_data(self, filename_phase, data, data_datetime):
1382 def save_data(self, filename_phase, data, data_datetime):
1376 f=open(filename_phase,'a')
1383 f=open(filename_phase,'a')
1377 timetuple_data = data_datetime.timetuple()
1384 timetuple_data = data_datetime.timetuple()
1378 day = str(timetuple_data.tm_mday)
1385 day = str(timetuple_data.tm_mday)
1379 month = str(timetuple_data.tm_mon)
1386 month = str(timetuple_data.tm_mon)
1380 year = str(timetuple_data.tm_year)
1387 year = str(timetuple_data.tm_year)
1381 hour = str(timetuple_data.tm_hour)
1388 hour = str(timetuple_data.tm_hour)
1382 minute = str(timetuple_data.tm_min)
1389 minute = str(timetuple_data.tm_min)
1383 second = str(timetuple_data.tm_sec)
1390 second = str(timetuple_data.tm_sec)
1384 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1391 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1385 f.close()
1392 f.close()
1386
1393
1387
1394
1388 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1395 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1389 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1396 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1390 timerange=None,
1397 timerange=None,
1391 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1398 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1392 server=None, folder=None, username=None, password=None,
1399 server=None, folder=None, username=None, password=None,
1393 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1400 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1394
1401
1395 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1402 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1396 return
1403 return
1397
1404
1398 if pairsList == None:
1405 if pairsList == None:
1399 pairsIndexList = dataOut.pairsIndexList[:10]
1406 pairsIndexList = dataOut.pairsIndexList[:10]
1400 else:
1407 else:
1401 pairsIndexList = []
1408 pairsIndexList = []
1402 for pair in pairsList:
1409 for pair in pairsList:
1403 if pair not in dataOut.pairsList:
1410 if pair not in dataOut.pairsList:
1404 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
1411 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
1405 pairsIndexList.append(dataOut.pairsList.index(pair))
1412 pairsIndexList.append(dataOut.pairsList.index(pair))
1406
1413
1407 if pairsIndexList == []:
1414 if pairsIndexList == []:
1408 return
1415 return
1409
1416
1410 # if len(pairsIndexList) > 4:
1417 # if len(pairsIndexList) > 4:
1411 # pairsIndexList = pairsIndexList[0:4]
1418 # pairsIndexList = pairsIndexList[0:4]
1412
1419
1413 hmin_index = None
1420 hmin_index = None
1414 hmax_index = None
1421 hmax_index = None
1415
1422
1416 if hmin != None and hmax != None:
1423 if hmin != None and hmax != None:
1417 indexes = numpy.arange(dataOut.nHeights)
1424 indexes = numpy.arange(dataOut.nHeights)
1418 hmin_list = indexes[dataOut.heightList >= hmin]
1425 hmin_list = indexes[dataOut.heightList >= hmin]
1419 hmax_list = indexes[dataOut.heightList <= hmax]
1426 hmax_list = indexes[dataOut.heightList <= hmax]
1420
1427
1421 if hmin_list.any():
1428 if hmin_list.any():
1422 hmin_index = hmin_list[0]
1429 hmin_index = hmin_list[0]
1423
1430
1424 if hmax_list.any():
1431 if hmax_list.any():
1425 hmax_index = hmax_list[-1]+1
1432 hmax_index = hmax_list[-1]+1
1426
1433
1427 x = dataOut.getTimeRange()
1434 x = dataOut.getTimeRange()
1428 #y = dataOut.getHeiRange()
1435 #y = dataOut.getHeiRange()
1429
1436
1430
1437
1431 thisDatetime = dataOut.datatime
1438 thisDatetime = dataOut.datatime
1432
1439
1433 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1440 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1434 xlabel = "Local Time"
1441 xlabel = "Local Time"
1435 ylabel = "Phase (degrees)"
1442 ylabel = "Phase (degrees)"
1436
1443
1437 update_figfile = False
1444 update_figfile = False
1438
1445
1439 nplots = len(pairsIndexList)
1446 nplots = len(pairsIndexList)
1440 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1447 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1441 phase_beacon = numpy.zeros(len(pairsIndexList))
1448 phase_beacon = numpy.zeros(len(pairsIndexList))
1442 for i in range(nplots):
1449 for i in range(nplots):
1443 pair = dataOut.pairsList[pairsIndexList[i]]
1450 pair = dataOut.pairsList[pairsIndexList[i]]
1444 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1451 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1445 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1452 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1446 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1453 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1447 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1454 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1448 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1455 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1449
1456
1450 #print "Phase %d%d" %(pair[0], pair[1])
1457 #print "Phase %d%d" %(pair[0], pair[1])
1451 #print phase[dataOut.beacon_heiIndexList]
1458 #print phase[dataOut.beacon_heiIndexList]
1452
1459
1453 if dataOut.beacon_heiIndexList:
1460 if dataOut.beacon_heiIndexList:
1454 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1461 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1455 else:
1462 else:
1456 phase_beacon[i] = numpy.average(phase)
1463 phase_beacon[i] = numpy.average(phase)
1457
1464
1458 if not self.isConfig:
1465 if not self.isConfig:
1459
1466
1460 nplots = len(pairsIndexList)
1467 nplots = len(pairsIndexList)
1461
1468
1462 self.setup(id=id,
1469 self.setup(id=id,
1463 nplots=nplots,
1470 nplots=nplots,
1464 wintitle=wintitle,
1471 wintitle=wintitle,
1465 showprofile=showprofile,
1472 showprofile=showprofile,
1466 show=show)
1473 show=show)
1467
1474
1468 if timerange != None:
1475 if timerange != None:
1469 self.timerange = timerange
1476 self.timerange = timerange
1470
1477
1471 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1478 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1472
1479
1473 if ymin == None: ymin = 0
1480 if ymin == None: ymin = 0
1474 if ymax == None: ymax = 360
1481 if ymax == None: ymax = 360
1475
1482
1476 self.FTP_WEI = ftp_wei
1483 self.FTP_WEI = ftp_wei
1477 self.EXP_CODE = exp_code
1484 self.EXP_CODE = exp_code
1478 self.SUB_EXP_CODE = sub_exp_code
1485 self.SUB_EXP_CODE = sub_exp_code
1479 self.PLOT_POS = plot_pos
1486 self.PLOT_POS = plot_pos
1480
1487
1481 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1488 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1482 self.isConfig = True
1489 self.isConfig = True
1483 self.figfile = figfile
1490 self.figfile = figfile
1484 self.xdata = numpy.array([])
1491 self.xdata = numpy.array([])
1485 self.ydata = numpy.array([])
1492 self.ydata = numpy.array([])
1486
1493
1487 update_figfile = True
1494 update_figfile = True
1488
1495
1489 #open file beacon phase
1496 #open file beacon phase
1490 path = '%s%03d' %(self.PREFIX, self.id)
1497 path = '%s%03d' %(self.PREFIX, self.id)
1491 beacon_file = os.path.join(path,'%s.txt'%self.name)
1498 beacon_file = os.path.join(path,'%s.txt'%self.name)
1492 self.filename_phase = os.path.join(figpath,beacon_file)
1499 self.filename_phase = os.path.join(figpath,beacon_file)
1493 #self.save_phase(self.filename_phase)
1500 #self.save_phase(self.filename_phase)
1494
1501
1495
1502
1496 #store data beacon phase
1503 #store data beacon phase
1497 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1504 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1498
1505
1499 self.setWinTitle(title)
1506 self.setWinTitle(title)
1500
1507
1501
1508
1502 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1509 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1503
1510
1504 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1511 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1505
1512
1506 axes = self.axesList[0]
1513 axes = self.axesList[0]
1507
1514
1508 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1515 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1509
1516
1510 if len(self.ydata)==0:
1517 if len(self.ydata)==0:
1511 self.ydata = phase_beacon.reshape(-1,1)
1518 self.ydata = phase_beacon.reshape(-1,1)
1512 else:
1519 else:
1513 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1520 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1514
1521
1515
1522
1516 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1523 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1517 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1524 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1518 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1525 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1519 XAxisAsTime=True, grid='both'
1526 XAxisAsTime=True, grid='both'
1520 )
1527 )
1521
1528
1522 self.draw()
1529 self.draw()
1523
1530
1524 if dataOut.ltctime >= self.xmax:
1531 if dataOut.ltctime >= self.xmax:
1525 self.counter_imagwr = wr_period
1532 self.counter_imagwr = wr_period
1526 self.isConfig = False
1533 self.isConfig = False
1527 update_figfile = True
1534 update_figfile = True
1528
1535
1529 self.save(figpath=figpath,
1536 self.save(figpath=figpath,
1530 figfile=figfile,
1537 figfile=figfile,
1531 save=save,
1538 save=save,
1532 ftp=ftp,
1539 ftp=ftp,
1533 wr_period=wr_period,
1540 wr_period=wr_period,
1534 thisDatetime=thisDatetime,
1541 thisDatetime=thisDatetime,
1535 update_figfile=update_figfile)
1542 update_figfile=update_figfile)
@@ -1,14 +1,20
1 '''
1 '''
2
2
3 $Author: murco $
3 $Author: murco $
4 $Id: JRODataIO.py 169 2012-11-19 21:57:03Z murco $
4 $Id: JRODataIO.py 169 2012-11-19 21:57:03Z murco $
5 '''
5 '''
6
6
7 from jroIO_voltage import *
7 from jroIO_voltage import *
8 from jroIO_spectra import *
8 from jroIO_spectra import *
9 from jroIO_heispectra import *
9 from jroIO_heispectra import *
10 from jroIO_usrp import *
10 from jroIO_usrp import *
11 from jroIO_digitalRF import *
11 from jroIO_digitalRF import *
12 from jroIO_kamisr import *
12 from jroIO_kamisr import *
13 from jroIO_param import *
13 from jroIO_param import *
14 from jroIO_hf import *
14 from jroIO_hf import *
15
16 from jroIO_madrigal import *
17
18 from bltrIO_param import *
19 from jroIO_bltr import *
20 from jroIO_mira35c import *
This diff has been collapsed as it changes many lines, (509 lines changed) Show them Hide them
@@ -1,1795 +1,1834
1 '''
1 '''
2 Created on Jul 2, 2014
2 Created on Jul 2, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import sys
7 import sys
8 import glob
8 import glob
9 import time
9 import time
10 import numpy
10 import numpy
11 import fnmatch
11 import fnmatch
12 import inspect
12 import inspect
13 import time, datetime
13 import time
14 import datetime
14 import traceback
15 import traceback
15 import zmq
16 import zmq
16
17
17 try:
18 try:
18 from gevent import sleep
19 from gevent import sleep
19 except:
20 except:
20 from time import sleep
21 from time import sleep
21
22
22 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
23 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
23 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
24 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
24
25
25 LOCALTIME = True
26 LOCALTIME = True
26
27
28
27 def isNumber(cad):
29 def isNumber(cad):
28 """
30 """
29 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
31 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
30
32
31 Excepciones:
33 Excepciones:
32 Si un determinado string no puede ser convertido a numero
34 Si un determinado string no puede ser convertido a numero
33 Input:
35 Input:
34 str, string al cual se le analiza para determinar si convertible a un numero o no
36 str, string al cual se le analiza para determinar si convertible a un numero o no
35
37
36 Return:
38 Return:
37 True : si el string es uno numerico
39 True : si el string es uno numerico
38 False : no es un string numerico
40 False : no es un string numerico
39 """
41 """
40 try:
42 try:
41 float( cad )
43 float(cad)
42 return True
44 return True
43 except:
45 except:
44 return False
46 return False
45
47
48
46 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
49 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
47 """
50 """
48 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
51 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
49
52
50 Inputs:
53 Inputs:
51 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
54 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
52
55
53 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
56 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
54 segundos contados desde 01/01/1970.
57 segundos contados desde 01/01/1970.
55 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
58 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
56 segundos contados desde 01/01/1970.
59 segundos contados desde 01/01/1970.
57
60
58 Return:
61 Return:
59 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
62 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
60 fecha especificado, de lo contrario retorna False.
63 fecha especificado, de lo contrario retorna False.
61
64
62 Excepciones:
65 Excepciones:
63 Si el archivo no existe o no puede ser abierto
66 Si el archivo no existe o no puede ser abierto
64 Si la cabecera no puede ser leida.
67 Si la cabecera no puede ser leida.
65
68
66 """
69 """
67 basicHeaderObj = BasicHeader(LOCALTIME)
70 basicHeaderObj = BasicHeader(LOCALTIME)
68
71
69 try:
72 try:
70 fp = open(filename,'rb')
73 fp = open(filename, 'rb')
71 except IOError:
74 except IOError:
72 print "The file %s can't be opened" %(filename)
75 print "The file %s can't be opened" % (filename)
73 return 0
76 return 0
74
77
75 sts = basicHeaderObj.read(fp)
78 sts = basicHeaderObj.read(fp)
76 fp.close()
79 fp.close()
77
80
78 if not(sts):
81 if not(sts):
79 print "Skipping the file %s because it has not a valid header" %(filename)
82 print "Skipping the file %s because it has not a valid header" % (filename)
80 return 0
83 return 0
81
84
82 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
85 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
83 return 0
86 return 0
84
87
85 return 1
88 return 1
86
89
90
87 def isTimeInRange(thisTime, startTime, endTime):
91 def isTimeInRange(thisTime, startTime, endTime):
88
92
89 if endTime >= startTime:
93 if endTime >= startTime:
90 if (thisTime < startTime) or (thisTime > endTime):
94 if (thisTime < startTime) or (thisTime > endTime):
91 return 0
95 return 0
92
96
93 return 1
97 return 1
94 else:
98 else:
95 if (thisTime < startTime) and (thisTime > endTime):
99 if (thisTime < startTime) and (thisTime > endTime):
96 return 0
100 return 0
97
101
98 return 1
102 return 1
99
103
104
100 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
105 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
101 """
106 """
102 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
107 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
103
108
104 Inputs:
109 Inputs:
105 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
110 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
106
111
107 startDate : fecha inicial del rango seleccionado en formato datetime.date
112 startDate : fecha inicial del rango seleccionado en formato datetime.date
108
113
109 endDate : fecha final del rango seleccionado en formato datetime.date
114 endDate : fecha final del rango seleccionado en formato datetime.date
110
115
111 startTime : tiempo inicial del rango seleccionado en formato datetime.time
116 startTime : tiempo inicial del rango seleccionado en formato datetime.time
112
117
113 endTime : tiempo final del rango seleccionado en formato datetime.time
118 endTime : tiempo final del rango seleccionado en formato datetime.time
114
119
115 Return:
120 Return:
116 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
121 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
117 fecha especificado, de lo contrario retorna False.
122 fecha especificado, de lo contrario retorna False.
118
123
119 Excepciones:
124 Excepciones:
120 Si el archivo no existe o no puede ser abierto
125 Si el archivo no existe o no puede ser abierto
121 Si la cabecera no puede ser leida.
126 Si la cabecera no puede ser leida.
122
127
123 """
128 """
124
129
125
126 try:
130 try:
127 fp = open(filename,'rb')
131 fp = open(filename, 'rb')
128 except IOError:
132 except IOError:
129 print "The file %s can't be opened" %(filename)
133 print "The file %s can't be opened" % (filename)
130 return None
134 return None
131
135
132 firstBasicHeaderObj = BasicHeader(LOCALTIME)
136 firstBasicHeaderObj = BasicHeader(LOCALTIME)
133 systemHeaderObj = SystemHeader()
137 systemHeaderObj = SystemHeader()
134 radarControllerHeaderObj = RadarControllerHeader()
138 radarControllerHeaderObj = RadarControllerHeader()
135 processingHeaderObj = ProcessingHeader()
139 processingHeaderObj = ProcessingHeader()
136
140
137 lastBasicHeaderObj = BasicHeader(LOCALTIME)
141 lastBasicHeaderObj = BasicHeader(LOCALTIME)
138
142
139 sts = firstBasicHeaderObj.read(fp)
143 sts = firstBasicHeaderObj.read(fp)
140
144
141 if not(sts):
145 if not(sts):
142 print "[Reading] Skipping the file %s because it has not a valid header" %(filename)
146 print "[Reading] Skipping the file %s because it has not a valid header" % (filename)
143 return None
147 return None
144
148
145 if not systemHeaderObj.read(fp):
149 if not systemHeaderObj.read(fp):
146 return None
150 return None
147
151
148 if not radarControllerHeaderObj.read(fp):
152 if not radarControllerHeaderObj.read(fp):
149 return None
153 return None
150
154
151 if not processingHeaderObj.read(fp):
155 if not processingHeaderObj.read(fp):
152 return None
156 return None
153
157
154 filesize = os.path.getsize(filename)
158 filesize = os.path.getsize(filename)
155
159
156 offset = processingHeaderObj.blockSize + 24 #header size
160 offset = processingHeaderObj.blockSize + 24 # header size
157
161
158 if filesize <= offset:
162 if filesize <= offset:
159 print "[Reading] %s: This file has not enough data" %filename
163 print "[Reading] %s: This file has not enough data" % filename
160 return None
164 return None
161
165
162 fp.seek(-offset, 2)
166 fp.seek(-offset, 2)
163
167
164 sts = lastBasicHeaderObj.read(fp)
168 sts = lastBasicHeaderObj.read(fp)
165
169
166 fp.close()
170 fp.close()
167
171
168 thisDatetime = lastBasicHeaderObj.datatime
172 thisDatetime = lastBasicHeaderObj.datatime
169 thisTime_last_block = thisDatetime.time()
173 thisTime_last_block = thisDatetime.time()
170
174
171 thisDatetime = firstBasicHeaderObj.datatime
175 thisDatetime = firstBasicHeaderObj.datatime
172 thisDate = thisDatetime.date()
176 thisDate = thisDatetime.date()
173 thisTime_first_block = thisDatetime.time()
177 thisTime_first_block = thisDatetime.time()
174
178
175 #General case
179 # General case
176 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
180 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
177 #-----------o----------------------------o-----------
181 #-----------o----------------------------o-----------
178 # startTime endTime
182 # startTime endTime
179
183
180 if endTime >= startTime:
184 if endTime >= startTime:
181 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
185 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
182 return None
186 return None
183
187
184 return thisDatetime
188 return thisDatetime
185
189
186 #If endTime < startTime then endTime belongs to the next day
190 # If endTime < startTime then endTime belongs to the next day
187
188
191
189 #<<<<<<<<<<<o o>>>>>>>>>>>
192 #<<<<<<<<<<<o o>>>>>>>>>>>
190 #-----------o----------------------------o-----------
193 #-----------o----------------------------o-----------
191 # endTime startTime
194 # endTime startTime
192
195
193 if (thisDate == startDate) and (thisTime_last_block < startTime):
196 if (thisDate == startDate) and (thisTime_last_block < startTime):
194 return None
197 return None
195
198
196 if (thisDate == endDate) and (thisTime_first_block > endTime):
199 if (thisDate == endDate) and (thisTime_first_block > endTime):
197 return None
200 return None
198
201
199 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
202 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
200 return None
203 return None
201
204
202 return thisDatetime
205 return thisDatetime
203
206
207
204 def isFolderInDateRange(folder, startDate=None, endDate=None):
208 def isFolderInDateRange(folder, startDate=None, endDate=None):
205 """
209 """
206 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
210 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
207
211
208 Inputs:
212 Inputs:
209 folder : nombre completo del directorio.
213 folder : nombre completo del directorio.
210 Su formato deberia ser "/path_root/?YYYYDDD"
214 Su formato deberia ser "/path_root/?YYYYDDD"
211
215
212 siendo:
216 siendo:
213 YYYY : Anio (ejemplo 2015)
217 YYYY : Anio (ejemplo 2015)
214 DDD : Dia del anio (ejemplo 305)
218 DDD : Dia del anio (ejemplo 305)
215
219
216 startDate : fecha inicial del rango seleccionado en formato datetime.date
220 startDate : fecha inicial del rango seleccionado en formato datetime.date
217
221
218 endDate : fecha final del rango seleccionado en formato datetime.date
222 endDate : fecha final del rango seleccionado en formato datetime.date
219
223
220 Return:
224 Return:
221 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
225 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
222 fecha especificado, de lo contrario retorna False.
226 fecha especificado, de lo contrario retorna False.
223 Excepciones:
227 Excepciones:
224 Si el directorio no tiene el formato adecuado
228 Si el directorio no tiene el formato adecuado
225 """
229 """
226
230
227 basename = os.path.basename(folder)
231 basename = os.path.basename(folder)
228
232
229 if not isRadarFolder(basename):
233 if not isRadarFolder(basename):
230 print "The folder %s has not the rigth format" %folder
234 print "The folder %s has not the rigth format" % folder
231 return 0
235 return 0
232
236
233 if startDate and endDate:
237 if startDate and endDate:
234 thisDate = getDateFromRadarFolder(basename)
238 thisDate = getDateFromRadarFolder(basename)
235
239
236 if thisDate < startDate:
240 if thisDate < startDate:
237 return 0
241 return 0
238
242
239 if thisDate > endDate:
243 if thisDate > endDate:
240 return 0
244 return 0
241
245
242 return 1
246 return 1
243
247
248
244 def isFileInDateRange(filename, startDate=None, endDate=None):
249 def isFileInDateRange(filename, startDate=None, endDate=None):
245 """
250 """
246 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
251 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
247
252
248 Inputs:
253 Inputs:
249 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
254 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
250
255
251 Su formato deberia ser "?YYYYDDDsss"
256 Su formato deberia ser "?YYYYDDDsss"
252
257
253 siendo:
258 siendo:
254 YYYY : Anio (ejemplo 2015)
259 YYYY : Anio (ejemplo 2015)
255 DDD : Dia del anio (ejemplo 305)
260 DDD : Dia del anio (ejemplo 305)
256 sss : set
261 sss : set
257
262
258 startDate : fecha inicial del rango seleccionado en formato datetime.date
263 startDate : fecha inicial del rango seleccionado en formato datetime.date
259
264
260 endDate : fecha final del rango seleccionado en formato datetime.date
265 endDate : fecha final del rango seleccionado en formato datetime.date
261
266
262 Return:
267 Return:
263 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
268 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
264 fecha especificado, de lo contrario retorna False.
269 fecha especificado, de lo contrario retorna False.
265 Excepciones:
270 Excepciones:
266 Si el archivo no tiene el formato adecuado
271 Si el archivo no tiene el formato adecuado
267 """
272 """
268
273
269 basename = os.path.basename(filename)
274 basename = os.path.basename(filename)
270
275
271 if not isRadarFile(basename):
276 if not isRadarFile(basename):
272 print "The filename %s has not the rigth format" %filename
277 print "The filename %s has not the rigth format" % filename
273 return 0
278 return 0
274
279
275 if startDate and endDate:
280 if startDate and endDate:
276 thisDate = getDateFromRadarFile(basename)
281 thisDate = getDateFromRadarFile(basename)
277
282
278 if thisDate < startDate:
283 if thisDate < startDate:
279 return 0
284 return 0
280
285
281 if thisDate > endDate:
286 if thisDate > endDate:
282 return 0
287 return 0
283
288
284 return 1
289 return 1
285
290
291
286 def getFileFromSet(path, ext, set):
292 def getFileFromSet(path, ext, set):
287 validFilelist = []
293 validFilelist = []
288 fileList = os.listdir(path)
294 fileList = os.listdir(path)
289
295
290 # 0 1234 567 89A BCDE
296 # 0 1234 567 89A BCDE
291 # H YYYY DDD SSS .ext
297 # H YYYY DDD SSS .ext
292
298
293 for thisFile in fileList:
299 for thisFile in fileList:
294 try:
300 try:
295 year = int(thisFile[1:5])
301 year = int(thisFile[1:5])
296 doy = int(thisFile[5:8])
302 doy = int(thisFile[5:8])
297 except:
303 except:
298 continue
304 continue
299
305
300 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
306 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
301 continue
307 continue
302
308
303 validFilelist.append(thisFile)
309 validFilelist.append(thisFile)
304
310
305 myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set))
311 myfile = fnmatch.filter(
312 validFilelist, '*%4.4d%3.3d%3.3d*' % (year, doy, set))
306
313
307 if len(myfile)!= 0:
314 if len(myfile) != 0:
308 return myfile[0]
315 return myfile[0]
309 else:
316 else:
310 filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower())
317 filename = '*%4.4d%3.3d%3.3d%s' % (year, doy, set, ext.lower())
311 print 'the filename %s does not exist'%filename
318 print 'the filename %s does not exist' % filename
312 print '...going to the last file: '
319 print '...going to the last file: '
313
320
314 if validFilelist:
321 if validFilelist:
315 validFilelist = sorted( validFilelist, key=str.lower )
322 validFilelist = sorted(validFilelist, key=str.lower)
316 return validFilelist[-1]
323 return validFilelist[-1]
317
324
318 return None
325 return None
319
326
327
320 def getlastFileFromPath(path, ext):
328 def getlastFileFromPath(path, ext):
321 """
329 """
322 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
330 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
323 al final de la depuracion devuelve el ultimo file de la lista que quedo.
331 al final de la depuracion devuelve el ultimo file de la lista que quedo.
324
332
325 Input:
333 Input:
326 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
334 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
327 ext : extension de los files contenidos en una carpeta
335 ext : extension de los files contenidos en una carpeta
328
336
329 Return:
337 Return:
330 El ultimo file de una determinada carpeta, no se considera el path.
338 El ultimo file de una determinada carpeta, no se considera el path.
331 """
339 """
332 validFilelist = []
340 validFilelist = []
333 fileList = os.listdir(path)
341 fileList = os.listdir(path)
334
342
335 # 0 1234 567 89A BCDE
343 # 0 1234 567 89A BCDE
336 # H YYYY DDD SSS .ext
344 # H YYYY DDD SSS .ext
337
345
338 for thisFile in fileList:
346 for thisFile in fileList:
339
347
340 year = thisFile[1:5]
348 year = thisFile[1:5]
341 if not isNumber(year):
349 if not isNumber(year):
342 continue
350 continue
343
351
344 doy = thisFile[5:8]
352 doy = thisFile[5:8]
345 if not isNumber(doy):
353 if not isNumber(doy):
346 continue
354 continue
347
355
348 year = int(year)
356 year = int(year)
349 doy = int(doy)
357 doy = int(doy)
350
358
351 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
359 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
352 continue
360 continue
353
361
354 validFilelist.append(thisFile)
362 validFilelist.append(thisFile)
355
363
356 if validFilelist:
364 if validFilelist:
357 validFilelist = sorted( validFilelist, key=str.lower )
365 validFilelist = sorted(validFilelist, key=str.lower)
358 return validFilelist[-1]
366 return validFilelist[-1]
359
367
360 return None
368 return None
361
369
370
362 def checkForRealPath(path, foldercounter, year, doy, set, ext):
371 def checkForRealPath(path, foldercounter, year, doy, set, ext):
363 """
372 """
364 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
373 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
365 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
374 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
366 el path exacto de un determinado file.
375 el path exacto de un determinado file.
367
376
368 Example :
377 Example :
369 nombre correcto del file es .../.../D2009307/P2009307367.ext
378 nombre correcto del file es .../.../D2009307/P2009307367.ext
370
379
371 Entonces la funcion prueba con las siguientes combinaciones
380 Entonces la funcion prueba con las siguientes combinaciones
372 .../.../y2009307367.ext
381 .../.../y2009307367.ext
373 .../.../Y2009307367.ext
382 .../.../Y2009307367.ext
374 .../.../x2009307/y2009307367.ext
383 .../.../x2009307/y2009307367.ext
375 .../.../x2009307/Y2009307367.ext
384 .../.../x2009307/Y2009307367.ext
376 .../.../X2009307/y2009307367.ext
385 .../.../X2009307/y2009307367.ext
377 .../.../X2009307/Y2009307367.ext
386 .../.../X2009307/Y2009307367.ext
378 siendo para este caso, la ultima combinacion de letras, identica al file buscado
387 siendo para este caso, la ultima combinacion de letras, identica al file buscado
379
388
380 Return:
389 Return:
381 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
390 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
382 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
391 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
383 para el filename
392 para el filename
384 """
393 """
385 fullfilename = None
394 fullfilename = None
386 find_flag = False
395 find_flag = False
387 filename = None
396 filename = None
388
397
389 prefixDirList = [None,'d','D']
398 prefixDirList = [None, 'd', 'D']
390 if ext.lower() == ".r": #voltage
399 if ext.lower() == ".r": # voltage
391 prefixFileList = ['d','D']
400 prefixFileList = ['d', 'D']
392 elif ext.lower() == ".pdata": #spectra
401 elif ext.lower() == ".pdata": # spectra
393 prefixFileList = ['p','P']
402 prefixFileList = ['p', 'P']
394 else:
403 else:
395 return None, filename
404 return None, filename
396
405
397 #barrido por las combinaciones posibles
406 # barrido por las combinaciones posibles
398 for prefixDir in prefixDirList:
407 for prefixDir in prefixDirList:
399 thispath = path
408 thispath = path
400 if prefixDir != None:
409 if prefixDir != None:
401 #formo el nombre del directorio xYYYYDDD (x=d o x=D)
410 # formo el nombre del directorio xYYYYDDD (x=d o x=D)
402 if foldercounter == 0:
411 if foldercounter == 0:
403 thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy ))
412 thispath = os.path.join(path, "%s%04d%03d" %
413 (prefixDir, year, doy))
404 else:
414 else:
405 thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter))
415 thispath = os.path.join(path, "%s%04d%03d_%02d" % (
406 for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D"
416 prefixDir, year, doy, foldercounter))
407 filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
417 for prefixFile in prefixFileList: # barrido por las dos combinaciones posibles de "D"
408 fullfilename = os.path.join( thispath, filename ) #formo el path completo
418 # formo el nombre del file xYYYYDDDSSS.ext
409
419 filename = "%s%04d%03d%03d%s" % (prefixFile, year, doy, set, ext)
410 if os.path.exists( fullfilename ): #verifico que exista
420 fullfilename = os.path.join(
421 thispath, filename) # formo el path completo
422
423 if os.path.exists(fullfilename): # verifico que exista
411 find_flag = True
424 find_flag = True
412 break
425 break
413 if find_flag:
426 if find_flag:
414 break
427 break
415
428
416 if not(find_flag):
429 if not(find_flag):
417 return None, filename
430 return None, filename
418
431
419 return fullfilename, filename
432 return fullfilename, filename
420
433
434
421 def isRadarFolder(folder):
435 def isRadarFolder(folder):
422 try:
436 try:
423 year = int(folder[1:5])
437 year = int(folder[1:5])
424 doy = int(folder[5:8])
438 doy = int(folder[5:8])
425 except:
439 except:
426 return 0
440 return 0
427
441
428 return 1
442 return 1
429
443
444
430 def isRadarFile(file):
445 def isRadarFile(file):
431 try:
446 try:
432 year = int(file[1:5])
447 year = int(file[1:5])
433 doy = int(file[5:8])
448 doy = int(file[5:8])
434 set = int(file[8:11])
449 set = int(file[8:11])
435 except:
450 except:
436 return 0
451 return 0
452
453 return 1
437
454
438 return 1
439
455
440 def getDateFromRadarFile(file):
456 def getDateFromRadarFile(file):
441 try:
457 try:
442 year = int(file[1:5])
458 year = int(file[1:5])
443 doy = int(file[5:8])
459 doy = int(file[5:8])
444 set = int(file[8:11])
460 set = int(file[8:11])
445 except:
461 except:
446 return None
462 return None
447
463
448 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
464 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
449 return thisDate
465 return thisDate
450
466
467
451 def getDateFromRadarFolder(folder):
468 def getDateFromRadarFolder(folder):
452 try:
469 try:
453 year = int(folder[1:5])
470 year = int(folder[1:5])
454 doy = int(folder[5:8])
471 doy = int(folder[5:8])
455 except:
472 except:
456 return None
473 return None
457
474
458 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
475 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
459 return thisDate
476 return thisDate
460
477
478
461 class JRODataIO:
479 class JRODataIO:
462
480
463 c = 3E8
481 c = 3E8
464
482
465 isConfig = False
483 isConfig = False
466
484
467 basicHeaderObj = None
485 basicHeaderObj = None
468
486
469 systemHeaderObj = None
487 systemHeaderObj = None
470
488
471 radarControllerHeaderObj = None
489 radarControllerHeaderObj = None
472
490
473 processingHeaderObj = None
491 processingHeaderObj = None
474
492
475 dtype = None
493 dtype = None
476
494
477 pathList = []
495 pathList = []
478
496
479 filenameList = []
497 filenameList = []
480
498
481 filename = None
499 filename = None
482
500
483 ext = None
501 ext = None
484
502
485 flagIsNewFile = 1
503 flagIsNewFile = 1
486
504
487 flagDiscontinuousBlock = 0
505 flagDiscontinuousBlock = 0
488
506
489 flagIsNewBlock = 0
507 flagIsNewBlock = 0
490
508
491 fp = None
509 fp = None
492
510
493 firstHeaderSize = 0
511 firstHeaderSize = 0
494
512
495 basicHeaderSize = 24
513 basicHeaderSize = 24
496
514
497 versionFile = 1103
515 versionFile = 1103
498
516
499 fileSize = None
517 fileSize = None
500
518
501 # ippSeconds = None
519 # ippSeconds = None
502
520
503 fileSizeByHeader = None
521 fileSizeByHeader = None
504
522
505 fileIndex = None
523 fileIndex = None
506
524
507 profileIndex = None
525 profileIndex = None
508
526
509 blockIndex = None
527 blockIndex = None
510
528
511 nTotalBlocks = None
529 nTotalBlocks = None
512
530
513 maxTimeStep = 30
531 maxTimeStep = 30
514
532
515 lastUTTime = None
533 lastUTTime = None
516
534
517 datablock = None
535 datablock = None
518
536
519 dataOut = None
537 dataOut = None
520
538
521 blocksize = None
539 blocksize = None
522
540
523 getByBlock = False
541 getByBlock = False
524
542
525 def __init__(self):
543 def __init__(self):
526
544
527 raise NotImplementedError
545 raise NotImplementedError
528
546
529 def run(self):
547 def run(self):
530
548
531 raise NotImplementedError
549 raise NotImplementedError
532
550
533 def getDtypeWidth(self):
551 def getDtypeWidth(self):
534
552
535 dtype_index = get_dtype_index(self.dtype)
553 dtype_index = get_dtype_index(self.dtype)
536 dtype_width = get_dtype_width(dtype_index)
554 dtype_width = get_dtype_width(dtype_index)
537
555
538 return dtype_width
556 return dtype_width
539
557
540 def getAllowedArgs(self):
558 def getAllowedArgs(self):
541 return inspect.getargspec(self.run).args
559 return inspect.getargspec(self.run).args
542
560
561
543 class JRODataReader(JRODataIO):
562 class JRODataReader(JRODataIO):
544
563
545 online = 0
564 online = 0
546
565
547 realtime = 0
566 realtime = 0
548
567
549 nReadBlocks = 0
568 nReadBlocks = 0
550
569
551 delay = 10 #number of seconds waiting a new file
570 delay = 10 # number of seconds waiting a new file
552
571
553 nTries = 3 #quantity tries
572 nTries = 3 # quantity tries
554
573
555 nFiles = 3 #number of files for searching
574 nFiles = 3 # number of files for searching
556
575
557 path = None
576 path = None
558
577
559 foldercounter = 0
578 foldercounter = 0
560
579
561 flagNoMoreFiles = 0
580 flagNoMoreFiles = 0
562
581
563 datetimeList = []
582 datetimeList = []
564
583
565 __isFirstTimeOnline = 1
584 __isFirstTimeOnline = 1
566
585
567 __printInfo = True
586 __printInfo = True
568
587
569 profileIndex = None
588 profileIndex = None
570
589
571 nTxs = 1
590 nTxs = 1
572
591
573 txIndex = None
592 txIndex = None
574
593
575 #Added--------------------
594 # Added--------------------
576
595
577 selBlocksize = None
596 selBlocksize = None
578
597
579 selBlocktime = None
598 selBlocktime = None
580
599
581 def __init__(self):
600 def __init__(self):
582
583 """
601 """
584 This class is used to find data files
602 This class is used to find data files
585
603
586 Example:
604 Example:
587 reader = JRODataReader()
605 reader = JRODataReader()
588 fileList = reader.findDataFiles()
606 fileList = reader.findDataFiles()
589
607
590 """
608 """
591 pass
609 pass
592
610
593
594 def createObjByDefault(self):
611 def createObjByDefault(self):
595 """
612 """
596
613
597 """
614 """
598 raise NotImplementedError
615 raise NotImplementedError
599
616
600 def getBlockDimension(self):
617 def getBlockDimension(self):
601
618
602 raise NotImplementedError
619 raise NotImplementedError
603
620
604 def searchFilesOffLine(self,
621 def searchFilesOffLine(self,
605 path,
622 path,
606 startDate=None,
623 startDate=None,
607 endDate=None,
624 endDate=None,
608 startTime=datetime.time(0,0,0),
625 startTime=datetime.time(0, 0, 0),
609 endTime=datetime.time(23,59,59),
626 endTime=datetime.time(23, 59, 59),
610 set=None,
627 set=None,
611 expLabel='',
628 expLabel='',
612 ext='.r',
629 ext='.r',
613 cursor=None,
630 cursor=None,
614 skip=None,
631 skip=None,
615 walk=True):
632 walk=True):
616
633
617 self.filenameList = []
634 self.filenameList = []
618 self.datetimeList = []
635 self.datetimeList = []
619
636
620 pathList = []
637 pathList = []
621
638
622 dateList, pathList = self.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
639 dateList, pathList = self.findDatafiles(
640 path, startDate, endDate, expLabel, ext, walk, include_path=True)
623
641
624 if dateList == []:
642 if dateList == []:
625 return [], []
643 return [], []
626
644
627 if len(dateList) > 1:
645 if len(dateList) > 1:
628 print "[Reading] Data found for date range [%s - %s]: total days = %d" %(startDate, endDate, len(dateList))
646 print "[Reading] Data found for date range [%s - %s]: total days = %d" % (startDate, endDate, len(dateList))
629 else:
647 else:
630 print "[Reading] Data found for date range [%s - %s]: date = %s" %(startDate, endDate, dateList[0])
648 print "[Reading] Data found for date range [%s - %s]: date = %s" % (startDate, endDate, dateList[0])
631
649
632 filenameList = []
650 filenameList = []
633 datetimeList = []
651 datetimeList = []
634
652
635 for thisPath in pathList:
653 for thisPath in pathList:
636
654
637 fileList = glob.glob1(thisPath, "*%s" %ext)
655 fileList = glob.glob1(thisPath, "*%s" % ext)
638 fileList.sort()
656 fileList.sort()
639
657
640 skippedFileList = []
658 skippedFileList = []
641
659
642 if cursor is not None and skip is not None:
660 if cursor is not None and skip is not None:
643
661
644 if skip == 0:
662 if skip == 0:
645 skippedFileList = []
663 skippedFileList = []
646 else:
664 else:
647 skippedFileList = fileList[cursor*skip: cursor*skip + skip]
665 skippedFileList = fileList[cursor *
666 skip: cursor * skip + skip]
648
667
649 else:
668 else:
650 skippedFileList = fileList
669 skippedFileList = fileList
651
670
652 for file in skippedFileList:
671 for file in skippedFileList:
653
672
654 filename = os.path.join(thisPath,file)
673 filename = os.path.join(thisPath, file)
655
674
656 if not isFileInDateRange(filename, startDate, endDate):
675 if not isFileInDateRange(filename, startDate, endDate):
657 continue
676 continue
658
677
659 thisDatetime = isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
678 thisDatetime = isFileInTimeRange(
679 filename, startDate, endDate, startTime, endTime)
660
680
661 if not(thisDatetime):
681 if not(thisDatetime):
662 continue
682 continue
663
683
664 filenameList.append(filename)
684 filenameList.append(filename)
665 datetimeList.append(thisDatetime)
685 datetimeList.append(thisDatetime)
666
686
667 if not(filenameList):
687 if not(filenameList):
668 print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" %(startTime, endTime, ext, path)
688 print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" % (startTime, endTime, ext, path)
669 return [], []
689 return [], []
670
690
671 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
691 print "[Reading] %d file(s) was(were) found in time range: %s - %s" % (len(filenameList), startTime, endTime)
672 print
692 print
673
693
674 # for i in range(len(filenameList)):
694 # for i in range(len(filenameList)):
675 # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
695 # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
676
696
677 self.filenameList = filenameList
697 self.filenameList = filenameList
678 self.datetimeList = datetimeList
698 self.datetimeList = datetimeList
679
699
680 return pathList, filenameList
700 return pathList, filenameList
681
701
682 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
702 def __searchFilesOnLine(self, path, expLabel="", ext=None, walk=True, set=None):
683
684 """
703 """
685 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
704 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
686 devuelve el archivo encontrado ademas de otros datos.
705 devuelve el archivo encontrado ademas de otros datos.
687
706
688 Input:
707 Input:
689 path : carpeta donde estan contenidos los files que contiene data
708 path : carpeta donde estan contenidos los files que contiene data
690
709
691 expLabel : Nombre del subexperimento (subfolder)
710 expLabel : Nombre del subexperimento (subfolder)
692
711
693 ext : extension de los files
712 ext : extension de los files
694
713
695 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
714 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
696
715
697 Return:
716 Return:
698 directory : eL directorio donde esta el file encontrado
717 directory : eL directorio donde esta el file encontrado
699 filename : el ultimo file de una determinada carpeta
718 filename : el ultimo file de una determinada carpeta
700 year : el anho
719 year : el anho
701 doy : el numero de dia del anho
720 doy : el numero de dia del anho
702 set : el set del archivo
721 set : el set del archivo
703
722
704
723
705 """
724 """
706 if not os.path.isdir(path):
725 if not os.path.isdir(path):
707 return None, None, None, None, None, None
726 return None, None, None, None, None, None
708
727
709 dirList = []
728 dirList = []
710
729
711 if not walk:
730 if not walk:
712 fullpath = path
731 fullpath = path
713 foldercounter = 0
732 foldercounter = 0
714 else:
733 else:
715 #Filtra solo los directorios
734 # Filtra solo los directorios
716 for thisPath in os.listdir(path):
735 for thisPath in os.listdir(path):
717 if not os.path.isdir(os.path.join(path,thisPath)):
736 if not os.path.isdir(os.path.join(path, thisPath)):
718 continue
737 continue
719 if not isRadarFolder(thisPath):
738 if not isRadarFolder(thisPath):
720 continue
739 continue
721
740
722 dirList.append(thisPath)
741 dirList.append(thisPath)
723
742
724 if not(dirList):
743 if not(dirList):
725 return None, None, None, None, None, None
744 return None, None, None, None, None, None
726
745
727 dirList = sorted( dirList, key=str.lower )
746 dirList = sorted(dirList, key=str.lower)
728
747
729 doypath = dirList[-1]
748 doypath = dirList[-1]
730 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
749 foldercounter = int(doypath.split('_')[1]) if len(
750 doypath.split('_')) > 1 else 0
731 fullpath = os.path.join(path, doypath, expLabel)
751 fullpath = os.path.join(path, doypath, expLabel)
732
752
733
753 print "[Reading] %s folder was found: " % (fullpath)
734 print "[Reading] %s folder was found: " %(fullpath )
735
754
736 if set == None:
755 if set == None:
737 filename = getlastFileFromPath(fullpath, ext)
756 filename = getlastFileFromPath(fullpath, ext)
738 else:
757 else:
739 filename = getFileFromSet(fullpath, ext, set)
758 filename = getFileFromSet(fullpath, ext, set)
740
759
741 if not(filename):
760 if not(filename):
742 return None, None, None, None, None, None
761 return None, None, None, None, None, None
743
762
744 print "[Reading] %s file was found" %(filename)
763 print "[Reading] %s file was found" % (filename)
745
764
746 if not(self.__verifyFile(os.path.join(fullpath, filename))):
765 if not(self.__verifyFile(os.path.join(fullpath, filename))):
747 return None, None, None, None, None, None
766 return None, None, None, None, None, None
748
767
749 year = int( filename[1:5] )
768 year = int(filename[1:5])
750 doy = int( filename[5:8] )
769 doy = int(filename[5:8])
751 set = int( filename[8:11] )
770 set = int(filename[8:11])
752
771
753 return fullpath, foldercounter, filename, year, doy, set
772 return fullpath, foldercounter, filename, year, doy, set
754
773
755 def __setNextFileOffline(self):
774 def __setNextFileOffline(self):
756
775
757 idFile = self.fileIndex
776 idFile = self.fileIndex
758
777
759 while (True):
778 while (True):
760 idFile += 1
779 idFile += 1
761 if not(idFile < len(self.filenameList)):
780 if not(idFile < len(self.filenameList)):
762 self.flagNoMoreFiles = 1
781 self.flagNoMoreFiles = 1
763 # print "[Reading] No more Files"
782 # print "[Reading] No more Files"
764 return 0
783 return 0
765
784
766 filename = self.filenameList[idFile]
785 filename = self.filenameList[idFile]
767
786
768 if not(self.__verifyFile(filename)):
787 if not(self.__verifyFile(filename)):
769 continue
788 continue
770
789
771 fileSize = os.path.getsize(filename)
790 fileSize = os.path.getsize(filename)
772 fp = open(filename,'rb')
791 fp = open(filename, 'rb')
773 break
792 break
774
793
775 self.flagIsNewFile = 1
794 self.flagIsNewFile = 1
776 self.fileIndex = idFile
795 self.fileIndex = idFile
777 self.filename = filename
796 self.filename = filename
778 self.fileSize = fileSize
797 self.fileSize = fileSize
779 self.fp = fp
798 self.fp = fp
780
799
781 # print "[Reading] Setting the file: %s"%self.filename
800 # print "[Reading] Setting the file: %s"%self.filename
782
801
783 return 1
802 return 1
784
803
785 def __setNextFileOnline(self):
804 def __setNextFileOnline(self):
786 """
805 """
787 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
806 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
788 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
807 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
789 siguientes.
808 siguientes.
790
809
791 Affected:
810 Affected:
792 self.flagIsNewFile
811 self.flagIsNewFile
793 self.filename
812 self.filename
794 self.fileSize
813 self.fileSize
795 self.fp
814 self.fp
796 self.set
815 self.set
797 self.flagNoMoreFiles
816 self.flagNoMoreFiles
798
817
799 Return:
818 Return:
800 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
819 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
801 1 : si el file fue abierto con exito y esta listo a ser leido
820 1 : si el file fue abierto con exito y esta listo a ser leido
802
821
803 Excepciones:
822 Excepciones:
804 Si un determinado file no puede ser abierto
823 Si un determinado file no puede ser abierto
805 """
824 """
806 nFiles = 0
825 nFiles = 0
807 fileOk_flag = False
826 fileOk_flag = False
808 firstTime_flag = True
827 firstTime_flag = True
809
828
810 self.set += 1
829 self.set += 1
811
830
812 if self.set > 999:
831 if self.set > 999:
813 self.set = 0
832 self.set = 0
814 self.foldercounter += 1
833 self.foldercounter += 1
815
834
816 #busca el 1er file disponible
835 # busca el 1er file disponible
817 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
836 fullfilename, filename = checkForRealPath(
837 self.path, self.foldercounter, self.year, self.doy, self.set, self.ext)
818 if fullfilename:
838 if fullfilename:
819 if self.__verifyFile(fullfilename, False):
839 if self.__verifyFile(fullfilename, False):
820 fileOk_flag = True
840 fileOk_flag = True
821
841
822 #si no encuentra un file entonces espera y vuelve a buscar
842 # si no encuentra un file entonces espera y vuelve a buscar
823 if not(fileOk_flag):
843 if not(fileOk_flag):
824 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
844 # busco en los siguientes self.nFiles+1 files posibles
845 for nFiles in range(self.nFiles + 1):
825
846
826 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
847 if firstTime_flag: # si es la 1era vez entonces hace el for self.nTries veces
827 tries = self.nTries
848 tries = self.nTries
828 else:
849 else:
829 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
850 tries = 1 # si no es la 1era vez entonces solo lo hace una vez
830
851
831 for nTries in range( tries ):
852 for nTries in range(tries):
832 if firstTime_flag:
853 if firstTime_flag:
833 print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
854 print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % (self.delay, filename, nTries + 1)
834 sleep( self.delay )
855 sleep(self.delay)
835 else:
856 else:
836 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
857 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
837
858
838 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
859 fullfilename, filename = checkForRealPath(
860 self.path, self.foldercounter, self.year, self.doy, self.set, self.ext)
839 if fullfilename:
861 if fullfilename:
840 if self.__verifyFile(fullfilename):
862 if self.__verifyFile(fullfilename):
841 fileOk_flag = True
863 fileOk_flag = True
842 break
864 break
843
865
844 if fileOk_flag:
866 if fileOk_flag:
845 break
867 break
846
868
847 firstTime_flag = False
869 firstTime_flag = False
848
870
849 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
871 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
850 self.set += 1
872 self.set += 1
851
873
852 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
874 # si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
875 if nFiles == (self.nFiles - 1):
853 self.set = 0
876 self.set = 0
854 self.doy += 1
877 self.doy += 1
855 self.foldercounter = 0
878 self.foldercounter = 0
856
879
857 if fileOk_flag:
880 if fileOk_flag:
858 self.fileSize = os.path.getsize( fullfilename )
881 self.fileSize = os.path.getsize(fullfilename)
859 self.filename = fullfilename
882 self.filename = fullfilename
860 self.flagIsNewFile = 1
883 self.flagIsNewFile = 1
861 if self.fp != None: self.fp.close()
884 if self.fp != None:
885 self.fp.close()
862 self.fp = open(fullfilename, 'rb')
886 self.fp = open(fullfilename, 'rb')
863 self.flagNoMoreFiles = 0
887 self.flagNoMoreFiles = 0
864 # print '[Reading] Setting the file: %s' % fullfilename
888 # print '[Reading] Setting the file: %s' % fullfilename
865 else:
889 else:
866 self.fileSize = 0
890 self.fileSize = 0
867 self.filename = None
891 self.filename = None
868 self.flagIsNewFile = 0
892 self.flagIsNewFile = 0
869 self.fp = None
893 self.fp = None
870 self.flagNoMoreFiles = 1
894 self.flagNoMoreFiles = 1
871 # print '[Reading] No more files to read'
895 # print '[Reading] No more files to read'
872
896
873 return fileOk_flag
897 return fileOk_flag
874
898
875 def setNextFile(self):
899 def setNextFile(self):
876 if self.fp != None:
900 if self.fp != None:
877 self.fp.close()
901 self.fp.close()
878
902
879 if self.online:
903 if self.online:
880 newFile = self.__setNextFileOnline()
904 newFile = self.__setNextFileOnline()
881 else:
905 else:
882 newFile = self.__setNextFileOffline()
906 newFile = self.__setNextFileOffline()
883
907
884 if not(newFile):
908 if not(newFile):
885 print '[Reading] No more files to read'
909 print '[Reading] No more files to read'
886 return 0
910 return 0
887
911
888 if self.verbose:
912 if self.verbose:
889 print '[Reading] Setting the file: %s' % self.filename
913 print '[Reading] Setting the file: %s' % self.filename
890
914
891 self.__readFirstHeader()
915 self.__readFirstHeader()
892 self.nReadBlocks = 0
916 self.nReadBlocks = 0
893 return 1
917 return 1
894
918
895 def __waitNewBlock(self):
919 def __waitNewBlock(self):
896 """
920 """
897 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
921 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
898
922
899 Si el modo de lectura es OffLine siempre retorn 0
923 Si el modo de lectura es OffLine siempre retorn 0
900 """
924 """
901 if not self.online:
925 if not self.online:
902 return 0
926 return 0
903
927
904 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
928 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
905 return 0
929 return 0
906
930
907 currentPointer = self.fp.tell()
931 currentPointer = self.fp.tell()
908
932
909 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
933 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
910
934
911 for nTries in range( self.nTries ):
935 for nTries in range(self.nTries):
912
936
913 self.fp.close()
937 self.fp.close()
914 self.fp = open( self.filename, 'rb' )
938 self.fp = open(self.filename, 'rb')
915 self.fp.seek( currentPointer )
939 self.fp.seek(currentPointer)
916
940
917 self.fileSize = os.path.getsize( self.filename )
941 self.fileSize = os.path.getsize(self.filename)
918 currentSize = self.fileSize - currentPointer
942 currentSize = self.fileSize - currentPointer
919
943
920 if ( currentSize >= neededSize ):
944 if (currentSize >= neededSize):
921 self.basicHeaderObj.read(self.fp)
945 self.basicHeaderObj.read(self.fp)
922 return 1
946 return 1
923
947
924 if self.fileSize == self.fileSizeByHeader:
948 if self.fileSize == self.fileSizeByHeader:
925 # self.flagEoF = True
949 # self.flagEoF = True
926 return 0
950 return 0
927
951
928 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
952 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1)
929 sleep( self.delay )
953 sleep(self.delay)
930
931
954
932 return 0
955 return 0
933
956
934 def waitDataBlock(self,pointer_location):
957 def waitDataBlock(self, pointer_location):
935
958
936 currentPointer = pointer_location
959 currentPointer = pointer_location
937
960
938 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
961 neededSize = self.processingHeaderObj.blockSize # + self.basicHeaderSize
939
962
940 for nTries in range( self.nTries ):
963 for nTries in range(self.nTries):
941 self.fp.close()
964 self.fp.close()
942 self.fp = open( self.filename, 'rb' )
965 self.fp = open(self.filename, 'rb')
943 self.fp.seek( currentPointer )
966 self.fp.seek(currentPointer)
944
967
945 self.fileSize = os.path.getsize( self.filename )
968 self.fileSize = os.path.getsize(self.filename)
946 currentSize = self.fileSize - currentPointer
969 currentSize = self.fileSize - currentPointer
947
970
948 if ( currentSize >= neededSize ):
971 if (currentSize >= neededSize):
949 return 1
972 return 1
950
973
951 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
974 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1)
952 sleep( self.delay )
975 sleep(self.delay)
953
976
954 return 0
977 return 0
955
978
956 def __jumpToLastBlock(self):
979 def __jumpToLastBlock(self):
957
980
958 if not(self.__isFirstTimeOnline):
981 if not(self.__isFirstTimeOnline):
959 return
982 return
960
983
961 csize = self.fileSize - self.fp.tell()
984 csize = self.fileSize - self.fp.tell()
962 blocksize = self.processingHeaderObj.blockSize
985 blocksize = self.processingHeaderObj.blockSize
963
986
964 #salta el primer bloque de datos
987 # salta el primer bloque de datos
965 if csize > self.processingHeaderObj.blockSize:
988 if csize > self.processingHeaderObj.blockSize:
966 self.fp.seek(self.fp.tell() + blocksize)
989 self.fp.seek(self.fp.tell() + blocksize)
967 else:
990 else:
968 return
991 return
969
992
970 csize = self.fileSize - self.fp.tell()
993 csize = self.fileSize - self.fp.tell()
971 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
994 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
972 while True:
995 while True:
973
996
974 if self.fp.tell()<self.fileSize:
997 if self.fp.tell() < self.fileSize:
975 self.fp.seek(self.fp.tell() + neededsize)
998 self.fp.seek(self.fp.tell() + neededsize)
976 else:
999 else:
977 self.fp.seek(self.fp.tell() - neededsize)
1000 self.fp.seek(self.fp.tell() - neededsize)
978 break
1001 break
979
1002
980 # csize = self.fileSize - self.fp.tell()
1003 # csize = self.fileSize - self.fp.tell()
981 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1004 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
982 # factor = int(csize/neededsize)
1005 # factor = int(csize/neededsize)
983 # if factor > 0:
1006 # if factor > 0:
984 # self.fp.seek(self.fp.tell() + factor*neededsize)
1007 # self.fp.seek(self.fp.tell() + factor*neededsize)
985
1008
986 self.flagIsNewFile = 0
1009 self.flagIsNewFile = 0
987 self.__isFirstTimeOnline = 0
1010 self.__isFirstTimeOnline = 0
988
1011
989 def __setNewBlock(self):
1012 def __setNewBlock(self):
990 #if self.server is None:
1013 # if self.server is None:
991 if self.fp == None:
1014 if self.fp == None:
992 return 0
1015 return 0
993
1016
994 # if self.online:
1017 # if self.online:
995 # self.__jumpToLastBlock()
1018 # self.__jumpToLastBlock()
996
1019
997 if self.flagIsNewFile:
1020 if self.flagIsNewFile:
998 self.lastUTTime = self.basicHeaderObj.utc
1021 self.lastUTTime = self.basicHeaderObj.utc
999 return 1
1022 return 1
1000
1023
1001 if self.realtime:
1024 if self.realtime:
1002 self.flagDiscontinuousBlock = 1
1025 self.flagDiscontinuousBlock = 1
1003 if not(self.setNextFile()):
1026 if not(self.setNextFile()):
1004 return 0
1027 return 0
1005 else:
1028 else:
1006 return 1
1029 return 1
1007 #if self.server is None:
1030 # if self.server is None:
1008 currentSize = self.fileSize - self.fp.tell()
1031 currentSize = self.fileSize - self.fp.tell()
1009 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1032 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1010 if (currentSize >= neededSize):
1033 if (currentSize >= neededSize):
1011 self.basicHeaderObj.read(self.fp)
1034 self.basicHeaderObj.read(self.fp)
1012 self.lastUTTime = self.basicHeaderObj.utc
1035 self.lastUTTime = self.basicHeaderObj.utc
1013 return 1
1036 return 1
1014 # else:
1037 # else:
1015 # self.basicHeaderObj.read(self.zHeader)
1038 # self.basicHeaderObj.read(self.zHeader)
1016 # self.lastUTTime = self.basicHeaderObj.utc
1039 # self.lastUTTime = self.basicHeaderObj.utc
1017 # return 1
1040 # return 1
1018 if self.__waitNewBlock():
1041 if self.__waitNewBlock():
1019 self.lastUTTime = self.basicHeaderObj.utc
1042 self.lastUTTime = self.basicHeaderObj.utc
1020 return 1
1043 return 1
1021 #if self.server is None:
1044 # if self.server is None:
1022 if not(self.setNextFile()):
1045 if not(self.setNextFile()):
1023 return 0
1046 return 0
1024
1047
1025 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
1048 deltaTime = self.basicHeaderObj.utc - self.lastUTTime
1026 self.lastUTTime = self.basicHeaderObj.utc
1049 self.lastUTTime = self.basicHeaderObj.utc
1027
1050
1028 self.flagDiscontinuousBlock = 0
1051 self.flagDiscontinuousBlock = 0
1029
1052
1030 if deltaTime > self.maxTimeStep:
1053 if deltaTime > self.maxTimeStep:
1031 self.flagDiscontinuousBlock = 1
1054 self.flagDiscontinuousBlock = 1
1032
1055
1033 return 1
1056 return 1
1034
1057
1035 def readNextBlock(self):
1058 def readNextBlock(self):
1036
1059
1037 #Skip block out of startTime and endTime
1060 # Skip block out of startTime and endTime
1038 while True:
1061 while True:
1039 if not(self.__setNewBlock()):
1062 if not(self.__setNewBlock()):
1040 return 0
1063 return 0
1041
1064
1042 if not(self.readBlock()):
1065 if not(self.readBlock()):
1043 return 0
1066 return 0
1044
1067
1045 self.getBasicHeader()
1068 self.getBasicHeader()
1046
1069
1047 if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime):
1070 if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime):
1048
1071
1049 print "[Reading] Block No. %d/%d -> %s [Skipping]" %(self.nReadBlocks,
1072 print "[Reading] Block No. %d/%d -> %s [Skipping]" % (self.nReadBlocks,
1050 self.processingHeaderObj.dataBlocksPerFile,
1073 self.processingHeaderObj.dataBlocksPerFile,
1051 self.dataOut.datatime.ctime())
1074 self.dataOut.datatime.ctime())
1052 continue
1075 continue
1053
1076
1054 break
1077 break
1055
1078
1056 if self.verbose:
1079 if self.verbose:
1057 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1080 print "[Reading] Block No. %d/%d -> %s" % (self.nReadBlocks,
1058 self.processingHeaderObj.dataBlocksPerFile,
1081 self.processingHeaderObj.dataBlocksPerFile,
1059 self.dataOut.datatime.ctime())
1082 self.dataOut.datatime.ctime())
1060 return 1
1083 return 1
1061
1084
1062 def __readFirstHeader(self):
1085 def __readFirstHeader(self):
1063
1086
1064 self.basicHeaderObj.read(self.fp)
1087 self.basicHeaderObj.read(self.fp)
1065 self.systemHeaderObj.read(self.fp)
1088 self.systemHeaderObj.read(self.fp)
1066 self.radarControllerHeaderObj.read(self.fp)
1089 self.radarControllerHeaderObj.read(self.fp)
1067 self.processingHeaderObj.read(self.fp)
1090 self.processingHeaderObj.read(self.fp)
1068
1091
1069 self.firstHeaderSize = self.basicHeaderObj.size
1092 self.firstHeaderSize = self.basicHeaderObj.size
1070
1093
1071 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
1094 datatype = int(numpy.log2((self.processingHeaderObj.processFlags &
1095 PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR))
1072 if datatype == 0:
1096 if datatype == 0:
1073 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
1097 datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
1074 elif datatype == 1:
1098 elif datatype == 1:
1075 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
1099 datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
1076 elif datatype == 2:
1100 elif datatype == 2:
1077 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
1101 datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
1078 elif datatype == 3:
1102 elif datatype == 3:
1079 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
1103 datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
1080 elif datatype == 4:
1104 elif datatype == 4:
1081 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
1105 datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
1082 elif datatype == 5:
1106 elif datatype == 5:
1083 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
1107 datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
1084 else:
1108 else:
1085 raise ValueError, 'Data type was not defined'
1109 raise ValueError, 'Data type was not defined'
1086
1110
1087 self.dtype = datatype_str
1111 self.dtype = datatype_str
1088 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1112 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1089 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
1113 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \
1114 self.firstHeaderSize + self.basicHeaderSize * \
1115 (self.processingHeaderObj.dataBlocksPerFile - 1)
1090 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1116 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1091 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1117 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1092 self.getBlockDimension()
1118 self.getBlockDimension()
1093
1119
1094 def __verifyFile(self, filename, msgFlag=True):
1120 def __verifyFile(self, filename, msgFlag=True):
1095
1121
1096 msg = None
1122 msg = None
1097
1123
1098 try:
1124 try:
1099 fp = open(filename, 'rb')
1125 fp = open(filename, 'rb')
1100 except IOError:
1126 except IOError:
1101
1127
1102 if msgFlag:
1128 if msgFlag:
1103 print "[Reading] File %s can't be opened" % (filename)
1129 print "[Reading] File %s can't be opened" % (filename)
1104
1130
1105 return False
1131 return False
1106
1132
1107 currentPosition = fp.tell()
1133 currentPosition = fp.tell()
1108 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1134 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1109
1135
1110 if neededSize == 0:
1136 if neededSize == 0:
1111 basicHeaderObj = BasicHeader(LOCALTIME)
1137 basicHeaderObj = BasicHeader(LOCALTIME)
1112 systemHeaderObj = SystemHeader()
1138 systemHeaderObj = SystemHeader()
1113 radarControllerHeaderObj = RadarControllerHeader()
1139 radarControllerHeaderObj = RadarControllerHeader()
1114 processingHeaderObj = ProcessingHeader()
1140 processingHeaderObj = ProcessingHeader()
1115
1141
1116 if not( basicHeaderObj.read(fp) ):
1142 if not(basicHeaderObj.read(fp)):
1117 fp.close()
1143 fp.close()
1118 return False
1144 return False
1119
1145
1120 if not( systemHeaderObj.read(fp) ):
1146 if not(systemHeaderObj.read(fp)):
1121 fp.close()
1147 fp.close()
1122 return False
1148 return False
1123
1149
1124 if not( radarControllerHeaderObj.read(fp) ):
1150 if not(radarControllerHeaderObj.read(fp)):
1125 fp.close()
1151 fp.close()
1126 return False
1152 return False
1127
1153
1128 if not( processingHeaderObj.read(fp) ):
1154 if not(processingHeaderObj.read(fp)):
1129 fp.close()
1155 fp.close()
1130 return False
1156 return False
1131
1157
1132 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1158 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1133 else:
1159 else:
1134 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
1160 msg = "[Reading] Skipping the file %s due to it hasn't enough data" % filename
1135
1161
1136 fp.close()
1162 fp.close()
1137
1163
1138 fileSize = os.path.getsize(filename)
1164 fileSize = os.path.getsize(filename)
1139 currentSize = fileSize - currentPosition
1165 currentSize = fileSize - currentPosition
1140
1166
1141 if currentSize < neededSize:
1167 if currentSize < neededSize:
1142 if msgFlag and (msg != None):
1168 if msgFlag and (msg != None):
1143 print msg
1169 print msg
1144 return False
1170 return False
1145
1171
1146 return True
1172 return True
1147
1173
1148 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1174 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1149
1175
1150 path_empty = True
1176 path_empty = True
1151
1177
1152 dateList = []
1178 dateList = []
1153 pathList = []
1179 pathList = []
1154
1180
1155 multi_path = path.split(',')
1181 multi_path = path.split(',')
1156
1182
1157 if not walk:
1183 if not walk:
1158
1184
1159 for single_path in multi_path:
1185 for single_path in multi_path:
1160
1186
1161 if not os.path.isdir(single_path):
1187 if not os.path.isdir(single_path):
1162 continue
1188 continue
1163
1189
1164 fileList = glob.glob1(single_path, "*"+ext)
1190 fileList = glob.glob1(single_path, "*" + ext)
1165
1191
1166 if not fileList:
1192 if not fileList:
1167 continue
1193 continue
1168
1194
1169 path_empty = False
1195 path_empty = False
1170
1196
1171 fileList.sort()
1197 fileList.sort()
1172
1198
1173 for thisFile in fileList:
1199 for thisFile in fileList:
1174
1200
1175 if not os.path.isfile(os.path.join(single_path, thisFile)):
1201 if not os.path.isfile(os.path.join(single_path, thisFile)):
1176 continue
1202 continue
1177
1203
1178 if not isRadarFile(thisFile):
1204 if not isRadarFile(thisFile):
1179 continue
1205 continue
1180
1206
1181 if not isFileInDateRange(thisFile, startDate, endDate):
1207 if not isFileInDateRange(thisFile, startDate, endDate):
1182 continue
1208 continue
1183
1209
1184 thisDate = getDateFromRadarFile(thisFile)
1210 thisDate = getDateFromRadarFile(thisFile)
1185
1211
1186 if thisDate in dateList:
1212 if thisDate in dateList:
1187 continue
1213 continue
1188
1214
1189 dateList.append(thisDate)
1215 dateList.append(thisDate)
1190 pathList.append(single_path)
1216 pathList.append(single_path)
1191
1217
1192 else:
1218 else:
1193 for single_path in multi_path:
1219 for single_path in multi_path:
1194
1220
1195 if not os.path.isdir(single_path):
1221 if not os.path.isdir(single_path):
1196 continue
1222 continue
1197
1223
1198 dirList = []
1224 dirList = []
1199
1225
1200 for thisPath in os.listdir(single_path):
1226 for thisPath in os.listdir(single_path):
1201
1227
1202 if not os.path.isdir(os.path.join(single_path,thisPath)):
1228 if not os.path.isdir(os.path.join(single_path, thisPath)):
1203 continue
1229 continue
1204
1230
1205 if not isRadarFolder(thisPath):
1231 if not isRadarFolder(thisPath):
1206 continue
1232 continue
1207
1233
1208 if not isFolderInDateRange(thisPath, startDate, endDate):
1234 if not isFolderInDateRange(thisPath, startDate, endDate):
1209 continue
1235 continue
1210
1236
1211 dirList.append(thisPath)
1237 dirList.append(thisPath)
1212
1238
1213 if not dirList:
1239 if not dirList:
1214 continue
1240 continue
1215
1241
1216 dirList.sort()
1242 dirList.sort()
1217
1243
1218 for thisDir in dirList:
1244 for thisDir in dirList:
1219
1245
1220 datapath = os.path.join(single_path, thisDir, expLabel)
1246 datapath = os.path.join(single_path, thisDir, expLabel)
1221 fileList = glob.glob1(datapath, "*"+ext)
1247 fileList = glob.glob1(datapath, "*" + ext)
1222
1248
1223 if not fileList:
1249 if not fileList:
1224 continue
1250 continue
1225
1251
1226 path_empty = False
1252 path_empty = False
1227
1253
1228 thisDate = getDateFromRadarFolder(thisDir)
1254 thisDate = getDateFromRadarFolder(thisDir)
1229
1255
1230 pathList.append(datapath)
1256 pathList.append(datapath)
1231 dateList.append(thisDate)
1257 dateList.append(thisDate)
1232
1258
1233 dateList.sort()
1259 dateList.sort()
1234
1260
1235 if walk:
1261 if walk:
1236 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1262 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1237 else:
1263 else:
1238 pattern_path = multi_path[0]
1264 pattern_path = multi_path[0]
1239
1265
1240 if path_empty:
1266 if path_empty:
1241 print "[Reading] No *%s files in %s for %s to %s" %(ext, pattern_path, startDate, endDate)
1267 print "[Reading] No *%s files in %s for %s to %s" % (ext, pattern_path, startDate, endDate)
1242 else:
1268 else:
1243 if not dateList:
1269 if not dateList:
1244 print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
1270 print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" % (startDate, endDate, ext, path)
1245
1271
1246 if include_path:
1272 if include_path:
1247 return dateList, pathList
1273 return dateList, pathList
1248
1274
1249 return dateList
1275 return dateList
1250
1276
1251 def setup(self,
1277 def setup(self,
1252 path=None,
1278 path=None,
1253 startDate=None,
1279 startDate=None,
1254 endDate=None,
1280 endDate=None,
1255 startTime=datetime.time(0,0,0),
1281 startTime=datetime.time(0, 0, 0),
1256 endTime=datetime.time(23,59,59),
1282 endTime=datetime.time(23, 59, 59),
1257 set=None,
1283 set=None,
1258 expLabel = "",
1284 expLabel="",
1259 ext = None,
1285 ext=None,
1260 online = False,
1286 online=False,
1261 delay = 60,
1287 delay=60,
1262 walk = True,
1288 walk=True,
1263 getblock = False,
1289 getblock=False,
1264 nTxs = 1,
1290 nTxs=1,
1265 realtime=False,
1291 realtime=False,
1266 blocksize=None,
1292 blocksize=None,
1267 blocktime=None,
1293 blocktime=None,
1268 skip=None,
1294 skip=None,
1269 cursor=None,
1295 cursor=None,
1270 warnings=True,
1296 warnings=True,
1271 verbose=True,
1297 verbose=True,
1272 server=None,
1298 server=None,
1273 **kwargs):
1299 format=None,
1300 oneDDict=None,
1301 twoDDict=None,
1302 ind2DList=None):
1274 if server is not None:
1303 if server is not None:
1275 if 'tcp://' in server:
1304 if 'tcp://' in server:
1276 address = server
1305 address = server
1277 else:
1306 else:
1278 address = 'ipc:///tmp/%s' % server
1307 address = 'ipc:///tmp/%s' % server
1279 self.server = address
1308 self.server = address
1280 self.context = zmq.Context()
1309 self.context = zmq.Context()
1281 self.receiver = self.context.socket(zmq.PULL)
1310 self.receiver = self.context.socket(zmq.PULL)
1282 self.receiver.connect(self.server)
1311 self.receiver.connect(self.server)
1283 time.sleep(0.5)
1312 time.sleep(0.5)
1284 print '[Starting] ReceiverData from {}'.format(self.server)
1313 print '[Starting] ReceiverData from {}'.format(self.server)
1285 else:
1314 else:
1286 self.server = None
1315 self.server = None
1287 if path == None:
1316 if path == None:
1288 raise ValueError, "[Reading] The path is not valid"
1317 raise ValueError, "[Reading] The path is not valid"
1289
1318
1290 if ext == None:
1319 if ext == None:
1291 ext = self.ext
1320 ext = self.ext
1292
1321
1293 if online:
1322 if online:
1294 print "[Reading] Searching files in online mode..."
1323 print "[Reading] Searching files in online mode..."
1295
1324
1296 for nTries in range( self.nTries ):
1325 for nTries in range(self.nTries):
1297 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1326 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(
1327 path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1298
1328
1299 if fullpath:
1329 if fullpath:
1300 break
1330 break
1301
1331
1302 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
1332 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries + 1)
1303 sleep( self.delay )
1333 sleep(self.delay)
1304
1334
1305 if not(fullpath):
1335 if not(fullpath):
1306 print "[Reading] There 'isn't any valid file in %s" % path
1336 print "[Reading] There 'isn't any valid file in %s" % path
1307 return
1337 return
1308
1338
1309 self.year = year
1339 self.year = year
1310 self.doy = doy
1340 self.doy = doy
1311 self.set = set - 1
1341 self.set = set - 1
1312 self.path = path
1342 self.path = path
1313 self.foldercounter = foldercounter
1343 self.foldercounter = foldercounter
1314 last_set = None
1344 last_set = None
1315 else:
1345 else:
1316 print "[Reading] Searching files in offline mode ..."
1346 print "[Reading] Searching files in offline mode ..."
1317 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1347 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1318 startTime=startTime, endTime=endTime,
1348 startTime=startTime, endTime=endTime,
1319 set=set, expLabel=expLabel, ext=ext,
1349 set=set, expLabel=expLabel, ext=ext,
1320 walk=walk, cursor=cursor,
1350 walk=walk, cursor=cursor,
1321 skip=skip)
1351 skip=skip)
1322
1352
1323 if not(pathList):
1353 if not(pathList):
1324 self.fileIndex = -1
1354 self.fileIndex = -1
1325 self.pathList = []
1355 self.pathList = []
1326 self.filenameList = []
1356 self.filenameList = []
1327 return
1357 return
1328
1358
1329 self.fileIndex = -1
1359 self.fileIndex = -1
1330 self.pathList = pathList
1360 self.pathList = pathList
1331 self.filenameList = filenameList
1361 self.filenameList = filenameList
1332 file_name = os.path.basename(filenameList[-1])
1362 file_name = os.path.basename(filenameList[-1])
1333 basename, ext = os.path.splitext(file_name)
1363 basename, ext = os.path.splitext(file_name)
1334 last_set = int(basename[-3:])
1364 last_set = int(basename[-3:])
1335
1365
1336 self.online = online
1366 self.online = online
1337 self.realtime = realtime
1367 self.realtime = realtime
1338 self.delay = delay
1368 self.delay = delay
1339 ext = ext.lower()
1369 ext = ext.lower()
1340 self.ext = ext
1370 self.ext = ext
1341 self.getByBlock = getblock
1371 self.getByBlock = getblock
1342 self.nTxs = nTxs
1372 self.nTxs = nTxs
1343 self.startTime = startTime
1373 self.startTime = startTime
1344 self.endTime = endTime
1374 self.endTime = endTime
1345
1375
1346 #Added-----------------
1376 # Added-----------------
1347 self.selBlocksize = blocksize
1377 self.selBlocksize = blocksize
1348 self.selBlocktime = blocktime
1378 self.selBlocktime = blocktime
1349
1379
1350 # Verbose-----------
1380 # Verbose-----------
1351 self.verbose = verbose
1381 self.verbose = verbose
1352 self.warnings = warnings
1382 self.warnings = warnings
1353
1383
1354 if not(self.setNextFile()):
1384 if not(self.setNextFile()):
1355 if (startDate!=None) and (endDate!=None):
1385 if (startDate != None) and (endDate != None):
1356 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1386 print "[Reading] No files in range: %s - %s" % (datetime.datetime.combine(startDate, startTime).ctime(), datetime.datetime.combine(endDate, endTime).ctime())
1357 elif startDate != None:
1387 elif startDate != None:
1358 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1388 print "[Reading] No files in range: %s" % (datetime.datetime.combine(startDate, startTime).ctime())
1359 else:
1389 else:
1360 print "[Reading] No files"
1390 print "[Reading] No files"
1361
1391
1362 self.fileIndex = -1
1392 self.fileIndex = -1
1363 self.pathList = []
1393 self.pathList = []
1364 self.filenameList = []
1394 self.filenameList = []
1365 return
1395 return
1366
1396
1367 # self.getBasicHeader()
1397 # self.getBasicHeader()
1368
1398
1369 if last_set != None:
1399 if last_set != None:
1370 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1400 self.dataOut.last_block = last_set * \
1401 self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1371 return
1402 return
1372
1403
1373 def getBasicHeader(self):
1404 def getBasicHeader(self):
1374
1405
1375 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1406 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond / \
1407 1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1376
1408
1377 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1409 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1378
1410
1379 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1411 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1380
1412
1381 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1413 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1382
1414
1383 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1415 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1384
1416
1385 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1417 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1386
1418
1387 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1419 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
1388
1420
1389 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1421 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1390
1422
1391
1392 def getFirstHeader(self):
1423 def getFirstHeader(self):
1393
1424
1394 raise NotImplementedError
1425 raise NotImplementedError
1395
1426
1396 def getData(self):
1427 def getData(self):
1397
1428
1398 raise NotImplementedError
1429 raise NotImplementedError
1399
1430
1400 def hasNotDataInBuffer(self):
1431 def hasNotDataInBuffer(self):
1401
1432
1402 raise NotImplementedError
1433 raise NotImplementedError
1403
1434
1404 def readBlock(self):
1435 def readBlock(self):
1405
1436
1406 raise NotImplementedError
1437 raise NotImplementedError
1407
1438
1408 def isEndProcess(self):
1439 def isEndProcess(self):
1409
1440
1410 return self.flagNoMoreFiles
1441 return self.flagNoMoreFiles
1411
1442
1412 def printReadBlocks(self):
1443 def printReadBlocks(self):
1413
1444
1414 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1445 print "[Reading] Number of read blocks per file %04d" % self.nReadBlocks
1415
1446
1416 def printTotalBlocks(self):
1447 def printTotalBlocks(self):
1417
1448
1418 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1449 print "[Reading] Number of read blocks %04d" % self.nTotalBlocks
1419
1450
1420 def printNumberOfBlock(self):
1451 def printNumberOfBlock(self):
1452 'SPAM!'
1421
1453
1422 if self.flagIsNewBlock:
1454 # if self.flagIsNewBlock:
1423 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1455 # print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1424 self.processingHeaderObj.dataBlocksPerFile,
1456 # self.processingHeaderObj.dataBlocksPerFile,
1425 self.dataOut.datatime.ctime())
1457 # self.dataOut.datatime.ctime())
1426
1458
1427 def printInfo(self):
1459 def printInfo(self):
1428
1460
1429 if self.__printInfo == False:
1461 if self.__printInfo == False:
1430 return
1462 return
1431
1463
1432 self.basicHeaderObj.printInfo()
1464 self.basicHeaderObj.printInfo()
1433 self.systemHeaderObj.printInfo()
1465 self.systemHeaderObj.printInfo()
1434 self.radarControllerHeaderObj.printInfo()
1466 self.radarControllerHeaderObj.printInfo()
1435 self.processingHeaderObj.printInfo()
1467 self.processingHeaderObj.printInfo()
1436
1468
1437 self.__printInfo = False
1469 self.__printInfo = False
1438
1470
1439 def run(self,
1471 def run(self,
1440 path=None,
1472 path=None,
1441 startDate=None,
1473 startDate=None,
1442 endDate=None,
1474 endDate=None,
1443 startTime=datetime.time(0,0,0),
1475 startTime=datetime.time(0, 0, 0),
1444 endTime=datetime.time(23,59,59),
1476 endTime=datetime.time(23, 59, 59),
1445 set=None,
1477 set=None,
1446 expLabel = "",
1478 expLabel="",
1447 ext = None,
1479 ext=None,
1448 online = False,
1480 online=False,
1449 delay = 60,
1481 delay=60,
1450 walk = True,
1482 walk=True,
1451 getblock = False,
1483 getblock=False,
1452 nTxs = 1,
1484 nTxs=1,
1453 realtime=False,
1485 realtime=False,
1454 blocksize=None,
1486 blocksize=None,
1455 blocktime=None,
1487 blocktime=None,
1456 queue=None,
1457 skip=None,
1488 skip=None,
1458 cursor=None,
1489 cursor=None,
1459 warnings=True,
1490 warnings=True,
1460 server=None,
1491 server=None,
1461 verbose=True, **kwargs):
1492 verbose=True,
1493 format=None,
1494 oneDDict=None,
1495 twoDDict=None,
1496 ind2DList=None, **kwargs):
1497
1462 if not(self.isConfig):
1498 if not(self.isConfig):
1463 self.setup(path=path,
1499 self.setup(path=path,
1464 startDate=startDate,
1500 startDate=startDate,
1465 endDate=endDate,
1501 endDate=endDate,
1466 startTime=startTime,
1502 startTime=startTime,
1467 endTime=endTime,
1503 endTime=endTime,
1468 set=set,
1504 set=set,
1469 expLabel=expLabel,
1505 expLabel=expLabel,
1470 ext=ext,
1506 ext=ext,
1471 online=online,
1507 online=online,
1472 delay=delay,
1508 delay=delay,
1473 walk=walk,
1509 walk=walk,
1474 getblock=getblock,
1510 getblock=getblock,
1475 nTxs=nTxs,
1511 nTxs=nTxs,
1476 realtime=realtime,
1512 realtime=realtime,
1477 blocksize=blocksize,
1513 blocksize=blocksize,
1478 blocktime=blocktime,
1514 blocktime=blocktime,
1479 skip=skip,
1515 skip=skip,
1480 cursor=cursor,
1516 cursor=cursor,
1481 warnings=warnings,
1517 warnings=warnings,
1482 server=server,
1518 server=server,
1483 verbose=verbose)
1519 verbose=verbose,
1520 format=format,
1521 oneDDict=oneDDict,
1522 twoDDict=twoDDict,
1523 ind2DList=ind2DList)
1484 self.isConfig = True
1524 self.isConfig = True
1485 if server is None:
1525 if server is None:
1486 self.getData()
1526 self.getData()
1487 else:
1527 else:
1488 self.getFromServer()
1528 self.getFromServer()
1489
1529
1530
1490 class JRODataWriter(JRODataIO):
1531 class JRODataWriter(JRODataIO):
1491
1532
1492 """
1533 """
1493 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1534 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1494 de los datos siempre se realiza por bloques.
1535 de los datos siempre se realiza por bloques.
1495 """
1536 """
1496
1537
1497 blockIndex = 0
1538 blockIndex = 0
1498
1539
1499 path = None
1540 path = None
1500
1541
1501 setFile = None
1542 setFile = None
1502
1543
1503 profilesPerBlock = None
1544 profilesPerBlock = None
1504
1545
1505 blocksPerFile = None
1546 blocksPerFile = None
1506
1547
1507 nWriteBlocks = 0
1548 nWriteBlocks = 0
1508
1549
1509 fileDate = None
1550 fileDate = None
1510
1551
1511 def __init__(self, dataOut=None):
1552 def __init__(self, dataOut=None):
1512 raise NotImplementedError
1553 raise NotImplementedError
1513
1554
1514
1515 def hasAllDataInBuffer(self):
1555 def hasAllDataInBuffer(self):
1516 raise NotImplementedError
1556 raise NotImplementedError
1517
1557
1518
1519 def setBlockDimension(self):
1558 def setBlockDimension(self):
1520 raise NotImplementedError
1559 raise NotImplementedError
1521
1560
1522
1523 def writeBlock(self):
1561 def writeBlock(self):
1524 raise NotImplementedError
1562 raise NotImplementedError
1525
1563
1526
1527 def putData(self):
1564 def putData(self):
1528 raise NotImplementedError
1565 raise NotImplementedError
1529
1566
1530
1531 def getProcessFlags(self):
1567 def getProcessFlags(self):
1532
1568
1533 processFlags = 0
1569 processFlags = 0
1534
1570
1535 dtype_index = get_dtype_index(self.dtype)
1571 dtype_index = get_dtype_index(self.dtype)
1536 procflag_dtype = get_procflag_dtype(dtype_index)
1572 procflag_dtype = get_procflag_dtype(dtype_index)
1537
1573
1538 processFlags += procflag_dtype
1574 processFlags += procflag_dtype
1539
1575
1540 if self.dataOut.flagDecodeData:
1576 if self.dataOut.flagDecodeData:
1541 processFlags += PROCFLAG.DECODE_DATA
1577 processFlags += PROCFLAG.DECODE_DATA
1542
1578
1543 if self.dataOut.flagDeflipData:
1579 if self.dataOut.flagDeflipData:
1544 processFlags += PROCFLAG.DEFLIP_DATA
1580 processFlags += PROCFLAG.DEFLIP_DATA
1545
1581
1546 if self.dataOut.code is not None:
1582 if self.dataOut.code is not None:
1547 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1583 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1548
1584
1549 if self.dataOut.nCohInt > 1:
1585 if self.dataOut.nCohInt > 1:
1550 processFlags += PROCFLAG.COHERENT_INTEGRATION
1586 processFlags += PROCFLAG.COHERENT_INTEGRATION
1551
1587
1552 if self.dataOut.type == "Spectra":
1588 if self.dataOut.type == "Spectra":
1553 if self.dataOut.nIncohInt > 1:
1589 if self.dataOut.nIncohInt > 1:
1554 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1590 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1555
1591
1556 if self.dataOut.data_dc is not None:
1592 if self.dataOut.data_dc is not None:
1557 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1593 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1558
1594
1559 if self.dataOut.flagShiftFFT:
1595 if self.dataOut.flagShiftFFT:
1560 processFlags += PROCFLAG.SHIFT_FFT_DATA
1596 processFlags += PROCFLAG.SHIFT_FFT_DATA
1561
1597
1562 return processFlags
1598 return processFlags
1563
1599
1564 def setBasicHeader(self):
1600 def setBasicHeader(self):
1565
1601
1566 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1602 self.basicHeaderObj.size = self.basicHeaderSize # bytes
1567 self.basicHeaderObj.version = self.versionFile
1603 self.basicHeaderObj.version = self.versionFile
1568 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1604 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1569
1605
1570 utc = numpy.floor(self.dataOut.utctime)
1606 utc = numpy.floor(self.dataOut.utctime)
1571 milisecond = (self.dataOut.utctime - utc)* 1000.0
1607 milisecond = (self.dataOut.utctime - utc) * 1000.0
1572
1608
1573 self.basicHeaderObj.utc = utc
1609 self.basicHeaderObj.utc = utc
1574 self.basicHeaderObj.miliSecond = milisecond
1610 self.basicHeaderObj.miliSecond = milisecond
1575 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1611 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1576 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1612 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1577 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1613 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1578
1614
1579 def setFirstHeader(self):
1615 def setFirstHeader(self):
1580 """
1616 """
1581 Obtiene una copia del First Header
1617 Obtiene una copia del First Header
1582
1618
1583 Affected:
1619 Affected:
1584
1620
1585 self.basicHeaderObj
1621 self.basicHeaderObj
1586 self.systemHeaderObj
1622 self.systemHeaderObj
1587 self.radarControllerHeaderObj
1623 self.radarControllerHeaderObj
1588 self.processingHeaderObj self.
1624 self.processingHeaderObj self.
1589
1625
1590 Return:
1626 Return:
1591 None
1627 None
1592 """
1628 """
1593
1629
1594 raise NotImplementedError
1630 raise NotImplementedError
1595
1631
1596 def __writeFirstHeader(self):
1632 def __writeFirstHeader(self):
1597 """
1633 """
1598 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1634 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1599
1635
1600 Affected:
1636 Affected:
1601 __dataType
1637 __dataType
1602
1638
1603 Return:
1639 Return:
1604 None
1640 None
1605 """
1641 """
1606
1642
1607 # CALCULAR PARAMETROS
1643 # CALCULAR PARAMETROS
1608
1644
1609 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1645 sizeLongHeader = self.systemHeaderObj.size + \
1646 self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1610 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1647 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1611
1648
1612 self.basicHeaderObj.write(self.fp)
1649 self.basicHeaderObj.write(self.fp)
1613 self.systemHeaderObj.write(self.fp)
1650 self.systemHeaderObj.write(self.fp)
1614 self.radarControllerHeaderObj.write(self.fp)
1651 self.radarControllerHeaderObj.write(self.fp)
1615 self.processingHeaderObj.write(self.fp)
1652 self.processingHeaderObj.write(self.fp)
1616
1653
1617 def __setNewBlock(self):
1654 def __setNewBlock(self):
1618 """
1655 """
1619 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1656 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1620
1657
1621 Return:
1658 Return:
1622 0 : si no pudo escribir nada
1659 0 : si no pudo escribir nada
1623 1 : Si escribio el Basic el First Header
1660 1 : Si escribio el Basic el First Header
1624 """
1661 """
1625 if self.fp == None:
1662 if self.fp == None:
1626 self.setNextFile()
1663 self.setNextFile()
1627
1664
1628 if self.flagIsNewFile:
1665 if self.flagIsNewFile:
1629 return 1
1666 return 1
1630
1667
1631 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1668 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1632 self.basicHeaderObj.write(self.fp)
1669 self.basicHeaderObj.write(self.fp)
1633 return 1
1670 return 1
1634
1671
1635 if not( self.setNextFile() ):
1672 if not(self.setNextFile()):
1636 return 0
1673 return 0
1637
1674
1638 return 1
1675 return 1
1639
1676
1640
1641 def writeNextBlock(self):
1677 def writeNextBlock(self):
1642 """
1678 """
1643 Selecciona el bloque siguiente de datos y los escribe en un file
1679 Selecciona el bloque siguiente de datos y los escribe en un file
1644
1680
1645 Return:
1681 Return:
1646 0 : Si no hizo pudo escribir el bloque de datos
1682 0 : Si no hizo pudo escribir el bloque de datos
1647 1 : Si no pudo escribir el bloque de datos
1683 1 : Si no pudo escribir el bloque de datos
1648 """
1684 """
1649 if not( self.__setNewBlock() ):
1685 if not(self.__setNewBlock()):
1650 return 0
1686 return 0
1651
1687
1652 self.writeBlock()
1688 self.writeBlock()
1653
1689
1654 print "[Writing] Block No. %d/%d" %(self.blockIndex,
1690 print "[Writing] Block No. %d/%d" % (self.blockIndex,
1655 self.processingHeaderObj.dataBlocksPerFile)
1691 self.processingHeaderObj.dataBlocksPerFile)
1656
1692
1657 return 1
1693 return 1
1658
1694
1659 def setNextFile(self):
1695 def setNextFile(self):
1660 """
1696 """
1661 Determina el siguiente file que sera escrito
1697 Determina el siguiente file que sera escrito
1662
1698
1663 Affected:
1699 Affected:
1664 self.filename
1700 self.filename
1665 self.subfolder
1701 self.subfolder
1666 self.fp
1702 self.fp
1667 self.setFile
1703 self.setFile
1668 self.flagIsNewFile
1704 self.flagIsNewFile
1669
1705
1670 Return:
1706 Return:
1671 0 : Si el archivo no puede ser escrito
1707 0 : Si el archivo no puede ser escrito
1672 1 : Si el archivo esta listo para ser escrito
1708 1 : Si el archivo esta listo para ser escrito
1673 """
1709 """
1674 ext = self.ext
1710 ext = self.ext
1675 path = self.path
1711 path = self.path
1676
1712
1677 if self.fp != None:
1713 if self.fp != None:
1678 self.fp.close()
1714 self.fp.close()
1679
1715
1680 timeTuple = time.localtime( self.dataOut.utctime)
1716 timeTuple = time.localtime(self.dataOut.utctime)
1681 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1717 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year, timeTuple.tm_yday)
1682
1718
1683 fullpath = os.path.join( path, subfolder )
1719 fullpath = os.path.join(path, subfolder)
1684 setFile = self.setFile
1720 setFile = self.setFile
1685
1721
1686 if not( os.path.exists(fullpath) ):
1722 if not(os.path.exists(fullpath)):
1687 os.mkdir(fullpath)
1723 os.mkdir(fullpath)
1688 setFile = -1 #inicializo mi contador de seteo
1724 setFile = -1 # inicializo mi contador de seteo
1689 else:
1725 else:
1690 filesList = os.listdir( fullpath )
1726 filesList = os.listdir(fullpath)
1691 if len( filesList ) > 0:
1727 if len(filesList) > 0:
1692 filesList = sorted( filesList, key=str.lower )
1728 filesList = sorted(filesList, key=str.lower)
1693 filen = filesList[-1]
1729 filen = filesList[-1]
1694 # el filename debera tener el siguiente formato
1730 # el filename debera tener el siguiente formato
1695 # 0 1234 567 89A BCDE (hex)
1731 # 0 1234 567 89A BCDE (hex)
1696 # x YYYY DDD SSS .ext
1732 # x YYYY DDD SSS .ext
1697 if isNumber( filen[8:11] ):
1733 if isNumber(filen[8:11]):
1698 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1734 # inicializo mi contador de seteo al seteo del ultimo file
1735 setFile = int(filen[8:11])
1699 else:
1736 else:
1700 setFile = -1
1737 setFile = -1
1701 else:
1738 else:
1702 setFile = -1 #inicializo mi contador de seteo
1739 setFile = -1 # inicializo mi contador de seteo
1703
1740
1704 setFile += 1
1741 setFile += 1
1705
1742
1706 #If this is a new day it resets some values
1743 # If this is a new day it resets some values
1707 if self.dataOut.datatime.date() > self.fileDate:
1744 if self.dataOut.datatime.date() > self.fileDate:
1708 setFile = 0
1745 setFile = 0
1709 self.nTotalBlocks = 0
1746 self.nTotalBlocks = 0
1710
1747
1711 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext )
1748 filen = '%s%4.4d%3.3d%3.3d%s' % (
1749 self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext)
1712
1750
1713 filename = os.path.join( path, subfolder, filen )
1751 filename = os.path.join(path, subfolder, filen)
1714
1752
1715 fp = open( filename,'wb' )
1753 fp = open(filename, 'wb')
1716
1754
1717 self.blockIndex = 0
1755 self.blockIndex = 0
1718
1756
1719 #guardando atributos
1757 # guardando atributos
1720 self.filename = filename
1758 self.filename = filename
1721 self.subfolder = subfolder
1759 self.subfolder = subfolder
1722 self.fp = fp
1760 self.fp = fp
1723 self.setFile = setFile
1761 self.setFile = setFile
1724 self.flagIsNewFile = 1
1762 self.flagIsNewFile = 1
1725 self.fileDate = self.dataOut.datatime.date()
1763 self.fileDate = self.dataOut.datatime.date()
1726
1764
1727 self.setFirstHeader()
1765 self.setFirstHeader()
1728
1766
1729 print '[Writing] Opening file: %s'%self.filename
1767 print '[Writing] Opening file: %s' % self.filename
1730
1768
1731 self.__writeFirstHeader()
1769 self.__writeFirstHeader()
1732
1770
1733 return 1
1771 return 1
1734
1772
1735 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1773 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1736 """
1774 """
1737 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1775 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1738
1776
1739 Inputs:
1777 Inputs:
1740 path : directory where data will be saved
1778 path : directory where data will be saved
1741 profilesPerBlock : number of profiles per block
1779 profilesPerBlock : number of profiles per block
1742 set : initial file set
1780 set : initial file set
1743 datatype : An integer number that defines data type:
1781 datatype : An integer number that defines data type:
1744 0 : int8 (1 byte)
1782 0 : int8 (1 byte)
1745 1 : int16 (2 bytes)
1783 1 : int16 (2 bytes)
1746 2 : int32 (4 bytes)
1784 2 : int32 (4 bytes)
1747 3 : int64 (8 bytes)
1785 3 : int64 (8 bytes)
1748 4 : float32 (4 bytes)
1786 4 : float32 (4 bytes)
1749 5 : double64 (8 bytes)
1787 5 : double64 (8 bytes)
1750
1788
1751 Return:
1789 Return:
1752 0 : Si no realizo un buen seteo
1790 0 : Si no realizo un buen seteo
1753 1 : Si realizo un buen seteo
1791 1 : Si realizo un buen seteo
1754 """
1792 """
1755
1793
1756 if ext == None:
1794 if ext == None:
1757 ext = self.ext
1795 ext = self.ext
1758
1796
1759 self.ext = ext.lower()
1797 self.ext = ext.lower()
1760
1798
1761 self.path = path
1799 self.path = path
1762
1800
1763 if set is None:
1801 if set is None:
1764 self.setFile = -1
1802 self.setFile = -1
1765 else:
1803 else:
1766 self.setFile = set - 1
1804 self.setFile = set - 1
1767
1805
1768 self.blocksPerFile = blocksPerFile
1806 self.blocksPerFile = blocksPerFile
1769
1807
1770 self.profilesPerBlock = profilesPerBlock
1808 self.profilesPerBlock = profilesPerBlock
1771
1809
1772 self.dataOut = dataOut
1810 self.dataOut = dataOut
1773 self.fileDate = self.dataOut.datatime.date()
1811 self.fileDate = self.dataOut.datatime.date()
1774 #By default
1812 # By default
1775 self.dtype = self.dataOut.dtype
1813 self.dtype = self.dataOut.dtype
1776
1814
1777 if datatype is not None:
1815 if datatype is not None:
1778 self.dtype = get_numpy_dtype(datatype)
1816 self.dtype = get_numpy_dtype(datatype)
1779
1817
1780 if not(self.setNextFile()):
1818 if not(self.setNextFile()):
1781 print "[Writing] There isn't a next file"
1819 print "[Writing] There isn't a next file"
1782 return 0
1820 return 0
1783
1821
1784 self.setBlockDimension()
1822 self.setBlockDimension()
1785
1823
1786 return 1
1824 return 1
1787
1825
1788 def run(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1826 def run(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1789
1827
1790 if not(self.isConfig):
1828 if not(self.isConfig):
1791
1829
1792 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock, set=set, ext=ext, datatype=datatype, **kwargs)
1830 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock,
1831 set=set, ext=ext, datatype=datatype, **kwargs)
1793 self.isConfig = True
1832 self.isConfig = True
1794
1833
1795 self.putData()
1834 self.putData()
@@ -1,1095 +1,1095
1 import numpy
1 import numpy
2 import time
2 import time
3 import os
3 import os
4 import h5py
4 import h5py
5 import re
5 import re
6 import datetime
6 import datetime
7
7
8 from schainpy.model.data.jrodata import *
8 from schainpy.model.data.jrodata import *
9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
10 # from jroIO_base import *
10 # from jroIO_base import *
11 from schainpy.model.io.jroIO_base import *
11 from schainpy.model.io.jroIO_base import *
12 import schainpy
12 import schainpy
13
13
14
14
15 class ParamReader(ProcessingUnit):
15 class ParamReader(ProcessingUnit):
16 '''
16 '''
17 Reads HDF5 format files
17 Reads HDF5 format files
18
18
19 path
19 path
20
20
21 startDate
21 startDate
22
22
23 endDate
23 endDate
24
24
25 startTime
25 startTime
26
26
27 endTime
27 endTime
28 '''
28 '''
29
29
30 ext = ".hdf5"
30 ext = ".hdf5"
31
31
32 optchar = "D"
32 optchar = "D"
33
33
34 timezone = None
34 timezone = None
35
35
36 startTime = None
36 startTime = None
37
37
38 endTime = None
38 endTime = None
39
39
40 fileIndex = None
40 fileIndex = None
41
41
42 utcList = None #To select data in the utctime list
42 utcList = None #To select data in the utctime list
43
43
44 blockList = None #List to blocks to be read from the file
44 blockList = None #List to blocks to be read from the file
45
45
46 blocksPerFile = None #Number of blocks to be read
46 blocksPerFile = None #Number of blocks to be read
47
47
48 blockIndex = None
48 blockIndex = None
49
49
50 path = None
50 path = None
51
51
52 #List of Files
52 #List of Files
53
53
54 filenameList = None
54 filenameList = None
55
55
56 datetimeList = None
56 datetimeList = None
57
57
58 #Hdf5 File
58 #Hdf5 File
59
59
60 listMetaname = None
60 listMetaname = None
61
61
62 listMeta = None
62 listMeta = None
63
63
64 listDataname = None
64 listDataname = None
65
65
66 listData = None
66 listData = None
67
67
68 listShapes = None
68 listShapes = None
69
69
70 fp = None
70 fp = None
71
71
72 #dataOut reconstruction
72 #dataOut reconstruction
73
73
74 dataOut = None
74 dataOut = None
75
75
76
76
77 def __init__(self, **kwargs):
77 def __init__(self, **kwargs):
78 ProcessingUnit.__init__(self, **kwargs)
78 ProcessingUnit.__init__(self, **kwargs)
79 self.dataOut = Parameters()
79 self.dataOut = Parameters()
80 return
80 return
81
81
82 def setup(self, **kwargs):
82 def setup(self, **kwargs):
83
83
84 path = kwargs['path']
84 path = kwargs['path']
85 startDate = kwargs['startDate']
85 startDate = kwargs['startDate']
86 endDate = kwargs['endDate']
86 endDate = kwargs['endDate']
87 startTime = kwargs['startTime']
87 startTime = kwargs['startTime']
88 endTime = kwargs['endTime']
88 endTime = kwargs['endTime']
89 walk = kwargs['walk']
89 walk = kwargs['walk']
90 if kwargs.has_key('ext'):
90 if kwargs.has_key('ext'):
91 ext = kwargs['ext']
91 ext = kwargs['ext']
92 else:
92 else:
93 ext = '.hdf5'
93 ext = '.hdf5'
94 if kwargs.has_key('timezone'):
94 if kwargs.has_key('timezone'):
95 self.timezone = kwargs['timezone']
95 self.timezone = kwargs['timezone']
96 else:
96 else:
97 self.timezone = 'lt'
97 self.timezone = 'lt'
98
98
99 print "[Reading] Searching files in offline mode ..."
99 print "[Reading] Searching files in offline mode ..."
100 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
100 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
101 startTime=startTime, endTime=endTime,
101 startTime=startTime, endTime=endTime,
102 ext=ext, walk=walk)
102 ext=ext, walk=walk)
103
103
104 if not(filenameList):
104 if not(filenameList):
105 print "There is no files into the folder: %s"%(path)
105 print "There is no files into the folder: %s"%(path)
106 sys.exit(-1)
106 sys.exit(-1)
107
107
108 self.fileIndex = -1
108 self.fileIndex = -1
109 self.startTime = startTime
109 self.startTime = startTime
110 self.endTime = endTime
110 self.endTime = endTime
111
111
112 self.__readMetadata()
112 self.__readMetadata()
113
113
114 self.__setNextFileOffline()
114 self.__setNextFileOffline()
115
115
116 return
116 return
117
117
118 def searchFilesOffLine(self,
118 def searchFilesOffLine(self,
119 path,
119 path,
120 startDate=None,
120 startDate=None,
121 endDate=None,
121 endDate=None,
122 startTime=datetime.time(0,0,0),
122 startTime=datetime.time(0,0,0),
123 endTime=datetime.time(23,59,59),
123 endTime=datetime.time(23,59,59),
124 ext='.hdf5',
124 ext='.hdf5',
125 walk=True):
125 walk=True):
126
126
127 expLabel = ''
127 expLabel = ''
128 self.filenameList = []
128 self.filenameList = []
129 self.datetimeList = []
129 self.datetimeList = []
130
130
131 pathList = []
131 pathList = []
132
132
133 JRODataObj = JRODataReader()
133 JRODataObj = JRODataReader()
134 dateList, pathList = JRODataObj.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
134 dateList, pathList = JRODataObj.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
135
135
136 if dateList == []:
136 if dateList == []:
137 print "[Reading] No *%s files in %s from %s to %s)"%(ext, path,
137 print "[Reading] No *%s files in %s from %s to %s)"%(ext, path,
138 datetime.datetime.combine(startDate,startTime).ctime(),
138 datetime.datetime.combine(startDate,startTime).ctime(),
139 datetime.datetime.combine(endDate,endTime).ctime())
139 datetime.datetime.combine(endDate,endTime).ctime())
140
140
141 return None, None
141 return None, None
142
142
143 if len(dateList) > 1:
143 if len(dateList) > 1:
144 print "[Reading] %d days were found in date range: %s - %s" %(len(dateList), startDate, endDate)
144 print "[Reading] %d days were found in date range: %s - %s" %(len(dateList), startDate, endDate)
145 else:
145 else:
146 print "[Reading] data was found for the date %s" %(dateList[0])
146 print "[Reading] data was found for the date %s" %(dateList[0])
147
147
148 filenameList = []
148 filenameList = []
149 datetimeList = []
149 datetimeList = []
150
150
151 #----------------------------------------------------------------------------------
151 #----------------------------------------------------------------------------------
152
152
153 for thisPath in pathList:
153 for thisPath in pathList:
154 # thisPath = pathList[pathDict[file]]
154 # thisPath = pathList[pathDict[file]]
155
155
156 fileList = glob.glob1(thisPath, "*%s" %ext)
156 fileList = glob.glob1(thisPath, "*%s" %ext)
157 fileList.sort()
157 fileList.sort()
158
158
159 for file in fileList:
159 for file in fileList:
160
160
161 filename = os.path.join(thisPath,file)
161 filename = os.path.join(thisPath,file)
162
162
163 if not isFileInDateRange(filename, startDate, endDate):
163 if not isFileInDateRange(filename, startDate, endDate):
164 continue
164 continue
165
165
166 thisDatetime = self.__isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
166 thisDatetime = self.__isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
167
167
168 if not(thisDatetime):
168 if not(thisDatetime):
169 continue
169 continue
170
170
171 filenameList.append(filename)
171 filenameList.append(filename)
172 datetimeList.append(thisDatetime)
172 datetimeList.append(thisDatetime)
173
173
174 if not(filenameList):
174 if not(filenameList):
175 print "[Reading] Any file was found int time range %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
175 print "[Reading] Any file was found int time range %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
176 return None, None
176 return None, None
177
177
178 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
178 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
179 print
179 print
180
180
181 for i in range(len(filenameList)):
181 # for i in range(len(filenameList)):
182 print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
182 # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
183
183
184 self.filenameList = filenameList
184 self.filenameList = filenameList
185 self.datetimeList = datetimeList
185 self.datetimeList = datetimeList
186
186
187 return pathList, filenameList
187 return pathList, filenameList
188
188
189 def __isFileInTimeRange(self,filename, startDate, endDate, startTime, endTime):
189 def __isFileInTimeRange(self,filename, startDate, endDate, startTime, endTime):
190
190
191 """
191 """
192 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
192 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
193
193
194 Inputs:
194 Inputs:
195 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
195 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
196
196
197 startDate : fecha inicial del rango seleccionado en formato datetime.date
197 startDate : fecha inicial del rango seleccionado en formato datetime.date
198
198
199 endDate : fecha final del rango seleccionado en formato datetime.date
199 endDate : fecha final del rango seleccionado en formato datetime.date
200
200
201 startTime : tiempo inicial del rango seleccionado en formato datetime.time
201 startTime : tiempo inicial del rango seleccionado en formato datetime.time
202
202
203 endTime : tiempo final del rango seleccionado en formato datetime.time
203 endTime : tiempo final del rango seleccionado en formato datetime.time
204
204
205 Return:
205 Return:
206 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
206 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
207 fecha especificado, de lo contrario retorna False.
207 fecha especificado, de lo contrario retorna False.
208
208
209 Excepciones:
209 Excepciones:
210 Si el archivo no existe o no puede ser abierto
210 Si el archivo no existe o no puede ser abierto
211 Si la cabecera no puede ser leida.
211 Si la cabecera no puede ser leida.
212
212
213 """
213 """
214
214
215 try:
215 try:
216 fp = h5py.File(filename,'r')
216 fp = h5py.File(filename,'r')
217 grp1 = fp['Data']
217 grp1 = fp['Data']
218
218
219 except IOError:
219 except IOError:
220 traceback.print_exc()
220 traceback.print_exc()
221 raise IOError, "The file %s can't be opened" %(filename)
221 raise IOError, "The file %s can't be opened" %(filename)
222 #chino rata
222 #chino rata
223 #In case has utctime attribute
223 #In case has utctime attribute
224 grp2 = grp1['utctime']
224 grp2 = grp1['utctime']
225 # thisUtcTime = grp2.value[0] - 5*3600 #To convert to local time
225 # thisUtcTime = grp2.value[0] - 5*3600 #To convert to local time
226 thisUtcTime = grp2.value[0]
226 thisUtcTime = grp2.value[0]
227
227
228 fp.close()
228 fp.close()
229
229
230 if self.timezone == 'lt':
230 if self.timezone == 'lt':
231 thisUtcTime -= 5*3600
231 thisUtcTime -= 5*3600
232
232
233 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
233 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
234 # thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0])
234 # thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0])
235 thisDate = thisDatetime.date()
235 thisDate = thisDatetime.date()
236 thisTime = thisDatetime.time()
236 thisTime = thisDatetime.time()
237
237
238 startUtcTime = (datetime.datetime.combine(thisDate,startTime)- datetime.datetime(1970, 1, 1)).total_seconds()
238 startUtcTime = (datetime.datetime.combine(thisDate,startTime)- datetime.datetime(1970, 1, 1)).total_seconds()
239 endUtcTime = (datetime.datetime.combine(thisDate,endTime)- datetime.datetime(1970, 1, 1)).total_seconds()
239 endUtcTime = (datetime.datetime.combine(thisDate,endTime)- datetime.datetime(1970, 1, 1)).total_seconds()
240
240
241 #General case
241 #General case
242 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
242 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
243 #-----------o----------------------------o-----------
243 #-----------o----------------------------o-----------
244 # startTime endTime
244 # startTime endTime
245
245
246 if endTime >= startTime:
246 if endTime >= startTime:
247 thisUtcLog = numpy.logical_and(thisUtcTime > startUtcTime, thisUtcTime < endUtcTime)
247 thisUtcLog = numpy.logical_and(thisUtcTime > startUtcTime, thisUtcTime < endUtcTime)
248 if numpy.any(thisUtcLog): #If there is one block between the hours mentioned
248 if numpy.any(thisUtcLog): #If there is one block between the hours mentioned
249 return thisDatetime
249 return thisDatetime
250 return None
250 return None
251
251
252 #If endTime < startTime then endTime belongs to the next day
252 #If endTime < startTime then endTime belongs to the next day
253 #<<<<<<<<<<<o o>>>>>>>>>>>
253 #<<<<<<<<<<<o o>>>>>>>>>>>
254 #-----------o----------------------------o-----------
254 #-----------o----------------------------o-----------
255 # endTime startTime
255 # endTime startTime
256
256
257 if (thisDate == startDate) and numpy.all(thisUtcTime < startUtcTime):
257 if (thisDate == startDate) and numpy.all(thisUtcTime < startUtcTime):
258 return None
258 return None
259
259
260 if (thisDate == endDate) and numpy.all(thisUtcTime > endUtcTime):
260 if (thisDate == endDate) and numpy.all(thisUtcTime > endUtcTime):
261 return None
261 return None
262
262
263 if numpy.all(thisUtcTime < startUtcTime) and numpy.all(thisUtcTime > endUtcTime):
263 if numpy.all(thisUtcTime < startUtcTime) and numpy.all(thisUtcTime > endUtcTime):
264 return None
264 return None
265
265
266 return thisDatetime
266 return thisDatetime
267
267
268 def __setNextFileOffline(self):
268 def __setNextFileOffline(self):
269
269
270 self.fileIndex += 1
270 self.fileIndex += 1
271 idFile = self.fileIndex
271 idFile = self.fileIndex
272
272
273 if not(idFile < len(self.filenameList)):
273 if not(idFile < len(self.filenameList)):
274 print "No more Files"
274 print "No more Files"
275 return 0
275 return 0
276
276
277 filename = self.filenameList[idFile]
277 filename = self.filenameList[idFile]
278
278
279 filePointer = h5py.File(filename,'r')
279 filePointer = h5py.File(filename,'r')
280
280
281 self.filename = filename
281 self.filename = filename
282
282
283 self.fp = filePointer
283 self.fp = filePointer
284
284
285 print "Setting the file: %s"%self.filename
285 print "Setting the file: %s"%self.filename
286
286
287 # self.__readMetadata()
287 # self.__readMetadata()
288 self.__setBlockList()
288 self.__setBlockList()
289 self.__readData()
289 self.__readData()
290 # self.nRecords = self.fp['Data'].attrs['blocksPerFile']
290 # self.nRecords = self.fp['Data'].attrs['blocksPerFile']
291 # self.nRecords = self.fp['Data'].attrs['nRecords']
291 # self.nRecords = self.fp['Data'].attrs['nRecords']
292 self.blockIndex = 0
292 self.blockIndex = 0
293 return 1
293 return 1
294
294
295 def __setBlockList(self):
295 def __setBlockList(self):
296 '''
296 '''
297 Selects the data within the times defined
297 Selects the data within the times defined
298
298
299 self.fp
299 self.fp
300 self.startTime
300 self.startTime
301 self.endTime
301 self.endTime
302
302
303 self.blockList
303 self.blockList
304 self.blocksPerFile
304 self.blocksPerFile
305
305
306 '''
306 '''
307 fp = self.fp
307 fp = self.fp
308 startTime = self.startTime
308 startTime = self.startTime
309 endTime = self.endTime
309 endTime = self.endTime
310
310
311 grp = fp['Data']
311 grp = fp['Data']
312 thisUtcTime = grp['utctime'].value.astype(numpy.float)[0]
312 thisUtcTime = grp['utctime'].value.astype(numpy.float)[0]
313
313
314 #ERROOOOR
314 #ERROOOOR
315 if self.timezone == 'lt':
315 if self.timezone == 'lt':
316 thisUtcTime -= 5*3600
316 thisUtcTime -= 5*3600
317
317
318 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
318 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
319
319
320 thisDate = thisDatetime.date()
320 thisDate = thisDatetime.date()
321 thisTime = thisDatetime.time()
321 thisTime = thisDatetime.time()
322
322
323 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
323 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
324 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
324 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
325
325
326 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
326 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
327
327
328 self.blockList = ind
328 self.blockList = ind
329 self.blocksPerFile = len(ind)
329 self.blocksPerFile = len(ind)
330
330
331 return
331 return
332
332
333 def __readMetadata(self):
333 def __readMetadata(self):
334 '''
334 '''
335 Reads Metadata
335 Reads Metadata
336
336
337 self.pathMeta
337 self.pathMeta
338
338
339 self.listShapes
339 self.listShapes
340 self.listMetaname
340 self.listMetaname
341 self.listMeta
341 self.listMeta
342
342
343 '''
343 '''
344
344
345 # grp = self.fp['Data']
345 # grp = self.fp['Data']
346 # pathMeta = os.path.join(self.path, grp.attrs['metadata'])
346 # pathMeta = os.path.join(self.path, grp.attrs['metadata'])
347 #
347 #
348 # if pathMeta == self.pathMeta:
348 # if pathMeta == self.pathMeta:
349 # return
349 # return
350 # else:
350 # else:
351 # self.pathMeta = pathMeta
351 # self.pathMeta = pathMeta
352 #
352 #
353 # filePointer = h5py.File(self.pathMeta,'r')
353 # filePointer = h5py.File(self.pathMeta,'r')
354 # groupPointer = filePointer['Metadata']
354 # groupPointer = filePointer['Metadata']
355
355
356 filename = self.filenameList[0]
356 filename = self.filenameList[0]
357
357
358 fp = h5py.File(filename,'r')
358 fp = h5py.File(filename,'r')
359
359
360 gp = fp['Metadata']
360 gp = fp['Metadata']
361
361
362 listMetaname = []
362 listMetaname = []
363 listMetadata = []
363 listMetadata = []
364 for item in gp.items():
364 for item in gp.items():
365 name = item[0]
365 name = item[0]
366
366
367 if name=='array dimensions':
367 if name=='array dimensions':
368 table = gp[name][:]
368 table = gp[name][:]
369 listShapes = {}
369 listShapes = {}
370 for shapes in table:
370 for shapes in table:
371 listShapes[shapes[0]] = numpy.array([shapes[1],shapes[2],shapes[3],shapes[4],shapes[5]])
371 listShapes[shapes[0]] = numpy.array([shapes[1],shapes[2],shapes[3],shapes[4],shapes[5]])
372 else:
372 else:
373 data = gp[name].value
373 data = gp[name].value
374 listMetaname.append(name)
374 listMetaname.append(name)
375 listMetadata.append(data)
375 listMetadata.append(data)
376
376
377 # if name=='type':
377 # if name=='type':
378 # self.__initDataOut(data)
378 # self.__initDataOut(data)
379
379
380 self.listShapes = listShapes
380 self.listShapes = listShapes
381 self.listMetaname = listMetaname
381 self.listMetaname = listMetaname
382 self.listMeta = listMetadata
382 self.listMeta = listMetadata
383
383
384 fp.close()
384 fp.close()
385 return
385 return
386
386
387 def __readData(self):
387 def __readData(self):
388 grp = self.fp['Data']
388 grp = self.fp['Data']
389 listdataname = []
389 listdataname = []
390 listdata = []
390 listdata = []
391
391
392 for item in grp.items():
392 for item in grp.items():
393 name = item[0]
393 name = item[0]
394 listdataname.append(name)
394 listdataname.append(name)
395
395
396 array = self.__setDataArray(grp[name],self.listShapes[name])
396 array = self.__setDataArray(grp[name],self.listShapes[name])
397 listdata.append(array)
397 listdata.append(array)
398
398
399 self.listDataname = listdataname
399 self.listDataname = listdataname
400 self.listData = listdata
400 self.listData = listdata
401 return
401 return
402
402
403 def __setDataArray(self, dataset, shapes):
403 def __setDataArray(self, dataset, shapes):
404
404
405 nDims = shapes[0]
405 nDims = shapes[0]
406
406
407 nDim2 = shapes[1] #Dimension 0
407 nDim2 = shapes[1] #Dimension 0
408
408
409 nDim1 = shapes[2] #Dimension 1, number of Points or Parameters
409 nDim1 = shapes[2] #Dimension 1, number of Points or Parameters
410
410
411 nDim0 = shapes[3] #Dimension 2, number of samples or ranges
411 nDim0 = shapes[3] #Dimension 2, number of samples or ranges
412
412
413 mode = shapes[4] #Mode of storing
413 mode = shapes[4] #Mode of storing
414
414
415 blockList = self.blockList
415 blockList = self.blockList
416
416
417 blocksPerFile = self.blocksPerFile
417 blocksPerFile = self.blocksPerFile
418
418
419 #Depending on what mode the data was stored
419 #Depending on what mode the data was stored
420 if mode == 0: #Divided in channels
420 if mode == 0: #Divided in channels
421 arrayData = dataset.value.astype(numpy.float)[0][blockList]
421 arrayData = dataset.value.astype(numpy.float)[0][blockList]
422 if mode == 1: #Divided in parameter
422 if mode == 1: #Divided in parameter
423 strds = 'table'
423 strds = 'table'
424 nDatas = nDim1
424 nDatas = nDim1
425 newShapes = (blocksPerFile,nDim2,nDim0)
425 newShapes = (blocksPerFile,nDim2,nDim0)
426 elif mode==2: #Concatenated in a table
426 elif mode==2: #Concatenated in a table
427 strds = 'table0'
427 strds = 'table0'
428 arrayData = dataset[strds].value
428 arrayData = dataset[strds].value
429 #Selecting part of the dataset
429 #Selecting part of the dataset
430 utctime = arrayData[:,0]
430 utctime = arrayData[:,0]
431 u, indices = numpy.unique(utctime, return_index=True)
431 u, indices = numpy.unique(utctime, return_index=True)
432
432
433 if blockList.size != indices.size:
433 if blockList.size != indices.size:
434 indMin = indices[blockList[0]]
434 indMin = indices[blockList[0]]
435 if blockList[1] + 1 >= indices.size:
435 if blockList[1] + 1 >= indices.size:
436 arrayData = arrayData[indMin:,:]
436 arrayData = arrayData[indMin:,:]
437 else:
437 else:
438 indMax = indices[blockList[1] + 1]
438 indMax = indices[blockList[1] + 1]
439 arrayData = arrayData[indMin:indMax,:]
439 arrayData = arrayData[indMin:indMax,:]
440 return arrayData
440 return arrayData
441
441
442 # One dimension
442 # One dimension
443 if nDims == 0:
443 if nDims == 0:
444 arrayData = dataset.value.astype(numpy.float)[0][blockList]
444 arrayData = dataset.value.astype(numpy.float)[0][blockList]
445
445
446 # Two dimensions
446 # Two dimensions
447 elif nDims == 2:
447 elif nDims == 2:
448 arrayData = numpy.zeros((blocksPerFile,nDim1,nDim0))
448 arrayData = numpy.zeros((blocksPerFile,nDim1,nDim0))
449 newShapes = (blocksPerFile,nDim0)
449 newShapes = (blocksPerFile,nDim0)
450 nDatas = nDim1
450 nDatas = nDim1
451
451
452 for i in range(nDatas):
452 for i in range(nDatas):
453 data = dataset[strds + str(i)].value
453 data = dataset[strds + str(i)].value
454 arrayData[:,i,:] = data[blockList,:]
454 arrayData[:,i,:] = data[blockList,:]
455
455
456 # Three dimensions
456 # Three dimensions
457 else:
457 else:
458 arrayData = numpy.zeros((blocksPerFile,nDim2,nDim1,nDim0))
458 arrayData = numpy.zeros((blocksPerFile,nDim2,nDim1,nDim0))
459 for i in range(nDatas):
459 for i in range(nDatas):
460
460
461 data = dataset[strds + str(i)].value
461 data = dataset[strds + str(i)].value
462
462
463 for b in range(blockList.size):
463 for b in range(blockList.size):
464 arrayData[b,:,i,:] = data[:,:,blockList[b]]
464 arrayData[b,:,i,:] = data[:,:,blockList[b]]
465
465
466 return arrayData
466 return arrayData
467
467
468 def __setDataOut(self):
468 def __setDataOut(self):
469 listMeta = self.listMeta
469 listMeta = self.listMeta
470 listMetaname = self.listMetaname
470 listMetaname = self.listMetaname
471 listDataname = self.listDataname
471 listDataname = self.listDataname
472 listData = self.listData
472 listData = self.listData
473 listShapes = self.listShapes
473 listShapes = self.listShapes
474
474
475 blockIndex = self.blockIndex
475 blockIndex = self.blockIndex
476 # blockList = self.blockList
476 # blockList = self.blockList
477
477
478 for i in range(len(listMeta)):
478 for i in range(len(listMeta)):
479 setattr(self.dataOut,listMetaname[i],listMeta[i])
479 setattr(self.dataOut,listMetaname[i],listMeta[i])
480
480
481 for j in range(len(listData)):
481 for j in range(len(listData)):
482 nShapes = listShapes[listDataname[j]][0]
482 nShapes = listShapes[listDataname[j]][0]
483 mode = listShapes[listDataname[j]][4]
483 mode = listShapes[listDataname[j]][4]
484 if nShapes == 1:
484 if nShapes == 1:
485 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
485 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
486 elif nShapes > 1:
486 elif nShapes > 1:
487 setattr(self.dataOut,listDataname[j],listData[j][blockIndex,:])
487 setattr(self.dataOut,listDataname[j],listData[j][blockIndex,:])
488 elif mode==0:
488 elif mode==0:
489 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
489 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
490 #Mode Meteors
490 #Mode Meteors
491 elif mode ==2:
491 elif mode ==2:
492 selectedData = self.__selectDataMode2(listData[j], blockIndex)
492 selectedData = self.__selectDataMode2(listData[j], blockIndex)
493 setattr(self.dataOut, listDataname[j], selectedData)
493 setattr(self.dataOut, listDataname[j], selectedData)
494 return
494 return
495
495
496 def __selectDataMode2(self, data, blockIndex):
496 def __selectDataMode2(self, data, blockIndex):
497 utctime = data[:,0]
497 utctime = data[:,0]
498 aux, indices = numpy.unique(utctime, return_inverse=True)
498 aux, indices = numpy.unique(utctime, return_inverse=True)
499 selInd = numpy.where(indices == blockIndex)[0]
499 selInd = numpy.where(indices == blockIndex)[0]
500 selData = data[selInd,:]
500 selData = data[selInd,:]
501
501
502 return selData
502 return selData
503
503
504 def getData(self):
504 def getData(self):
505
505
506 # if self.flagNoMoreFiles:
506 # if self.flagNoMoreFiles:
507 # self.dataOut.flagNoData = True
507 # self.dataOut.flagNoData = True
508 # print 'Process finished'
508 # print 'Process finished'
509 # return 0
509 # return 0
510 #
510 #
511 if self.blockIndex==self.blocksPerFile:
511 if self.blockIndex==self.blocksPerFile:
512 if not( self.__setNextFileOffline() ):
512 if not( self.__setNextFileOffline() ):
513 self.dataOut.flagNoData = True
513 self.dataOut.flagNoData = True
514 return 0
514 return 0
515
515
516 # if self.datablock == None: # setear esta condicion cuando no hayan datos por leers
516 # if self.datablock == None: # setear esta condicion cuando no hayan datos por leers
517 # self.dataOut.flagNoData = True
517 # self.dataOut.flagNoData = True
518 # return 0
518 # return 0
519 # self.__readData()
519 # self.__readData()
520 self.__setDataOut()
520 self.__setDataOut()
521 self.dataOut.flagNoData = False
521 self.dataOut.flagNoData = False
522
522
523 self.blockIndex += 1
523 self.blockIndex += 1
524
524
525 return
525 return
526
526
527 def run(self, **kwargs):
527 def run(self, **kwargs):
528
528
529 if not(self.isConfig):
529 if not(self.isConfig):
530 self.setup(**kwargs)
530 self.setup(**kwargs)
531 # self.setObjProperties()
531 # self.setObjProperties()
532 self.isConfig = True
532 self.isConfig = True
533
533
534 self.getData()
534 self.getData()
535
535
536 return
536 return
537
537
538 class ParamWriter(Operation):
538 class ParamWriter(Operation):
539 '''
539 '''
540 HDF5 Writer, stores parameters data in HDF5 format files
540 HDF5 Writer, stores parameters data in HDF5 format files
541
541
542 path: path where the files will be stored
542 path: path where the files will be stored
543
543
544 blocksPerFile: number of blocks that will be saved in per HDF5 format file
544 blocksPerFile: number of blocks that will be saved in per HDF5 format file
545
545
546 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
546 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
547
547
548 metadataList: list of attributes that will be stored as metadata
548 metadataList: list of attributes that will be stored as metadata
549
549
550 dataList: list of attributes that will be stores as data
550 dataList: list of attributes that will be stores as data
551
551
552 '''
552 '''
553
553
554
554
555 ext = ".hdf5"
555 ext = ".hdf5"
556
556
557 optchar = "D"
557 optchar = "D"
558
558
559 metaoptchar = "M"
559 metaoptchar = "M"
560
560
561 metaFile = None
561 metaFile = None
562
562
563 filename = None
563 filename = None
564
564
565 path = None
565 path = None
566
566
567 setFile = None
567 setFile = None
568
568
569 fp = None
569 fp = None
570
570
571 grp = None
571 grp = None
572
572
573 ds = None
573 ds = None
574
574
575 firsttime = True
575 firsttime = True
576
576
577 #Configurations
577 #Configurations
578
578
579 blocksPerFile = None
579 blocksPerFile = None
580
580
581 blockIndex = None
581 blockIndex = None
582
582
583 dataOut = None
583 dataOut = None
584
584
585 #Data Arrays
585 #Data Arrays
586
586
587 dataList = None
587 dataList = None
588
588
589 metadataList = None
589 metadataList = None
590
590
591 # arrayDim = None
591 # arrayDim = None
592
592
593 dsList = None #List of dictionaries with dataset properties
593 dsList = None #List of dictionaries with dataset properties
594
594
595 tableDim = None
595 tableDim = None
596
596
597 # dtype = [('arrayName', 'S20'),('nChannels', 'i'), ('nPoints', 'i'), ('nSamples', 'i'),('mode', 'b')]
597 # dtype = [('arrayName', 'S20'),('nChannels', 'i'), ('nPoints', 'i'), ('nSamples', 'i'),('mode', 'b')]
598
598
599 dtype = [('arrayName', 'S20'),('nDimensions', 'i'), ('dim2', 'i'), ('dim1', 'i'),('dim0', 'i'),('mode', 'b')]
599 dtype = [('arrayName', 'S20'),('nDimensions', 'i'), ('dim2', 'i'), ('dim1', 'i'),('dim0', 'i'),('mode', 'b')]
600
600
601 currentDay = None
601 currentDay = None
602
602
603 lastTime = None
603 lastTime = None
604
604
605 def __init__(self, **kwargs):
605 def __init__(self, **kwargs):
606 Operation.__init__(self, **kwargs)
606 Operation.__init__(self, **kwargs)
607 self.isConfig = False
607 self.isConfig = False
608 return
608 return
609
609
610 def setup(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, **kwargs):
610 def setup(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, **kwargs):
611 self.path = path
611 self.path = path
612 self.blocksPerFile = blocksPerFile
612 self.blocksPerFile = blocksPerFile
613 self.metadataList = metadataList
613 self.metadataList = metadataList
614 self.dataList = dataList
614 self.dataList = dataList
615 self.dataOut = dataOut
615 self.dataOut = dataOut
616 self.mode = mode
616 self.mode = mode
617
617
618 if self.mode is not None:
618 if self.mode is not None:
619 self.mode = numpy.zeros(len(self.dataList)) + mode
619 self.mode = numpy.zeros(len(self.dataList)) + mode
620 else:
620 else:
621 self.mode = numpy.ones(len(self.dataList))
621 self.mode = numpy.ones(len(self.dataList))
622
622
623 arrayDim = numpy.zeros((len(self.dataList),5))
623 arrayDim = numpy.zeros((len(self.dataList),5))
624
624
625 #Table dimensions
625 #Table dimensions
626 dtype0 = self.dtype
626 dtype0 = self.dtype
627 tableList = []
627 tableList = []
628
628
629 #Dictionary and list of tables
629 #Dictionary and list of tables
630 dsList = []
630 dsList = []
631
631
632 for i in range(len(self.dataList)):
632 for i in range(len(self.dataList)):
633 dsDict = {}
633 dsDict = {}
634 dataAux = getattr(self.dataOut, self.dataList[i])
634 dataAux = getattr(self.dataOut, self.dataList[i])
635 dsDict['variable'] = self.dataList[i]
635 dsDict['variable'] = self.dataList[i]
636 #--------------------- Conditionals ------------------------
636 #--------------------- Conditionals ------------------------
637 #There is no data
637 #There is no data
638 if dataAux is None:
638 if dataAux is None:
639 return 0
639 return 0
640
640
641 #Not array, just a number
641 #Not array, just a number
642 #Mode 0
642 #Mode 0
643 if type(dataAux)==float or type(dataAux)==int:
643 if type(dataAux)==float or type(dataAux)==int:
644 dsDict['mode'] = 0
644 dsDict['mode'] = 0
645 dsDict['nDim'] = 0
645 dsDict['nDim'] = 0
646 arrayDim[i,0] = 0
646 arrayDim[i,0] = 0
647 dsList.append(dsDict)
647 dsList.append(dsDict)
648
648
649 #Mode 2: meteors
649 #Mode 2: meteors
650 elif mode[i] == 2:
650 elif mode[i] == 2:
651 # dsDict['nDim'] = 0
651 # dsDict['nDim'] = 0
652 dsDict['dsName'] = 'table0'
652 dsDict['dsName'] = 'table0'
653 dsDict['mode'] = 2 # Mode meteors
653 dsDict['mode'] = 2 # Mode meteors
654 dsDict['shape'] = dataAux.shape[-1]
654 dsDict['shape'] = dataAux.shape[-1]
655 dsDict['nDim'] = 0
655 dsDict['nDim'] = 0
656 dsDict['dsNumber'] = 1
656 dsDict['dsNumber'] = 1
657
657
658 arrayDim[i,3] = dataAux.shape[-1]
658 arrayDim[i,3] = dataAux.shape[-1]
659 arrayDim[i,4] = mode[i] #Mode the data was stored
659 arrayDim[i,4] = mode[i] #Mode the data was stored
660
660
661 dsList.append(dsDict)
661 dsList.append(dsDict)
662
662
663 #Mode 1
663 #Mode 1
664 else:
664 else:
665 arrayDim0 = dataAux.shape #Data dimensions
665 arrayDim0 = dataAux.shape #Data dimensions
666 arrayDim[i,0] = len(arrayDim0) #Number of array dimensions
666 arrayDim[i,0] = len(arrayDim0) #Number of array dimensions
667 arrayDim[i,4] = mode[i] #Mode the data was stored
667 arrayDim[i,4] = mode[i] #Mode the data was stored
668
668
669 strtable = 'table'
669 strtable = 'table'
670 dsDict['mode'] = 1 # Mode parameters
670 dsDict['mode'] = 1 # Mode parameters
671
671
672 # Three-dimension arrays
672 # Three-dimension arrays
673 if len(arrayDim0) == 3:
673 if len(arrayDim0) == 3:
674 arrayDim[i,1:-1] = numpy.array(arrayDim0)
674 arrayDim[i,1:-1] = numpy.array(arrayDim0)
675 nTables = int(arrayDim[i,2])
675 nTables = int(arrayDim[i,2])
676 dsDict['dsNumber'] = nTables
676 dsDict['dsNumber'] = nTables
677 dsDict['shape'] = arrayDim[i,2:4]
677 dsDict['shape'] = arrayDim[i,2:4]
678 dsDict['nDim'] = 3
678 dsDict['nDim'] = 3
679
679
680 for j in range(nTables):
680 for j in range(nTables):
681 dsDict = dsDict.copy()
681 dsDict = dsDict.copy()
682 dsDict['dsName'] = strtable + str(j)
682 dsDict['dsName'] = strtable + str(j)
683 dsList.append(dsDict)
683 dsList.append(dsDict)
684
684
685 # Two-dimension arrays
685 # Two-dimension arrays
686 elif len(arrayDim0) == 2:
686 elif len(arrayDim0) == 2:
687 arrayDim[i,2:-1] = numpy.array(arrayDim0)
687 arrayDim[i,2:-1] = numpy.array(arrayDim0)
688 nTables = int(arrayDim[i,2])
688 nTables = int(arrayDim[i,2])
689 dsDict['dsNumber'] = nTables
689 dsDict['dsNumber'] = nTables
690 dsDict['shape'] = arrayDim[i,3]
690 dsDict['shape'] = arrayDim[i,3]
691 dsDict['nDim'] = 2
691 dsDict['nDim'] = 2
692
692
693 for j in range(nTables):
693 for j in range(nTables):
694 dsDict = dsDict.copy()
694 dsDict = dsDict.copy()
695 dsDict['dsName'] = strtable + str(j)
695 dsDict['dsName'] = strtable + str(j)
696 dsList.append(dsDict)
696 dsList.append(dsDict)
697
697
698 # One-dimension arrays
698 # One-dimension arrays
699 elif len(arrayDim0) == 1:
699 elif len(arrayDim0) == 1:
700 arrayDim[i,3] = arrayDim0[0]
700 arrayDim[i,3] = arrayDim0[0]
701 dsDict['shape'] = arrayDim0[0]
701 dsDict['shape'] = arrayDim0[0]
702 dsDict['dsNumber'] = 1
702 dsDict['dsNumber'] = 1
703 dsDict['dsName'] = strtable + str(0)
703 dsDict['dsName'] = strtable + str(0)
704 dsDict['nDim'] = 1
704 dsDict['nDim'] = 1
705 dsList.append(dsDict)
705 dsList.append(dsDict)
706
706
707 table = numpy.array((self.dataList[i],) + tuple(arrayDim[i,:]),dtype = dtype0)
707 table = numpy.array((self.dataList[i],) + tuple(arrayDim[i,:]),dtype = dtype0)
708 tableList.append(table)
708 tableList.append(table)
709
709
710 # self.arrayDim = arrayDim
710 # self.arrayDim = arrayDim
711 self.dsList = dsList
711 self.dsList = dsList
712 self.tableDim = numpy.array(tableList, dtype = dtype0)
712 self.tableDim = numpy.array(tableList, dtype = dtype0)
713 self.blockIndex = 0
713 self.blockIndex = 0
714
714
715 timeTuple = time.localtime(dataOut.utctime)
715 timeTuple = time.localtime(dataOut.utctime)
716 self.currentDay = timeTuple.tm_yday
716 self.currentDay = timeTuple.tm_yday
717 return 1
717 return 1
718
718
719 def putMetadata(self):
719 def putMetadata(self):
720
720
721 fp = self.createMetadataFile()
721 fp = self.createMetadataFile()
722 self.writeMetadata(fp)
722 self.writeMetadata(fp)
723 fp.close()
723 fp.close()
724 return
724 return
725
725
726 def createMetadataFile(self):
726 def createMetadataFile(self):
727 ext = self.ext
727 ext = self.ext
728 path = self.path
728 path = self.path
729 setFile = self.setFile
729 setFile = self.setFile
730
730
731 timeTuple = time.localtime(self.dataOut.utctime)
731 timeTuple = time.localtime(self.dataOut.utctime)
732
732
733 subfolder = ''
733 subfolder = ''
734 fullpath = os.path.join( path, subfolder )
734 fullpath = os.path.join( path, subfolder )
735
735
736 if not( os.path.exists(fullpath) ):
736 if not( os.path.exists(fullpath) ):
737 os.mkdir(fullpath)
737 os.mkdir(fullpath)
738 setFile = -1 #inicializo mi contador de seteo
738 setFile = -1 #inicializo mi contador de seteo
739
739
740 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
740 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
741 fullpath = os.path.join( path, subfolder )
741 fullpath = os.path.join( path, subfolder )
742
742
743 if not( os.path.exists(fullpath) ):
743 if not( os.path.exists(fullpath) ):
744 os.mkdir(fullpath)
744 os.mkdir(fullpath)
745 setFile = -1 #inicializo mi contador de seteo
745 setFile = -1 #inicializo mi contador de seteo
746
746
747 else:
747 else:
748 filesList = os.listdir( fullpath )
748 filesList = os.listdir( fullpath )
749 filesList = sorted( filesList, key=str.lower )
749 filesList = sorted( filesList, key=str.lower )
750 if len( filesList ) > 0:
750 if len( filesList ) > 0:
751 filesList = [k for k in filesList if 'M' in k]
751 filesList = [k for k in filesList if 'M' in k]
752 filen = filesList[-1]
752 filen = filesList[-1]
753 # el filename debera tener el siguiente formato
753 # el filename debera tener el siguiente formato
754 # 0 1234 567 89A BCDE (hex)
754 # 0 1234 567 89A BCDE (hex)
755 # x YYYY DDD SSS .ext
755 # x YYYY DDD SSS .ext
756 if isNumber( filen[8:11] ):
756 if isNumber( filen[8:11] ):
757 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
757 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
758 else:
758 else:
759 setFile = -1
759 setFile = -1
760 else:
760 else:
761 setFile = -1 #inicializo mi contador de seteo
761 setFile = -1 #inicializo mi contador de seteo
762
762
763 if self.setType is None:
763 if self.setType is None:
764 setFile += 1
764 setFile += 1
765 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
765 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
766 timeTuple.tm_year,
766 timeTuple.tm_year,
767 timeTuple.tm_yday,
767 timeTuple.tm_yday,
768 setFile,
768 setFile,
769 ext )
769 ext )
770 else:
770 else:
771 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
771 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
772 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
772 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
773 timeTuple.tm_year,
773 timeTuple.tm_year,
774 timeTuple.tm_yday,
774 timeTuple.tm_yday,
775 setFile,
775 setFile,
776 ext )
776 ext )
777
777
778 filename = os.path.join( path, subfolder, file )
778 filename = os.path.join( path, subfolder, file )
779 self.metaFile = file
779 self.metaFile = file
780 #Setting HDF5 File
780 #Setting HDF5 File
781 fp = h5py.File(filename,'w')
781 fp = h5py.File(filename,'w')
782
782
783 return fp
783 return fp
784
784
785 def writeMetadata(self, fp):
785 def writeMetadata(self, fp):
786
786
787 grp = fp.create_group("Metadata")
787 grp = fp.create_group("Metadata")
788 grp.create_dataset('array dimensions', data = self.tableDim, dtype = self.dtype)
788 grp.create_dataset('array dimensions', data = self.tableDim, dtype = self.dtype)
789
789
790 for i in range(len(self.metadataList)):
790 for i in range(len(self.metadataList)):
791 grp.create_dataset(self.metadataList[i], data=getattr(self.dataOut, self.metadataList[i]))
791 grp.create_dataset(self.metadataList[i], data=getattr(self.dataOut, self.metadataList[i]))
792 return
792 return
793
793
794 def timeFlag(self):
794 def timeFlag(self):
795 currentTime = self.dataOut.utctime
795 currentTime = self.dataOut.utctime
796
796
797 if self.lastTime is None:
797 if self.lastTime is None:
798 self.lastTime = currentTime
798 self.lastTime = currentTime
799
799
800 #Day
800 #Day
801 timeTuple = time.localtime(currentTime)
801 timeTuple = time.localtime(currentTime)
802 dataDay = timeTuple.tm_yday
802 dataDay = timeTuple.tm_yday
803
803
804 #Time
804 #Time
805 timeDiff = currentTime - self.lastTime
805 timeDiff = currentTime - self.lastTime
806
806
807 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
807 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
808 if dataDay != self.currentDay:
808 if dataDay != self.currentDay:
809 self.currentDay = dataDay
809 self.currentDay = dataDay
810 return True
810 return True
811 elif timeDiff > 3*60*60:
811 elif timeDiff > 3*60*60:
812 self.lastTime = currentTime
812 self.lastTime = currentTime
813 return True
813 return True
814 else:
814 else:
815 self.lastTime = currentTime
815 self.lastTime = currentTime
816 return False
816 return False
817
817
818 def setNextFile(self):
818 def setNextFile(self):
819
819
820 ext = self.ext
820 ext = self.ext
821 path = self.path
821 path = self.path
822 setFile = self.setFile
822 setFile = self.setFile
823 mode = self.mode
823 mode = self.mode
824
824
825 timeTuple = time.localtime(self.dataOut.utctime)
825 timeTuple = time.localtime(self.dataOut.utctime)
826 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
826 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
827
827
828 fullpath = os.path.join( path, subfolder )
828 fullpath = os.path.join( path, subfolder )
829
829
830 if os.path.exists(fullpath):
830 if os.path.exists(fullpath):
831 filesList = os.listdir( fullpath )
831 filesList = os.listdir( fullpath )
832 filesList = [k for k in filesList if 'D' in k]
832 filesList = [k for k in filesList if 'D' in k]
833 if len( filesList ) > 0:
833 if len( filesList ) > 0:
834 filesList = sorted( filesList, key=str.lower )
834 filesList = sorted( filesList, key=str.lower )
835 filen = filesList[-1]
835 filen = filesList[-1]
836 # el filename debera tener el siguiente formato
836 # el filename debera tener el siguiente formato
837 # 0 1234 567 89A BCDE (hex)
837 # 0 1234 567 89A BCDE (hex)
838 # x YYYY DDD SSS .ext
838 # x YYYY DDD SSS .ext
839 if isNumber( filen[8:11] ):
839 if isNumber( filen[8:11] ):
840 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
840 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
841 else:
841 else:
842 setFile = -1
842 setFile = -1
843 else:
843 else:
844 setFile = -1 #inicializo mi contador de seteo
844 setFile = -1 #inicializo mi contador de seteo
845 else:
845 else:
846 os.makedirs(fullpath)
846 os.makedirs(fullpath)
847 setFile = -1 #inicializo mi contador de seteo
847 setFile = -1 #inicializo mi contador de seteo
848
848
849 if self.setType is None:
849 if self.setType is None:
850 setFile += 1
850 setFile += 1
851 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
851 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
852 timeTuple.tm_year,
852 timeTuple.tm_year,
853 timeTuple.tm_yday,
853 timeTuple.tm_yday,
854 setFile,
854 setFile,
855 ext )
855 ext )
856 else:
856 else:
857 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
857 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
858 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
858 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
859 timeTuple.tm_year,
859 timeTuple.tm_year,
860 timeTuple.tm_yday,
860 timeTuple.tm_yday,
861 setFile,
861 setFile,
862 ext )
862 ext )
863
863
864 filename = os.path.join( path, subfolder, file )
864 filename = os.path.join( path, subfolder, file )
865
865
866 #Setting HDF5 File
866 #Setting HDF5 File
867 fp = h5py.File(filename,'w')
867 fp = h5py.File(filename,'w')
868 #write metadata
868 #write metadata
869 self.writeMetadata(fp)
869 self.writeMetadata(fp)
870 #Write data
870 #Write data
871 grp = fp.create_group("Data")
871 grp = fp.create_group("Data")
872 # grp.attrs['metadata'] = self.metaFile
872 # grp.attrs['metadata'] = self.metaFile
873
873
874 # grp.attrs['blocksPerFile'] = 0
874 # grp.attrs['blocksPerFile'] = 0
875 ds = []
875 ds = []
876 data = []
876 data = []
877 dsList = self.dsList
877 dsList = self.dsList
878 i = 0
878 i = 0
879 while i < len(dsList):
879 while i < len(dsList):
880 dsInfo = dsList[i]
880 dsInfo = dsList[i]
881 #One-dimension data
881 #One-dimension data
882 if dsInfo['mode'] == 0:
882 if dsInfo['mode'] == 0:
883 # ds0 = grp.create_dataset(self.dataList[i], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype='S20')
883 # ds0 = grp.create_dataset(self.dataList[i], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype='S20')
884 ds0 = grp.create_dataset(dsInfo['variable'], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype=numpy.float64)
884 ds0 = grp.create_dataset(dsInfo['variable'], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype=numpy.float64)
885 ds.append(ds0)
885 ds.append(ds0)
886 data.append([])
886 data.append([])
887 i += 1
887 i += 1
888 continue
888 continue
889 # nDimsForDs.append(nDims[i])
889 # nDimsForDs.append(nDims[i])
890
890
891 elif dsInfo['mode'] == 2:
891 elif dsInfo['mode'] == 2:
892 grp0 = grp.create_group(dsInfo['variable'])
892 grp0 = grp.create_group(dsInfo['variable'])
893 ds0 = grp0.create_dataset(dsInfo['dsName'], (1,dsInfo['shape']), data = numpy.zeros((1,dsInfo['shape'])) , maxshape=(None,dsInfo['shape']), chunks=True)
893 ds0 = grp0.create_dataset(dsInfo['dsName'], (1,dsInfo['shape']), data = numpy.zeros((1,dsInfo['shape'])) , maxshape=(None,dsInfo['shape']), chunks=True)
894 ds.append(ds0)
894 ds.append(ds0)
895 data.append([])
895 data.append([])
896 i += 1
896 i += 1
897 continue
897 continue
898
898
899 elif dsInfo['mode'] == 1:
899 elif dsInfo['mode'] == 1:
900 grp0 = grp.create_group(dsInfo['variable'])
900 grp0 = grp.create_group(dsInfo['variable'])
901
901
902 for j in range(dsInfo['dsNumber']):
902 for j in range(dsInfo['dsNumber']):
903 dsInfo = dsList[i]
903 dsInfo = dsList[i]
904 tableName = dsInfo['dsName']
904 tableName = dsInfo['dsName']
905 shape = int(dsInfo['shape'])
905 shape = int(dsInfo['shape'])
906
906
907 if dsInfo['nDim'] == 3:
907 if dsInfo['nDim'] == 3:
908 ds0 = grp0.create_dataset(tableName, (shape[0],shape[1],1) , data = numpy.zeros((shape[0],shape[1],1)), maxshape = (None,shape[1],None), chunks=True)
908 ds0 = grp0.create_dataset(tableName, (shape[0],shape[1],1) , data = numpy.zeros((shape[0],shape[1],1)), maxshape = (None,shape[1],None), chunks=True)
909 else:
909 else:
910 ds0 = grp0.create_dataset(tableName, (1,shape), data = numpy.zeros((1,shape)) , maxshape=(None,shape), chunks=True)
910 ds0 = grp0.create_dataset(tableName, (1,shape), data = numpy.zeros((1,shape)) , maxshape=(None,shape), chunks=True)
911
911
912 ds.append(ds0)
912 ds.append(ds0)
913 data.append([])
913 data.append([])
914 i += 1
914 i += 1
915 # nDimsForDs.append(nDims[i])
915 # nDimsForDs.append(nDims[i])
916
916
917 fp.flush()
917 fp.flush()
918 fp.close()
918 fp.close()
919
919
920 # self.nDatas = nDatas
920 # self.nDatas = nDatas
921 # self.nDims = nDims
921 # self.nDims = nDims
922 # self.nDimsForDs = nDimsForDs
922 # self.nDimsForDs = nDimsForDs
923 #Saving variables
923 #Saving variables
924 print 'Writing the file: %s'%filename
924 print 'Writing the file: %s'%filename
925 self.filename = filename
925 self.filename = filename
926 # self.fp = fp
926 # self.fp = fp
927 # self.grp = grp
927 # self.grp = grp
928 # self.grp.attrs.modify('nRecords', 1)
928 # self.grp.attrs.modify('nRecords', 1)
929 self.ds = ds
929 self.ds = ds
930 self.data = data
930 self.data = data
931 # self.setFile = setFile
931 # self.setFile = setFile
932 self.firsttime = True
932 self.firsttime = True
933 self.blockIndex = 0
933 self.blockIndex = 0
934 return
934 return
935
935
936 def putData(self):
936 def putData(self):
937
937
938 if self.blockIndex == self.blocksPerFile or self.timeFlag():
938 if self.blockIndex == self.blocksPerFile or self.timeFlag():
939 self.setNextFile()
939 self.setNextFile()
940
940
941 # if not self.firsttime:
941 # if not self.firsttime:
942 self.readBlock()
942 self.readBlock()
943 self.setBlock() #Prepare data to be written
943 self.setBlock() #Prepare data to be written
944 self.writeBlock() #Write data
944 self.writeBlock() #Write data
945
945
946 return
946 return
947
947
948 def readBlock(self):
948 def readBlock(self):
949
949
950 '''
950 '''
951 data Array configured
951 data Array configured
952
952
953
953
954 self.data
954 self.data
955 '''
955 '''
956 dsList = self.dsList
956 dsList = self.dsList
957 ds = self.ds
957 ds = self.ds
958 #Setting HDF5 File
958 #Setting HDF5 File
959 fp = h5py.File(self.filename,'r+')
959 fp = h5py.File(self.filename,'r+')
960 grp = fp["Data"]
960 grp = fp["Data"]
961 ind = 0
961 ind = 0
962
962
963 # grp.attrs['blocksPerFile'] = 0
963 # grp.attrs['blocksPerFile'] = 0
964 while ind < len(dsList):
964 while ind < len(dsList):
965 dsInfo = dsList[ind]
965 dsInfo = dsList[ind]
966
966
967 if dsInfo['mode'] == 0:
967 if dsInfo['mode'] == 0:
968 ds0 = grp[dsInfo['variable']]
968 ds0 = grp[dsInfo['variable']]
969 ds[ind] = ds0
969 ds[ind] = ds0
970 ind += 1
970 ind += 1
971 else:
971 else:
972
972
973 grp0 = grp[dsInfo['variable']]
973 grp0 = grp[dsInfo['variable']]
974
974
975 for j in range(dsInfo['dsNumber']):
975 for j in range(dsInfo['dsNumber']):
976 dsInfo = dsList[ind]
976 dsInfo = dsList[ind]
977 ds0 = grp0[dsInfo['dsName']]
977 ds0 = grp0[dsInfo['dsName']]
978 ds[ind] = ds0
978 ds[ind] = ds0
979 ind += 1
979 ind += 1
980
980
981 self.fp = fp
981 self.fp = fp
982 self.grp = grp
982 self.grp = grp
983 self.ds = ds
983 self.ds = ds
984
984
985 return
985 return
986
986
987 def setBlock(self):
987 def setBlock(self):
988 '''
988 '''
989 data Array configured
989 data Array configured
990
990
991
991
992 self.data
992 self.data
993 '''
993 '''
994 #Creating Arrays
994 #Creating Arrays
995 dsList = self.dsList
995 dsList = self.dsList
996 data = self.data
996 data = self.data
997 ind = 0
997 ind = 0
998
998
999 while ind < len(dsList):
999 while ind < len(dsList):
1000 dsInfo = dsList[ind]
1000 dsInfo = dsList[ind]
1001 dataAux = getattr(self.dataOut, dsInfo['variable'])
1001 dataAux = getattr(self.dataOut, dsInfo['variable'])
1002
1002
1003 mode = dsInfo['mode']
1003 mode = dsInfo['mode']
1004 nDim = dsInfo['nDim']
1004 nDim = dsInfo['nDim']
1005
1005
1006 if mode == 0 or mode == 2 or nDim == 1:
1006 if mode == 0 or mode == 2 or nDim == 1:
1007 data[ind] = dataAux
1007 data[ind] = dataAux
1008 ind += 1
1008 ind += 1
1009 # elif nDim == 1:
1009 # elif nDim == 1:
1010 # data[ind] = numpy.reshape(dataAux,(numpy.size(dataAux),1))
1010 # data[ind] = numpy.reshape(dataAux,(numpy.size(dataAux),1))
1011 # ind += 1
1011 # ind += 1
1012 elif nDim == 2:
1012 elif nDim == 2:
1013 for j in range(dsInfo['dsNumber']):
1013 for j in range(dsInfo['dsNumber']):
1014 data[ind] = dataAux[j,:]
1014 data[ind] = dataAux[j,:]
1015 ind += 1
1015 ind += 1
1016 elif nDim == 3:
1016 elif nDim == 3:
1017 for j in range(dsInfo['dsNumber']):
1017 for j in range(dsInfo['dsNumber']):
1018 data[ind] = dataAux[:,j,:]
1018 data[ind] = dataAux[:,j,:]
1019 ind += 1
1019 ind += 1
1020
1020
1021 self.data = data
1021 self.data = data
1022 return
1022 return
1023
1023
1024 def writeBlock(self):
1024 def writeBlock(self):
1025 '''
1025 '''
1026 Saves the block in the HDF5 file
1026 Saves the block in the HDF5 file
1027 '''
1027 '''
1028 dsList = self.dsList
1028 dsList = self.dsList
1029
1029
1030 for i in range(len(self.ds)):
1030 for i in range(len(self.ds)):
1031 dsInfo = dsList[i]
1031 dsInfo = dsList[i]
1032 nDim = dsInfo['nDim']
1032 nDim = dsInfo['nDim']
1033 mode = dsInfo['mode']
1033 mode = dsInfo['mode']
1034
1034
1035 # First time
1035 # First time
1036 if self.firsttime:
1036 if self.firsttime:
1037 # self.ds[i].resize(self.data[i].shape)
1037 # self.ds[i].resize(self.data[i].shape)
1038 # self.ds[i][self.blockIndex,:] = self.data[i]
1038 # self.ds[i][self.blockIndex,:] = self.data[i]
1039 if type(self.data[i]) == numpy.ndarray:
1039 if type(self.data[i]) == numpy.ndarray:
1040
1040
1041 if nDim == 3:
1041 if nDim == 3:
1042 self.data[i] = self.data[i].reshape((self.data[i].shape[0],self.data[i].shape[1],1))
1042 self.data[i] = self.data[i].reshape((self.data[i].shape[0],self.data[i].shape[1],1))
1043 self.ds[i].resize(self.data[i].shape)
1043 self.ds[i].resize(self.data[i].shape)
1044 if mode == 2:
1044 if mode == 2:
1045 self.ds[i].resize(self.data[i].shape)
1045 self.ds[i].resize(self.data[i].shape)
1046 self.ds[i][:] = self.data[i]
1046 self.ds[i][:] = self.data[i]
1047 else:
1047 else:
1048
1048
1049 # From second time
1049 # From second time
1050 # Meteors!
1050 # Meteors!
1051 if mode == 2:
1051 if mode == 2:
1052 dataShape = self.data[i].shape
1052 dataShape = self.data[i].shape
1053 dsShape = self.ds[i].shape
1053 dsShape = self.ds[i].shape
1054 self.ds[i].resize((self.ds[i].shape[0] + dataShape[0],self.ds[i].shape[1]))
1054 self.ds[i].resize((self.ds[i].shape[0] + dataShape[0],self.ds[i].shape[1]))
1055 self.ds[i][dsShape[0]:,:] = self.data[i]
1055 self.ds[i][dsShape[0]:,:] = self.data[i]
1056 # No dimension
1056 # No dimension
1057 elif mode == 0:
1057 elif mode == 0:
1058 self.ds[i].resize((self.ds[i].shape[0], self.ds[i].shape[1] + 1))
1058 self.ds[i].resize((self.ds[i].shape[0], self.ds[i].shape[1] + 1))
1059 self.ds[i][0,-1] = self.data[i]
1059 self.ds[i][0,-1] = self.data[i]
1060 # One dimension
1060 # One dimension
1061 elif nDim == 1:
1061 elif nDim == 1:
1062 self.ds[i].resize((self.ds[i].shape[0] + 1, self.ds[i].shape[1]))
1062 self.ds[i].resize((self.ds[i].shape[0] + 1, self.ds[i].shape[1]))
1063 self.ds[i][-1,:] = self.data[i]
1063 self.ds[i][-1,:] = self.data[i]
1064 # Two dimension
1064 # Two dimension
1065 elif nDim == 2:
1065 elif nDim == 2:
1066 self.ds[i].resize((self.ds[i].shape[0] + 1,self.ds[i].shape[1]))
1066 self.ds[i].resize((self.ds[i].shape[0] + 1,self.ds[i].shape[1]))
1067 self.ds[i][self.blockIndex,:] = self.data[i]
1067 self.ds[i][self.blockIndex,:] = self.data[i]
1068 # Three dimensions
1068 # Three dimensions
1069 elif nDim == 3:
1069 elif nDim == 3:
1070 self.ds[i].resize((self.ds[i].shape[0],self.ds[i].shape[1],self.ds[i].shape[2]+1))
1070 self.ds[i].resize((self.ds[i].shape[0],self.ds[i].shape[1],self.ds[i].shape[2]+1))
1071 self.ds[i][:,:,-1] = self.data[i]
1071 self.ds[i][:,:,-1] = self.data[i]
1072
1072
1073 self.firsttime = False
1073 self.firsttime = False
1074 self.blockIndex += 1
1074 self.blockIndex += 1
1075
1075
1076 #Close to save changes
1076 #Close to save changes
1077 self.fp.flush()
1077 self.fp.flush()
1078 self.fp.close()
1078 self.fp.close()
1079 return
1079 return
1080
1080
1081 def run(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, **kwargs):
1081 def run(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, **kwargs):
1082
1082
1083 if not(self.isConfig):
1083 if not(self.isConfig):
1084 flagdata = self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
1084 flagdata = self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
1085 metadataList=metadataList, dataList=dataList, mode=mode, **kwargs)
1085 metadataList=metadataList, dataList=dataList, mode=mode, **kwargs)
1086
1086
1087 if not(flagdata):
1087 if not(flagdata):
1088 return
1088 return
1089
1089
1090 self.isConfig = True
1090 self.isConfig = True
1091 # self.putMetadata()
1091 # self.putMetadata()
1092 self.setNextFile()
1092 self.setNextFile()
1093
1093
1094 self.putData()
1094 self.putData()
1095 return
1095 return
@@ -1,14 +1,15
1 '''
1 '''
2
2
3 $Author: murco $
3 $Author: murco $
4 $Id: Processor.py 1 2012-11-12 18:56:07Z murco $
4 $Id: Processor.py 1 2012-11-12 18:56:07Z murco $
5 '''
5 '''
6
6
7 from jroproc_voltage import *
7 from jroproc_voltage import *
8 from jroproc_spectra import *
8 from jroproc_spectra import *
9 from jroproc_heispectra import *
9 from jroproc_heispectra import *
10 from jroproc_amisr import *
10 from jroproc_amisr import *
11 from jroproc_correlation import *
11 from jroproc_correlation import *
12 from jroproc_parameters import *
12 from jroproc_parameters import *
13 from jroproc_spectra_lags import *
13 from jroproc_spectra_lags import *
14 from jroproc_spectra_acf import * No newline at end of file
14 from jroproc_spectra_acf import *
15 from bltrproc_parameters import *
@@ -1,604 +1,607
1 '''
1 '''
2 @author: Juan C. Espinoza
2 @author: Juan C. Espinoza
3 '''
3 '''
4
4
5 import time
5 import time
6 import json
6 import json
7 import numpy
7 import numpy
8 import paho.mqtt.client as mqtt
8 import paho.mqtt.client as mqtt
9 import zmq
9 import zmq
10 import datetime
10 import datetime
11 from zmq.utils.monitor import recv_monitor_message
11 from zmq.utils.monitor import recv_monitor_message
12 from functools import wraps
12 from functools import wraps
13 from threading import Thread
13 from threading import Thread
14 from multiprocessing import Process
14 from multiprocessing import Process
15
15
16 from schainpy.model.proc.jroproc_base import Operation, ProcessingUnit
16 from schainpy.model.proc.jroproc_base import Operation, ProcessingUnit
17 from schainpy.model.data.jrodata import JROData
17 from schainpy.model.data.jrodata import JROData
18 from schainpy.utils import log
18 from schainpy.utils import log
19
19
20 MAXNUMX = 100
20 MAXNUMX = 100
21 MAXNUMY = 100
21 MAXNUMY = 100
22
22
23 class PrettyFloat(float):
23 class PrettyFloat(float):
24 def __repr__(self):
24 def __repr__(self):
25 return '%.2f' % self
25 return '%.2f' % self
26
26
27 def roundFloats(obj):
27 def roundFloats(obj):
28 if isinstance(obj, list):
28 if isinstance(obj, list):
29 return map(roundFloats, obj)
29 return map(roundFloats, obj)
30 elif isinstance(obj, float):
30 elif isinstance(obj, float):
31 return round(obj, 2)
31 return round(obj, 2)
32
32
33 def decimate(z, MAXNUMY):
33 def decimate(z, MAXNUMY):
34 dy = int(len(z[0])/MAXNUMY) + 1
34 dy = int(len(z[0])/MAXNUMY) + 1
35
35
36 return z[::, ::dy]
36 return z[::, ::dy]
37
37
38 class throttle(object):
38 class throttle(object):
39 '''
39 '''
40 Decorator that prevents a function from being called more than once every
40 Decorator that prevents a function from being called more than once every
41 time period.
41 time period.
42 To create a function that cannot be called more than once a minute, but
42 To create a function that cannot be called more than once a minute, but
43 will sleep until it can be called:
43 will sleep until it can be called:
44 @throttle(minutes=1)
44 @throttle(minutes=1)
45 def foo():
45 def foo():
46 pass
46 pass
47
47
48 for i in range(10):
48 for i in range(10):
49 foo()
49 foo()
50 print "This function has run %s times." % i
50 print "This function has run %s times." % i
51 '''
51 '''
52
52
53 def __init__(self, seconds=0, minutes=0, hours=0):
53 def __init__(self, seconds=0, minutes=0, hours=0):
54 self.throttle_period = datetime.timedelta(
54 self.throttle_period = datetime.timedelta(
55 seconds=seconds, minutes=minutes, hours=hours
55 seconds=seconds, minutes=minutes, hours=hours
56 )
56 )
57
57
58 self.time_of_last_call = datetime.datetime.min
58 self.time_of_last_call = datetime.datetime.min
59
59
60 def __call__(self, fn):
60 def __call__(self, fn):
61 @wraps(fn)
61 @wraps(fn)
62 def wrapper(*args, **kwargs):
62 def wrapper(*args, **kwargs):
63 now = datetime.datetime.now()
63 now = datetime.datetime.now()
64 time_since_last_call = now - self.time_of_last_call
64 time_since_last_call = now - self.time_of_last_call
65 time_left = self.throttle_period - time_since_last_call
65 time_left = self.throttle_period - time_since_last_call
66
66
67 if time_left > datetime.timedelta(seconds=0):
67 if time_left > datetime.timedelta(seconds=0):
68 return
68 return
69
69
70 self.time_of_last_call = datetime.datetime.now()
70 self.time_of_last_call = datetime.datetime.now()
71 return fn(*args, **kwargs)
71 return fn(*args, **kwargs)
72
72
73 return wrapper
73 return wrapper
74
74
75 class Data(object):
75 class Data(object):
76 '''
76 '''
77 Object to hold data to be plotted
77 Object to hold data to be plotted
78 '''
78 '''
79
79
80 def __init__(self, plottypes, throttle_value):
80 def __init__(self, plottypes, throttle_value):
81 self.plottypes = plottypes
81 self.plottypes = plottypes
82 self.throttle = throttle_value
82 self.throttle = throttle_value
83 self.ended = False
83 self.ended = False
84 self.__times = []
84 self.__times = []
85
85
86 def __str__(self):
86 def __str__(self):
87 dum = ['{}{}'.format(key, self.shape(key)) for key in self.data]
87 dum = ['{}{}'.format(key, self.shape(key)) for key in self.data]
88 return 'Data[{}][{}]'.format(';'.join(dum), len(self.__times))
88 return 'Data[{}][{}]'.format(';'.join(dum), len(self.__times))
89
89
90 def __len__(self):
90 def __len__(self):
91 return len(self.__times)
91 return len(self.__times)
92
92
93 def __getitem__(self, key):
93 def __getitem__(self, key):
94 if key not in self.data:
94 if key not in self.data:
95 raise KeyError(log.error('Missing key: {}'.format(key)))
95 raise KeyError(log.error('Missing key: {}'.format(key)))
96
96
97 if 'spc' in key:
97 if 'spc' in key:
98 ret = self.data[key]
98 ret = self.data[key]
99 else:
99 else:
100 ret = numpy.array([self.data[key][x] for x in self.times])
100 ret = numpy.array([self.data[key][x] for x in self.times])
101 if ret.ndim > 1:
101 if ret.ndim > 1:
102 ret = numpy.swapaxes(ret, 0, 1)
102 ret = numpy.swapaxes(ret, 0, 1)
103 return ret
103 return ret
104
104
105 def setup(self):
105 def setup(self):
106 '''
106 '''
107 Configure object
107 Configure object
108 '''
108 '''
109
109
110 self.ended = False
110 self.ended = False
111 self.data = {}
111 self.data = {}
112 self.__times = []
112 self.__times = []
113 self.__heights = []
113 self.__heights = []
114 self.__all_heights = set()
114 self.__all_heights = set()
115 for plot in self.plottypes:
115 for plot in self.plottypes:
116 if 'snr' in plot:
117 plot = 'snr'
116 self.data[plot] = {}
118 self.data[plot] = {}
117
119
118 def shape(self, key):
120 def shape(self, key):
119 '''
121 '''
120 Get the shape of the one-element data for the given key
122 Get the shape of the one-element data for the given key
121 '''
123 '''
122
124
123 if len(self.data[key]):
125 if len(self.data[key]):
124 if 'spc' in key:
126 if 'spc' in key:
125 return self.data[key].shape
127 return self.data[key].shape
126 return self.data[key][self.__times[0]].shape
128 return self.data[key][self.__times[0]].shape
127 return (0,)
129 return (0,)
128
130
129 def update(self, dataOut):
131 def update(self, dataOut):
130 '''
132 '''
131 Update data object with new dataOut
133 Update data object with new dataOut
132 '''
134 '''
133
135
134 tm = dataOut.utctime
136 tm = dataOut.utctime
135 if tm in self.__times:
137 if tm in self.__times:
136 return
138 return
137
139
138 self.parameters = getattr(dataOut, 'parameters', [])
140 self.parameters = getattr(dataOut, 'parameters', [])
139 self.pairs = dataOut.pairsList
141 self.pairs = dataOut.pairsList
140 self.channels = dataOut.channelList
142 self.channels = dataOut.channelList
141 self.xrange = (dataOut.getFreqRange(1)/1000. , dataOut.getAcfRange(1) , dataOut.getVelRange(1))
142 self.interval = dataOut.getTimeInterval()
143 self.interval = dataOut.getTimeInterval()
144 if 'spc' in self.plottypes or 'cspc' in self.plottypes:
145 self.xrange = (dataOut.getFreqRange(1)/1000. , dataOut.getAcfRange(1) , dataOut.getVelRange(1))
143 self.__heights.append(dataOut.heightList)
146 self.__heights.append(dataOut.heightList)
144 self.__all_heights.update(dataOut.heightList)
147 self.__all_heights.update(dataOut.heightList)
145 self.__times.append(tm)
148 self.__times.append(tm)
146
149
147 for plot in self.plottypes:
150 for plot in self.plottypes:
148 if plot == 'spc':
151 if plot == 'spc':
149 z = dataOut.data_spc/dataOut.normFactor
152 z = dataOut.data_spc/dataOut.normFactor
150 self.data[plot] = 10*numpy.log10(z)
153 self.data[plot] = 10*numpy.log10(z)
151 if plot == 'cspc':
154 if plot == 'cspc':
152 self.data[plot] = dataOut.data_cspc
155 self.data[plot] = dataOut.data_cspc
153 if plot == 'noise':
156 if plot == 'noise':
154 self.data[plot][tm] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
157 self.data[plot][tm] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
155 if plot == 'rti':
158 if plot == 'rti':
156 self.data[plot][tm] = dataOut.getPower()
159 self.data[plot][tm] = dataOut.getPower()
157 if plot == 'snr_db':
160 if plot == 'snr_db':
158 self.data['snr'][tm] = dataOut.data_SNR
161 self.data['snr'][tm] = dataOut.data_SNR
159 if plot == 'snr':
162 if plot == 'snr':
160 self.data[plot][tm] = 10*numpy.log10(dataOut.data_SNR)
163 self.data[plot][tm] = 10*numpy.log10(dataOut.data_SNR)
161 if plot == 'dop':
164 if plot == 'dop':
162 self.data[plot][tm] = 10*numpy.log10(dataOut.data_DOP)
165 self.data[plot][tm] = 10*numpy.log10(dataOut.data_DOP)
163 if plot == 'mean':
166 if plot == 'mean':
164 self.data[plot][tm] = dataOut.data_MEAN
167 self.data[plot][tm] = dataOut.data_MEAN
165 if plot == 'std':
168 if plot == 'std':
166 self.data[plot][tm] = dataOut.data_STD
169 self.data[plot][tm] = dataOut.data_STD
167 if plot == 'coh':
170 if plot == 'coh':
168 self.data[plot][tm] = dataOut.getCoherence()
171 self.data[plot][tm] = dataOut.getCoherence()
169 if plot == 'phase':
172 if plot == 'phase':
170 self.data[plot][tm] = dataOut.getCoherence(phase=True)
173 self.data[plot][tm] = dataOut.getCoherence(phase=True)
171 if plot == 'output':
174 if plot == 'output':
172 self.data[plot][tm] = dataOut.data_output
175 self.data[plot][tm] = dataOut.data_output
173 if plot == 'param':
176 if plot == 'param':
174 self.data[plot][tm] = dataOut.data_param
177 self.data[plot][tm] = dataOut.data_param
175
178
176 def normalize_heights(self):
179 def normalize_heights(self):
177 '''
180 '''
178 Ensure same-dimension of the data for different heighList
181 Ensure same-dimension of the data for different heighList
179 '''
182 '''
180
183
181 H = numpy.array(list(self.__all_heights))
184 H = numpy.array(list(self.__all_heights))
182 H.sort()
185 H.sort()
183 for key in self.data:
186 for key in self.data:
184 shape = self.shape(key)[:-1] + H.shape
187 shape = self.shape(key)[:-1] + H.shape
185 for tm, obj in self.data[key].items():
188 for tm, obj in self.data[key].items():
186 h = self.__heights[self.__times.index(tm)]
189 h = self.__heights[self.__times.index(tm)]
187 if H.size == h.size:
190 if H.size == h.size:
188 continue
191 continue
189 index = numpy.where(numpy.in1d(H, h))[0]
192 index = numpy.where(numpy.in1d(H, h))[0]
190 dummy = numpy.zeros(shape) + numpy.nan
193 dummy = numpy.zeros(shape) + numpy.nan
191 if len(shape) == 2:
194 if len(shape) == 2:
192 dummy[:, index] = obj
195 dummy[:, index] = obj
193 else:
196 else:
194 dummy[index] = obj
197 dummy[index] = obj
195 self.data[key][tm] = dummy
198 self.data[key][tm] = dummy
196
199
197 self.__heights = [H for tm in self.__times]
200 self.__heights = [H for tm in self.__times]
198
201
199 def jsonify(self, decimate=False):
202 def jsonify(self, decimate=False):
200 '''
203 '''
201 Convert data to json
204 Convert data to json
202 '''
205 '''
203
206
204 ret = {}
207 ret = {}
205 tm = self.times[-1]
208 tm = self.times[-1]
206
209
207 for key, value in self.data:
210 for key, value in self.data:
208 if key in ('spc', 'cspc'):
211 if key in ('spc', 'cspc'):
209 ret[key] = roundFloats(self.data[key].to_list())
212 ret[key] = roundFloats(self.data[key].to_list())
210 else:
213 else:
211 ret[key] = roundFloats(self.data[key][tm].to_list())
214 ret[key] = roundFloats(self.data[key][tm].to_list())
212
215
213 ret['timestamp'] = tm
216 ret['timestamp'] = tm
214 ret['interval'] = self.interval
217 ret['interval'] = self.interval
215
218
216 @property
219 @property
217 def times(self):
220 def times(self):
218 '''
221 '''
219 Return the list of times of the current data
222 Return the list of times of the current data
220 '''
223 '''
221
224
222 ret = numpy.array(self.__times)
225 ret = numpy.array(self.__times)
223 ret.sort()
226 ret.sort()
224 return ret
227 return ret
225
228
226 @property
229 @property
227 def heights(self):
230 def heights(self):
228 '''
231 '''
229 Return the list of heights of the current data
232 Return the list of heights of the current data
230 '''
233 '''
231
234
232 return numpy.array(self.__heights[-1])
235 return numpy.array(self.__heights[-1])
233
236
234 class PublishData(Operation):
237 class PublishData(Operation):
235 '''
238 '''
236 Operation to send data over zmq.
239 Operation to send data over zmq.
237 '''
240 '''
238
241
239 def __init__(self, **kwargs):
242 def __init__(self, **kwargs):
240 """Inicio."""
243 """Inicio."""
241 Operation.__init__(self, **kwargs)
244 Operation.__init__(self, **kwargs)
242 self.isConfig = False
245 self.isConfig = False
243 self.client = None
246 self.client = None
244 self.zeromq = None
247 self.zeromq = None
245 self.mqtt = None
248 self.mqtt = None
246
249
247 def on_disconnect(self, client, userdata, rc):
250 def on_disconnect(self, client, userdata, rc):
248 if rc != 0:
251 if rc != 0:
249 log.warning('Unexpected disconnection.')
252 log.warning('Unexpected disconnection.')
250 self.connect()
253 self.connect()
251
254
252 def connect(self):
255 def connect(self):
253 log.warning('trying to connect')
256 log.warning('trying to connect')
254 try:
257 try:
255 self.client.connect(
258 self.client.connect(
256 host=self.host,
259 host=self.host,
257 port=self.port,
260 port=self.port,
258 keepalive=60*10,
261 keepalive=60*10,
259 bind_address='')
262 bind_address='')
260 self.client.loop_start()
263 self.client.loop_start()
261 # self.client.publish(
264 # self.client.publish(
262 # self.topic + 'SETUP',
265 # self.topic + 'SETUP',
263 # json.dumps(setup),
266 # json.dumps(setup),
264 # retain=True
267 # retain=True
265 # )
268 # )
266 except:
269 except:
267 log.error('MQTT Conection error.')
270 log.error('MQTT Conection error.')
268 self.client = False
271 self.client = False
269
272
270 def setup(self, port=1883, username=None, password=None, clientId="user", zeromq=1, verbose=True, **kwargs):
273 def setup(self, port=1883, username=None, password=None, clientId="user", zeromq=1, verbose=True, **kwargs):
271 self.counter = 0
274 self.counter = 0
272 self.topic = kwargs.get('topic', 'schain')
275 self.topic = kwargs.get('topic', 'schain')
273 self.delay = kwargs.get('delay', 0)
276 self.delay = kwargs.get('delay', 0)
274 self.plottype = kwargs.get('plottype', 'spectra')
277 self.plottype = kwargs.get('plottype', 'spectra')
275 self.host = kwargs.get('host', "10.10.10.82")
278 self.host = kwargs.get('host', "10.10.10.82")
276 self.port = kwargs.get('port', 3000)
279 self.port = kwargs.get('port', 3000)
277 self.clientId = clientId
280 self.clientId = clientId
278 self.cnt = 0
281 self.cnt = 0
279 self.zeromq = zeromq
282 self.zeromq = zeromq
280 self.mqtt = kwargs.get('plottype', 0)
283 self.mqtt = kwargs.get('plottype', 0)
281 self.client = None
284 self.client = None
282 self.verbose = verbose
285 self.verbose = verbose
283 setup = []
286 setup = []
284 if mqtt is 1:
287 if mqtt is 1:
285 self.client = mqtt.Client(
288 self.client = mqtt.Client(
286 client_id=self.clientId + self.topic + 'SCHAIN',
289 client_id=self.clientId + self.topic + 'SCHAIN',
287 clean_session=True)
290 clean_session=True)
288 self.client.on_disconnect = self.on_disconnect
291 self.client.on_disconnect = self.on_disconnect
289 self.connect()
292 self.connect()
290 for plot in self.plottype:
293 for plot in self.plottype:
291 setup.append({
294 setup.append({
292 'plot': plot,
295 'plot': plot,
293 'topic': self.topic + plot,
296 'topic': self.topic + plot,
294 'title': getattr(self, plot + '_' + 'title', False),
297 'title': getattr(self, plot + '_' + 'title', False),
295 'xlabel': getattr(self, plot + '_' + 'xlabel', False),
298 'xlabel': getattr(self, plot + '_' + 'xlabel', False),
296 'ylabel': getattr(self, plot + '_' + 'ylabel', False),
299 'ylabel': getattr(self, plot + '_' + 'ylabel', False),
297 'xrange': getattr(self, plot + '_' + 'xrange', False),
300 'xrange': getattr(self, plot + '_' + 'xrange', False),
298 'yrange': getattr(self, plot + '_' + 'yrange', False),
301 'yrange': getattr(self, plot + '_' + 'yrange', False),
299 'zrange': getattr(self, plot + '_' + 'zrange', False),
302 'zrange': getattr(self, plot + '_' + 'zrange', False),
300 })
303 })
301 if zeromq is 1:
304 if zeromq is 1:
302 context = zmq.Context()
305 context = zmq.Context()
303 self.zmq_socket = context.socket(zmq.PUSH)
306 self.zmq_socket = context.socket(zmq.PUSH)
304 server = kwargs.get('server', 'zmq.pipe')
307 server = kwargs.get('server', 'zmq.pipe')
305
308
306 if 'tcp://' in server:
309 if 'tcp://' in server:
307 address = server
310 address = server
308 else:
311 else:
309 address = 'ipc:///tmp/%s' % server
312 address = 'ipc:///tmp/%s' % server
310
313
311 self.zmq_socket.connect(address)
314 self.zmq_socket.connect(address)
312 time.sleep(1)
315 time.sleep(1)
313
316
314
317
315 def publish_data(self):
318 def publish_data(self):
316 self.dataOut.finished = False
319 self.dataOut.finished = False
317 if self.mqtt is 1:
320 if self.mqtt is 1:
318 yData = self.dataOut.heightList[:2].tolist()
321 yData = self.dataOut.heightList[:2].tolist()
319 if self.plottype == 'spectra':
322 if self.plottype == 'spectra':
320 data = getattr(self.dataOut, 'data_spc')
323 data = getattr(self.dataOut, 'data_spc')
321 z = data/self.dataOut.normFactor
324 z = data/self.dataOut.normFactor
322 zdB = 10*numpy.log10(z)
325 zdB = 10*numpy.log10(z)
323 xlen, ylen = zdB[0].shape
326 xlen, ylen = zdB[0].shape
324 dx = int(xlen/MAXNUMX) + 1
327 dx = int(xlen/MAXNUMX) + 1
325 dy = int(ylen/MAXNUMY) + 1
328 dy = int(ylen/MAXNUMY) + 1
326 Z = [0 for i in self.dataOut.channelList]
329 Z = [0 for i in self.dataOut.channelList]
327 for i in self.dataOut.channelList:
330 for i in self.dataOut.channelList:
328 Z[i] = zdB[i][::dx, ::dy].tolist()
331 Z[i] = zdB[i][::dx, ::dy].tolist()
329 payload = {
332 payload = {
330 'timestamp': self.dataOut.utctime,
333 'timestamp': self.dataOut.utctime,
331 'data': roundFloats(Z),
334 'data': roundFloats(Z),
332 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
335 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
333 'interval': self.dataOut.getTimeInterval(),
336 'interval': self.dataOut.getTimeInterval(),
334 'type': self.plottype,
337 'type': self.plottype,
335 'yData': yData
338 'yData': yData
336 }
339 }
337
340
338 elif self.plottype in ('rti', 'power'):
341 elif self.plottype in ('rti', 'power'):
339 data = getattr(self.dataOut, 'data_spc')
342 data = getattr(self.dataOut, 'data_spc')
340 z = data/self.dataOut.normFactor
343 z = data/self.dataOut.normFactor
341 avg = numpy.average(z, axis=1)
344 avg = numpy.average(z, axis=1)
342 avgdB = 10*numpy.log10(avg)
345 avgdB = 10*numpy.log10(avg)
343 xlen, ylen = z[0].shape
346 xlen, ylen = z[0].shape
344 dy = numpy.floor(ylen/self.__MAXNUMY) + 1
347 dy = numpy.floor(ylen/self.__MAXNUMY) + 1
345 AVG = [0 for i in self.dataOut.channelList]
348 AVG = [0 for i in self.dataOut.channelList]
346 for i in self.dataOut.channelList:
349 for i in self.dataOut.channelList:
347 AVG[i] = avgdB[i][::dy].tolist()
350 AVG[i] = avgdB[i][::dy].tolist()
348 payload = {
351 payload = {
349 'timestamp': self.dataOut.utctime,
352 'timestamp': self.dataOut.utctime,
350 'data': roundFloats(AVG),
353 'data': roundFloats(AVG),
351 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
354 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
352 'interval': self.dataOut.getTimeInterval(),
355 'interval': self.dataOut.getTimeInterval(),
353 'type': self.plottype,
356 'type': self.plottype,
354 'yData': yData
357 'yData': yData
355 }
358 }
356 elif self.plottype == 'noise':
359 elif self.plottype == 'noise':
357 noise = self.dataOut.getNoise()/self.dataOut.normFactor
360 noise = self.dataOut.getNoise()/self.dataOut.normFactor
358 noisedB = 10*numpy.log10(noise)
361 noisedB = 10*numpy.log10(noise)
359 payload = {
362 payload = {
360 'timestamp': self.dataOut.utctime,
363 'timestamp': self.dataOut.utctime,
361 'data': roundFloats(noisedB.reshape(-1, 1).tolist()),
364 'data': roundFloats(noisedB.reshape(-1, 1).tolist()),
362 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
365 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
363 'interval': self.dataOut.getTimeInterval(),
366 'interval': self.dataOut.getTimeInterval(),
364 'type': self.plottype,
367 'type': self.plottype,
365 'yData': yData
368 'yData': yData
366 }
369 }
367 elif self.plottype == 'snr':
370 elif self.plottype == 'snr':
368 data = getattr(self.dataOut, 'data_SNR')
371 data = getattr(self.dataOut, 'data_SNR')
369 avgdB = 10*numpy.log10(data)
372 avgdB = 10*numpy.log10(data)
370
373
371 ylen = data[0].size
374 ylen = data[0].size
372 dy = numpy.floor(ylen/self.__MAXNUMY) + 1
375 dy = numpy.floor(ylen/self.__MAXNUMY) + 1
373 AVG = [0 for i in self.dataOut.channelList]
376 AVG = [0 for i in self.dataOut.channelList]
374 for i in self.dataOut.channelList:
377 for i in self.dataOut.channelList:
375 AVG[i] = avgdB[i][::dy].tolist()
378 AVG[i] = avgdB[i][::dy].tolist()
376 payload = {
379 payload = {
377 'timestamp': self.dataOut.utctime,
380 'timestamp': self.dataOut.utctime,
378 'data': roundFloats(AVG),
381 'data': roundFloats(AVG),
379 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
382 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
380 'type': self.plottype,
383 'type': self.plottype,
381 'yData': yData
384 'yData': yData
382 }
385 }
383 else:
386 else:
384 print "Tipo de grafico invalido"
387 print "Tipo de grafico invalido"
385 payload = {
388 payload = {
386 'data': 'None',
389 'data': 'None',
387 'timestamp': 'None',
390 'timestamp': 'None',
388 'type': None
391 'type': None
389 }
392 }
390
393
391 self.client.publish(self.topic + self.plottype, json.dumps(payload), qos=0)
394 self.client.publish(self.topic + self.plottype, json.dumps(payload), qos=0)
392
395
393 if self.zeromq is 1:
396 if self.zeromq is 1:
394 if self.verbose:
397 if self.verbose:
395 log.log(
398 log.log(
396 '{} - {}'.format(self.dataOut.type, self.dataOut.datatime),
399 '{} - {}'.format(self.dataOut.type, self.dataOut.datatime),
397 'Sending'
400 'Sending'
398 )
401 )
399 self.zmq_socket.send_pyobj(self.dataOut)
402 self.zmq_socket.send_pyobj(self.dataOut)
400
403
401 def run(self, dataOut, **kwargs):
404 def run(self, dataOut, **kwargs):
402 self.dataOut = dataOut
405 self.dataOut = dataOut
403 if not self.isConfig:
406 if not self.isConfig:
404 self.setup(**kwargs)
407 self.setup(**kwargs)
405 self.isConfig = True
408 self.isConfig = True
406
409
407 self.publish_data()
410 self.publish_data()
408 time.sleep(self.delay)
411 time.sleep(self.delay)
409
412
410 def close(self):
413 def close(self):
411 if self.zeromq is 1:
414 if self.zeromq is 1:
412 self.dataOut.finished = True
415 self.dataOut.finished = True
413 self.zmq_socket.send_pyobj(self.dataOut)
416 self.zmq_socket.send_pyobj(self.dataOut)
414 time.sleep(0.1)
417 time.sleep(0.1)
415 self.zmq_socket.close()
418 self.zmq_socket.close()
416 if self.client:
419 if self.client:
417 self.client.loop_stop()
420 self.client.loop_stop()
418 self.client.disconnect()
421 self.client.disconnect()
419
422
420
423
421 class ReceiverData(ProcessingUnit):
424 class ReceiverData(ProcessingUnit):
422
425
423 def __init__(self, **kwargs):
426 def __init__(self, **kwargs):
424
427
425 ProcessingUnit.__init__(self, **kwargs)
428 ProcessingUnit.__init__(self, **kwargs)
426
429
427 self.isConfig = False
430 self.isConfig = False
428 server = kwargs.get('server', 'zmq.pipe')
431 server = kwargs.get('server', 'zmq.pipe')
429 if 'tcp://' in server:
432 if 'tcp://' in server:
430 address = server
433 address = server
431 else:
434 else:
432 address = 'ipc:///tmp/%s' % server
435 address = 'ipc:///tmp/%s' % server
433
436
434 self.address = address
437 self.address = address
435 self.dataOut = JROData()
438 self.dataOut = JROData()
436
439
437 def setup(self):
440 def setup(self):
438
441
439 self.context = zmq.Context()
442 self.context = zmq.Context()
440 self.receiver = self.context.socket(zmq.PULL)
443 self.receiver = self.context.socket(zmq.PULL)
441 self.receiver.bind(self.address)
444 self.receiver.bind(self.address)
442 time.sleep(0.5)
445 time.sleep(0.5)
443 log.success('ReceiverData from {}'.format(self.address))
446 log.success('ReceiverData from {}'.format(self.address))
444
447
445
448
446 def run(self):
449 def run(self):
447
450
448 if not self.isConfig:
451 if not self.isConfig:
449 self.setup()
452 self.setup()
450 self.isConfig = True
453 self.isConfig = True
451
454
452 self.dataOut = self.receiver.recv_pyobj()
455 self.dataOut = self.receiver.recv_pyobj()
453 log.log('{} - {}'.format(self.dataOut.type,
456 log.log('{} - {}'.format(self.dataOut.type,
454 self.dataOut.datatime.ctime(),),
457 self.dataOut.datatime.ctime(),),
455 'Receiving')
458 'Receiving')
456
459
457
460
458 class PlotterReceiver(ProcessingUnit, Process):
461 class PlotterReceiver(ProcessingUnit, Process):
459
462
460 throttle_value = 5
463 throttle_value = 5
461
464
462 def __init__(self, **kwargs):
465 def __init__(self, **kwargs):
463
466
464 ProcessingUnit.__init__(self, **kwargs)
467 ProcessingUnit.__init__(self, **kwargs)
465 Process.__init__(self)
468 Process.__init__(self)
466 self.mp = False
469 self.mp = False
467 self.isConfig = False
470 self.isConfig = False
468 self.isWebConfig = False
471 self.isWebConfig = False
469 self.connections = 0
472 self.connections = 0
470 server = kwargs.get('server', 'zmq.pipe')
473 server = kwargs.get('server', 'zmq.pipe')
471 plot_server = kwargs.get('plot_server', 'zmq.web')
474 plot_server = kwargs.get('plot_server', 'zmq.web')
472 if 'tcp://' in server:
475 if 'tcp://' in server:
473 address = server
476 address = server
474 else:
477 else:
475 address = 'ipc:///tmp/%s' % server
478 address = 'ipc:///tmp/%s' % server
476
479
477 if 'tcp://' in plot_server:
480 if 'tcp://' in plot_server:
478 plot_address = plot_server
481 plot_address = plot_server
479 else:
482 else:
480 plot_address = 'ipc:///tmp/%s' % plot_server
483 plot_address = 'ipc:///tmp/%s' % plot_server
481
484
482 self.address = address
485 self.address = address
483 self.plot_address = plot_address
486 self.plot_address = plot_address
484 self.plottypes = [s.strip() for s in kwargs.get('plottypes', 'rti').split(',')]
487 self.plottypes = [s.strip() for s in kwargs.get('plottypes', 'rti').split(',')]
485 self.realtime = kwargs.get('realtime', False)
488 self.realtime = kwargs.get('realtime', False)
486 self.throttle_value = kwargs.get('throttle', 5)
489 self.throttle_value = kwargs.get('throttle', 5)
487 self.sendData = self.initThrottle(self.throttle_value)
490 self.sendData = self.initThrottle(self.throttle_value)
488 self.dates = []
491 self.dates = []
489 self.setup()
492 self.setup()
490
493
491 def setup(self):
494 def setup(self):
492
495
493 self.data = Data(self.plottypes, self.throttle_value)
496 self.data = Data(self.plottypes, self.throttle_value)
494 self.isConfig = True
497 self.isConfig = True
495
498
496 def event_monitor(self, monitor):
499 def event_monitor(self, monitor):
497
500
498 events = {}
501 events = {}
499
502
500 for name in dir(zmq):
503 for name in dir(zmq):
501 if name.startswith('EVENT_'):
504 if name.startswith('EVENT_'):
502 value = getattr(zmq, name)
505 value = getattr(zmq, name)
503 events[value] = name
506 events[value] = name
504
507
505 while monitor.poll():
508 while monitor.poll():
506 evt = recv_monitor_message(monitor)
509 evt = recv_monitor_message(monitor)
507 if evt['event'] == 32:
510 if evt['event'] == 32:
508 self.connections += 1
511 self.connections += 1
509 if evt['event'] == 512:
512 if evt['event'] == 512:
510 pass
513 pass
511
514
512 evt.update({'description': events[evt['event']]})
515 evt.update({'description': events[evt['event']]})
513
516
514 if evt['event'] == zmq.EVENT_MONITOR_STOPPED:
517 if evt['event'] == zmq.EVENT_MONITOR_STOPPED:
515 break
518 break
516 monitor.close()
519 monitor.close()
517 print('event monitor thread done!')
520 print('event monitor thread done!')
518
521
519 def initThrottle(self, throttle_value):
522 def initThrottle(self, throttle_value):
520
523
521 @throttle(seconds=throttle_value)
524 @throttle(seconds=throttle_value)
522 def sendDataThrottled(fn_sender, data):
525 def sendDataThrottled(fn_sender, data):
523 fn_sender(data)
526 fn_sender(data)
524
527
525 return sendDataThrottled
528 return sendDataThrottled
526
529
527 def send(self, data):
530 def send(self, data):
528 log.success('Sending {}'.format(data), self.name)
531 log.success('Sending {}'.format(data), self.name)
529 self.sender.send_pyobj(data)
532 self.sender.send_pyobj(data)
530
533
531 def run(self):
534 def run(self):
532
535
533 log.success(
536 log.success(
534 'Starting from {}'.format(self.address),
537 'Starting from {}'.format(self.address),
535 self.name
538 self.name
536 )
539 )
537
540
538 self.context = zmq.Context()
541 self.context = zmq.Context()
539 self.receiver = self.context.socket(zmq.PULL)
542 self.receiver = self.context.socket(zmq.PULL)
540 self.receiver.bind(self.address)
543 self.receiver.bind(self.address)
541 monitor = self.receiver.get_monitor_socket()
544 monitor = self.receiver.get_monitor_socket()
542 self.sender = self.context.socket(zmq.PUB)
545 self.sender = self.context.socket(zmq.PUB)
543 if self.realtime:
546 if self.realtime:
544 self.sender_web = self.context.socket(zmq.PUB)
547 self.sender_web = self.context.socket(zmq.PUB)
545 self.sender_web.connect(self.plot_address)
548 self.sender_web.connect(self.plot_address)
546 time.sleep(1)
549 time.sleep(1)
547
550
548 if 'server' in self.kwargs:
551 if 'server' in self.kwargs:
549 self.sender.bind("ipc:///tmp/{}.plots".format(self.kwargs['server']))
552 self.sender.bind("ipc:///tmp/{}.plots".format(self.kwargs['server']))
550 else:
553 else:
551 self.sender.bind("ipc:///tmp/zmq.plots")
554 self.sender.bind("ipc:///tmp/zmq.plots")
552
555
553 time.sleep(2)
556 time.sleep(2)
554
557
555 t = Thread(target=self.event_monitor, args=(monitor,))
558 t = Thread(target=self.event_monitor, args=(monitor,))
556 t.start()
559 t.start()
557
560
558 while True:
561 while True:
559 dataOut = self.receiver.recv_pyobj()
562 dataOut = self.receiver.recv_pyobj()
560 dt = datetime.datetime.fromtimestamp(dataOut.utctime).date()
563 dt = datetime.datetime.fromtimestamp(dataOut.utctime).date()
561 sended = False
564 sended = False
562 if dt not in self.dates:
565 if dt not in self.dates:
563 if self.data:
566 if self.data:
564 self.data.ended = True
567 self.data.ended = True
565 self.send(self.data)
568 self.send(self.data)
566 sended = True
569 sended = True
567 self.data.setup()
570 self.data.setup()
568 self.dates.append(dt)
571 self.dates.append(dt)
569
572
570 self.data.update(dataOut)
573 self.data.update(dataOut)
571
574
572 if dataOut.finished is True:
575 if dataOut.finished is True:
573 self.connections -= 1
576 self.connections -= 1
574 if self.connections == 0 and dt in self.dates:
577 if self.connections == 0 and dt in self.dates:
575 self.data.ended = True
578 self.data.ended = True
576 self.send(self.data)
579 self.send(self.data)
577 self.data.setup()
580 self.data.setup()
578 else:
581 else:
579 if self.realtime:
582 if self.realtime:
580 self.send(self.data)
583 self.send(self.data)
581 # self.sender_web.send_string(self.data.jsonify())
584 # self.sender_web.send_string(self.data.jsonify())
582 else:
585 else:
583 if not sended:
586 if not sended:
584 self.sendData(self.send, self.data)
587 self.sendData(self.send, self.data)
585
588
586 return
589 return
587
590
588 def sendToWeb(self):
591 def sendToWeb(self):
589
592
590 if not self.isWebConfig:
593 if not self.isWebConfig:
591 context = zmq.Context()
594 context = zmq.Context()
592 sender_web_config = context.socket(zmq.PUB)
595 sender_web_config = context.socket(zmq.PUB)
593 if 'tcp://' in self.plot_address:
596 if 'tcp://' in self.plot_address:
594 dum, address, port = self.plot_address.split(':')
597 dum, address, port = self.plot_address.split(':')
595 conf_address = '{}:{}:{}'.format(dum, address, int(port)+1)
598 conf_address = '{}:{}:{}'.format(dum, address, int(port)+1)
596 else:
599 else:
597 conf_address = self.plot_address + '.config'
600 conf_address = self.plot_address + '.config'
598 sender_web_config.bind(conf_address)
601 sender_web_config.bind(conf_address)
599 time.sleep(1)
602 time.sleep(1)
600 for kwargs in self.operationKwargs.values():
603 for kwargs in self.operationKwargs.values():
601 if 'plot' in kwargs:
604 if 'plot' in kwargs:
602 log.success('[Sending] Config data to web for {}'.format(kwargs['code'].upper()))
605 log.success('[Sending] Config data to web for {}'.format(kwargs['code'].upper()))
603 sender_web_config.send_string(json.dumps(kwargs))
606 sender_web_config.send_string(json.dumps(kwargs))
604 self.isWebConfig = True No newline at end of file
607 self.isWebConfig = True
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now