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