##// END OF EJS Templates
19 DE AGOSTO 2021 RM
avaldez -
r1367:42e9a23049f5
parent child
Show More

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

@@ -0,0 +1,31
1 import os,sys
2 import datetime
3 import time
4 from schainpy.controller import Project
5 path='/DATA_RM/TEST_HDF5'
6 path_adq=path
7 path_ped='/DATA_RM/TEST_PEDESTAL/P2021200'
8 figpath = '/home/soporte/Pictures'
9 desc = "Simulator Test"
10
11 controllerObj = Project()
12 controllerObj.setup(id='10',name='Test Simulator',description=desc)
13 readUnitConfObj = controllerObj.addReadUnit(datatype='HDFReader',
14 path=path,
15 startDate="2021/01/01", #"2020/01/01",#today,
16 endDate= "2021/12/01", #"2020/12/30",#today,
17 startTime='00:00:00',
18 endTime='23:59:59',
19 t_Interval_p=0.01,
20 n_Muestras_p=100,
21 delay=5,
22 #set=0,
23 online=0,
24 walk=1)#1
25
26 procUnitConfObjA = controllerObj.addProcUnit(datatype='ParametersProc',inputId=readUnitConfObj.getId())
27
28
29 controllerObj.start()
30 #online 1 utc_adq 1617490240.48
31 #online 0 utc_adq 1617489815.4804
@@ -0,0 +1,92
1 import numpy
2 import sys
3 import zmq
4 import time
5 import h5py
6 import os
7
8 timetuple=time.localtime()
9 meta='P'
10 dir="%s%4.4d%3.3d"%(meta,timetuple.tm_year,timetuple.tm_yday)
11
12 path="/home/soporte/Downloads/PEDESTAL/"+dir
13
14 ext=".hdf5"
15
16 port ="5556"
17 if len(sys.argv)>1:
18 port = sys.argv[1]
19 int(port)
20
21 if len(sys.argv)>2:
22 port1 = sys.argv[2]
23 int(port1)
24
25 #Socket to talk to server
26 context = zmq.Context()
27 socket = context.socket(zmq.SUB)
28
29 print("Collecting updates from weather server...")
30 socket.connect("tcp://localhost:%s"%port)
31
32 if len(sys.argv)>2:
33 socket.connect("tcp://localhost:%s"%port1)
34
35 #Subscribe to zipcode, default is NYC,10001
36 topicfilter = "10001"
37 socket.setsockopt_string(zmq.SUBSCRIBE,topicfilter)
38 #Process 5 updates
39 total_value=0
40 count= -1
41 azi= []
42 elev=[]
43 time0=[]
44 #for update_nbr in range(250):
45 while(True):
46 string= socket.recv()
47 topic,ang_elev,ang_elev_dec,ang_azi,ang_azi_dec,seconds,seconds_dec= string.split()
48 ang_azi =float(ang_azi)+1e-3*float(ang_azi_dec)
49 ang_elev =float(ang_elev)+1e-3*float(ang_elev_dec)
50 seconds =float(seconds) +1e-6*float(seconds_dec)
51 azi.append(ang_azi)
52 elev.append(ang_elev)
53 time0.append(seconds)
54 count +=1
55 if count == 100:
56 timetuple=time.localtime()
57 epoc = time.mktime(timetuple)
58 #print(epoc)
59 fullpath = path + ("/" if path[-1]!="/" else "")
60
61 if not os.path.exists(fullpath):
62 os.mkdir(fullpath)
63
64 azi_array = numpy.array(azi)
65 elev_array = numpy.array(elev)
66 time0_array= numpy.array(time0)
67 pedestal_array=numpy.array([azi,elev,time0])
68 count=0
69 azi= []
70 elev=[]
71 time0=[]
72 #print(pedestal_array[0])
73 #print(pedestal_array[1])
74
75 meta='PE'
76 filex="%s%4.4d%3.3d%10.4d%s"%(meta,timetuple.tm_year,timetuple.tm_yday,epoc,ext)
77 filename = os.path.join(fullpath,filex)
78 fp = h5py.File(filename,'w')
79 #print("Escribiendo HDF5...",epoc)
80 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β· DataΒ·....Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·
81 grp = fp.create_group("Data")
82 dset = grp.create_dataset("azimuth" , data=pedestal_array[0])
83 dset = grp.create_dataset("elevacion", data=pedestal_array[1])
84 dset = grp.create_dataset("utc" , data=pedestal_array[2])
85 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β· MetadataΒ·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·
86 grp = fp.create_group("Metadata")
87 dset = grp.create_dataset("utctimeInit", data=pedestal_array[2][0])
88 timeInterval = pedestal_array[2][1]-pedestal_array[2][0]
89 dset = grp.create_dataset("timeInterval", data=timeInterval)
90 fp.close()
91
92 #print ("Average messagedata value for topic '%s' was %dF" % ( topicfilter,total_value / update_nbr))
@@ -0,0 +1,48
1 ###########################################################################
2 ############################### SERVIDOR###################################
3 ######################### SIMULADOR DE PEDESTAL############################
4 ###########################################################################
5 import time
6 import math
7 import numpy
8 import struct
9 from time import sleep
10 import zmq
11 import pickle
12 port="5556"
13 context = zmq.Context()
14 socket = context.socket(zmq.PUB)
15 socket.bind("tcp://*:%s"%port)
16 ###### PARAMETROS DE ENTRADA################################
17 print("PEDESTAL RESOLUCION 0.01")
18 print("MAXIMA VELOCIDAD DEL PEDESTAL")
19 ang_elev = 4.12
20 ang_azi = 30
21 velocidad= input ("Ingresa velocidad:")
22 velocidad= float(velocidad)
23 print (velocidad)
24 ############################################################
25 sleep(3)
26 print("Start program")
27 t1 = time.time()
28 count=0
29 while(True):
30 tmp_vuelta = int(360/velocidad)
31 t1=t1+tmp_vuelta*count
32 count= count+1
33 muestras_seg = 100
34 t2 = time.time()
35 for i in range(tmp_vuelta):
36 for j in range(muestras_seg):
37 tmp_variable = (i+j/100.0)
38 ang_azi = (tmp_variable)*float(velocidad)
39 seconds = t1+ tmp_variable
40 topic=10001
41 print ("AzimΒ°: ","%.4f"%ang_azi,"Time:" ,"%.5f"%seconds)
42 seconds_dec=(seconds-int(seconds))*1e6
43 ang_azi_dec= (ang_azi-int(ang_azi))*1e3
44 ang_elev_dec=(ang_elev-int(ang_elev))*1e3
45 sleep(0.0088)
46 socket.send_string("%d %d %d %d %d %d %d"%(topic,ang_elev,ang_elev_dec,ang_azi,ang_azi_dec,seconds,seconds_dec))
47 t3 = time.time()
48 print ("Total time for 1 vuelta in Seconds",t3-t2)
@@ -0,0 +1,275
1 #!python
2 '''
3 '''
4
5 import os, sys
6 import datetime
7 import time
8
9 #path = os.path.dirname(os.getcwd())
10 #path = os.path.dirname(path)
11 #sys.path.insert(0, path)
12
13 from schainpy.controller import Project
14
15 desc = "USRP_test"
16 filename = "USRP_processing.xml"
17 controllerObj = Project()
18 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
19
20 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
21
22 #######################################################################
23 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
24 #######################################################################
25 #path = '/media/data/data/vientos/57.2063km/echoes/NCO_Woodman'
26 #path = '/DATA_RM/TEST_INTEGRACION'
27 #path = '/DATA_RM/PRUEBA_USRP_RP'
28 path = '/DATA_RM/PRUEBA_USRP_RP'
29
30 figpath = '/home/soporte/Pictures/TEST_RP_0001'
31 figpath = '/home/soporte/Pictures/TEST_RP_6000'
32 figpath = '/home/soporte/Pictures/USRP'
33 #remotefolder = "/home/wmaster/graficos"
34 #######################################################################
35 ################# RANGO DE PLOTEO######################################
36 #######################################################################
37 dBmin = '-5'
38 dBmax = '20'
39 xmin = '0'
40 xmax ='24'
41 ymin = '0'
42 ymax = '600'
43 #######################################################################
44 ########################FECHA##########################################
45 #######################################################################
46 str = datetime.date.today()
47 today = str.strftime("%Y/%m/%d")
48 str2 = str - datetime.timedelta(days=1)
49 yesterday = str2.strftime("%Y/%m/%d")
50 #######################################################################
51 ######################## UNIDAD DE LECTURA#############################
52 #######################################################################
53 readUnitConfObj = controllerObj.addReadUnit(datatype='DigitalRFReader',
54 path=path,
55 startDate="2021/07/02",#today,
56 endDate="2021/07/02",#today,
57 startTime='14:50:00',# inicio libre
58 #startTime='00:00:00',
59 endTime='14:55:59',
60 delay=0,
61 #set=0,
62 online=0,
63 walk=1,
64 ippKm = 6000)
65
66 opObj11 = readUnitConfObj.addOperation(name='printInfo')
67 #opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
68 #######################################################################
69 ################ OPERACIONES DOMINIO DEL TIEMPO########################
70 #######################################################################
71
72 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
73
74 opObj11 = procUnitConfObjA.addOperation(name='selectHeights')
75 opObj11.addParameter(name='minIndex', value='1', format='int')
76 # opObj11.addParameter(name='maxIndex', value='10000', format='int')
77 opObj11.addParameter(name='maxIndex', value='39980', format='int')
78
79 #
80 # codigo64='1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0,'+\
81 # '1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1'
82
83 #opObj11 = procUnitConfObjA.addOperation(name='setRadarFrequency')
84 #opObj11.addParameter(name='frequency', value='49920000')
85
86 '''
87 opObj11 = procUnitConfObjA.addOperation(name='PulsePair', optype='other')
88 opObj11.addParameter(name='n', value='625', format='int')#10
89 opObj11.addParameter(name='removeDC', value=1, format='int')
90 '''
91
92 # Ploteo TEST
93 '''
94 opObj11 = procUnitConfObjA.addOperation(name='PulsepairPowerPlot', optype='other')
95 opObj11 = procUnitConfObjA.addOperation(name='PulsepairSignalPlot', optype='other')
96 opObj11 = procUnitConfObjA.addOperation(name='PulsepairVelocityPlot', optype='other')
97 #opObj11.addParameter(name='xmax', value=8)
98 opObj11 = procUnitConfObjA.addOperation(name='PulsepairSpecwidthPlot', optype='other')
99 '''
100 # OJO SCOPE
101 #opObj10 = procUnitConfObjA.addOperation(name='ScopePlot', optype='external')
102 #opObj10.addParameter(name='id', value='10', format='int')
103 ##opObj10.addParameter(name='xmin', value='0', format='int')
104 ##opObj10.addParameter(name='xmax', value='50', format='int')
105 #opObj10.addParameter(name='type', value='iq')
106 ##opObj10.addParameter(name='ymin', value='-5000', format='int')
107 ##opObj10.addParameter(name='ymax', value='8500', format='int')
108 #opObj11.addParameter(name='save', value=figpath, format='str')
109 #opObj11.addParameter(name='save_period', value=10, format='int')
110
111 #opObj10 = procUnitConfObjA.addOperation(name='setH0')
112 #opObj10.addParameter(name='h0', value='-5000', format='float')
113
114 #opObj11 = procUnitConfObjA.addOperation(name='filterByHeights')
115 #opObj11.addParameter(name='window', value='1', format='int')
116
117 #codigo='1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,-1,-1,-1'
118 #opObj11 = procUnitConfObjSousy.addOperation(name='Decoder', optype='other')
119 #opObj11.addParameter(name='code', value=codigo, format='floatlist')
120 #opObj11.addParameter(name='nCode', value='1', format='int')
121 #opObj11.addParameter(name='nBaud', value='28', format='int')
122
123 #opObj11 = procUnitConfObjA.addOperation(name='CohInt', optype='other')
124 #opObj11.addParameter(name='n', value='100', format='int')
125
126 #######################################################################
127 ########## OPERACIONES ParametersProc########################
128 #######################################################################
129 ###procUnitConfObjB= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjA.getId())
130 '''
131
132 opObj11 = procUnitConfObjA.addOperation(name='PedestalInformation')
133 opObj11.addParameter(name='path_ped', value=path_ped)
134 opObj11.addParameter(name='path_adq', value=path_adq)
135 opObj11.addParameter(name='t_Interval_p', value='0.01', format='float')
136 opObj11.addParameter(name='n_Muestras_p', value='100', format='float')
137 opObj11.addParameter(name='blocksPerfile', value='100', format='int')
138 opObj11.addParameter(name='f_a_p', value='25', format='int')
139 opObj11.addParameter(name='online', value='0', format='int')
140
141 opObj11 = procUnitConfObjA.addOperation(name='Block360')
142 opObj11.addParameter(name='n', value='40', format='int')
143
144 opObj11= procUnitConfObjA.addOperation(name='WeatherPlot',optype='other')
145 opObj11.addParameter(name='save', value=figpath)
146 opObj11.addParameter(name='save_period', value=1)
147
148 8
149 '''
150
151 #######################################################################
152 ########## OPERACIONES DOMINIO DE LA FRECUENCIA########################
153 #######################################################################
154
155 #procUnitConfObjB = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjA.getId())
156 #procUnitConfObjB.addParameter(name='nFFTPoints', value='32', format='int')
157 #procUnitConfObjB.addParameter(name='nProfiles', value='32', format='int')
158
159 procUnitConfObjC = controllerObj.addProcUnit(datatype='SpectraHeisProc', inputId=procUnitConfObjA.getId())
160 #procUnitConfObjB.addParameter(name='nFFTPoints', value='64', format='int')
161 #procUnitConfObjB.addParameter(name='nProfiles', value='64', format='int')
162 opObj11 = procUnitConfObjC.addOperation(name='IncohInt4SpectraHeis', optype='other')
163 #opObj11.addParameter(name='timeInterval', value='4', format='int')
164 opObj11.addParameter(name='n', value='100', format='int')
165
166 #procUnitConfObjB.addParameter(name='pairsList', value='(0,0),(1,1),(0,1)', format='pairsList')
167
168 #opObj13 = procUnitConfObjB.addOperation(name='removeDC')
169 #opObj13.addParameter(name='mode', value='2', format='int')
170
171 #opObj11 = procUnitConfObjB.addOperation(name='IncohInt', optype='other')
172 #opObj11.addParameter(name='n', value='8', format='float')
173 #######################################################################
174 ########## PLOTEO DOMINIO DE LA FRECUENCIA#############################
175 #######################################################################
176 #----
177
178 opObj11 = procUnitConfObjC.addOperation(name='SpectraHeisPlot')
179 opObj11.addParameter(name='id', value='10', format='int')
180 opObj11.addParameter(name='wintitle', value='Spectra_Alturas', format='str')
181 #opObj11.addParameter(name='xmin', value=-100000, format='float')
182 #opObj11.addParameter(name='xmax', value=100000, format='float')
183 opObj11.addParameter(name='oneFigure', value=False,format='bool')
184 #opObj11.addParameter(name='zmin', value=-10, format='int')
185 #opObj11.addParameter(name='zmax', value=40, format='int')
186 opObj11.addParameter(name='ymin', value=10, format='int')
187 opObj11.addParameter(name='ymax', value=55, format='int')
188 opObj11.addParameter(name='grid', value=True, format='bool')
189 #opObj11.addParameter(name='showprofile', value='1', format='int')
190 opObj11.addParameter(name='save', value=figpath, format='str')
191 #opObj11.addParameter(name='save_period', value=10, format='int')
192
193 '''
194 opObj11 = procUnitConfObjC.addOperation(name='RTIHeisPlot')
195 opObj11.addParameter(name='id', value='10', format='int')
196 opObj11.addParameter(name='wintitle', value='RTI_Alturas', format='str')
197 opObj11.addParameter(name='xmin', value=11.0, format='float')
198 opObj11.addParameter(name='xmax', value=18.0, format='float')
199 opObj11.addParameter(name='zmin', value=10, format='int')
200 opObj11.addParameter(name='zmax', value=30, format='int')
201 opObj11.addParameter(name='ymin', value=5, format='int')
202 opObj11.addParameter(name='ymax', value=28, format='int')
203 opObj11.addParameter(name='showprofile', value='1', format='int')
204 opObj11.addParameter(name='save', value=figpath, format='str')
205 opObj11.addParameter(name='save_period', value=10, format='int')
206 '''
207 '''
208 #SpectraPlot
209
210 opObj11 = procUnitConfObjB.addOperation(name='SpectraPlot', optype='external')
211 opObj11.addParameter(name='id', value='1', format='int')
212 opObj11.addParameter(name='wintitle', value='Spectra', format='str')
213 #opObj11.addParameter(name='xmin', value=-0.01, format='float')
214 #opObj11.addParameter(name='xmax', value=0.01, format='float')
215 opObj11.addParameter(name='zmin', value=dBmin, format='int')
216 opObj11.addParameter(name='zmax', value=dBmax, format='int')
217 #opObj11.addParameter(name='ymin', value=ymin, format='int')
218 #opObj11.addParameter(name='ymax', value=ymax, format='int')
219 opObj11.addParameter(name='showprofile', value='1', format='int')
220 opObj11.addParameter(name='save', value=figpath, format='str')
221 opObj11.addParameter(name='save_period', value=10, format='int')
222
223 #RTIPLOT
224
225 opObj11 = procUnitConfObjB.addOperation(name='RTIPlot', optype='external')
226 opObj11.addParameter(name='id', value='2', format='int')
227 opObj11.addParameter(name='wintitle', value='RTIPlot', format='str')
228 opObj11.addParameter(name='zmin', value=dBmin, format='int')
229 opObj11.addParameter(name='zmax', value=dBmax, format='int')
230 #opObj11.addParameter(name='ymin', value=ymin, format='int')
231 #opObj11.addParameter(name='ymax', value=ymax, format='int')
232 #opObj11.addParameter(name='xmin', value=15, format='int')
233 #opObj11.addParameter(name='xmax', value=16, format='int')
234
235 opObj11.addParameter(name='showprofile', value='1', format='int')
236 opObj11.addParameter(name='save', value=figpath, format='str')
237 opObj11.addParameter(name='save_period', value=10, format='int')
238
239 '''
240 # opObj11 = procUnitConfObjB.addOperation(name='CrossSpectraPlot', optype='other')
241 # opObj11.addParameter(name='id', value='3', format='int')
242 # opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str')
243 # opObj11.addParameter(name='ymin', value=ymin, format='int')
244 # opObj11.addParameter(name='ymax', value=ymax, format='int')
245 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
246 # opObj11.addParameter(name='zmin', value=dBmin, format='int')
247 # opObj11.addParameter(name='zmax', value=dBmax, format='int')
248 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
249 # opObj11.addParameter(name='save', value=0, format='bool')
250 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
251 # #
252 # opObj11 = procUnitConfObjB.addOperation(name='CoherenceMap', optype='other')
253 # opObj11.addParameter(name='id', value='4', format='int')
254 # opObj11.addParameter(name='wintitle', value='Coherence', format='str')
255 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
256 # opObj11.addParameter(name='xmin', value=xmin, format='float')
257 # opObj11.addParameter(name='xmax', value=xmax, format='float')
258 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
259 # opObj11.addParameter(name='save', value=0, format='bool')
260 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
261 #
262
263 '''
264 #######################################################################
265 ############### UNIDAD DE ESCRITURA ###################################
266 #######################################################################
267 #opObj11 = procUnitConfObjB.addOperation(name='SpectraWriter', optype='other')
268 #opObj11.addParameter(name='path', value=wr_path)
269 #opObj11.addParameter(name='blocksPerFile', value='50', format='int')
270 print ("Escribiendo el archivo XML")
271 print ("Leyendo el archivo XML")
272 '''
273
274
275 controllerObj.start()
@@ -0,0 +1,126
1 #!python
2 '''
3 '''
4
5 import os, sys
6 import datetime
7 import time
8
9 #path = os.path.dirname(os.getcwd())
10 #path = os.path.dirname(path)
11 #sys.path.insert(0, path)
12
13 from schainpy.controller import Project
14
15 desc = "USRP_test"
16 filename = "USRP_processing.xml"
17 controllerObj = Project()
18 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
19
20 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
21
22 #######################################################################
23 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
24 #######################################################################
25 #path = '/media/data/data/vientos/57.2063km/echoes/NCO_Woodman'
26 #path = '/DATA_RM/TEST_INTEGRACION'
27 path = '/DATA_RM/TEST_ONLINE'
28 path_pp = '/DATA_RM/TEST_HDF5'
29
30 figpath = '/home/soporte/Pictures/TEST_INTEGRACION_IMG'
31 #remotefolder = "/home/wmaster/graficos"
32 #######################################################################
33 ################# RANGO DE PLOTEO######################################
34 #######################################################################
35 dBmin = '-5'
36 dBmax = '20'
37 xmin = '0'
38 xmax ='24'
39 ymin = '0'
40 ymax = '600'
41 #######################################################################
42 ########################FECHA##########################################
43 #######################################################################
44 str = datetime.date.today()
45 today = str.strftime("%Y/%m/%d")
46 str2 = str - datetime.timedelta(days=1)
47 yesterday = str2.strftime("%Y/%m/%d")
48 #######################################################################
49 ######################## UNIDAD DE LECTURA#############################
50 #######################################################################
51 readUnitConfObj = controllerObj.addReadUnit(datatype='DigitalRFReader',
52 path=path,
53 startDate="2021/01/01",#today,
54 endDate="2021/12/30",#today,
55 startTime='00:00:00',
56 endTime='23:59:59',
57 delay=0,
58 #set=0,
59 online=1,
60 walk=1,
61 ippKm = 60)
62
63 opObj11 = readUnitConfObj.addOperation(name='printInfo')
64 #opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
65 #######################################################################
66 ################ OPERACIONES DOMINIO DEL TIEMPO########################
67 #######################################################################
68
69 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
70
71 #
72 # codigo64='1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0,'+\
73 # '1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1'
74
75 #opObj11 = procUnitConfObjA.addOperation(name='setRadarFrequency')
76 #opObj11.addParameter(name='frequency', value='70312500')
77 opObj11 = procUnitConfObjA.addOperation(name='PulsePair', optype='other')
78 opObj11.addParameter(name='n', value='625', format='int')#10
79 opObj11.addParameter(name='removeDC', value=1, format='int')
80 # Ploteo TEST
81 '''
82 opObj11 = procUnitConfObjA.addOperation(name='PulsepairPowerPlot', optype='other')
83 opObj11 = procUnitConfObjA.addOperation(name='PulsepairSignalPlot', optype='other')
84 opObj11 = procUnitConfObjA.addOperation(name='PulsepairVelocityPlot', optype='other')
85 #opObj11.addParameter(name='xmax', value=8)
86 opObj11 = procUnitConfObjA.addOperation(name='PulsepairSpecwidthPlot', optype='other')
87 '''
88 # OJO SCOPE
89 #opObj10 = procUnitConfObjA.addOperation(name='ScopePlot', optype='external')
90 #opObj10.addParameter(name='id', value='10', format='int')
91 ##opObj10.addParameter(name='xmin', value='0', format='int')
92 ##opObj10.addParameter(name='xmax', value='50', format='int')
93 #opObj10.addParameter(name='type', value='iq')
94 ##opObj10.addParameter(name='ymin', value='-5000', format='int')
95 ##opObj10.addParameter(name='ymax', value='8500', format='int')
96 #opObj11.addParameter(name='save', value=figpath, format='str')
97 #opObj11.addParameter(name='save_period', value=10, format='int')
98
99 #opObj10 = procUnitConfObjA.addOperation(name='setH0')
100 #opObj10.addParameter(name='h0', value='-5000', format='float')
101
102 #opObj11 = procUnitConfObjA.addOperation(name='filterByHeights')
103 #opObj11.addParameter(name='window', value='1', format='int')
104
105 #codigo='1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,-1,-1,-1'
106 #opObj11 = procUnitConfObjSousy.addOperation(name='Decoder', optype='other')
107 #opObj11.addParameter(name='code', value=codigo, formatyesterday='floatlist')
108 #opObj11.addParameter(name='nCode', value='1', format='int')
109 #opObj11.addParameter(name='nBaud', value='28', format='int')
110
111 #opObj11 = procUnitConfObjA.addOperation(name='CohInt', optype='other')
112 #opObj11.addParameter(name='n', value='100', format='int')
113
114 #######################################################################
115 ########## OPERACIONES ParametersProc########################
116 #######################################################################
117
118 procUnitConfObjB= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjA.getId())
119 opObj10 = procUnitConfObjB.addOperation(name='HDFWriter')
120 opObj10.addParameter(name='path',value=path_pp)
121 #opObj10.addParameter(name='mode',value=0)
122 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
123 opObj10.addParameter(name='metadataList',value='utctimeInit,timeZone,paramInterval,profileIndex,channelList,heightList,flagDataAsBlock',format='list')
124 opObj10.addParameter(name='dataList',value='dataPP_POW,dataPP_DOP,utctime',format='list')#,format='list'
125
126 controllerObj.start()
@@ -0,0 +1,126
1 #!python
2 '''
3 '''
4
5 import os, sys
6 import datetime
7 import time
8
9 #path = os.path.dirname(os.getcwd())
10 #path = os.path.dirname(path)
11 #sys.path.insert(0, path)
12
13 from schainpy.controller import Project
14
15 desc = "USRP_test"
16 filename = "USRP_processing.xml"
17 controllerObj = Project()
18 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
19
20 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
21
22 #######################################################################
23 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
24 #######################################################################
25 #path = '/media/data/data/vientos/57.2063km/echoes/NCO_Woodman'
26 #path = '/DATA_RM/TEST_INTEGRACION'
27 path = '/DATA_RM/TEST_ONLINE'
28 path_pp = '/DATA_RM/TEST_HDF5'
29
30 figpath = '/home/soporte/Pictures/TEST_INTEGRACION_IMG'
31 #remotefolder = "/home/wmaster/graficos"
32 #######################################################################
33 ################# RANGO DE PLOTEO######################################
34 #######################################################################
35 dBmin = '-5'
36 dBmax = '20'
37 xmin = '0'
38 xmax ='24'
39 ymin = '0'
40 ymax = '600'
41 #######################################################################
42 ########################FECHA##########################################
43 #######################################################################
44 str = datetime.date.today()
45 today = str.strftime("%Y/%m/%d")
46 str2 = str - datetime.timedelta(days=1)
47 yesterday = str2.strftime("%Y/%m/%d")
48 #######################################################################
49 ######################## UNIDAD DE LECTURA#############################
50 #######################################################################
51 readUnitConfObj = controllerObj.addReadUnit(datatype='DigitalRFReader',
52 path=path,
53 startDate="2021/01/01",#today,
54 endDate="2021/12/30",#today,
55 startTime='00:00:00',
56 endTime='23:59:59',
57 delay=0,
58 #set=0,
59 online=1,
60 walk=1,
61 ippKm = 60)
62
63 opObj11 = readUnitConfObj.addOperation(name='printInfo')
64 #opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
65 #######################################################################
66 ################ OPERACIONES DOMINIO DEL TIEMPO########################
67 #######################################################################
68
69 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
70
71 #
72 # codigo64='1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0,'+\
73 # '1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1'
74
75 #opObj11 = procUnitConfObjA.addOperation(name='setRadarFrequency')
76 #opObj11.addParameter(name='frequency', value='70312500')
77 opObj11 = procUnitConfObjA.addOperation(name='PulsePair', optype='other')
78 opObj11.addParameter(name='n', value='625', format='int')#10
79 opObj11.addParameter(name='removeDC', value=1, format='int')
80 # Ploteo TEST
81 '''
82 opObj11 = procUnitConfObjA.addOperation(name='PulsepairPowerPlot', optype='other')
83 opObj11 = procUnitConfObjA.addOperation(name='PulsepairSignalPlot', optype='other')
84 opObj11 = procUnitConfObjA.addOperation(name='PulsepairVelocityPlot', optype='other')
85 #opObj11.addParameter(name='xmax', value=8)
86 opObj11 = procUnitConfObjA.addOperation(name='PulsepairSpecwidthPlot', optype='other')
87 '''
88 # OJO SCOPE
89 #opObj10 = procUnitConfObjA.addOperation(name='ScopePlot', optype='external')
90 #opObj10.addParameter(name='buffer_sizeid', value='10', format='int')
91 ##opObj10.addParameter(name='xmin', value='0', format='int')
92 ##opObj10.addParameter(name='xmax', value='50', format='int')
93 #opObj10.addParameter(name='type', value='iq')
94 ##opObj10.addParameter(name='ymin', value='-5000', format='int')
95 ##opObj10.addParameter(name='ymax', value='8500', format='int')
96 #opObj11.addParameter(name='save', value=figpath, format='str')
97 #opObj11.addParameter(name='save_period', value=10, format='int')
98
99 #opObj10 = procUnitConfObjA.addOperation(name='setH0')
100 #opObj10.addParameter(name='h0', value='-5000', format='float')
101
102 #opObj11 = procUnitConfObjA.addOperation(name='filterByHeights')
103 #opObj11.addParameter(name='window', value='1', format='int')
104
105 #codigo='1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,-1,-1,-1'
106 #opObj11 = procUnitConfObjSousy.addOperation(name='Decoder', optype='other')
107 #opObj11.addParameter(name='code', value=codigo, formatyesterday='floatlist')
108 #opObj11.addParameter(name='nCode', value='1', format='int')
109 #opObj11.addParameter(name='nBaud', value='28', format='int')
110
111 #opObj11 = procUnitConfObjA.addOperation(name='CohInt', optype='other')
112 #opObj11.addParameter(name='n', value='100', format='int')
113
114 #######################################################################
115 ########## OPERACIONES ParametersProc########################
116 #######################################################################
117
118 procUnitConfObjB= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjA.getId())
119 opObj10 = procUnitConfObjB.addOperation(name='HDFWriter')
120 opObj10.addParameter(name='path',value=path_pp)
121 #opObj10.addParameter(name='mode',value=0)
122 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
123 opObj10.addParameter(name='metadataList',value='utctimeInit,timeZone,paramInterval,profileIndex,channelList,heightList,flagDataAsBlock',format='list')
124 opObj10.addParameter(name='dataList',value='dataPP_POW,dataPP_DOP,utctime',format='list')#,format='list'
125
126 controllerObj.start()
@@ -0,0 +1,52
1 import os,sys
2 import datetime
3 import time
4 from schainpy.controller import Project
5 #path='/DATA_RM/TEST_HDF5/d2021200'
6 #path='/DATA_RM/TEST_HDF5/d2021200'
7 path='/DATA_RM/TEST_HDF5/d2021203'
8
9 path_adq=path
10 #path_ped='/DATA_RM/TEST_PEDESTAL/P2021200'
11 path_ped='/DATA_RM/TEST_PEDESTAL/P2021203'
12
13 figpath = '/home/soporte/Pictures'
14 desc = "Simulator Test"
15
16 controllerObj = Project()
17 controllerObj.setup(id='10',name='Test Simulator',description=desc)
18 readUnitConfObj = controllerObj.addReadUnit(datatype='HDFReader',
19 path=path,
20 startDate="2021/01/01", #"2020/01/01",#today,
21 endDate= "2021/12/01", #"2020/12/30",#today,
22 startTime='00:00:00',
23 endTime='23:59:59',
24 t_Interval_p=0.01,
25 n_Muestras_p=100,
26 delay=5,
27 #set=0,
28 online=0,
29 walk=0)#1
30
31 procUnitConfObjA = controllerObj.addProcUnit(datatype='ParametersProc',inputId=readUnitConfObj.getId())
32
33 opObj11 = procUnitConfObjA.addOperation(name='PedestalInformation')
34 opObj11.addParameter(name='path_ped', value=path_ped)
35 opObj11.addParameter(name='path_adq', value=path_adq)
36 opObj11.addParameter(name='t_Interval_p', value='0.01', format='float')
37 opObj11.addParameter(name='n_Muestras_p', value='100', format='float')
38 opObj11.addParameter(name='blocksPerfile', value='100', format='int')
39 opObj11.addParameter(name='f_a_p', value='25', format='int')
40 opObj11.addParameter(name='online', value='0', format='int')
41
42
43 opObj11 = procUnitConfObjA.addOperation(name='Block360')
44 opObj11.addParameter(name='n', value='40', format='int')
45
46 opObj11= procUnitConfObjA.addOperation(name='WeatherPlot',optype='other')
47 opObj11.addParameter(name='save', value=figpath)
48 opObj11.addParameter(name='save_period', value=1)
49
50 controllerObj.start()
51 #online 1 utc_adq 1617490240.48
52 #online 0 utc_adq 1617489815.4804
@@ -0,0 +1,59
1 import os,sys
2 import datetime
3 import time
4 from schainpy.controller import Project
5 #path='/DATA_RM/TEST_HDF5/d2021200'
6 #path='/DATA_RM/TEST_HDF5/d2021200'
7 #path='/DATA_RM/TEST_HDF5/d2021214'
8 #path='/DATA_RM/TEST_HDF5/d2021229'
9
10 path='/DATA_RM/TEST_HDF5/d2021231'
11
12
13 path_adq=path
14 #path_ped='/DATA_RM/TEST_PEDESTAL/P2021200'
15 #path_ped='/DATA_RM/TEST_PEDESTAL/P2021214'
16 #path_ped='/DATA_RM/TEST_PEDESTAL/P2021230'
17 path_ped='/DATA_RM/TEST_PEDESTAL/P20210819'
18 figpath = '/home/soporte/Pictures'
19 desc = "Simulator Test"
20
21 controllerObj = Project()
22 controllerObj.setup(id='10',name='Test Simulator',description=desc)
23 readUnitConfObj = controllerObj.addReadUnit(datatype='HDFReader',
24 path=path,
25 startDate="2021/01/01", #"2020/01/01",#today,
26 endDate= "2021/12/01", #"2020/12/30",#today,
27 startTime='00:00:00',
28 endTime='23:59:59',
29 t_Interval_p=0.01,
30 n_Muestras_p=100,
31 delay=30,
32 #set=0,
33 online=1,
34 walk=0,
35 nTries=6)#1
36
37 procUnitConfObjA = controllerObj.addProcUnit(datatype='ParametersProc',inputId=readUnitConfObj.getId())
38
39 opObj11 = procUnitConfObjA.addOperation(name='PedestalInformation')
40 opObj11.addParameter(name='path_ped', value=path_ped)
41 opObj11.addParameter(name='path_adq', value=path_adq)
42 opObj11.addParameter(name='t_Interval_p', value='0.01', format='float')
43 opObj11.addParameter(name='n_Muestras_p', value='100', format='float')
44 opObj11.addParameter(name='blocksPerfile', value='100', format='int')
45 opObj11.addParameter(name='f_a_p', value='25', format='int')
46 opObj11.addParameter(name='online', value='1', format='int')# habilitar el enable aqui tambien
47
48
49 opObj11 = procUnitConfObjA.addOperation(name='Block360')
50 opObj11.addParameter(name='n', value='40', format='int')
51 # este bloque funciona bien con divisores de 360 no olvidar 0 10 20 30 40 60 90 120 180
52
53 opObj11= procUnitConfObjA.addOperation(name='WeatherPlot',optype='other')
54 opObj11.addParameter(name='save', value=figpath)
55 opObj11.addParameter(name='save_period', value=1)
56
57 controllerObj.start()
58 #online 1 utc_adq 1617490240.48
59 #online 0 utc_adq 1617489815.4804
@@ -0,0 +1,35
1 #*******************************************************************************
2 #*************ARCHIVO DE CONFIGURACION - RADAR METEOROLOGICO********************
3 #*******************************************************************************
4 # 1-Resolucion_angular(Grados ΒΊ)-F
5 1.0
6 # 2-Velocidad_Pedestal Azimuth(ΒΊ/s)-F
7 4.0
8 # 3-Posicion_Pedestal Azimuth(ΒΊ/s)-F
9 0.0
10 # 4-Posicion_Pedestal Elevacion(ΒΊ/s)-F
11 30.0
12 # 5-IPP(useg)-F
13 400
14 # n-PulsePair-nFFTPoints-R
15 625
16 # 6-Cantidad_Muestras_archivo_pedestal-F
17 100
18 # 7-Tiempo_por_muestra_pedestal-F
19 0.01
20 # Tiempo_archivo_por_pedestal-R
21 1.0
22 # 8-Bloques_por_arhivo_adquisicion-F
23 100.0
24 # tiempo_por_archivo_adquisicion-R
25 25.0
26 # mode Time Domain(T , 1) or Frequency Domain(F , 0)
27 1
28 # path_p
29 /home/developer/Downloads/Pedestal/P2021093
30 # path_a
31 /home/developer/Downloads/HDF5_TESTPP2V3/d2021093
32 # online
33 0
34 # Directorio final
35 /home/developer/Downloads/HDF5_WR/
@@ -0,0 +1,70
1 print("LECTURA DE ARCHIVOS DE CONFIGURACION")
2 class ReadfileWR():
3 def __init__(self,filename):
4 f = open(filename, "r")
5 i=0
6 self.dict={'paht_ped':None,'path_adq':None,'path_res':None,'resolution':None,'vel_ped_azi':None,'pos_ped_azi':None,'pos_ped_ele':None,'ipp':None,'n':None,'len_ped':None,\
7 't_s_ped':None,'t_f_ped':None,'b_f_adq':None,'t_f_adq':None,'mode':None,'online':None}
8 while(True):
9 ##print(i)
10 linea = f.readline()
11 if i==4:
12 resolution=float(linea)
13 self.dict['resolution']=resolution
14 if i==6:
15 vel_pedestal_a=float(linea)
16 self.dict['vel_ped_azi']=vel_pedestal_a
17 if i==8:
18 pos_pedestal_a=float(linea)
19 self.dict['pos_ped_azi']=pos_pedestal_a
20 if i==10:
21 pos_pedestal_e=float(linea)
22 self.dict['pos_ped_ele']=pos_pedestal_e
23 if i==12:
24 ipp = float(linea)
25 self.dict['ipp']= round(ipp,5)
26 if i==14:
27 n = float(linea)
28 self.dict['n']= n
29 if i==16:
30 len_pedestal= float(linea)
31 self.dict['len_ped']= len_pedestal
32 if i==18:
33 time_x_sample_ped=float(linea)
34 self.dict['t_s_ped']= time_x_sample_ped
35 if i==20:
36 time_x_file_ped = float(linea)
37 self.dict['t_f_ped']= time_x_file_ped
38 if i==22:
39 bloques_x_file_adq= float(linea)
40 self.dict['b_f_adq']=bloques_x_file_adq
41 if i==24:
42 time_x_file_adq = float(linea)
43 self.dict['t_f_adq'] = time_x_file_adq
44 if i==26:
45 mode= int(linea)
46 self.dict['mode'] = mode
47 if i==28:
48 path_p= str(linea)
49 self.dict['path_ped'] = path_p
50 if i==30:
51 path_a= str(linea)
52 self.dict['path_adq'] = path_a
53 if i==32:
54 online= int(linea)
55 self.dict['online'] = online
56 if i==34:
57 path_r= str(linea)
58 self.dict['path_res'] = path_r
59 #print(linea)
60 if not linea:
61 break
62 i+=1
63 f.close()
64 def getDict(self):
65 return self.dict
66
67
68 #filename= "/home/developer/Downloads/config_WR.txt"
69 #dict= ReadfileWR(filename).getDict()
70 #print(dict)
@@ -0,0 +1,118
1 #!python
2 '''
3 '''
4
5 import os, sys
6 import datetime
7 import time
8
9
10 from schainpy.controller import Project
11
12 desc = "USRP_test"
13 filename = "USRP_processing.xml"
14 controllerObj = Project()
15 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
16
17 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
18
19 #######################################################################
20 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
21 #######################################################################
22 # path IVAN
23 path = '/home/soporte/jarsjuliahigh/high'
24
25 figpath = '/home/soporte/Pictures/IVAN'
26 #remotefolder = "/home/wmaster/graficos"
27 #######################################################################
28 ################# RANGO DE PLOTEO######################################
29 #######################################################################
30 dBmin = '10'
31 dBmax = '55'
32 xmin = '0'
33 xmax ='24'
34 ymin = '0'
35 ymax = '600'
36 #######################################################################
37 ########################FECHA##########################################
38 #######################################################################
39 str = datetime.date.today()
40 today = str.strftime("%Y/%m/%d")
41 str2 = str - datetime.timedelta(days=1)
42 yesterday = str2.strftime("%Y/%m/%d")
43 #######################################################################
44 ######################## UNIDAD DE LECTURA#############################
45 #######################################################################
46 readUnitConfObj = controllerObj.addReadUnit(datatype='VoltageReader',
47 path=path,
48 startDate="2021/07/02",#today,
49 endDate="2021/07/02",#today,
50 startTime='14:50:01',# inicio libre
51 endTime='14:55:59',
52 delay=0,
53 #set=0,
54 online=0,
55 walk=0)
56
57 opObj11 = readUnitConfObj.addOperation(name='printInfo')
58 #opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
59 #######################################################################
60 ################ OPERACIONES DOMINIO DEL TIEMPO########################
61 #######################################################################
62
63 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
64
65 #opObj10 = procUnitConfObjA.addOperation(name='selectChannels')
66 #opObj10.addParameter(name='channelList', value=[0])
67
68 '''
69 opObj10 = procUnitConfObjA.addOperation(name='ScopePlot', optype='external')
70 opObj10.addParameter(name='id', value='10', format='int')
71 #opObj10.addParameter(name='xmin', value='0', format='int')
72 ##opObj10.addParameter(name='xmax', value='50', format='int')
73 opObj10.addParameter(name='type', value='iq')
74 ##opObj10.addParameter(name='ymin', value='-5000', format='int')
75 ##opObj10.addParameter(name='ymax', value='8500', format='int')
76 #opObj11.addParameter(name='save', value=figpath, format='str')
77 #opObj11.addParameter(name='save_period', value=10, format='int')
78 '''
79 ###opObj11 = procUnitConfObjA.addOperation(name='selectHeights')
80 ###opObj11.addParameter(name='minIndex', value='1', format='int')
81 #### opObj11.addParameter(name='maxIndex', value='10000', format='int')
82 ####opObj11.addParameter(name='maxIndex', value='39980', format='int')
83
84 #######################################################################
85 ########## OPERACIONES DOMINIO DE LA FRECUENCIA########################
86 #######################################################################
87
88 #procUnitConfObjB = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjA.getId())
89 #procUnitConfObjB.addParameter(name='nFFTPoints', value='32', format='int')
90 #procUnitConfObjB.addParameter(name='nProfiles', value='32', format='int')
91
92 procUnitConfObjC = controllerObj.addProcUnit(datatype='SpectraHeisProc', inputId=procUnitConfObjA.getId())
93
94 opObj11 = procUnitConfObjC.addOperation(name='IncohInt4SpectraHeis', optype='other')
95 #opObj11.addParameter(name='timeInterval', value='4', format='int')
96 opObj11.addParameter(name='n', value='100', format='int')
97
98 #opObj11.addParameter(name='overlapping', value=True, format='bool')
99
100 opObj11 = procUnitConfObjC.addOperation(name='SpectraHeisPlot')
101 opObj11.addParameter(name='id', value='10', format='int')
102 opObj11.addParameter(name='wintitle', value='Spectra_Alturas', format='str')
103
104 #opObj11.addParameter(name='xmin', value=-100000, format='float')
105 #opObj11.addParameter(name='xmax', value=100000, format='float')
106 opObj11.addParameter(name='oneFigure', value=False,format='bool')
107 #opObj11.addParameter(name='zmin', value=-10, format='int')
108 #opObj11.addParameter(name='zmax', value=40, format='int')
109 opObj11.addParameter(name='ymin', value=dBmin, format='int')
110 opObj11.addParameter(name='ymax', value=dBmax, format='int')
111 opObj11.addParameter(name='grid', value=True, format='bool')
112 #opObj11.addParameter(name='showprofile', value='1', format='int')
113 opObj11.addParameter(name='save', value=figpath, format='str')
114 #opObj11.addParameter(name='save_period', value=10, format='int')
115
116
117
118 controllerObj.start()
@@ -0,0 +1,103
1 #!python
2 '''
3 '''
4
5 import os, sys
6 import datetime
7 import time
8
9
10 from schainpy.controller import Project
11
12 desc = "USRP_test"
13 filename = "USRP_processing.xml"
14 controllerObj = Project()
15 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
16
17 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
18
19 #######################################################################
20 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
21 #######################################################################
22 # path JHON
23 path = '/home/soporte/jars2'
24
25 figpath = '/home/soporte/Pictures/JHON'
26 #remotefolder = "/home/wmaster/graficos"
27 #######################################################################
28 ################# RANGO DE PLOTEO######################################
29 #######################################################################
30 dBmin = '0'
31 dBmax = '50'
32 xmin = '0'
33 xmax ='24'
34 ymin = '0'
35 ymax = '600'
36 #######################################################################
37 ########################FECHA##########################################
38 #######################################################################
39 str = datetime.date.today()
40 today = str.strftime("%Y/%m/%d")
41 str2 = str - datetime.timedelta(days=1)
42 yesterday = str2.strftime("%Y/%m/%d")
43 #######################################################################
44 ######################## UNIDAD DE LECTURA#############################
45 #######################################################################
46 readUnitConfObj = controllerObj.addReadUnit(datatype='VoltageReader',
47 path=path,
48 startDate="2021/07/02",#today,
49 endDate="2021/07/02",#today,
50 startTime='19:45:00',# inicio libre
51 endTime='19:50:59',
52 delay=0,
53 #set=0,
54 online=0,
55 walk=0)
56
57 opObj11 = readUnitConfObj.addOperation(name='printInfo')
58 #opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
59 #######################################################################
60 ################ OPERACIONES DOMINIO DEL TIEMPO########################
61 #######################################################################
62
63 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
64
65 opObj11 = procUnitConfObjA.addOperation(name='selectHeights')
66 opObj11.addParameter(name='minIndex', value='1', format='int')
67 # opObj11.addParameter(name='maxIndex', value='10000', format='int')
68 opObj11.addParameter(name='maxIndex', value='39980', format='int')
69
70
71 #######################################################################
72 ########## OPERACIONES DOMINIO DE LA FRECUENCIA########################
73 #######################################################################
74
75 #procUnitConfObjB = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjA.getId())
76 #procUnitConfObjB.addParameter(name='nFFTPoints', value='32', format='int')
77 #procUnitConfObjB.addParameter(name='nProfiles', value='32', format='int')
78
79 procUnitConfObjC = controllerObj.addProcUnit(datatype='SpectraHeisProc', inputId=procUnitConfObjA.getId())
80
81 #opObj11 = procUnitConfObjC.addOperation(name='IncohInt4SpectraHeis', optype='other')
82 #opObj11.addParameter(name='timeInterval', value='4', format='int')
83 opObj11 = procUnitConfObjC.addOperation(name='IncohInt4SpectraHeis', optype='other')
84 #opObj11.addParameter(name='timeInterval', value='4', format='int')
85 opObj11.addParameter(name='n', value='100', format='int')
86
87
88 opObj11 = procUnitConfObjC.addOperation(name='SpectraHeisPlot')
89 opObj11.addParameter(name='id', value='10', format='int')
90 opObj11.addParameter(name='wintitle', value='Spectra_Alturas', format='str')
91 #opObj11.addParameter(name='xmin', value=-100000, format='float')
92 #opObj11.addParameter(name='xmax', value=100000, format='float')
93 opObj11.addParameter(name='oneFigure', value=False,format='bool')
94 #opObj11.addParameter(name='zmin', value=-10, format='int')
95 #opObj11.addParameter(name='zmax', value=40, format='int')
96 opObj11.addParameter(name='ymin', value=dBmin, format='int')
97 opObj11.addParameter(name='ymax', value=dBmax, format='int')
98 opObj11.addParameter(name='grid', value=True, format='bool')
99 #opObj11.addParameter(name='showprofile', value='1', format='int')
100 opObj11.addParameter(name='save', value=figpath, format='str')
101 #opObj11.addParameter(name='save_period', value=10, format='int')
102
103 controllerObj.start()
@@ -0,0 +1,47
1 import os,sys
2 import datetime
3 import time
4 from schainpy.controller import Project
5 '''
6 NOTA:
7 Este script de prueba.
8 - Unidad del lectura 'HDFReader'.
9 - Unidad de procesamiento VoltageProc
10 - Unidad de procesamiento SpectraProc
11 - Operacion removeDC.
12 - Unidad de procesamiento ParametersProc
13 - Operacion SpectralMoments
14 - Operacion SpectralMomentsPlot
15 - Unidad de escrituda 'HDFWriter'.
16 '''
17 path='/home/developer/Downloads/HDF5_WR'
18 figpath = path
19 desc = "Simulator Test"
20
21 controllerObj = Project()
22
23 controllerObj.setup(id='10',name='Test Simulator',description=desc)
24
25 readUnitConfObj = controllerObj.addReadUnit(datatype='HDFReader',
26 path=path,
27 startDate="2021/01/01", #"2020/01/01",#today,
28 endDate= "2021/12/01", #"2020/12/30",#today,
29 startTime='00:00:00',
30 endTime='23:59:59',
31 delay=0,
32 #set=0,
33 online=0,
34 walk=0)#1
35
36 procUnitConfObjA = controllerObj.addProcUnit(datatype='ParametersProc',inputId=readUnitConfObj.getId())
37
38 opObj11 = procUnitConfObjA.addOperation(name='Block360')
39 opObj11.addParameter(name='n', value='40', format='int')
40
41 opObj11= procUnitConfObjA.addOperation(name='WeatherPlot',optype='other')
42 opObj11.addParameter(name='save', value=figpath)
43 opObj11.addParameter(name='save_period', value=1)
44 #opObj11 = procUnitConfObjA.addOperation(name='PowerPlot', optype='other')#PulsepairPowerPlot
45 #opObj11 = procUnitConfObjA.addOperation(name='PPSignalPlot', optype='other')
46
47 controllerObj.start()
@@ -0,0 +1,51
1 import os,sys,json
2 import datetime
3 import time
4 from schainpy.controller import Project
5 '''
6 NOTA:
7 Este script de prueba.
8 - Unidad del lectura 'HDFReader'.
9 - Unidad de procesamiento ParametersProc
10 - Operacion SpectralMomentsPlot
11
12 '''
13 path = '/home/soporte/Downloads/RAWDATA_PP'
14 path='/DATA_RM/TEST_HDF5/d2021203'
15 figpath = '/home/soporte/Downloads/IMAGE'
16 desc = "Simulator Test"
17 desc_data = {
18 'Data': {
19 'dataPP_POW': 'Data/dataPP_POW/channel00',
20 'utctime':'Data/utctime'
21 },
22 'Metadata': {
23 'heightList' :'Metadata/heightList',
24 'flagDataAsBlock':'Metadata/flagDataAsBlock',
25 'profileIndex':'Metadata/profileIndex'
26 }
27 }
28
29 controllerObj = Project()
30
31 controllerObj.setup(id='10',name='Test Simulator',description=desc)
32
33 readUnitConfObj = controllerObj.addReadUnit(datatype='HDFReader',
34 path=path,
35 startDate="2021/01/01", #"2020/01/01",#today,
36 endDate= "2021/12/01", #"2020/12/30",#today,
37 startTime='00:00:00',
38 endTime='23:59:59',
39 delay=0,
40 #set=0,
41 online=0,
42 walk=0,
43 description= json.dumps(desc_data))#1
44
45 procUnitConfObjA = controllerObj.addProcUnit(datatype='ParametersProc',inputId=readUnitConfObj.getId())
46
47 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairPowerPlot', optype='other')#PulsepairPowerPlot
48 opObj11 = procUnitConfObjA.addOperation(name='PulsepairSignalPlot', optype='other')
49
50
51 controllerObj.start()
@@ -0,0 +1,56
1 import os,sys,json
2 import datetime
3 import time
4 from schainpy.controller import Project
5 '''
6 NOTA:
7 Este script de prueba.
8 - Unidad del lectura 'HDFReader'.
9 - Unidad de procesamiento ParametersProc
10 - Operacion SpectralMomentsPlot
11
12 '''
13 path = '/home/soporte/Downloads/RAWDATA'
14 figpath = '/home/soporte/Downloads/IMAGE'
15 desc = "Simulator Test"
16 desc_data = {
17 'Data': {
18 'data_pow': 'Data/data_pow/channel00',
19 'data_dop': 'Data/data_dop/channel00',
20 'utctime':'Data/utctime'
21 },
22 'Metadata': {
23 'heightList':'Metadata/heightList',
24 'nIncohInt' :'Metadata/nIncohInt',
25 'nCohInt' :'Metadata/nCohInt',
26 'nProfiles' :'Metadata/nProfiles',
27 'channelList' :'Metadata/channelList'
28 }
29 }
30
31 controllerObj = Project()
32
33 controllerObj.setup(id='10',name='Test Simulator',description=desc)
34
35 readUnitConfObj = controllerObj.addReadUnit(datatype='HDFReader',
36 path=path,
37 startDate="2021/01/01", #"2020/01/01",#today,
38 endDate= "2021/12/01", #"2020/12/30",#today,
39 startTime='00:00:00',
40 endTime='23:59:59',
41 delay=0,
42 #set=0,
43 online=0,
44 walk=1,
45 description= json.dumps(desc_data))#1
46
47 procUnitConfObjA = controllerObj.addProcUnit(datatype='ParametersProc',inputId=readUnitConfObj.getId())
48 '''
49 opObj11 = procUnitConfObjA.addOperation(name='DopplerPlot',optype='external')
50 #opObj11.addParameter(name='xmin', value=0)
51 #opObj11.addParameter(name='xmax', value=23)
52 opObj11.addParameter(name='save', value=figpath)
53 opObj11.addParameter(name='showprofile', value=0)
54 opObj11.addParameter(name='save_period', value=10)
55 '''
56 controllerObj.start()
@@ -0,0 +1,55
1 import os,sys
2 import datetime
3 import time
4 from schainpy.controller import Project
5
6 #*************************************************************************
7 #**************************LECTURA config_WR.txt**************************
8 #*************************************************************************
9 from readFileconfig import ReadfileWR
10 filename= "/home/soporte/schainv3/schain/schainpy/scripts/config_WR.txt"
11 dict= ReadfileWR(filename).getDict()
12
13 FixRCP_IPP = dict['ipp']*0.15 #equivalencia
14 dataBlocksPerFile= dict['b_f_adq']
15 profilesPerBlock= int(dict['n'])
16 pulsepair = int(dict['n'])
17 #*************************************************************************
18 path = '/home/soporte/Downloads/RAWDATA_PP_C'
19 figpath = path
20 desc = "Simulator Test"
21 controllerObj = Project()
22 controllerObj.setup(id='10',name='Test Simulator',description=desc)
23 readUnitConfObj = controllerObj.addReadUnit(datatype='SimulatorReader',
24 frequency=9.345e9,
25 FixRCP_IPP= FixRCP_IPP,
26 Tau_0 = 30,
27 AcqH0_0=0,
28 samples=330,
29 AcqDH_0=0.15,
30 FixRCP_TXA=0.15,
31 FixRCP_TXB=0.15,
32 Fdoppler=600.0,
33 Hdoppler=36,
34 Adoppler=300,#300
35 delay=0,
36 online=0,
37 walk=0,
38 profilesPerBlock=profilesPerBlock,
39 dataBlocksPerFile=dataBlocksPerFile)#,#nTotalReadFiles=2)
40 #opObj11 = readUnitConfObj.addOperation(name='printInfo')
41 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
42
43 opObj11 = procUnitConfObjA.addOperation(name='PulsePair')
44 opObj11.addParameter(name='n', value=pulsepair, format='int')#10
45
46 procUnitConfObjB= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjA.getId())
47
48 opObj10 = procUnitConfObjB.addOperation(name='HDFWriter')
49 opObj10.addParameter(name='path',value=figpath)
50 #opObj10.addParameter(name='mode',value=2)
51 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
52 opObj10.addParameter(name='metadataList',value='utctimeInit,paramInterval,heightList,profileIndex,flagDataAsBlock',format='list')
53 opObj10.addParameter(name='dataList',value='dataPP_POW,dataPP_DOP,utctime',format='list')#,format='list'
54
55 controllerObj.start()
@@ -0,0 +1,50
1 import os,sys
2 import datetime
3 import time
4 from schainpy.controller import Project
5 path = '/home/soporte/Downloads/RAWDATA_PP_Z'
6 figpath = path
7 desc = "Simulator Test"
8
9 controllerObj = Project()
10
11 controllerObj.setup(id='10',name='Test Simulator',description=desc)
12
13 readUnitConfObj = controllerObj.addReadUnit(datatype='SimulatorReader',
14 frequency=9.345e9,
15 FixRCP_IPP= 60,
16 Tau_0 = 30,
17 AcqH0_0=0,
18 samples=330,
19 AcqDH_0=0.15,
20 FixRCP_TXA=0.15,
21 FixRCP_TXB=0.15,
22 Fdoppler=600.0,
23 Hdoppler=36,
24 Adoppler=300,#300
25 delay=0,
26 online=0,
27 walk=0,
28 profilesPerBlock=625,
29 dataBlocksPerFile=360)#,#nTotalReadFiles=2)
30
31 ### opObj11 = readUnitConfObj.addOperation(name='printInfo')
32
33 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
34
35 opObj11 = procUnitConfObjA.addOperation(name='PulsePair', optype='other')
36 opObj11.addParameter(name='n', value='625', format='int')#10
37 opObj11.addParameter(name='removeDC', value=1, format='int')
38
39 procUnitConfObjB= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjA.getId())
40
41 opObj10 = procUnitConfObjB.addOperation(name="WeatherRadar")
42
43 opObj10 = procUnitConfObjB.addOperation(name='HDFWriter')
44 opObj10.addParameter(name='path',value=figpath)
45 #opObj10.addParameter(name='mode',value=0)
46 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
47 opObj10.addParameter(name='metadataList',value='utctimeInit,timeInterval',format='list')
48 opObj10.addParameter(name='dataList',value='dataPP_POW,dataPP_DOP,dataPP_SNR,dataPP_WIDTH,factor_Zeh,utctime')#,format='list'
49
50 controllerObj.start()
1 NO CONTENT: modified file
NO CONTENT: modified file
@@ -1,693 +1,704
1 # Copyright (c) 2012-2020 Jicamarca Radio Observatory
1 # Copyright (c) 2012-2020 Jicamarca Radio Observatory
2 # All rights reserved.
2 # All rights reserved.
3 #
3 #
4 # Distributed under the terms of the BSD 3-clause license.
4 # Distributed under the terms of the BSD 3-clause license.
5 """Base class to create plot operations
5 """Base class to create plot operations
6
6
7 """
7 """
8
8
9 import os
9 import os
10 import sys
10 import sys
11 import zmq
11 import zmq
12 import time
12 import time
13 import numpy
13 import numpy
14 import datetime
14 import datetime
15 from collections import deque
15 from collections import deque
16 from functools import wraps
16 from functools import wraps
17 from threading import Thread
17 from threading import Thread
18 import matplotlib
18 import matplotlib
19
19
20 if 'BACKEND' in os.environ:
20 if 'BACKEND' in os.environ:
21 matplotlib.use(os.environ['BACKEND'])
21 matplotlib.use(os.environ['BACKEND'])
22 elif 'linux' in sys.platform:
22 elif 'linux' in sys.platform:
23 matplotlib.use("TkAgg")
23 matplotlib.use("TkAgg")
24 elif 'darwin' in sys.platform:
24 elif 'darwin' in sys.platform:
25 matplotlib.use('MacOSX')
25 matplotlib.use('MacOSX')
26 else:
26 else:
27 from schainpy.utils import log
27 from schainpy.utils import log
28 log.warning('Using default Backend="Agg"', 'INFO')
28 log.warning('Using default Backend="Agg"', 'INFO')
29 matplotlib.use('Agg')
29 matplotlib.use('Agg')
30
30
31 import matplotlib.pyplot as plt
31 import matplotlib.pyplot as plt
32 from matplotlib.patches import Polygon
32 from matplotlib.patches import Polygon
33 from mpl_toolkits.axes_grid1 import make_axes_locatable
33 from mpl_toolkits.axes_grid1 import make_axes_locatable
34 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
34 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
35
35
36 from schainpy.model.data.jrodata import PlotterData
36 from schainpy.model.data.jrodata import PlotterData
37 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
37 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
38 from schainpy.utils import log
38 from schainpy.utils import log
39
39
40 jet_values = matplotlib.pyplot.get_cmap('jet', 100)(numpy.arange(100))[10:90]
40 jet_values = matplotlib.pyplot.get_cmap('jet', 100)(numpy.arange(100))[10:90]
41 blu_values = matplotlib.pyplot.get_cmap(
41 blu_values = matplotlib.pyplot.get_cmap(
42 'seismic_r', 20)(numpy.arange(20))[10:15]
42 'seismic_r', 20)(numpy.arange(20))[10:15]
43 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list(
43 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list(
44 'jro', numpy.vstack((blu_values, jet_values)))
44 'jro', numpy.vstack((blu_values, jet_values)))
45 matplotlib.pyplot.register_cmap(cmap=ncmap)
45 matplotlib.pyplot.register_cmap(cmap=ncmap)
46
46
47 CMAPS = [plt.get_cmap(s) for s in ('jro', 'jet', 'viridis',
47 CMAPS = [plt.get_cmap(s) for s in ('jro', 'jet', 'viridis',
48 'plasma', 'inferno', 'Greys', 'seismic', 'bwr', 'coolwarm')]
48 'plasma', 'inferno', 'Greys', 'seismic', 'bwr', 'coolwarm')]
49
49
50 EARTH_RADIUS = 6.3710e3
50 EARTH_RADIUS = 6.3710e3
51
51
52 def ll2xy(lat1, lon1, lat2, lon2):
52 def ll2xy(lat1, lon1, lat2, lon2):
53
53
54 p = 0.017453292519943295
54 p = 0.017453292519943295
55 a = 0.5 - numpy.cos((lat2 - lat1) * p)/2 + numpy.cos(lat1 * p) * \
55 a = 0.5 - numpy.cos((lat2 - lat1) * p)/2 + numpy.cos(lat1 * p) * \
56 numpy.cos(lat2 * p) * (1 - numpy.cos((lon2 - lon1) * p)) / 2
56 numpy.cos(lat2 * p) * (1 - numpy.cos((lon2 - lon1) * p)) / 2
57 r = 12742 * numpy.arcsin(numpy.sqrt(a))
57 r = 12742 * numpy.arcsin(numpy.sqrt(a))
58 theta = numpy.arctan2(numpy.sin((lon2-lon1)*p)*numpy.cos(lat2*p), numpy.cos(lat1*p)
58 theta = numpy.arctan2(numpy.sin((lon2-lon1)*p)*numpy.cos(lat2*p), numpy.cos(lat1*p)
59 * numpy.sin(lat2*p)-numpy.sin(lat1*p)*numpy.cos(lat2*p)*numpy.cos((lon2-lon1)*p))
59 * numpy.sin(lat2*p)-numpy.sin(lat1*p)*numpy.cos(lat2*p)*numpy.cos((lon2-lon1)*p))
60 theta = -theta + numpy.pi/2
60 theta = -theta + numpy.pi/2
61 return r*numpy.cos(theta), r*numpy.sin(theta)
61 return r*numpy.cos(theta), r*numpy.sin(theta)
62
62
63
63
64 def km2deg(km):
64 def km2deg(km):
65 '''
65 '''
66 Convert distance in km to degrees
66 Convert distance in km to degrees
67 '''
67 '''
68
68
69 return numpy.rad2deg(km/EARTH_RADIUS)
69 return numpy.rad2deg(km/EARTH_RADIUS)
70
70
71
71
72 def figpause(interval):
72 def figpause(interval):
73 backend = plt.rcParams['backend']
73 backend = plt.rcParams['backend']
74 if backend in matplotlib.rcsetup.interactive_bk:
74 if backend in matplotlib.rcsetup.interactive_bk:
75 figManager = matplotlib._pylab_helpers.Gcf.get_active()
75 figManager = matplotlib._pylab_helpers.Gcf.get_active()
76 if figManager is not None:
76 if figManager is not None:
77 canvas = figManager.canvas
77 canvas = figManager.canvas
78 if canvas.figure.stale:
78 if canvas.figure.stale:
79 canvas.draw()
79 canvas.draw()
80 try:
80 try:
81 canvas.start_event_loop(interval)
81 canvas.start_event_loop(interval)
82 except:
82 except:
83 pass
83 pass
84 return
84 return
85
85
86 def popup(message):
86 def popup(message):
87 '''
87 '''
88 '''
88 '''
89
89
90 fig = plt.figure(figsize=(12, 8), facecolor='r')
90 fig = plt.figure(figsize=(12, 8), facecolor='r')
91 text = '\n'.join([s.strip() for s in message.split(':')])
91 text = '\n'.join([s.strip() for s in message.split(':')])
92 fig.text(0.01, 0.5, text, ha='left', va='center',
92 fig.text(0.01, 0.5, text, ha='left', va='center',
93 size='20', weight='heavy', color='w')
93 size='20', weight='heavy', color='w')
94 fig.show()
94 fig.show()
95 figpause(1000)
95 figpause(1000)
96
96
97
97
98 class Throttle(object):
98 class Throttle(object):
99 '''
99 '''
100 Decorator that prevents a function from being called more than once every
100 Decorator that prevents a function from being called more than once every
101 time period.
101 time period.
102 To create a function that cannot be called more than once a minute, but
102 To create a function that cannot be called more than once a minute, but
103 will sleep until it can be called:
103 will sleep until it can be called:
104 @Throttle(minutes=1)
104 @Throttle(minutes=1)
105 def foo():
105 def foo():
106 pass
106 pass
107
107
108 for i in range(10):
108 for i in range(10):
109 foo()
109 foo()
110 print "This function has run %s times." % i
110 print "This function has run %s times." % i
111 '''
111 '''
112
112
113 def __init__(self, seconds=0, minutes=0, hours=0):
113 def __init__(self, seconds=0, minutes=0, hours=0):
114 self.throttle_period = datetime.timedelta(
114 self.throttle_period = datetime.timedelta(
115 seconds=seconds, minutes=minutes, hours=hours
115 seconds=seconds, minutes=minutes, hours=hours
116 )
116 )
117
117
118 self.time_of_last_call = datetime.datetime.min
118 self.time_of_last_call = datetime.datetime.min
119
119
120 def __call__(self, fn):
120 def __call__(self, fn):
121 @wraps(fn)
121 @wraps(fn)
122 def wrapper(*args, **kwargs):
122 def wrapper(*args, **kwargs):
123 coerce = kwargs.pop('coerce', None)
123 coerce = kwargs.pop('coerce', None)
124 if coerce:
124 if coerce:
125 self.time_of_last_call = datetime.datetime.now()
125 self.time_of_last_call = datetime.datetime.now()
126 return fn(*args, **kwargs)
126 return fn(*args, **kwargs)
127 else:
127 else:
128 now = datetime.datetime.now()
128 now = datetime.datetime.now()
129 time_since_last_call = now - self.time_of_last_call
129 time_since_last_call = now - self.time_of_last_call
130 time_left = self.throttle_period - time_since_last_call
130 time_left = self.throttle_period - time_since_last_call
131
131
132 if time_left > datetime.timedelta(seconds=0):
132 if time_left > datetime.timedelta(seconds=0):
133 return
133 return
134
134
135 self.time_of_last_call = datetime.datetime.now()
135 self.time_of_last_call = datetime.datetime.now()
136 return fn(*args, **kwargs)
136 return fn(*args, **kwargs)
137
137
138 return wrapper
138 return wrapper
139
139
140 def apply_throttle(value):
140 def apply_throttle(value):
141
141
142 @Throttle(seconds=value)
142 @Throttle(seconds=value)
143 def fnThrottled(fn):
143 def fnThrottled(fn):
144 fn()
144 fn()
145
145
146 return fnThrottled
146 return fnThrottled
147
147
148
148
149 @MPDecorator
149 @MPDecorator
150 class Plot(Operation):
150 class Plot(Operation):
151 """Base class for Schain plotting operations
151 """Base class for Schain plotting operations
152
152
153 This class should never be use directtly you must subclass a new operation,
153 This class should never be use directtly you must subclass a new operation,
154 children classes must be defined as follow:
154 children classes must be defined as follow:
155
155
156 ExamplePlot(Plot):
156 ExamplePlot(Plot):
157
157
158 CODE = 'code'
158 CODE = 'code'
159 colormap = 'jet'
159 colormap = 'jet'
160 plot_type = 'pcolor' # options are ('pcolor', 'pcolorbuffer', 'scatter', 'scatterbuffer')
160 plot_type = 'pcolor' # options are ('pcolor', 'pcolorbuffer', 'scatter', 'scatterbuffer')
161
161
162 def setup(self):
162 def setup(self):
163 pass
163 pass
164
164
165 def plot(self):
165 def plot(self):
166 pass
166 pass
167
167
168 """
168 """
169
169
170 CODE = 'Figure'
170 CODE = 'Figure'
171 colormap = 'jet'
171 colormap = 'jet'
172 bgcolor = 'white'
172 bgcolor = 'white'
173 buffering = True
173 buffering = True
174 __missing = 1E30
174 __missing = 1E30
175
175
176 __attrs__ = ['show', 'save', 'ymin', 'ymax', 'zmin', 'zmax', 'title',
176 __attrs__ = ['show', 'save', 'ymin', 'ymax', 'zmin', 'zmax', 'title',
177 'showprofile']
177 'showprofile']
178
178
179 def __init__(self):
179 def __init__(self):
180
180
181 Operation.__init__(self)
181 Operation.__init__(self)
182 self.isConfig = False
182 self.isConfig = False
183 self.isPlotConfig = False
183 self.isPlotConfig = False
184 self.save_time = 0
184 self.save_time = 0
185 self.sender_time = 0
185 self.sender_time = 0
186 self.data = None
186 self.data = None
187 self.firsttime = True
187 self.firsttime = True
188 self.sender_queue = deque(maxlen=10)
188 self.sender_queue = deque(maxlen=10)
189 self.plots_adjust = {'left': 0.125, 'right': 0.9, 'bottom': 0.15, 'top': 0.9, 'wspace': 0.2, 'hspace': 0.2}
189 self.plots_adjust = {'left': 0.125, 'right': 0.9, 'bottom': 0.15, 'top': 0.9, 'wspace': 0.2, 'hspace': 0.2}
190
190
191 def __fmtTime(self, x, pos):
191 def __fmtTime(self, x, pos):
192 '''
192 '''
193 '''
193 '''
194
194
195 return '{}'.format(self.getDateTime(x).strftime('%H:%M'))
195 return '{}'.format(self.getDateTime(x).strftime('%H:%M'))
196
196
197 def __setup(self, **kwargs):
197 def __setup(self, **kwargs):
198 '''
198 '''
199 Initialize variables
199 Initialize variables
200 '''
200 '''
201
201
202 self.figures = []
202 self.figures = []
203 self.axes = []
203 self.axes = []
204 self.cb_axes = []
204 self.cb_axes = []
205 self.localtime = kwargs.pop('localtime', True)
205 self.localtime = kwargs.pop('localtime', True)
206 self.show = kwargs.get('show', True)
206 self.show = kwargs.get('show', True)
207 self.save = kwargs.get('save', False)
207 self.save = kwargs.get('save', False)
208 self.save_period = kwargs.get('save_period', 0)
208 self.save_period = kwargs.get('save_period', 0)
209 self.colormap = kwargs.get('colormap', self.colormap)
209 self.colormap = kwargs.get('colormap', self.colormap)
210 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
210 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
211 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
211 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
212 self.colormaps = kwargs.get('colormaps', None)
212 self.colormaps = kwargs.get('colormaps', None)
213 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
213 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
214 self.showprofile = kwargs.get('showprofile', False)
214 self.showprofile = kwargs.get('showprofile', False)
215 self.title = kwargs.get('wintitle', self.CODE.upper())
215 self.title = kwargs.get('wintitle', self.CODE.upper())
216 self.cb_label = kwargs.get('cb_label', None)
216 self.cb_label = kwargs.get('cb_label', None)
217 self.cb_labels = kwargs.get('cb_labels', None)
217 self.cb_labels = kwargs.get('cb_labels', None)
218 self.labels = kwargs.get('labels', None)
218 self.labels = kwargs.get('labels', None)
219 self.xaxis = kwargs.get('xaxis', 'frequency')
219 self.xaxis = kwargs.get('xaxis', 'frequency')
220 self.zmin = kwargs.get('zmin', None)
220 self.zmin = kwargs.get('zmin', None)
221 self.zmax = kwargs.get('zmax', None)
221 self.zmax = kwargs.get('zmax', None)
222 self.zlimits = kwargs.get('zlimits', None)
222 self.zlimits = kwargs.get('zlimits', None)
223 self.xmin = kwargs.get('xmin', None)
223 self.xmin = kwargs.get('xmin', None)
224 self.xmax = kwargs.get('xmax', None)
224 self.xmax = kwargs.get('xmax', None)
225 self.xrange = kwargs.get('xrange', 12)
225 self.xrange = kwargs.get('xrange', 12)
226 self.xscale = kwargs.get('xscale', None)
226 self.xscale = kwargs.get('xscale', None)
227 self.ymin = kwargs.get('ymin', None)
227 self.ymin = kwargs.get('ymin', None)
228 self.ymax = kwargs.get('ymax', None)
228 self.ymax = kwargs.get('ymax', None)
229 self.yscale = kwargs.get('yscale', None)
229 self.yscale = kwargs.get('yscale', None)
230 self.xlabel = kwargs.get('xlabel', None)
230 self.xlabel = kwargs.get('xlabel', None)
231 self.attr_time = kwargs.get('attr_time', 'utctime')
231 self.attr_time = kwargs.get('attr_time', 'utctime')
232 self.attr_data = kwargs.get('attr_data', 'data_param')
232 self.attr_data = kwargs.get('attr_data', 'data_param')
233 self.decimation = kwargs.get('decimation', None)
233 self.decimation = kwargs.get('decimation', None)
234 self.oneFigure = kwargs.get('oneFigure', True)
234 self.oneFigure = kwargs.get('oneFigure', True)
235 self.width = kwargs.get('width', None)
235 self.width = kwargs.get('width', None)
236 self.height = kwargs.get('height', None)
236 self.height = kwargs.get('height', None)
237 self.colorbar = kwargs.get('colorbar', True)
237 self.colorbar = kwargs.get('colorbar', True)
238 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
238 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
239 self.channels = kwargs.get('channels', None)
239 self.channels = kwargs.get('channels', None)
240 self.titles = kwargs.get('titles', [])
240 self.titles = kwargs.get('titles', [])
241 self.polar = False
241 self.polar = False
242 self.type = kwargs.get('type', 'iq')
242 self.type = kwargs.get('type', 'iq')
243 self.grid = kwargs.get('grid', False)
243 self.grid = kwargs.get('grid', False)
244 self.pause = kwargs.get('pause', False)
244 self.pause = kwargs.get('pause', False)
245 self.save_code = kwargs.get('save_code', self.CODE)
245 self.save_code = kwargs.get('save_code', self.CODE)
246 self.throttle = kwargs.get('throttle', 0)
246 self.throttle = kwargs.get('throttle', 0)
247 self.exp_code = kwargs.get('exp_code', None)
247 self.exp_code = kwargs.get('exp_code', None)
248 self.server = kwargs.get('server', False)
248 self.server = kwargs.get('server', False)
249 self.sender_period = kwargs.get('sender_period', 60)
249 self.sender_period = kwargs.get('sender_period', 60)
250 self.tag = kwargs.get('tag', '')
250 self.tag = kwargs.get('tag', '')
251 self.height_index = kwargs.get('height_index', None)
251 self.height_index = kwargs.get('height_index', None)
252 self.__throttle_plot = apply_throttle(self.throttle)
252 self.__throttle_plot = apply_throttle(self.throttle)
253 code = self.attr_data if self.attr_data else self.CODE
253 code = self.attr_data if self.attr_data else self.CODE
254 self.data = PlotterData(self.CODE, self.exp_code, self.localtime)
254 self.data = PlotterData(self.CODE, self.exp_code, self.localtime)
255
255
256 if self.server:
256 if self.server:
257 if not self.server.startswith('tcp://'):
257 if not self.server.startswith('tcp://'):
258 self.server = 'tcp://{}'.format(self.server)
258 self.server = 'tcp://{}'.format(self.server)
259 log.success(
259 log.success(
260 'Sending to server: {}'.format(self.server),
260 'Sending to server: {}'.format(self.server),
261 self.name
261 self.name
262 )
262 )
263
263
264 if isinstance(self.attr_data, str):
264 if isinstance(self.attr_data, str):
265 self.attr_data = [self.attr_data]
265 self.attr_data = [self.attr_data]
266
266
267 def __setup_plot(self):
267 def __setup_plot(self):
268 '''
268 '''
269 Common setup for all figures, here figures and axes are created
269 Common setup for all figures, here figures and axes are created
270 '''
270 '''
271
271
272 self.setup()
272 self.setup()
273
273
274 self.time_label = 'LT' if self.localtime else 'UTC'
274 self.time_label = 'LT' if self.localtime else 'UTC'
275
275
276 if self.width is None:
276 if self.width is None:
277 self.width = 8
277 self.width = 8
278
278
279 self.figures = []
279 self.figures = []
280 self.axes = []
280 self.axes = []
281 self.cb_axes = []
281 self.cb_axes = []
282 self.pf_axes = []
282 self.pf_axes = []
283 self.cmaps = []
283 self.cmaps = []
284
284
285 size = '15%' if self.ncols == 1 else '30%'
285 size = '15%' if self.ncols == 1 else '30%'
286 pad = '4%' if self.ncols == 1 else '8%'
286 pad = '4%' if self.ncols == 1 else '8%'
287
287
288 if self.oneFigure:
288 if self.oneFigure:
289 if self.height is None:
289 if self.height is None:
290 self.height = 1.4 * self.nrows + 1
290 self.height = 1.4 * self.nrows + 1
291 fig = plt.figure(figsize=(self.width, self.height),
291 fig = plt.figure(figsize=(self.width, self.height),
292 edgecolor='k',
292 edgecolor='k',
293 facecolor='w')
293 facecolor='w')
294 self.figures.append(fig)
294 self.figures.append(fig)
295 for n in range(self.nplots):
295 for n in range(self.nplots):
296 ax = fig.add_subplot(self.nrows, self.ncols,
296 ax = fig.add_subplot(self.nrows, self.ncols,
297 n + 1, polar=self.polar)
297 n + 1, polar=self.polar)
298 ax.tick_params(labelsize=8)
298 ax.tick_params(labelsize=8)
299 ax.firsttime = True
299 ax.firsttime = True
300 ax.index = 0
300 ax.index = 0
301 ax.press = None
301 ax.press = None
302 self.axes.append(ax)
302 self.axes.append(ax)
303 if self.showprofile:
303 if self.showprofile:
304 cax = self.__add_axes(ax, size=size, pad=pad)
304 cax = self.__add_axes(ax, size=size, pad=pad)
305 cax.tick_params(labelsize=8)
305 cax.tick_params(labelsize=8)
306 self.pf_axes.append(cax)
306 self.pf_axes.append(cax)
307 else:
307 else:
308 if self.height is None:
308 if self.height is None:
309 self.height = 3
309 self.height = 3
310 for n in range(self.nplots):
310 for n in range(self.nplots):
311 fig = plt.figure(figsize=(self.width, self.height),
311 fig = plt.figure(figsize=(self.width, self.height),
312 edgecolor='k',
312 edgecolor='k',
313 facecolor='w')
313 facecolor='w')
314 ax = fig.add_subplot(1, 1, 1, polar=self.polar)
314 ax = fig.add_subplot(1, 1, 1, polar=self.polar)
315 ax.tick_params(labelsize=8)
315 ax.tick_params(labelsize=8)
316 ax.firsttime = True
316 ax.firsttime = True
317 ax.index = 0
317 ax.index = 0
318 ax.press = None
318 ax.press = None
319 self.figures.append(fig)
319 self.figures.append(fig)
320 self.axes.append(ax)
320 self.axes.append(ax)
321 if self.showprofile:
321 if self.showprofile:
322 cax = self.__add_axes(ax, size=size, pad=pad)
322 cax = self.__add_axes(ax, size=size, pad=pad)
323 cax.tick_params(labelsize=8)
323 cax.tick_params(labelsize=8)
324 self.pf_axes.append(cax)
324 self.pf_axes.append(cax)
325
325
326 for n in range(self.nrows):
326 for n in range(self.nrows):
327 if self.colormaps is not None:
327 if self.colormaps is not None:
328 cmap = plt.get_cmap(self.colormaps[n])
328 cmap = plt.get_cmap(self.colormaps[n])
329 else:
329 else:
330 cmap = plt.get_cmap(self.colormap)
330 cmap = plt.get_cmap(self.colormap)
331 cmap.set_bad(self.bgcolor, 1.)
331 cmap.set_bad(self.bgcolor, 1.)
332 self.cmaps.append(cmap)
332 self.cmaps.append(cmap)
333
333
334 def __add_axes(self, ax, size='30%', pad='8%'):
334 def __add_axes(self, ax, size='30%', pad='8%'):
335 '''
335 '''
336 Add new axes to the given figure
336 Add new axes to the given figure
337 '''
337 '''
338 divider = make_axes_locatable(ax)
338 divider = make_axes_locatable(ax)
339 nax = divider.new_horizontal(size=size, pad=pad)
339 nax = divider.new_horizontal(size=size, pad=pad)
340 ax.figure.add_axes(nax)
340 ax.figure.add_axes(nax)
341 return nax
341 return nax
342
342
343 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
343 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
344 '''
344 '''
345 Create a masked array for missing data
345 Create a masked array for missing data
346 '''
346 '''
347 if x_buffer.shape[0] < 2:
347 if x_buffer.shape[0] < 2:
348 return x_buffer, y_buffer, z_buffer
348 return x_buffer, y_buffer, z_buffer
349
349
350 deltas = x_buffer[1:] - x_buffer[0:-1]
350 deltas = x_buffer[1:] - x_buffer[0:-1]
351 x_median = numpy.median(deltas)
351 x_median = numpy.median(deltas)
352
352
353 index = numpy.where(deltas > 5 * x_median)
353 index = numpy.where(deltas > 5 * x_median)
354
354
355 if len(index[0]) != 0:
355 if len(index[0]) != 0:
356 z_buffer[::, index[0], ::] = self.__missing
356 z_buffer[::, index[0], ::] = self.__missing
357 z_buffer = numpy.ma.masked_inside(z_buffer,
357 z_buffer = numpy.ma.masked_inside(z_buffer,
358 0.99 * self.__missing,
358 0.99 * self.__missing,
359 1.01 * self.__missing)
359 1.01 * self.__missing)
360
360
361 return x_buffer, y_buffer, z_buffer
361 return x_buffer, y_buffer, z_buffer
362
362
363 def decimate(self):
363 def decimate(self):
364
364
365 # dx = int(len(self.x)/self.__MAXNUMX) + 1
365 # dx = int(len(self.x)/self.__MAXNUMX) + 1
366 dy = int(len(self.y) / self.decimation) + 1
366 dy = int(len(self.y) / self.decimation) + 1
367
367
368 # x = self.x[::dx]
368 # x = self.x[::dx]
369 x = self.x
369 x = self.x
370 y = self.y[::dy]
370 y = self.y[::dy]
371 z = self.z[::, ::, ::dy]
371 z = self.z[::, ::, ::dy]
372
372
373 return x, y, z
373 return x, y, z
374
374
375 def format(self):
375 def format(self):
376 '''
376 '''
377 Set min and max values, labels, ticks and titles
377 Set min and max values, labels, ticks and titles
378 '''
378 '''
379
379
380 for n, ax in enumerate(self.axes):
380 for n, ax in enumerate(self.axes):
381 if ax.firsttime:
381 if ax.firsttime:
382 if self.xaxis != 'time':
382 if self.xaxis != 'time':
383 xmin = self.xmin
383 xmin = self.xmin
384 xmax = self.xmax
384 xmax = self.xmax
385 else:
385 else:
386 xmin = self.tmin
386 xmin = self.tmin
387 xmax = self.tmin + self.xrange*60*60
387 xmax = self.tmin + self.xrange*60*60
388 ax.xaxis.set_major_formatter(FuncFormatter(self.__fmtTime))
388 ax.xaxis.set_major_formatter(FuncFormatter(self.__fmtTime))
389 ax.xaxis.set_major_locator(LinearLocator(9))
389 ax.xaxis.set_major_locator(LinearLocator(9))
390 ymin = self.ymin if self.ymin is not None else numpy.nanmin(self.y[numpy.isfinite(self.y)])
390 ymin = self.ymin if self.ymin is not None else numpy.nanmin(self.y[numpy.isfinite(self.y)])
391 ymax = self.ymax if self.ymax is not None else numpy.nanmax(self.y[numpy.isfinite(self.y)])
391 ymax = self.ymax if self.ymax is not None else numpy.nanmax(self.y[numpy.isfinite(self.y)])
392 ax.set_facecolor(self.bgcolor)
392 ax.set_facecolor(self.bgcolor)
393 if self.xscale:
393 if self.xscale:
394 ax.xaxis.set_major_formatter(FuncFormatter(
394 ax.xaxis.set_major_formatter(FuncFormatter(
395 lambda x, pos: '{0:g}'.format(x*self.xscale)))
395 lambda x, pos: '{0:g}'.format(x*self.xscale)))
396 if self.yscale:
396 if self.yscale:
397 ax.yaxis.set_major_formatter(FuncFormatter(
397 ax.yaxis.set_major_formatter(FuncFormatter(
398 lambda x, pos: '{0:g}'.format(x*self.yscale)))
398 lambda x, pos: '{0:g}'.format(x*self.yscale)))
399 if self.xlabel is not None:
399 if self.xlabel is not None:
400 ax.set_xlabel(self.xlabel)
400 ax.set_xlabel(self.xlabel)
401 if self.ylabel is not None:
401 if self.ylabel is not None:
402 ax.set_ylabel(self.ylabel)
402 ax.set_ylabel(self.ylabel)
403 if self.showprofile:
403 if self.showprofile:
404 self.pf_axes[n].set_ylim(ymin, ymax)
404 self.pf_axes[n].set_ylim(ymin, ymax)
405 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
405 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
406 self.pf_axes[n].set_xlabel('dB')
406 self.pf_axes[n].set_xlabel('dB')
407 self.pf_axes[n].grid(b=True, axis='x')
407 self.pf_axes[n].grid(b=True, axis='x')
408 [tick.set_visible(False)
408 [tick.set_visible(False)
409 for tick in self.pf_axes[n].get_yticklabels()]
409 for tick in self.pf_axes[n].get_yticklabels()]
410 if self.colorbar:
410 if self.colorbar:
411 ax.cbar = plt.colorbar(
411 ax.cbar = plt.colorbar(
412 ax.plt, ax=ax, fraction=0.05, pad=0.02, aspect=10)
412 ax.plt, ax=ax, fraction=0.05, pad=0.02, aspect=10)
413 ax.cbar.ax.tick_params(labelsize=8)
413 ax.cbar.ax.tick_params(labelsize=8)
414 ax.cbar.ax.press = None
414 ax.cbar.ax.press = None
415 if self.cb_label:
415 if self.cb_label:
416 ax.cbar.set_label(self.cb_label, size=8)
416 ax.cbar.set_label(self.cb_label, size=8)
417 elif self.cb_labels:
417 elif self.cb_labels:
418 ax.cbar.set_label(self.cb_labels[n], size=8)
418 ax.cbar.set_label(self.cb_labels[n], size=8)
419 else:
419 else:
420 ax.cbar = None
420 ax.cbar = None
421 ax.set_xlim(xmin, xmax)
421 ax.set_xlim(xmin, xmax)
422 ax.set_ylim(ymin, ymax)
422 ax.set_ylim(ymin, ymax)
423 ax.firsttime = False
423 ax.firsttime = False
424 if self.grid:
424 if self.grid:
425 ax.grid(True)
425 ax.grid(True)
426 if not self.polar:
426 if not self.polar:
427 ax.set_title('{} {} {}'.format(
427 ax.set_title('{} {} {}'.format(
428 self.titles[n],
428 self.titles[n],
429 self.getDateTime(self.data.max_time).strftime(
429 self.getDateTime(self.data.max_time).strftime(
430 '%Y-%m-%d %H:%M:%S'),
430 '%Y-%m-%d %H:%M:%S'),
431 self.time_label),
431 self.time_label),
432 size=8)
432 size=8)
433 else:
433 else:
434 ax.set_title('{}'.format(self.titles[n]), size=8)
434 ax.set_title('{}'.format(self.titles[n]), size=8)
435 ax.set_ylim(0, 90)
435 ax.set_ylim(0, 90)
436 ax.set_yticks(numpy.arange(0, 90, 20))
436 ax.set_yticks(numpy.arange(0, 90, 20))
437 ax.yaxis.labelpad = 40
437 ax.yaxis.labelpad = 40
438
438
439 if self.firsttime:
439 if self.firsttime:
440 for n, fig in enumerate(self.figures):
440 for n, fig in enumerate(self.figures):
441 fig.subplots_adjust(**self.plots_adjust)
441 fig.subplots_adjust(**self.plots_adjust)
442 self.firsttime = False
442 self.firsttime = False
443
443
444 def clear_figures(self):
444 def clear_figures(self):
445 '''
445 '''
446 Reset axes for redraw plots
446 Reset axes for redraw plots
447 '''
447 '''
448
448
449 for ax in self.axes+self.pf_axes+self.cb_axes:
449 for ax in self.axes+self.pf_axes+self.cb_axes:
450 ax.clear()
450 ax.clear()
451 ax.firsttime = True
451 ax.firsttime = True
452 if hasattr(ax, 'cbar') and ax.cbar:
452 if hasattr(ax, 'cbar') and ax.cbar:
453 ax.cbar.remove()
453 ax.cbar.remove()
454
454
455 def __plot(self):
455 def __plot(self):
456 '''
456 '''
457 Main function to plot, format and save figures
457 Main function to plot, format and save figures
458 '''
458 '''
459
459
460 self.plot()
460 self.plot()
461 self.format()
461 self.format()
462
462
463 for n, fig in enumerate(self.figures):
463 for n, fig in enumerate(self.figures):
464 if self.nrows == 0 or self.nplots == 0:
464 if self.nrows == 0 or self.nplots == 0:
465 log.warning('No data', self.name)
465 log.warning('No data', self.name)
466 fig.text(0.5, 0.5, 'No Data', fontsize='large', ha='center')
466 fig.text(0.5, 0.5, 'No Data', fontsize='large', ha='center')
467 fig.canvas.manager.set_window_title(self.CODE)
467 fig.canvas.manager.set_window_title(self.CODE)
468 continue
468 continue
469
469
470 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
470 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
471 self.getDateTime(self.data.max_time).strftime('%Y/%m/%d')))
471 self.getDateTime(self.data.max_time).strftime('%Y/%m/%d')))
472 fig.canvas.draw()
472 fig.canvas.draw()
473 if self.show:
473 if self.show:
474 fig.show()
474 fig.show()
475 figpause(0.01)
475 figpause(0.01)
476
476
477 if self.save:
477 if self.save:
478 self.save_figure(n)
478 self.save_figure(n)
479
479
480 if self.server:
480 if self.server:
481 self.send_to_server()
481 self.send_to_server()
482
482
483 def __update(self, dataOut, timestamp):
483 def __update(self, dataOut, timestamp):
484 '''
484 '''
485 '''
485 '''
486
486
487 metadata = {
487 metadata = {
488 'yrange': dataOut.heightList,
488 'yrange': dataOut.heightList,
489 'interval': dataOut.timeInterval,
489 'interval': dataOut.timeInterval,
490 'channels': dataOut.channelList
490 'channels': dataOut.channelList
491 }
491 }
492
492
493 data, meta = self.update(dataOut)
493 data, meta = self.update(dataOut)
494 metadata.update(meta)
494 metadata.update(meta)
495 self.data.update(data, timestamp, metadata)
495 self.data.update(data, timestamp, metadata)
496
496
497 def save_figure(self, n):
497 def save_figure(self, n):
498 '''
498 '''
499 '''
499 '''
500
500 if self.oneFigure:
501 if (self.data.max_time - self.save_time) <= self.save_period:
501 if (self.data.max_time - self.save_time) <= self.save_period:
502 return
502 return
503
503
504 self.save_time = self.data.max_time
504 self.save_time = self.data.max_time
505
505
506 fig = self.figures[n]
506 fig = self.figures[n]
507
508 if self.throttle == 0:
507 if self.throttle == 0:
508 if self.oneFigure:
509 figname = os.path.join(
509 figname = os.path.join(
510 self.save,
510 self.save,
511 self.save_code,
511 self.save_code,
512 '{}_{}.png'.format(
512 '{}_{}.png'.format(
513 self.save_code,
513 self.save_code,
514 self.getDateTime(self.data.max_time).strftime(
514 self.getDateTime(self.data.max_time).strftime(
515 '%Y%m%d_%H%M%S'
515 '%Y%m%d_%H%M%S'
516 ),
516 ),
517 )
517 )
518 )
518 )
519 else:
520 figname = os.path.join(
521 self.save,
522 self.save_code,
523 '{}_ch{}_{}.png'.format(
524 self.save_code,n,
525 self.getDateTime(self.data.max_time).strftime(
526 '%Y%m%d_%H%M%S'
527 ),
528 )
529 )
519 log.log('Saving figure: {}'.format(figname), self.name)
530 log.log('Saving figure: {}'.format(figname), self.name)
520 if not os.path.isdir(os.path.dirname(figname)):
531 if not os.path.isdir(os.path.dirname(figname)):
521 os.makedirs(os.path.dirname(figname))
532 os.makedirs(os.path.dirname(figname))
522 fig.savefig(figname)
533 fig.savefig(figname)
523
534
524 figname = os.path.join(
535 figname = os.path.join(
525 self.save,
536 self.save,
526 '{}_{}.png'.format(
537 '{}_{}.png'.format(
527 self.save_code,
538 self.save_code,
528 self.getDateTime(self.data.min_time).strftime(
539 self.getDateTime(self.data.min_time).strftime(
529 '%Y%m%d'
540 '%Y%m%d'
530 ),
541 ),
531 )
542 )
532 )
543 )
544
533 log.log('Saving figure: {}'.format(figname), self.name)
545 log.log('Saving figure: {}'.format(figname), self.name)
534 if not os.path.isdir(os.path.dirname(figname)):
546 if not os.path.isdir(os.path.dirname(figname)):
535 os.makedirs(os.path.dirname(figname))
547 os.makedirs(os.path.dirname(figname))
536 fig.savefig(figname)
548 fig.savefig(figname)
537
549
538 def send_to_server(self):
550 def send_to_server(self):
539 '''
551 '''
540 '''
552 '''
541
553
542 if self.exp_code == None:
554 if self.exp_code == None:
543 log.warning('Missing `exp_code` skipping sending to server...')
555 log.warning('Missing `exp_code` skipping sending to server...')
544
556
545 last_time = self.data.max_time
557 last_time = self.data.max_time
546 interval = last_time - self.sender_time
558 interval = last_time - self.sender_time
547 if interval < self.sender_period:
559 if interval < self.sender_period:
548 return
560 return
549
561
550 self.sender_time = last_time
562 self.sender_time = last_time
551
563
552 attrs = ['titles', 'zmin', 'zmax', 'tag', 'ymin', 'ymax']
564 attrs = ['titles', 'zmin', 'zmax', 'tag', 'ymin', 'ymax']
553 for attr in attrs:
565 for attr in attrs:
554 value = getattr(self, attr)
566 value = getattr(self, attr)
555 if value:
567 if value:
556 if isinstance(value, (numpy.float32, numpy.float64)):
568 if isinstance(value, (numpy.float32, numpy.float64)):
557 value = round(float(value), 2)
569 value = round(float(value), 2)
558 self.data.meta[attr] = value
570 self.data.meta[attr] = value
559 if self.colormap == 'jet':
571 if self.colormap == 'jet':
560 self.data.meta['colormap'] = 'Jet'
572 self.data.meta['colormap'] = 'Jet'
561 elif 'RdBu' in self.colormap:
573 elif 'RdBu' in self.colormap:
562 self.data.meta['colormap'] = 'RdBu'
574 self.data.meta['colormap'] = 'RdBu'
563 else:
575 else:
564 self.data.meta['colormap'] = 'Viridis'
576 self.data.meta['colormap'] = 'Viridis'
565 self.data.meta['interval'] = int(interval)
577 self.data.meta['interval'] = int(interval)
566
578
567 self.sender_queue.append(last_time)
579 self.sender_queue.append(last_time)
568
580
569 while True:
581 while True:
570 try:
582 try:
571 tm = self.sender_queue.popleft()
583 tm = self.sender_queue.popleft()
572 except IndexError:
584 except IndexError:
573 break
585 break
574 msg = self.data.jsonify(tm, self.save_code, self.plot_type)
586 msg = self.data.jsonify(tm, self.save_code, self.plot_type)
575 self.socket.send_string(msg)
587 self.socket.send_string(msg)
576 socks = dict(self.poll.poll(2000))
588 socks = dict(self.poll.poll(2000))
577 if socks.get(self.socket) == zmq.POLLIN:
589 if socks.get(self.socket) == zmq.POLLIN:
578 reply = self.socket.recv_string()
590 reply = self.socket.recv_string()
579 if reply == 'ok':
591 if reply == 'ok':
580 log.log("Response from server ok", self.name)
592 log.log("Response from server ok", self.name)
581 time.sleep(0.1)
593 time.sleep(0.1)
582 continue
594 continue
583 else:
595 else:
584 log.warning(
596 log.warning(
585 "Malformed reply from server: {}".format(reply), self.name)
597 "Malformed reply from server: {}".format(reply), self.name)
586 else:
598 else:
587 log.warning(
599 log.warning(
588 "No response from server, retrying...", self.name)
600 "No response from server, retrying...", self.name)
589 self.sender_queue.appendleft(tm)
601 self.sender_queue.appendleft(tm)
590 self.socket.setsockopt(zmq.LINGER, 0)
602 self.socket.setsockopt(zmq.LINGER, 0)
591 self.socket.close()
603 self.socket.close()
592 self.poll.unregister(self.socket)
604 self.poll.unregister(self.socket)
593 self.socket = self.context.socket(zmq.REQ)
605 self.socket = self.context.socket(zmq.REQ)
594 self.socket.connect(self.server)
606 self.socket.connect(self.server)
595 self.poll.register(self.socket, zmq.POLLIN)
607 self.poll.register(self.socket, zmq.POLLIN)
596 break
608 break
597
609
598 def setup(self):
610 def setup(self):
599 '''
611 '''
600 This method should be implemented in the child class, the following
612 This method should be implemented in the child class, the following
601 attributes should be set:
613 attributes should be set:
602
614
603 self.nrows: number of rows
615 self.nrows: number of rows
604 self.ncols: number of cols
616 self.ncols: number of cols
605 self.nplots: number of plots (channels or pairs)
617 self.nplots: number of plots (channels or pairs)
606 self.ylabel: label for Y axes
618 self.ylabel: label for Y axes
607 self.titles: list of axes title
619 self.titles: list of axes title
608
620
609 '''
621 '''
610 raise NotImplementedError
622 raise NotImplementedError
611
623
612 def plot(self):
624 def plot(self):
613 '''
625 '''
614 Must be defined in the child class, the actual plotting method
626 Must be defined in the child class, the actual plotting method
615 '''
627 '''
616 raise NotImplementedError
628 raise NotImplementedError
617
629
618 def update(self, dataOut):
630 def update(self, dataOut):
619 '''
631 '''
620 Must be defined in the child class, update self.data with new data
632 Must be defined in the child class, update self.data with new data
621 '''
633 '''
622
634
623 data = {
635 data = {
624 self.CODE: getattr(dataOut, 'data_{}'.format(self.CODE))
636 self.CODE: getattr(dataOut, 'data_{}'.format(self.CODE))
625 }
637 }
626 meta = {}
638 meta = {}
627
639
628 return data, meta
640 return data, meta
629
641
630 def run(self, dataOut, **kwargs):
642 def run(self, dataOut, **kwargs):
631 '''
643 '''
632 Main plotting routine
644 Main plotting routine
633 '''
645 '''
634
646
635 if self.isConfig is False:
647 if self.isConfig is False:
636 self.__setup(**kwargs)
648 self.__setup(**kwargs)
637
649
638 if self.localtime:
650 if self.localtime:
639 self.getDateTime = datetime.datetime.fromtimestamp
651 self.getDateTime = datetime.datetime.fromtimestamp
640 else:
652 else:
641 self.getDateTime = datetime.datetime.utcfromtimestamp
653 self.getDateTime = datetime.datetime.utcfromtimestamp
642
654
643 self.data.setup()
655 self.data.setup()
644 self.isConfig = True
656 self.isConfig = True
645 if self.server:
657 if self.server:
646 self.context = zmq.Context()
658 self.context = zmq.Context()
647 self.socket = self.context.socket(zmq.REQ)
659 self.socket = self.context.socket(zmq.REQ)
648 self.socket.connect(self.server)
660 self.socket.connect(self.server)
649 self.poll = zmq.Poller()
661 self.poll = zmq.Poller()
650 self.poll.register(self.socket, zmq.POLLIN)
662 self.poll.register(self.socket, zmq.POLLIN)
651
663
652 tm = getattr(dataOut, self.attr_time)
664 tm = getattr(dataOut, self.attr_time)
653
665
654 if self.data and 'time' in self.xaxis and (tm - self.tmin) >= self.xrange*60*60:
666 if self.data and 'time' in self.xaxis and (tm - self.tmin) >= self.xrange*60*60:
655 self.save_time = tm
667 self.save_time = tm
656 self.__plot()
668 self.__plot()
657 self.tmin += self.xrange*60*60
669 self.tmin += self.xrange*60*60
658 self.data.setup()
670 self.data.setup()
659 self.clear_figures()
671 self.clear_figures()
660
672
661 self.__update(dataOut, tm)
673 self.__update(dataOut, tm)
662
674
663 if self.isPlotConfig is False:
675 if self.isPlotConfig is False:
664 self.__setup_plot()
676 self.__setup_plot()
665 self.isPlotConfig = True
677 self.isPlotConfig = True
666 if self.xaxis == 'time':
678 if self.xaxis == 'time':
667 dt = self.getDateTime(tm)
679 dt = self.getDateTime(tm)
668 if self.xmin is None:
680 if self.xmin is None:
669 self.tmin = tm
681 self.tmin = tm
670 self.xmin = dt.hour
682 self.xmin = dt.hour
671 minutes = (self.xmin-int(self.xmin)) * 60
683 minutes = (self.xmin-int(self.xmin)) * 60
672 seconds = (minutes - int(minutes)) * 60
684 seconds = (minutes - int(minutes)) * 60
673 self.tmin = (dt.replace(hour=int(self.xmin), minute=int(minutes), second=int(seconds)) -
685 self.tmin = (dt.replace(hour=int(self.xmin), minute=int(minutes), second=int(seconds)) -
674 datetime.datetime(1970, 1, 1)).total_seconds()
686 datetime.datetime(1970, 1, 1)).total_seconds()
675 if self.localtime:
687 if self.localtime:
676 self.tmin += time.timezone
688 self.tmin += time.timezone
677
689
678 if self.xmin is not None and self.xmax is not None:
690 if self.xmin is not None and self.xmax is not None:
679 self.xrange = self.xmax - self.xmin
691 self.xrange = self.xmax - self.xmin
680
692
681 if self.throttle == 0:
693 if self.throttle == 0:
682 self.__plot()
694 self.__plot()
683 else:
695 else:
684 self.__throttle_plot(self.__plot)#, coerce=coerce)
696 self.__throttle_plot(self.__plot)#, coerce=coerce)
685
697
686 def close(self):
698 def close(self):
687
699
688 if self.data and not self.data.flagNoData:
700 if self.data and not self.data.flagNoData:
689 self.save_time = 0
701 self.save_time = 0
690 self.__plot()
702 self.__plot()
691 if self.data and not self.data.flagNoData and self.pause:
703 if self.data and not self.data.flagNoData and self.pause:
692 figpause(10)
704 figpause(10)
693
@@ -1,101 +1,103
1 # Copyright (c) 2012-2020 Jicamarca Radio Observatory
1 # Copyright (c) 2012-2020 Jicamarca Radio Observatory
2 # All rights reserved.
2 # All rights reserved.
3 #
3 #
4 # Distributed under the terms of the BSD 3-clause license.
4 # Distributed under the terms of the BSD 3-clause license.
5 """Classes to plo Specra Heis data
5 """Classes to plo Specra Heis data
6
6
7 """
7 """
8
8
9 import numpy
9 import numpy
10
10
11 from schainpy.model.graphics.jroplot_base import Plot, plt
11 from schainpy.model.graphics.jroplot_base import Plot, plt
12
12
13
13
14 class SpectraHeisPlot(Plot):
14 class SpectraHeisPlot(Plot):
15
15
16 CODE = 'spc_heis'
16 CODE = 'spc_heis'
17
17
18 def setup(self):
18 def setup(self):
19
19
20 self.nplots = len(self.data.channels)
20 self.nplots = len(self.data.channels)
21 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
21 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
22 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
22 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
23 self.height = 2.6 * self.nrows
23 self.height = 2.6 * self.nrows
24 self.width = 3.5 * self.ncols
24 self.width = 3.5 * self.ncols
25 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.95, 'bottom': 0.08})
25 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.95, 'bottom': 0.08})
26 self.ylabel = 'Intensity [dB]'
26 self.ylabel = 'Intensity [dB]'
27 self.xlabel = 'Frequency [KHz]'
27 self.xlabel = 'Frequency [KHz]'
28 self.colorbar = False
28 self.colorbar = False
29
29
30 def update(self, dataOut):
30 def update(self, dataOut):
31
31
32 data = {}
32 data = {}
33 meta = {}
33 meta = {}
34 spc = 10*numpy.log10(dataOut.data_spc / dataOut.normFactor)
34 spc = 10*numpy.log10(dataOut.data_spc / dataOut.normFactor)
35 data['spc_heis'] = spc
35 data['spc_heis'] = spc
36
36
37 return data, meta
37 return data, meta
38
38
39 def plot(self):
39 def plot(self):
40
40
41 c = 3E8
41 c = 3E8
42 deltaHeight = self.data.yrange[1] - self.data.yrange[0]
42 deltaHeight = self.data.yrange[1] - self.data.yrange[0]
43 x = numpy.arange(-1*len(self.data.yrange)/2., len(self.data.yrange)/2.)*(c/(2*deltaHeight*len(self.data.yrange)*1000))
43 x = numpy.arange(-1*len(self.data.yrange)/2., len(self.data.yrange)/2.)*(c/(2*deltaHeight*len(self.data.yrange)*1000))
44 #x = (1/1000.0)*numpy.arange(-1*len(self.data.yrange)/2., len(self.data.yrange)/2.)*(c/(2*deltaHeight*len(self.data.yrange)*1000))
45
44 self.y = self.data[-1]['spc_heis']
46 self.y = self.data[-1]['spc_heis']
45 self.titles = []
47 self.titles = []
46
48
47 for n, ax in enumerate(self.axes):
49 for n, ax in enumerate(self.axes):
48 ychannel = self.y[n,:]
50 ychannel = self.y[n,:]
49 if ax.firsttime:
51 if ax.firsttime:
50 self.xmin = min(x) if self.xmin is None else self.xmin
52 self.xmin = min(x) if self.xmin is None else self.xmin
51 self.xmax = max(x) if self.xmax is None else self.xmax
53 self.xmax = max(x) if self.xmax is None else self.xmax
52 ax.plt = ax.plot(x, ychannel, lw=1, color='b')[0]
54 ax.plt = ax.plot(x, ychannel, lw=1, color='b')[0]
53 else:
55 else:
54 ax.plt.set_data(x, ychannel)
56 ax.plt.set_data(x, ychannel)
55
57
56 self.titles.append("Channel {}: {:4.2f}dB".format(n, numpy.max(ychannel)))
58 self.titles.append("Channel {}: {:4.2f}dB".format(n, numpy.max(ychannel)))
57
59
58
60
59 class RTIHeisPlot(Plot):
61 class RTIHeisPlot(Plot):
60
62
61 CODE = 'rti_heis'
63 CODE = 'rti_heis'
62
64
63 def setup(self):
65 def setup(self):
64
66
65 self.xaxis = 'time'
67 self.xaxis = 'time'
66 self.ncols = 1
68 self.ncols = 1
67 self.nrows = 1
69 self.nrows = 1
68 self.nplots = 1
70 self.nplots = 1
69 self.ylabel = 'Intensity [dB]'
71 self.ylabel = 'Intensity [dB]'
70 self.xlabel = 'Time'
72 self.xlabel = 'Time'
71 self.titles = ['RTI']
73 self.titles = ['RTI']
72 self.colorbar = False
74 self.colorbar = False
73 self.height = 4
75 self.height = 4
74 self.plots_adjust.update({'right': 0.85 })
76 self.plots_adjust.update({'right': 0.85 })
75
77
76 def update(self, dataOut):
78 def update(self, dataOut):
77
79
78 data = {}
80 data = {}
79 meta = {}
81 meta = {}
80 spc = dataOut.data_spc / dataOut.normFactor
82 spc = dataOut.data_spc / dataOut.normFactor
81 spc = 10*numpy.log10(numpy.average(spc, axis=1))
83 spc = 10*numpy.log10(numpy.average(spc, axis=1))
82 data['rti_heis'] = spc
84 data['rti_heis'] = spc
83
85
84 return data, meta
86 return data, meta
85
87
86 def plot(self):
88 def plot(self):
87
89
88 x = self.data.times
90 x = self.data.times
89 Y = self.data['rti_heis']
91 Y = self.data['rti_heis']
90
92
91 if self.axes[0].firsttime:
93 if self.axes[0].firsttime:
92 self.ymin = numpy.nanmin(Y) - 5 if self.ymin == None else self.ymin
94 self.ymin = numpy.nanmin(Y) - 5 if self.ymin == None else self.ymin
93 self.ymax = numpy.nanmax(Y) + 5 if self.ymax == None else self.ymax
95 self.ymax = numpy.nanmax(Y) + 5 if self.ymax == None else self.ymax
94 for ch in self.data.channels:
96 for ch in self.data.channels:
95 y = Y[ch]
97 y = Y[ch]
96 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
98 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
97 plt.legend(bbox_to_anchor=(1.18, 1.0))
99 plt.legend(bbox_to_anchor=(1.18, 1.0))
98 else:
100 else:
99 for ch in self.data.channels:
101 for ch in self.data.channels:
100 y = Y[ch]
102 y = Y[ch]
101 self.axes[0].lines[ch].set_data(x, y)
103 self.axes[0].lines[ch].set_data(x, y)
@@ -1,370 +1,585
1 import os
1 import os
2 import datetime
2 import datetime
3 import numpy
3 import numpy
4
4
5 from schainpy.model.graphics.jroplot_base import Plot, plt
5 from schainpy.model.graphics.jroplot_base import Plot, plt
6 from schainpy.model.graphics.jroplot_spectra import SpectraPlot, RTIPlot, CoherencePlot, SpectraCutPlot
6 from schainpy.model.graphics.jroplot_spectra import SpectraPlot, RTIPlot, CoherencePlot, SpectraCutPlot
7 from schainpy.utils import log
7 from schainpy.utils import log
8 # libreria wradlib
9 import wradlib as wrl
8
10
9 EARTH_RADIUS = 6.3710e3
11 EARTH_RADIUS = 6.3710e3
10
12
11
13
12 def ll2xy(lat1, lon1, lat2, lon2):
14 def ll2xy(lat1, lon1, lat2, lon2):
13
15
14 p = 0.017453292519943295
16 p = 0.017453292519943295
15 a = 0.5 - numpy.cos((lat2 - lat1) * p)/2 + numpy.cos(lat1 * p) * \
17 a = 0.5 - numpy.cos((lat2 - lat1) * p)/2 + numpy.cos(lat1 * p) * \
16 numpy.cos(lat2 * p) * (1 - numpy.cos((lon2 - lon1) * p)) / 2
18 numpy.cos(lat2 * p) * (1 - numpy.cos((lon2 - lon1) * p)) / 2
17 r = 12742 * numpy.arcsin(numpy.sqrt(a))
19 r = 12742 * numpy.arcsin(numpy.sqrt(a))
18 theta = numpy.arctan2(numpy.sin((lon2-lon1)*p)*numpy.cos(lat2*p), numpy.cos(lat1*p)
20 theta = numpy.arctan2(numpy.sin((lon2-lon1)*p)*numpy.cos(lat2*p), numpy.cos(lat1*p)
19 * numpy.sin(lat2*p)-numpy.sin(lat1*p)*numpy.cos(lat2*p)*numpy.cos((lon2-lon1)*p))
21 * numpy.sin(lat2*p)-numpy.sin(lat1*p)*numpy.cos(lat2*p)*numpy.cos((lon2-lon1)*p))
20 theta = -theta + numpy.pi/2
22 theta = -theta + numpy.pi/2
21 return r*numpy.cos(theta), r*numpy.sin(theta)
23 return r*numpy.cos(theta), r*numpy.sin(theta)
22
24
23
25
24 def km2deg(km):
26 def km2deg(km):
25 '''
27 '''
26 Convert distance in km to degrees
28 Convert distance in km to degrees
27 '''
29 '''
28
30
29 return numpy.rad2deg(km/EARTH_RADIUS)
31 return numpy.rad2deg(km/EARTH_RADIUS)
30
32
31
33
32
34
33 class SpectralMomentsPlot(SpectraPlot):
35 class SpectralMomentsPlot(SpectraPlot):
34 '''
36 '''
35 Plot for Spectral Moments
37 Plot for Spectral Moments
36 '''
38 '''
37 CODE = 'spc_moments'
39 CODE = 'spc_moments'
38 # colormap = 'jet'
40 # colormap = 'jet'
39 # plot_type = 'pcolor'
41 # plot_type = 'pcolor'
40
42
41 class DobleGaussianPlot(SpectraPlot):
43 class DobleGaussianPlot(SpectraPlot):
42 '''
44 '''
43 Plot for Double Gaussian Plot
45 Plot for Double Gaussian Plot
44 '''
46 '''
45 CODE = 'gaussian_fit'
47 CODE = 'gaussian_fit'
46 # colormap = 'jet'
48 # colormap = 'jet'
47 # plot_type = 'pcolor'
49 # plot_type = 'pcolor'
48
50
49 class DoubleGaussianSpectraCutPlot(SpectraCutPlot):
51 class DoubleGaussianSpectraCutPlot(SpectraCutPlot):
50 '''
52 '''
51 Plot SpectraCut with Double Gaussian Fit
53 Plot SpectraCut with Double Gaussian Fit
52 '''
54 '''
53 CODE = 'cut_gaussian_fit'
55 CODE = 'cut_gaussian_fit'
54
56
55 class SnrPlot(RTIPlot):
57 class SnrPlot(RTIPlot):
56 '''
58 '''
57 Plot for SNR Data
59 Plot for SNR Data
58 '''
60 '''
59
61
60 CODE = 'snr'
62 CODE = 'snr'
61 colormap = 'jet'
63 colormap = 'jet'
62
64
63 def update(self, dataOut):
65 def update(self, dataOut):
64
66
65 data = {
67 data = {
66 'snr': 10*numpy.log10(dataOut.data_snr)
68 'snr': 10*numpy.log10(dataOut.data_snr)
67 }
69 }
68
70
69 return data, {}
71 return data, {}
70
72
71 class DopplerPlot(RTIPlot):
73 class DopplerPlot(RTIPlot):
72 '''
74 '''
73 Plot for DOPPLER Data (1st moment)
75 Plot for DOPPLER Data (1st moment)
74 '''
76 '''
75
77
76 CODE = 'dop'
78 CODE = 'dop'
77 colormap = 'jet'
79 colormap = 'jet'
78
80
79 def update(self, dataOut):
81 def update(self, dataOut):
80
82
81 data = {
83 data = {
82 'dop': 10*numpy.log10(dataOut.data_dop)
84 'dop': 10*numpy.log10(dataOut.data_dop)
83 }
85 }
84
86
85 return data, {}
87 return data, {}
86
88
87 class PowerPlot(RTIPlot):
89 class PowerPlot(RTIPlot):
88 '''
90 '''
89 Plot for Power Data (0 moment)
91 Plot for Power Data (0 moment)
90 '''
92 '''
91
93
92 CODE = 'pow'
94 CODE = 'pow'
93 colormap = 'jet'
95 colormap = 'jet'
94
96
95 def update(self, dataOut):
97 def update(self, dataOut):
96
98
97 data = {
99 data = {
98 'pow': 10*numpy.log10(dataOut.data_pow/dataOut.normFactor)
100 'pow': 10*numpy.log10(dataOut.data_pow/dataOut.normFactor)
99 }
101 }
100
102
101 return data, {}
103 return data, {}
102
104
103 class SpectralWidthPlot(RTIPlot):
105 class SpectralWidthPlot(RTIPlot):
104 '''
106 '''
105 Plot for Spectral Width Data (2nd moment)
107 Plot for Spectral Width Data (2nd moment)
106 '''
108 '''
107
109
108 CODE = 'width'
110 CODE = 'width'
109 colormap = 'jet'
111 colormap = 'jet'
110
112
111 def update(self, dataOut):
113 def update(self, dataOut):
112
114
113 data = {
115 data = {
114 'width': dataOut.data_width
116 'width': dataOut.data_width
115 }
117 }
116
118
117 return data, {}
119 return data, {}
118
120
119 class SkyMapPlot(Plot):
121 class SkyMapPlot(Plot):
120 '''
122 '''
121 Plot for meteors detection data
123 Plot for meteors detection data
122 '''
124 '''
123
125
124 CODE = 'param'
126 CODE = 'param'
125
127
126 def setup(self):
128 def setup(self):
127
129
128 self.ncols = 1
130 self.ncols = 1
129 self.nrows = 1
131 self.nrows = 1
130 self.width = 7.2
132 self.width = 7.2
131 self.height = 7.2
133 self.height = 7.2
132 self.nplots = 1
134 self.nplots = 1
133 self.xlabel = 'Zonal Zenith Angle (deg)'
135 self.xlabel = 'Zonal Zenith Angle (deg)'
134 self.ylabel = 'Meridional Zenith Angle (deg)'
136 self.ylabel = 'Meridional Zenith Angle (deg)'
135 self.polar = True
137 self.polar = True
136 self.ymin = -180
138 self.ymin = -180
137 self.ymax = 180
139 self.ymax = 180
138 self.colorbar = False
140 self.colorbar = False
139
141
140 def plot(self):
142 def plot(self):
141
143
142 arrayParameters = numpy.concatenate(self.data['param'])
144 arrayParameters = numpy.concatenate(self.data['param'])
143 error = arrayParameters[:, -1]
145 error = arrayParameters[:, -1]
144 indValid = numpy.where(error == 0)[0]
146 indValid = numpy.where(error == 0)[0]
145 finalMeteor = arrayParameters[indValid, :]
147 finalMeteor = arrayParameters[indValid, :]
146 finalAzimuth = finalMeteor[:, 3]
148 finalAzimuth = finalMeteor[:, 3]
147 finalZenith = finalMeteor[:, 4]
149 finalZenith = finalMeteor[:, 4]
148
150
149 x = finalAzimuth * numpy.pi / 180
151 x = finalAzimuth * numpy.pi / 180
150 y = finalZenith
152 y = finalZenith
151
153
152 ax = self.axes[0]
154 ax = self.axes[0]
153
155
154 if ax.firsttime:
156 if ax.firsttime:
155 ax.plot = ax.plot(x, y, 'bo', markersize=5)[0]
157 ax.plot = ax.plot(x, y, 'bo', markersize=5)[0]
156 else:
158 else:
157 ax.plot.set_data(x, y)
159 ax.plot.set_data(x, y)
158
160
159 dt1 = self.getDateTime(self.data.min_time).strftime('%y/%m/%d %H:%M:%S')
161 dt1 = self.getDateTime(self.data.min_time).strftime('%y/%m/%d %H:%M:%S')
160 dt2 = self.getDateTime(self.data.max_time).strftime('%y/%m/%d %H:%M:%S')
162 dt2 = self.getDateTime(self.data.max_time).strftime('%y/%m/%d %H:%M:%S')
161 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
163 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
162 dt2,
164 dt2,
163 len(x))
165 len(x))
164 self.titles[0] = title
166 self.titles[0] = title
165
167
166
168
167 class GenericRTIPlot(Plot):
169 class GenericRTIPlot(Plot):
168 '''
170 '''
169 Plot for data_xxxx object
171 Plot for data_xxxx object
170 '''
172 '''
171
173
172 CODE = 'param'
174 CODE = 'param'
173 colormap = 'viridis'
175 colormap = 'viridis'
174 plot_type = 'pcolorbuffer'
176 plot_type = 'pcolorbuffer'
175
177
176 def setup(self):
178 def setup(self):
177 self.xaxis = 'time'
179 self.xaxis = 'time'
178 self.ncols = 1
180 self.ncols = 1
179 self.nrows = self.data.shape('param')[0]
181 self.nrows = self.data.shape('param')[0]
180 self.nplots = self.nrows
182 self.nplots = self.nrows
181 self.plots_adjust.update({'hspace':0.8, 'left': 0.1, 'bottom': 0.08, 'right':0.95, 'top': 0.95})
183 self.plots_adjust.update({'hspace':0.8, 'left': 0.1, 'bottom': 0.08, 'right':0.95, 'top': 0.95})
182
184
183 if not self.xlabel:
185 if not self.xlabel:
184 self.xlabel = 'Time'
186 self.xlabel = 'Time'
185
187
186 self.ylabel = 'Range [km]'
188 self.ylabel = 'Range [km]'
187 if not self.titles:
189 if not self.titles:
188 self.titles = ['Param {}'.format(x) for x in range(self.nrows)]
190 self.titles = ['Param {}'.format(x) for x in range(self.nrows)]
189
191
190 def update(self, dataOut):
192 def update(self, dataOut):
191
193
192 data = {
194 data = {
193 'param' : numpy.concatenate([getattr(dataOut, attr) for attr in self.attr_data], axis=0)
195 'param' : numpy.concatenate([getattr(dataOut, attr) for attr in self.attr_data], axis=0)
194 }
196 }
195
197
196 meta = {}
198 meta = {}
197
199
198 return data, meta
200 return data, meta
199
201
200 def plot(self):
202 def plot(self):
201 # self.data.normalize_heights()
203 # self.data.normalize_heights()
202 self.x = self.data.times
204 self.x = self.data.times
203 self.y = self.data.yrange
205 self.y = self.data.yrange
204 self.z = self.data['param']
206 self.z = self.data['param']
205
207
206 self.z = numpy.ma.masked_invalid(self.z)
208 self.z = numpy.ma.masked_invalid(self.z)
207
209
208 if self.decimation is None:
210 if self.decimation is None:
209 x, y, z = self.fill_gaps(self.x, self.y, self.z)
211 x, y, z = self.fill_gaps(self.x, self.y, self.z)
210 else:
212 else:
211 x, y, z = self.fill_gaps(*self.decimate())
213 x, y, z = self.fill_gaps(*self.decimate())
212
214
213 for n, ax in enumerate(self.axes):
215 for n, ax in enumerate(self.axes):
214
216
215 self.zmax = self.zmax if self.zmax is not None else numpy.max(
217 self.zmax = self.zmax if self.zmax is not None else numpy.max(
216 self.z[n])
218 self.z[n])
217 self.zmin = self.zmin if self.zmin is not None else numpy.min(
219 self.zmin = self.zmin if self.zmin is not None else numpy.min(
218 self.z[n])
220 self.z[n])
219
221
220 if ax.firsttime:
222 if ax.firsttime:
221 if self.zlimits is not None:
223 if self.zlimits is not None:
222 self.zmin, self.zmax = self.zlimits[n]
224 self.zmin, self.zmax = self.zlimits[n]
223
225
224 ax.plt = ax.pcolormesh(x, y, z[n].T * self.factors[n],
226 ax.plt = ax.pcolormesh(x, y, z[n].T * self.factors[n],
225 vmin=self.zmin,
227 vmin=self.zmin,
226 vmax=self.zmax,
228 vmax=self.zmax,
227 cmap=self.cmaps[n]
229 cmap=self.cmaps[n]
228 )
230 )
229 else:
231 else:
230 if self.zlimits is not None:
232 if self.zlimits is not None:
231 self.zmin, self.zmax = self.zlimits[n]
233 self.zmin, self.zmax = self.zlimits[n]
232 ax.collections.remove(ax.collections[0])
234 ax.collections.remove(ax.collections[0])
233 ax.plt = ax.pcolormesh(x, y, z[n].T * self.factors[n],
235 ax.plt = ax.pcolormesh(x, y, z[n].T * self.factors[n],
234 vmin=self.zmin,
236 vmin=self.zmin,
235 vmax=self.zmax,
237 vmax=self.zmax,
236 cmap=self.cmaps[n]
238 cmap=self.cmaps[n]
237 )
239 )
238
240
239
241
240 class PolarMapPlot(Plot):
242 class PolarMapPlot(Plot):
241 '''
243 '''
242 Plot for weather radar
244 Plot for weather radar
243 '''
245 '''
244
246
245 CODE = 'param'
247 CODE = 'param'
246 colormap = 'seismic'
248 colormap = 'seismic'
247
249
248 def setup(self):
250 def setup(self):
249 self.ncols = 1
251 self.ncols = 1
250 self.nrows = 1
252 self.nrows = 1
251 self.width = 9
253 self.width = 9
252 self.height = 8
254 self.height = 8
253 self.mode = self.data.meta['mode']
255 self.mode = self.data.meta['mode']
254 if self.channels is not None:
256 if self.channels is not None:
255 self.nplots = len(self.channels)
257 self.nplots = len(self.channels)
256 self.nrows = len(self.channels)
258 self.nrows = len(self.channels)
257 else:
259 else:
258 self.nplots = self.data.shape(self.CODE)[0]
260 self.nplots = self.data.shape(self.CODE)[0]
259 self.nrows = self.nplots
261 self.nrows = self.nplots
260 self.channels = list(range(self.nplots))
262 self.channels = list(range(self.nplots))
261 if self.mode == 'E':
263 if self.mode == 'E':
262 self.xlabel = 'Longitude'
264 self.xlabel = 'Longitude'
263 self.ylabel = 'Latitude'
265 self.ylabel = 'Latitude'
264 else:
266 else:
265 self.xlabel = 'Range (km)'
267 self.xlabel = 'Range (km)'
266 self.ylabel = 'Height (km)'
268 self.ylabel = 'Height (km)'
267 self.bgcolor = 'white'
269 self.bgcolor = 'white'
268 self.cb_labels = self.data.meta['units']
270 self.cb_labels = self.data.meta['units']
269 self.lat = self.data.meta['latitude']
271 self.lat = self.data.meta['latitude']
270 self.lon = self.data.meta['longitude']
272 self.lon = self.data.meta['longitude']
271 self.xmin, self.xmax = float(
273 self.xmin, self.xmax = float(
272 km2deg(self.xmin) + self.lon), float(km2deg(self.xmax) + self.lon)
274 km2deg(self.xmin) + self.lon), float(km2deg(self.xmax) + self.lon)
273 self.ymin, self.ymax = float(
275 self.ymin, self.ymax = float(
274 km2deg(self.ymin) + self.lat), float(km2deg(self.ymax) + self.lat)
276 km2deg(self.ymin) + self.lat), float(km2deg(self.ymax) + self.lat)
275 # self.polar = True
277 # self.polar = True
276
278
277 def plot(self):
279 def plot(self):
278
280
279 for n, ax in enumerate(self.axes):
281 for n, ax in enumerate(self.axes):
280 data = self.data['param'][self.channels[n]]
282 data = self.data['param'][self.channels[n]]
281
283
282 zeniths = numpy.linspace(
284 zeniths = numpy.linspace(
283 0, self.data.meta['max_range'], data.shape[1])
285 0, self.data.meta['max_range'], data.shape[1])
284 if self.mode == 'E':
286 if self.mode == 'E':
285 azimuths = -numpy.radians(self.data.yrange)+numpy.pi/2
287 azimuths = -numpy.radians(self.data.yrange)+numpy.pi/2
286 r, theta = numpy.meshgrid(zeniths, azimuths)
288 r, theta = numpy.meshgrid(zeniths, azimuths)
287 x, y = r*numpy.cos(theta)*numpy.cos(numpy.radians(self.data.meta['elevation'])), r*numpy.sin(
289 x, y = r*numpy.cos(theta)*numpy.cos(numpy.radians(self.data.meta['elevation'])), r*numpy.sin(
288 theta)*numpy.cos(numpy.radians(self.data.meta['elevation']))
290 theta)*numpy.cos(numpy.radians(self.data.meta['elevation']))
289 x = km2deg(x) + self.lon
291 x = km2deg(x) + self.lon
290 y = km2deg(y) + self.lat
292 y = km2deg(y) + self.lat
291 else:
293 else:
292 azimuths = numpy.radians(self.data.yrange)
294 azimuths = numpy.radians(self.data.yrange)
293 r, theta = numpy.meshgrid(zeniths, azimuths)
295 r, theta = numpy.meshgrid(zeniths, azimuths)
294 x, y = r*numpy.cos(theta), r*numpy.sin(theta)
296 x, y = r*numpy.cos(theta), r*numpy.sin(theta)
295 self.y = zeniths
297 self.y = zeniths
296
298
297 if ax.firsttime:
299 if ax.firsttime:
298 if self.zlimits is not None:
300 if self.zlimits is not None:
299 self.zmin, self.zmax = self.zlimits[n]
301 self.zmin, self.zmax = self.zlimits[n]
300 ax.plt = ax.pcolormesh( # r, theta, numpy.ma.array(data, mask=numpy.isnan(data)),
302 ax.plt = ax.pcolormesh( # r, theta, numpy.ma.array(data, mask=numpy.isnan(data)),
301 x, y, numpy.ma.array(data, mask=numpy.isnan(data)),
303 x, y, numpy.ma.array(data, mask=numpy.isnan(data)),
302 vmin=self.zmin,
304 vmin=self.zmin,
303 vmax=self.zmax,
305 vmax=self.zmax,
304 cmap=self.cmaps[n])
306 cmap=self.cmaps[n])
305 else:
307 else:
306 if self.zlimits is not None:
308 if self.zlimits is not None:
307 self.zmin, self.zmax = self.zlimits[n]
309 self.zmin, self.zmax = self.zlimits[n]
308 ax.collections.remove(ax.collections[0])
310 ax.collections.remove(ax.collections[0])
309 ax.plt = ax.pcolormesh( # r, theta, numpy.ma.array(data, mask=numpy.isnan(data)),
311 ax.plt = ax.pcolormesh( # r, theta, numpy.ma.array(data, mask=numpy.isnan(data)),
310 x, y, numpy.ma.array(data, mask=numpy.isnan(data)),
312 x, y, numpy.ma.array(data, mask=numpy.isnan(data)),
311 vmin=self.zmin,
313 vmin=self.zmin,
312 vmax=self.zmax,
314 vmax=self.zmax,
313 cmap=self.cmaps[n])
315 cmap=self.cmaps[n])
314
316
315 if self.mode == 'A':
317 if self.mode == 'A':
316 continue
318 continue
317
319
318 # plot district names
320 # plot district names
319 f = open('/data/workspace/schain_scripts/distrito.csv')
321 f = open('/data/workspace/schain_scripts/distrito.csv')
320 for line in f:
322 for line in f:
321 label, lon, lat = [s.strip() for s in line.split(',') if s]
323 label, lon, lat = [s.strip() for s in line.split(',') if s]
322 lat = float(lat)
324 lat = float(lat)
323 lon = float(lon)
325 lon = float(lon)
324 # ax.plot(lon, lat, '.b', ms=2)
326 # ax.plot(lon, lat, '.b', ms=2)
325 ax.text(lon, lat, label.decode('utf8'), ha='center',
327 ax.text(lon, lat, label.decode('utf8'), ha='center',
326 va='bottom', size='8', color='black')
328 va='bottom', size='8', color='black')
327
329
328 # plot limites
330 # plot limites
329 limites = []
331 limites = []
330 tmp = []
332 tmp = []
331 for line in open('/data/workspace/schain_scripts/lima.csv'):
333 for line in open('/data/workspace/schain_scripts/lima.csv'):
332 if '#' in line:
334 if '#' in line:
333 if tmp:
335 if tmp:
334 limites.append(tmp)
336 limites.append(tmp)
335 tmp = []
337 tmp = []
336 continue
338 continue
337 values = line.strip().split(',')
339 values = line.strip().split(',')
338 tmp.append((float(values[0]), float(values[1])))
340 tmp.append((float(values[0]), float(values[1])))
339 for points in limites:
341 for points in limites:
340 ax.add_patch(
342 ax.add_patch(
341 Polygon(points, ec='k', fc='none', ls='--', lw=0.5))
343 Polygon(points, ec='k', fc='none', ls='--', lw=0.5))
342
344
343 # plot Cuencas
345 # plot Cuencas
344 for cuenca in ('rimac', 'lurin', 'mala', 'chillon', 'chilca', 'chancay-huaral'):
346 for cuenca in ('rimac', 'lurin', 'mala', 'chillon', 'chilca', 'chancay-huaral'):
345 f = open('/data/workspace/schain_scripts/{}.csv'.format(cuenca))
347 f = open('/data/workspace/schain_scripts/{}.csv'.format(cuenca))
346 values = [line.strip().split(',') for line in f]
348 values = [line.strip().split(',') for line in f]
347 points = [(float(s[0]), float(s[1])) for s in values]
349 points = [(float(s[0]), float(s[1])) for s in values]
348 ax.add_patch(Polygon(points, ec='b', fc='none'))
350 ax.add_patch(Polygon(points, ec='b', fc='none'))
349
351
350 # plot grid
352 # plot grid
351 for r in (15, 30, 45, 60):
353 for r in (15, 30, 45, 60):
352 ax.add_artist(plt.Circle((self.lon, self.lat),
354 ax.add_artist(plt.Circle((self.lon, self.lat),
353 km2deg(r), color='0.6', fill=False, lw=0.2))
355 km2deg(r), color='0.6', fill=False, lw=0.2))
354 ax.text(
356 ax.text(
355 self.lon + (km2deg(r))*numpy.cos(60*numpy.pi/180),
357 self.lon + (km2deg(r))*numpy.cos(60*numpy.pi/180),
356 self.lat + (km2deg(r))*numpy.sin(60*numpy.pi/180),
358 self.lat + (km2deg(r))*numpy.sin(60*numpy.pi/180),
357 '{}km'.format(r),
359 '{}km'.format(r),
358 ha='center', va='bottom', size='8', color='0.6', weight='heavy')
360 ha='center', va='bottom', size='8', color='0.6', weight='heavy')
359
361
360 if self.mode == 'E':
362 if self.mode == 'E':
361 title = 'El={}$^\circ$'.format(self.data.meta['elevation'])
363 title = 'El={}$^\circ$'.format(self.data.meta['elevation'])
362 label = 'E{:02d}'.format(int(self.data.meta['elevation']))
364 label = 'E{:02d}'.format(int(self.data.meta['elevation']))
363 else:
365 else:
364 title = 'Az={}$^\circ$'.format(self.data.meta['azimuth'])
366 title = 'Az={}$^\circ$'.format(self.data.meta['azimuth'])
365 label = 'A{:02d}'.format(int(self.data.meta['azimuth']))
367 label = 'A{:02d}'.format(int(self.data.meta['azimuth']))
366
368
367 self.save_labels = ['{}-{}'.format(lbl, label) for lbl in self.labels]
369 self.save_labels = ['{}-{}'.format(lbl, label) for lbl in self.labels]
368 self.titles = ['{} {}'.format(
370 self.titles = ['{} {}'.format(
369 self.data.parameters[x], title) for x in self.channels]
371 self.data.parameters[x], title) for x in self.channels]
370
372
373 class WeatherPlot(Plot):
374 CODE = 'weather'
375 plot_name = 'weather'
376 plot_type = 'ppistyle'
377 buffering = False
378
379 def setup(self):
380 self.ncols = 1
381 self.nrows = 1
382 self.nplots= 1
383 self.ylabel= 'Range [Km]'
384 self.titles= ['Weather']
385 self.colorbar=False
386 self.width =8
387 self.height =8
388 self.ini =0
389 self.len_azi =0
390 self.buffer_ini = None
391 self.buffer_azi = None
392 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.9, 'bottom': 0.08})
393 self.flag =0
394 self.indicador= 0
395
396 def update(self, dataOut):
397
398 data = {}
399 meta = {}
400 data['weather'] = 10*numpy.log10(dataOut.data_360[0]/(650**2))
401 data['azi'] = dataOut.data_azi
402
403 return data, meta
404
405 def plot(self):
406 thisDatetime = datetime.datetime.utcfromtimestamp(self.data.times[-1])
407
408 data = self.data[-1]
409 tmp_h = (data['weather'].shape[1])/10.0
410 stoprange = float(tmp_h*1.5)#stoprange = float(33*1.5) por ahora 400
411 rangestep = float(0.15)
412 r = numpy.arange(0, stoprange, rangestep)
413 self.y = 2*r
414
415 tmp_v = data['weather']
416 print("tmp_v",tmp_v.shape)
417 tmp_z = data['azi']
418 #print("tmp_z",tmp_z.shape)
419 res = 1
420 step = (360/(res*tmp_v.shape[0]))
421 print("step",step)
422 mode = 1
423 if mode==0:
424 #print("self.ini",self.ini)
425 val = numpy.mean(tmp_v[:,0])
426 self.len_azi = len(tmp_z)
427 ones = numpy.ones([(360-tmp_v.shape[0]),tmp_v.shape[1]])*val
428 self.buffer_ini = numpy.vstack((tmp_v,ones))
429
430 n = ((360/res)-len(tmp_z))
431 start = tmp_z[-1]+res
432 end = tmp_z[0]-res
433 if start>end:
434 end = end+360
435 azi_zeros = numpy.linspace(start,end,int(n))
436 azi_zeros = numpy.where(azi_zeros>360,azi_zeros-360,azi_zeros)
437 self.buffer_ini_azi = numpy.hstack((tmp_z,azi_zeros))
438 self.ini = self.ini+1
439
440 if mode==1:
441 #print("self.ini",self.ini)
442 if self.ini==0:
443 res = 1
444 step = (360/(res*tmp_v.shape[0]))
445 val = numpy.mean(tmp_v[:,0])
446 self.len_azi = len(tmp_z)
447 self.buf_tmp = tmp_v
448 ones = numpy.ones([(360-tmp_v.shape[0]),tmp_v.shape[1]])*val
449 self.buffer_ini = numpy.vstack((tmp_v,ones))
450
451 n = ((360/res)-len(tmp_z))
452 start = tmp_z[-1]+res
453 end = tmp_z[0]-res
454 if start>end:
455 end =end+360
456 azi_zeros = numpy.linspace(start,end,int(n))
457 azi_zeros = numpy.where(azi_zeros>360,azi_zeros-360,azi_zeros)
458 self.buf_azi = tmp_z
459 self.buffer_ini_azi = numpy.hstack((tmp_z,azi_zeros))
460 self.ini = self.ini+1
461 elif 0<self.ini<step:
462 '''
463 if self.ini>31:
464 start= tmp_z[0]
465 end =tmp_z[-1]
466 print("start","end",start,end)
467 if self.ini==32:
468 tmp_v=tmp_v+20
469 if self.ini==33:
470 tmp_v=tmp_v+10
471 if self.ini==34:
472 tmp_v=tmp_v+20
473 if self.ini==35:
474 tmp_v=tmp_v+20
475 '''
476 self.buf_tmp= numpy.vstack((self.buf_tmp,tmp_v))
477 print("ERROR_INMINENTE",self.buf_tmp.shape)
478 if self.buf_tmp.shape[0]==360:
479 self.buffer_ini=self.buf_tmp
480 else:
481 val=30.0
482 ones = numpy.ones([(360-self.buf_tmp.shape[0]),self.buf_tmp.shape[1]])*val
483 self.buffer_ini = numpy.vstack((self.buf_tmp,ones))
484
485 self.buf_azi = numpy.hstack((self.buf_azi,tmp_z))
486 n = ((360/res)-len(self.buf_azi))
487 if n==0:
488 self.buffer_ini_azi = self.buf_azi
489 else:
490 start = self.buf_azi[-1]+res
491 end = self.buf_azi[0]-res
492 if start>end:
493 end =end+360
494 azi_zeros = numpy.linspace(start,end,int(n))
495 azi_zeros = numpy.where(azi_zeros>360,azi_zeros-360,azi_zeros)
496 if tmp_z[0]<self.buf_azi[0] <tmp_z[-1]:
497 self.indicador=1
498 if self.indicador==1:
499 azi_zeros = numpy.ones(360-len(self.buf_azi))*(tmp_z[-1]+res)
500 # self.indicador = True
501 #if self.indicador==True:
502 # azi_zeros = numpy.ones(360-len(self.buf_azi))*(tmp_z[-1]+res)
503
504 #self.buf_azi = tmp_z
505 self.buffer_ini_azi = numpy.hstack((self.buf_azi,azi_zeros))
506
507 if self.ini==step-1:
508 start= tmp_z[0]
509 end = tmp_z[-1]
510 #print("start","end",start,end)
511 ###print(self.buffer_ini_azi[:80])
512 self.ini = self.ini+1
513
514 else:
515 step = (360/(res*tmp_v.shape[0]))
516 tmp_v=tmp_v+5+(self.ini-step)*1
517
518 start= tmp_z[0]
519 end = tmp_z[-1]
520 #print("start","end",start,end)
521 ###print(self.buffer_ini_azi[:120])
522
523 if step>=2:
524 if self.flag<step-1:
525 limit_i=self.buf_azi[len(tmp_z)*(self.flag+1)]
526 limit_s=self.buf_azi[len(tmp_z)*(self.flag+2)-1]
527 print("flag",self.flag,limit_i,limit_s)
528 if limit_i< tmp_z[-1]< limit_s:
529 index_i=int(numpy.where(tmp_z<=self.buf_azi[len(tmp_z)*(self.flag+1)])[0][-1])
530 tmp_r =int(numpy.where(self.buf_azi[(self.flag+1)*len(tmp_z):(self.flag+2)*len(tmp_z)]>=tmp_z[-1])[0][0])
531 print("tmp_r",tmp_r)
532 index_f=(self.flag+1)*len(tmp_z)+tmp_r
533
534 if len(tmp_z[index_i:])>len(self.buf_azi[len(tmp_z)*(self.flag+1):index_f]):
535 final = len(self.buf_azi[len(tmp_z)*(self.flag+1):index_f])
536 else:
537 final= len(tmp_z[index_i:])
538 self.buf_azi[len(tmp_z)*(self.flag+1):index_f]=tmp_z[index_i:index_i+final]
539 self.buf_tmp[len(tmp_z)*(self.flag+1):index_f,:]=tmp_v[index_i:index_i+final,:]
540 if limit_i<tmp_z[0]<limit_s:
541 index_f =int(numpy.where(self.buf_azi>=tmp_z[-1])[0][0])
542 n_p =index_f-len(tmp_z)*(self.flag+1)
543 if n_p>0:
544 self.buf_azi[len(tmp_z)*(self.flag+1):index_f]=tmp_z[-1]*numpy.ones(n_p)
545 self.buf_tmp[len(tmp_z)*(self.flag+1):index_f,:]=tmp_v[-1,:]*numpy.ones([n_p,tmp_v.shape[1]])
546
547 '''
548 if self.buf_azi[len(tmp_z)]<tmp_z[-1]<self.buf_azi[2*len(tmp_z)-1]:
549 index_i= int(numpy.where(tmp_z <= self.buf_azi[len(tmp_z)])[0][-1])
550 index_f= int(numpy.where(self.buf_azi>=tmp_z[-1])[0][0])
551 #print("index",index_i,index_f)
552 if len(tmp_z[index_i:])>len(self.buf_azi[len(tmp_z):index_f]):
553 final = len(self.buf_azi[len(tmp_z):index_f])
554 else:
555 final = len(tmp_z[index_i:])
556 self.buf_azi[len(tmp_z):index_f]=tmp_z[index_i:index_i+final]
557 self.buf_tmp[len(tmp_z):index_f,:]=tmp_v[index_i:index_i+final,:]
558 '''
559 self.buf_tmp[len(tmp_z)*(self.flag):len(tmp_z)*(self.flag+1),:]=tmp_v
560 self.buf_azi[len(tmp_z)*(self.flag):len(tmp_z)*(self.flag+1)] = tmp_z
561 self.buffer_ini=self.buf_tmp
562 self.buffer_ini_azi = self.buf_azi
563 ##print("--------salida------------")
564 start= tmp_z[0]
565 end = tmp_z[-1]
566 ##print("start","end",start,end)
567 ##print(self.buffer_ini_azi[:120])
568 self.ini= self.ini+1
569 self.flag = self.flag +1
570 if self.flag==step:
571 self.flag=0
572
573 for i,ax in enumerate(self.axes):
574 if ax.firsttime:
575 plt.clf()
576 cgax, pm = wrl.vis.plot_ppi(self.buffer_ini,r=r,az=self.buffer_ini_azi,fig=self.figures[0], proj='cg', vmin=30, vmax=70)
577 else:
578 plt.clf()
579 cgax, pm = wrl.vis.plot_ppi(self.buffer_ini,r=r,az=self.buffer_ini_azi,fig=self.figures[0], proj='cg', vmin=30, vmax=70)
580 caax = cgax.parasites[0]
581 paax = cgax.parasites[1]
582 cbar = plt.gcf().colorbar(pm, pad=0.075)
583 caax.set_xlabel('x_range [km]')
584 caax.set_ylabel('y_range [km]')
585 plt.text(1.0, 1.05, 'azimuth '+str(thisDatetime), transform=caax.transAxes, va='bottom',ha='right')
@@ -1,743 +1,745
1 # Copyright (c) 2012-2021 Jicamarca Radio Observatory
1 # Copyright (c) 2012-2021 Jicamarca Radio Observatory
2 # All rights reserved.
2 # All rights reserved.
3 #
3 #
4 # Distributed under the terms of the BSD 3-clause license.
4 # Distributed under the terms of the BSD 3-clause license.
5 """Classes to plot Spectra data
5 """Classes to plot Spectra data
6
6
7 """
7 """
8
8
9 import os
9 import os
10 import numpy
10 import numpy
11
11
12 from schainpy.model.graphics.jroplot_base import Plot, plt, log
12 from schainpy.model.graphics.jroplot_base import Plot, plt, log
13
13
14
14
15 class SpectraPlot(Plot):
15 class SpectraPlot(Plot):
16 '''
16 '''
17 Plot for Spectra data
17 Plot for Spectra data
18 '''
18 '''
19
19
20 CODE = 'spc'
20 CODE = 'spc'
21 colormap = 'jet'
21 colormap = 'jet'
22 plot_type = 'pcolor'
22 plot_type = 'pcolor'
23 buffering = False
23 buffering = False
24
24
25 def setup(self):
25 def setup(self):
26 self.nplots = len(self.data.channels)
26 self.nplots = len(self.data.channels)
27 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
27 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
28 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
28 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
29 self.height = 2.6 * self.nrows
29 self.height = 2.6 * self.nrows
30 self.cb_label = 'dB'
30 self.cb_label = 'dB'
31 if self.showprofile:
31 if self.showprofile:
32 self.width = 4 * self.ncols
32 self.width = 4 * self.ncols
33 else:
33 else:
34 self.width = 3.5 * self.ncols
34 self.width = 3.5 * self.ncols
35 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.9, 'bottom': 0.08})
35 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.9, 'bottom': 0.08})
36 self.ylabel = 'Range [km]'
36 self.ylabel = 'Range [km]'
37
37
38 def update(self, dataOut):
38 def update(self, dataOut):
39
39
40 data = {}
40 data = {}
41 meta = {}
41 meta = {}
42 spc = 10*numpy.log10(dataOut.data_spc/dataOut.normFactor)
42 spc = 10*numpy.log10(dataOut.data_spc/dataOut.normFactor)
43 data['spc'] = spc
43 data['spc'] = spc
44 data['rti'] = dataOut.getPower()
44 data['rti'] = dataOut.getPower()
45 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
45 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
46 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
46 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
47
47
48 if self.CODE == 'spc_moments':
48 if self.CODE == 'spc_moments':
49 data['moments'] = dataOut.moments
49 data['moments'] = dataOut.moments
50 # data['spc'] = 10*numpy.log10(dataOut.data_pre[0]/dataOut.normFactor)
50 # data['spc'] = 10*numpy.log10(dataOut.data_pre[0]/dataOut.normFactor)
51 if self.CODE == 'gaussian_fit':
51 if self.CODE == 'gaussian_fit':
52 # data['moments'] = dataOut.moments
52 # data['moments'] = dataOut.moments
53 data['gaussfit'] = dataOut.DGauFitParams
53 data['gaussfit'] = dataOut.DGauFitParams
54 # data['spc'] = 10*numpy.log10(dataOut.data_pre[0]/dataOut.normFactor)
54 # data['spc'] = 10*numpy.log10(dataOut.data_pre[0]/dataOut.normFactor)
55
55
56 return data, meta
56 return data, meta
57
57
58 def plot(self):
58 def plot(self):
59 if self.xaxis == "frequency":
59 if self.xaxis == "frequency":
60 x = self.data.xrange[0]
60 x = self.data.xrange[0]
61 self.xlabel = "Frequency (kHz)"
61 self.xlabel = "Frequency (kHz)"
62 elif self.xaxis == "time":
62 elif self.xaxis == "time":
63 x = self.data.xrange[1]
63 x = self.data.xrange[1]
64 self.xlabel = "Time (ms)"
64 self.xlabel = "Time (ms)"
65 else:
65 else:
66 x = self.data.xrange[2]
66 x = self.data.xrange[2]
67 self.xlabel = "Velocity (m/s)"
67 self.xlabel = "Velocity (m/s)"
68
68
69 if (self.CODE == 'spc_moments') | (self.CODE == 'gaussian_fit'):
69 if (self.CODE == 'spc_moments') | (self.CODE == 'gaussian_fit'):
70 x = self.data.xrange[2]
70 x = self.data.xrange[2]
71 self.xlabel = "Velocity (m/s)"
71 self.xlabel = "Velocity (m/s)"
72
72
73 self.titles = []
73 self.titles = []
74
74
75 y = self.data.yrange
75 y = self.data.yrange
76 self.y = y
76 self.y = y
77
77
78 data = self.data[-1]
78 data = self.data[-1]
79 z = data['spc']
79 z = data['spc']
80
80
81 for n, ax in enumerate(self.axes):
81 for n, ax in enumerate(self.axes):
82 noise = data['noise'][n]
82 noise = data['noise'][n]
83 if self.CODE == 'spc_moments':
83 if self.CODE == 'spc_moments':
84 mean = data['moments'][n, 1]
84 mean = data['moments'][n, 1]
85 if self.CODE == 'gaussian_fit':
85 if self.CODE == 'gaussian_fit':
86 # mean = data['moments'][n, 1]
86 # mean = data['moments'][n, 1]
87 gau0 = data['gaussfit'][n][2,:,0]
87 gau0 = data['gaussfit'][n][2,:,0]
88 gau1 = data['gaussfit'][n][2,:,1]
88 gau1 = data['gaussfit'][n][2,:,1]
89 if ax.firsttime:
89 if ax.firsttime:
90 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
90 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
91 self.xmin = self.xmin if self.xmin else -self.xmax
91 self.xmin = self.xmin if self.xmin else -self.xmax
92 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
92 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
93 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
93 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
94 ax.plt = ax.pcolormesh(x, y, z[n].T,
94 ax.plt = ax.pcolormesh(x, y, z[n].T,
95 vmin=self.zmin,
95 vmin=self.zmin,
96 vmax=self.zmax,
96 vmax=self.zmax,
97 cmap=plt.get_cmap(self.colormap)
97 cmap=plt.get_cmap(self.colormap)
98 )
98 )
99
99
100 if self.showprofile:
100 if self.showprofile:
101 ax.plt_profile = self.pf_axes[n].plot(
101 ax.plt_profile = self.pf_axes[n].plot(
102 data['rti'][n], y)[0]
102 data['rti'][n], y)[0]
103 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
103 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
104 color="k", linestyle="dashed", lw=1)[0]
104 color="k", linestyle="dashed", lw=1)[0]
105 if self.CODE == 'spc_moments':
105 if self.CODE == 'spc_moments':
106 ax.plt_mean = ax.plot(mean, y, color='k', lw=1)[0]
106 ax.plt_mean = ax.plot(mean, y, color='k', lw=1)[0]
107 if self.CODE == 'gaussian_fit':
107 if self.CODE == 'gaussian_fit':
108 # ax.plt_mean = ax.plot(mean, y, color='k', lw=1)[0]
108 # ax.plt_mean = ax.plot(mean, y, color='k', lw=1)[0]
109 ax.plt_gau0 = ax.plot(gau0, y, color='r', lw=1)[0]
109 ax.plt_gau0 = ax.plot(gau0, y, color='r', lw=1)[0]
110 ax.plt_gau1 = ax.plot(gau1, y, color='y', lw=1)[0]
110 ax.plt_gau1 = ax.plot(gau1, y, color='y', lw=1)[0]
111 else:
111 else:
112 ax.plt.set_array(z[n].T.ravel())
112 ax.plt.set_array(z[n].T.ravel())
113 if self.showprofile:
113 if self.showprofile:
114 ax.plt_profile.set_data(data['rti'][n], y)
114 ax.plt_profile.set_data(data['rti'][n], y)
115 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
115 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
116 if self.CODE == 'spc_moments':
116 if self.CODE == 'spc_moments':
117 ax.plt_mean.set_data(mean, y)
117 ax.plt_mean.set_data(mean, y)
118 if self.CODE == 'gaussian_fit':
118 if self.CODE == 'gaussian_fit':
119 # ax.plt_mean.set_data(mean, y)
119 # ax.plt_mean.set_data(mean, y)
120 ax.plt_gau0.set_data(gau0, y)
120 ax.plt_gau0.set_data(gau0, y)
121 ax.plt_gau1.set_data(gau1, y)
121 ax.plt_gau1.set_data(gau1, y)
122 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
122 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
123
123
124
124
125 class CrossSpectraPlot(Plot):
125 class CrossSpectraPlot(Plot):
126
126
127 CODE = 'cspc'
127 CODE = 'cspc'
128 colormap = 'jet'
128 colormap = 'jet'
129 plot_type = 'pcolor'
129 plot_type = 'pcolor'
130 zmin_coh = None
130 zmin_coh = None
131 zmax_coh = None
131 zmax_coh = None
132 zmin_phase = None
132 zmin_phase = None
133 zmax_phase = None
133 zmax_phase = None
134
134
135 def setup(self):
135 def setup(self):
136
136
137 self.ncols = 4
137 self.ncols = 4
138 self.nplots = len(self.data.pairs) * 2
138 self.nplots = len(self.data.pairs) * 2
139 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
139 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
140 self.width = 3.1 * self.ncols
140 self.width = 3.1 * self.ncols
141 self.height = 2.6 * self.nrows
141 self.height = 2.6 * self.nrows
142 self.ylabel = 'Range [km]'
142 self.ylabel = 'Range [km]'
143 self.showprofile = False
143 self.showprofile = False
144 self.plots_adjust.update({'left': 0.08, 'right': 0.92, 'wspace': 0.5, 'hspace':0.4, 'top':0.95, 'bottom': 0.08})
144 self.plots_adjust.update({'left': 0.08, 'right': 0.92, 'wspace': 0.5, 'hspace':0.4, 'top':0.95, 'bottom': 0.08})
145
145
146 def update(self, dataOut):
146 def update(self, dataOut):
147
147
148 data = {}
148 data = {}
149 meta = {}
149 meta = {}
150
150
151 spc = dataOut.data_spc
151 spc = dataOut.data_spc
152 cspc = dataOut.data_cspc
152 cspc = dataOut.data_cspc
153 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
153 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
154 meta['pairs'] = dataOut.pairsList
154 meta['pairs'] = dataOut.pairsList
155
155
156 tmp = []
156 tmp = []
157
157
158 for n, pair in enumerate(meta['pairs']):
158 for n, pair in enumerate(meta['pairs']):
159 out = cspc[n] / numpy.sqrt(spc[pair[0]] * spc[pair[1]])
159 out = cspc[n] / numpy.sqrt(spc[pair[0]] * spc[pair[1]])
160 coh = numpy.abs(out)
160 coh = numpy.abs(out)
161 phase = numpy.arctan2(out.imag, out.real) * 180 / numpy.pi
161 phase = numpy.arctan2(out.imag, out.real) * 180 / numpy.pi
162 tmp.append(coh)
162 tmp.append(coh)
163 tmp.append(phase)
163 tmp.append(phase)
164
164
165 data['cspc'] = numpy.array(tmp)
165 data['cspc'] = numpy.array(tmp)
166
166
167 return data, meta
167 return data, meta
168
168
169 def plot(self):
169 def plot(self):
170
170
171 if self.xaxis == "frequency":
171 if self.xaxis == "frequency":
172 x = self.data.xrange[0]
172 x = self.data.xrange[0]
173 self.xlabel = "Frequency (kHz)"
173 self.xlabel = "Frequency (kHz)"
174 elif self.xaxis == "time":
174 elif self.xaxis == "time":
175 x = self.data.xrange[1]
175 x = self.data.xrange[1]
176 self.xlabel = "Time (ms)"
176 self.xlabel = "Time (ms)"
177 else:
177 else:
178 x = self.data.xrange[2]
178 x = self.data.xrange[2]
179 self.xlabel = "Velocity (m/s)"
179 self.xlabel = "Velocity (m/s)"
180
180
181 self.titles = []
181 self.titles = []
182
182
183 y = self.data.yrange
183 y = self.data.yrange
184 self.y = y
184 self.y = y
185
185
186 data = self.data[-1]
186 data = self.data[-1]
187 cspc = data['cspc']
187 cspc = data['cspc']
188
188
189 for n in range(len(self.data.pairs)):
189 for n in range(len(self.data.pairs)):
190 pair = self.data.pairs[n]
190 pair = self.data.pairs[n]
191 coh = cspc[n*2]
191 coh = cspc[n*2]
192 phase = cspc[n*2+1]
192 phase = cspc[n*2+1]
193 ax = self.axes[2 * n]
193 ax = self.axes[2 * n]
194 if ax.firsttime:
194 if ax.firsttime:
195 ax.plt = ax.pcolormesh(x, y, coh.T,
195 ax.plt = ax.pcolormesh(x, y, coh.T,
196 vmin=0,
196 vmin=0,
197 vmax=1,
197 vmax=1,
198 cmap=plt.get_cmap(self.colormap_coh)
198 cmap=plt.get_cmap(self.colormap_coh)
199 )
199 )
200 else:
200 else:
201 ax.plt.set_array(coh.T.ravel())
201 ax.plt.set_array(coh.T.ravel())
202 self.titles.append(
202 self.titles.append(
203 'Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
203 'Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
204
204
205 ax = self.axes[2 * n + 1]
205 ax = self.axes[2 * n + 1]
206 if ax.firsttime:
206 if ax.firsttime:
207 ax.plt = ax.pcolormesh(x, y, phase.T,
207 ax.plt = ax.pcolormesh(x, y, phase.T,
208 vmin=-180,
208 vmin=-180,
209 vmax=180,
209 vmax=180,
210 cmap=plt.get_cmap(self.colormap_phase)
210 cmap=plt.get_cmap(self.colormap_phase)
211 )
211 )
212 else:
212 else:
213 ax.plt.set_array(phase.T.ravel())
213 ax.plt.set_array(phase.T.ravel())
214 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
214 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
215
215
216
216
217 class RTIPlot(Plot):
217 class RTIPlot(Plot):
218 '''
218 '''
219 Plot for RTI data
219 Plot for RTI data
220 '''
220 '''
221
221
222 CODE = 'rti'
222 CODE = 'rti'
223 colormap = 'jet'
223 colormap = 'jet'
224 plot_type = 'pcolorbuffer'
224 plot_type = 'pcolorbuffer'
225
225
226 def setup(self):
226 def setup(self):
227 self.xaxis = 'time'
227 self.xaxis = 'time'
228 self.ncols = 1
228 self.ncols = 1
229 print("ch",self.data.channels)
229 self.nrows = len(self.data.channels)
230 self.nrows = len(self.data.channels)
230 self.nplots = len(self.data.channels)
231 self.nplots = len(self.data.channels)
231 self.ylabel = 'Range [km]'
232 self.ylabel = 'Range [km]'
232 self.xlabel = 'Time'
233 self.xlabel = 'Time'
233 self.cb_label = 'dB'
234 self.cb_label = 'dB'
234 self.plots_adjust.update({'hspace':0.8, 'left': 0.1, 'bottom': 0.08, 'right':0.95})
235 self.plots_adjust.update({'hspace':0.8, 'left': 0.1, 'bottom': 0.08, 'right':0.95})
235 self.titles = ['{} Channel {}'.format(
236 self.titles = ['{} Channel {}'.format(
236 self.CODE.upper(), x) for x in range(self.nrows)]
237 self.CODE.upper(), x) for x in range(self.nrows)]
237
238
238 def update(self, dataOut):
239 def update(self, dataOut):
239
240
240 data = {}
241 data = {}
241 meta = {}
242 meta = {}
242 data['rti'] = dataOut.getPower()
243 data['rti'] = dataOut.getPower()
243 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
244 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
244
245
245 return data, meta
246 return data, meta
246
247
247 def plot(self):
248 def plot(self):
248 self.x = self.data.times
249 self.x = self.data.times
249 self.y = self.data.yrange
250 self.y = self.data.yrange
250 self.z = self.data[self.CODE]
251 self.z = self.data[self.CODE]
251 self.z = numpy.ma.masked_invalid(self.z)
252 self.z = numpy.ma.masked_invalid(self.z)
252
253
253 if self.decimation is None:
254 if self.decimation is None:
254 x, y, z = self.fill_gaps(self.x, self.y, self.z)
255 x, y, z = self.fill_gaps(self.x, self.y, self.z)
255 else:
256 else:
256 x, y, z = self.fill_gaps(*self.decimate())
257 x, y, z = self.fill_gaps(*self.decimate())
257
258
258 for n, ax in enumerate(self.axes):
259 for n, ax in enumerate(self.axes):
259 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
260 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
260 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
261 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
261 data = self.data[-1]
262 data = self.data[-1]
262 if ax.firsttime:
263 if ax.firsttime:
263 ax.plt = ax.pcolormesh(x, y, z[n].T,
264 ax.plt = ax.pcolormesh(x, y, z[n].T,
264 vmin=self.zmin,
265 vmin=self.zmin,
265 vmax=self.zmax,
266 vmax=self.zmax,
266 cmap=plt.get_cmap(self.colormap)
267 cmap=plt.get_cmap(self.colormap)
267 )
268 )
268 if self.showprofile:
269 if self.showprofile:
270 print("test-------------------------------------1")
269 ax.plot_profile = self.pf_axes[n].plot(
271 ax.plot_profile = self.pf_axes[n].plot(
270 data['rti'][n], self.y)[0]
272 data['rti'][n], self.y)[0]
271 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(data['noise'][n], len(self.y)), self.y,
273 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(data['noise'][n], len(self.y)), self.y,
272 color="k", linestyle="dashed", lw=1)[0]
274 color="k", linestyle="dashed", lw=1)[0]
273 else:
275 else:
274 ax.collections.remove(ax.collections[0])
276 ax.collections.remove(ax.collections[0])
275 ax.plt = ax.pcolormesh(x, y, z[n].T,
277 ax.plt = ax.pcolormesh(x, y, z[n].T,
276 vmin=self.zmin,
278 vmin=self.zmin,
277 vmax=self.zmax,
279 vmax=self.zmax,
278 cmap=plt.get_cmap(self.colormap)
280 cmap=plt.get_cmap(self.colormap)
279 )
281 )
280 if self.showprofile:
282 if self.showprofile:
281 ax.plot_profile.set_data(data['rti'][n], self.y)
283 ax.plot_profile.set_data(data['rti'][n], self.y)
282 ax.plot_noise.set_data(numpy.repeat(
284 ax.plot_noise.set_data(numpy.repeat(
283 data['noise'][n], len(self.y)), self.y)
285 data['noise'][n], len(self.y)), self.y)
284
286
285
287
286 class CoherencePlot(RTIPlot):
288 class CoherencePlot(RTIPlot):
287 '''
289 '''
288 Plot for Coherence data
290 Plot for Coherence data
289 '''
291 '''
290
292
291 CODE = 'coh'
293 CODE = 'coh'
292
294
293 def setup(self):
295 def setup(self):
294 self.xaxis = 'time'
296 self.xaxis = 'time'
295 self.ncols = 1
297 self.ncols = 1
296 self.nrows = len(self.data.pairs)
298 self.nrows = len(self.data.pairs)
297 self.nplots = len(self.data.pairs)
299 self.nplots = len(self.data.pairs)
298 self.ylabel = 'Range [km]'
300 self.ylabel = 'Range [km]'
299 self.xlabel = 'Time'
301 self.xlabel = 'Time'
300 self.plots_adjust.update({'hspace':0.6, 'left': 0.1, 'bottom': 0.1,'right':0.95})
302 self.plots_adjust.update({'hspace':0.6, 'left': 0.1, 'bottom': 0.1,'right':0.95})
301 if self.CODE == 'coh':
303 if self.CODE == 'coh':
302 self.cb_label = ''
304 self.cb_label = ''
303 self.titles = [
305 self.titles = [
304 'Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
306 'Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
305 else:
307 else:
306 self.cb_label = 'Degrees'
308 self.cb_label = 'Degrees'
307 self.titles = [
309 self.titles = [
308 'Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
310 'Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
309
311
310 def update(self, dataOut):
312 def update(self, dataOut):
311
313
312 data = {}
314 data = {}
313 meta = {}
315 meta = {}
314 data['coh'] = dataOut.getCoherence()
316 data['coh'] = dataOut.getCoherence()
315 meta['pairs'] = dataOut.pairsList
317 meta['pairs'] = dataOut.pairsList
316
318
317 return data, meta
319 return data, meta
318
320
319 class PhasePlot(CoherencePlot):
321 class PhasePlot(CoherencePlot):
320 '''
322 '''
321 Plot for Phase map data
323 Plot for Phase map data
322 '''
324 '''
323
325
324 CODE = 'phase'
326 CODE = 'phase'
325 colormap = 'seismic'
327 colormap = 'seismic'
326
328
327 def update(self, dataOut):
329 def update(self, dataOut):
328
330
329 data = {}
331 data = {}
330 meta = {}
332 meta = {}
331 data['phase'] = dataOut.getCoherence(phase=True)
333 data['phase'] = dataOut.getCoherence(phase=True)
332 meta['pairs'] = dataOut.pairsList
334 meta['pairs'] = dataOut.pairsList
333
335
334 return data, meta
336 return data, meta
335
337
336 class NoisePlot(Plot):
338 class NoisePlot(Plot):
337 '''
339 '''
338 Plot for noise
340 Plot for noise
339 '''
341 '''
340
342
341 CODE = 'noise'
343 CODE = 'noise'
342 plot_type = 'scatterbuffer'
344 plot_type = 'scatterbuffer'
343
345
344 def setup(self):
346 def setup(self):
345 self.xaxis = 'time'
347 self.xaxis = 'time'
346 self.ncols = 1
348 self.ncols = 1
347 self.nrows = 1
349 self.nrows = 1
348 self.nplots = 1
350 self.nplots = 1
349 self.ylabel = 'Intensity [dB]'
351 self.ylabel = 'Intensity [dB]'
350 self.xlabel = 'Time'
352 self.xlabel = 'Time'
351 self.titles = ['Noise']
353 self.titles = ['Noise']
352 self.colorbar = False
354 self.colorbar = False
353 self.plots_adjust.update({'right': 0.85 })
355 self.plots_adjust.update({'right': 0.85 })
354
356
355 def update(self, dataOut):
357 def update(self, dataOut):
356
358
357 data = {}
359 data = {}
358 meta = {}
360 meta = {}
359 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor).reshape(dataOut.nChannels, 1)
361 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor).reshape(dataOut.nChannels, 1)
360 meta['yrange'] = numpy.array([])
362 meta['yrange'] = numpy.array([])
361
363
362 return data, meta
364 return data, meta
363
365
364 def plot(self):
366 def plot(self):
365
367
366 x = self.data.times
368 x = self.data.times
367 xmin = self.data.min_time
369 xmin = self.data.min_time
368 xmax = xmin + self.xrange * 60 * 60
370 xmax = xmin + self.xrange * 60 * 60
369 Y = self.data['noise']
371 Y = self.data['noise']
370
372
371 if self.axes[0].firsttime:
373 if self.axes[0].firsttime:
372 self.ymin = numpy.nanmin(Y) - 5
374 self.ymin = numpy.nanmin(Y) - 5
373 self.ymax = numpy.nanmax(Y) + 5
375 self.ymax = numpy.nanmax(Y) + 5
374 for ch in self.data.channels:
376 for ch in self.data.channels:
375 y = Y[ch]
377 y = Y[ch]
376 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
378 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
377 plt.legend(bbox_to_anchor=(1.18, 1.0))
379 plt.legend(bbox_to_anchor=(1.18, 1.0))
378 else:
380 else:
379 for ch in self.data.channels:
381 for ch in self.data.channels:
380 y = Y[ch]
382 y = Y[ch]
381 self.axes[0].lines[ch].set_data(x, y)
383 self.axes[0].lines[ch].set_data(x, y)
382
384
383
385
384 class PowerProfilePlot(Plot):
386 class PowerProfilePlot(Plot):
385
387
386 CODE = 'pow_profile'
388 CODE = 'pow_profile'
387 plot_type = 'scatter'
389 plot_type = 'scatter'
388
390
389 def setup(self):
391 def setup(self):
390
392
391 self.ncols = 1
393 self.ncols = 1
392 self.nrows = 1
394 self.nrows = 1
393 self.nplots = 1
395 self.nplots = 1
394 self.height = 4
396 self.height = 4
395 self.width = 3
397 self.width = 3
396 self.ylabel = 'Range [km]'
398 self.ylabel = 'Range [km]'
397 self.xlabel = 'Intensity [dB]'
399 self.xlabel = 'Intensity [dB]'
398 self.titles = ['Power Profile']
400 self.titles = ['Power Profile']
399 self.colorbar = False
401 self.colorbar = False
400
402
401 def update(self, dataOut):
403 def update(self, dataOut):
402
404
403 data = {}
405 data = {}
404 meta = {}
406 meta = {}
405 data[self.CODE] = dataOut.getPower()
407 data[self.CODE] = dataOut.getPower()
406
408
407 return data, meta
409 return data, meta
408
410
409 def plot(self):
411 def plot(self):
410
412
411 y = self.data.yrange
413 y = self.data.yrange
412 self.y = y
414 self.y = y
413
415
414 x = self.data[-1][self.CODE]
416 x = self.data[-1][self.CODE]
415
417
416 if self.xmin is None: self.xmin = numpy.nanmin(x)*0.9
418 if self.xmin is None: self.xmin = numpy.nanmin(x)*0.9
417 if self.xmax is None: self.xmax = numpy.nanmax(x)*1.1
419 if self.xmax is None: self.xmax = numpy.nanmax(x)*1.1
418
420
419 if self.axes[0].firsttime:
421 if self.axes[0].firsttime:
420 for ch in self.data.channels:
422 for ch in self.data.channels:
421 self.axes[0].plot(x[ch], y, lw=1, label='Ch{}'.format(ch))
423 self.axes[0].plot(x[ch], y, lw=1, label='Ch{}'.format(ch))
422 plt.legend()
424 plt.legend()
423 else:
425 else:
424 for ch in self.data.channels:
426 for ch in self.data.channels:
425 self.axes[0].lines[ch].set_data(x[ch], y)
427 self.axes[0].lines[ch].set_data(x[ch], y)
426
428
427
429
428 class SpectraCutPlot(Plot):
430 class SpectraCutPlot(Plot):
429
431
430 CODE = 'spc_cut'
432 CODE = 'spc_cut'
431 plot_type = 'scatter'
433 plot_type = 'scatter'
432 buffering = False
434 buffering = False
433
435
434 def setup(self):
436 def setup(self):
435
437
436 self.nplots = len(self.data.channels)
438 self.nplots = len(self.data.channels)
437 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
439 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
438 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
440 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
439 self.width = 3.4 * self.ncols + 1.5
441 self.width = 3.4 * self.ncols + 1.5
440 self.height = 3 * self.nrows
442 self.height = 3 * self.nrows
441 self.ylabel = 'Power [dB]'
443 self.ylabel = 'Power [dB]'
442 self.colorbar = False
444 self.colorbar = False
443 self.plots_adjust.update({'left':0.1, 'hspace':0.3, 'right': 0.75, 'bottom':0.08})
445 self.plots_adjust.update({'left':0.1, 'hspace':0.3, 'right': 0.75, 'bottom':0.08})
444
446
445 def update(self, dataOut):
447 def update(self, dataOut):
446
448
447 data = {}
449 data = {}
448 meta = {}
450 meta = {}
449 spc = 10*numpy.log10(dataOut.data_pre[0]/dataOut.normFactor)
451 spc = 10*numpy.log10(dataOut.data_pre[0]/dataOut.normFactor)
450 data['spc'] = spc
452 data['spc'] = spc
451 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
453 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
452 if self.CODE == 'cut_gaussian_fit':
454 if self.CODE == 'cut_gaussian_fit':
453 data['gauss_fit0'] = 10*numpy.log10(dataOut.GaussFit0/dataOut.normFactor)
455 data['gauss_fit0'] = 10*numpy.log10(dataOut.GaussFit0/dataOut.normFactor)
454 data['gauss_fit1'] = 10*numpy.log10(dataOut.GaussFit1/dataOut.normFactor)
456 data['gauss_fit1'] = 10*numpy.log10(dataOut.GaussFit1/dataOut.normFactor)
455 return data, meta
457 return data, meta
456
458
457 def plot(self):
459 def plot(self):
458 if self.xaxis == "frequency":
460 if self.xaxis == "frequency":
459 x = self.data.xrange[0][1:]
461 x = self.data.xrange[0][1:]
460 self.xlabel = "Frequency (kHz)"
462 self.xlabel = "Frequency (kHz)"
461 elif self.xaxis == "time":
463 elif self.xaxis == "time":
462 x = self.data.xrange[1]
464 x = self.data.xrange[1]
463 self.xlabel = "Time (ms)"
465 self.xlabel = "Time (ms)"
464 else:
466 else:
465 x = self.data.xrange[2][:-1]
467 x = self.data.xrange[2][:-1]
466 self.xlabel = "Velocity (m/s)"
468 self.xlabel = "Velocity (m/s)"
467
469
468 if self.CODE == 'cut_gaussian_fit':
470 if self.CODE == 'cut_gaussian_fit':
469 x = self.data.xrange[2][:-1]
471 x = self.data.xrange[2][:-1]
470 self.xlabel = "Velocity (m/s)"
472 self.xlabel = "Velocity (m/s)"
471
473
472 self.titles = []
474 self.titles = []
473
475
474 y = self.data.yrange
476 y = self.data.yrange
475 data = self.data[-1]
477 data = self.data[-1]
476 z = data['spc']
478 z = data['spc']
477
479
478 if self.height_index:
480 if self.height_index:
479 index = numpy.array(self.height_index)
481 index = numpy.array(self.height_index)
480 else:
482 else:
481 index = numpy.arange(0, len(y), int((len(y))/9))
483 index = numpy.arange(0, len(y), int((len(y))/9))
482
484
483 for n, ax in enumerate(self.axes):
485 for n, ax in enumerate(self.axes):
484 if self.CODE == 'cut_gaussian_fit':
486 if self.CODE == 'cut_gaussian_fit':
485 gau0 = data['gauss_fit0']
487 gau0 = data['gauss_fit0']
486 gau1 = data['gauss_fit1']
488 gau1 = data['gauss_fit1']
487 if ax.firsttime:
489 if ax.firsttime:
488 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
490 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
489 self.xmin = self.xmin if self.xmin else -self.xmax
491 self.xmin = self.xmin if self.xmin else -self.xmax
490 self.ymin = self.ymin if self.ymin else numpy.nanmin(z)
492 self.ymin = self.ymin if self.ymin else numpy.nanmin(z)
491 self.ymax = self.ymax if self.ymax else numpy.nanmax(z)
493 self.ymax = self.ymax if self.ymax else numpy.nanmax(z)
492 ax.plt = ax.plot(x, z[n, :, index].T, lw=0.25)
494 ax.plt = ax.plot(x, z[n, :, index].T, lw=0.25)
493 if self.CODE == 'cut_gaussian_fit':
495 if self.CODE == 'cut_gaussian_fit':
494 ax.plt_gau0 = ax.plot(x, gau0[n, :, index].T, lw=1, linestyle='-.')
496 ax.plt_gau0 = ax.plot(x, gau0[n, :, index].T, lw=1, linestyle='-.')
495 for i, line in enumerate(ax.plt_gau0):
497 for i, line in enumerate(ax.plt_gau0):
496 line.set_color(ax.plt[i].get_color())
498 line.set_color(ax.plt[i].get_color())
497 ax.plt_gau1 = ax.plot(x, gau1[n, :, index].T, lw=1, linestyle='--')
499 ax.plt_gau1 = ax.plot(x, gau1[n, :, index].T, lw=1, linestyle='--')
498 for i, line in enumerate(ax.plt_gau1):
500 for i, line in enumerate(ax.plt_gau1):
499 line.set_color(ax.plt[i].get_color())
501 line.set_color(ax.plt[i].get_color())
500 labels = ['Range = {:2.1f}km'.format(y[i]) for i in index]
502 labels = ['Range = {:2.1f}km'.format(y[i]) for i in index]
501 self.figures[0].legend(ax.plt, labels, loc='center right')
503 self.figures[0].legend(ax.plt, labels, loc='center right')
502 else:
504 else:
503 for i, line in enumerate(ax.plt):
505 for i, line in enumerate(ax.plt):
504 line.set_data(x, z[n, :, index[i]].T)
506 line.set_data(x, z[n, :, index[i]].T)
505 for i, line in enumerate(ax.plt_gau0):
507 for i, line in enumerate(ax.plt_gau0):
506 line.set_data(x, gau0[n, :, index[i]].T)
508 line.set_data(x, gau0[n, :, index[i]].T)
507 line.set_color(ax.plt[i].get_color())
509 line.set_color(ax.plt[i].get_color())
508 for i, line in enumerate(ax.plt_gau1):
510 for i, line in enumerate(ax.plt_gau1):
509 line.set_data(x, gau1[n, :, index[i]].T)
511 line.set_data(x, gau1[n, :, index[i]].T)
510 line.set_color(ax.plt[i].get_color())
512 line.set_color(ax.plt[i].get_color())
511 self.titles.append('CH {}'.format(n))
513 self.titles.append('CH {}'.format(n))
512
514
513
515
514 class BeaconPhase(Plot):
516 class BeaconPhase(Plot):
515
517
516 __isConfig = None
518 __isConfig = None
517 __nsubplots = None
519 __nsubplots = None
518
520
519 PREFIX = 'beacon_phase'
521 PREFIX = 'beacon_phase'
520
522
521 def __init__(self):
523 def __init__(self):
522 Plot.__init__(self)
524 Plot.__init__(self)
523 self.timerange = 24*60*60
525 self.timerange = 24*60*60
524 self.isConfig = False
526 self.isConfig = False
525 self.__nsubplots = 1
527 self.__nsubplots = 1
526 self.counter_imagwr = 0
528 self.counter_imagwr = 0
527 self.WIDTH = 800
529 self.WIDTH = 800
528 self.HEIGHT = 400
530 self.HEIGHT = 400
529 self.WIDTHPROF = 120
531 self.WIDTHPROF = 120
530 self.HEIGHTPROF = 0
532 self.HEIGHTPROF = 0
531 self.xdata = None
533 self.xdata = None
532 self.ydata = None
534 self.ydata = None
533
535
534 self.PLOT_CODE = BEACON_CODE
536 self.PLOT_CODE = BEACON_CODE
535
537
536 self.FTP_WEI = None
538 self.FTP_WEI = None
537 self.EXP_CODE = None
539 self.EXP_CODE = None
538 self.SUB_EXP_CODE = None
540 self.SUB_EXP_CODE = None
539 self.PLOT_POS = None
541 self.PLOT_POS = None
540
542
541 self.filename_phase = None
543 self.filename_phase = None
542
544
543 self.figfile = None
545 self.figfile = None
544
546
545 self.xmin = None
547 self.xmin = None
546 self.xmax = None
548 self.xmax = None
547
549
548 def getSubplots(self):
550 def getSubplots(self):
549
551
550 ncol = 1
552 ncol = 1
551 nrow = 1
553 nrow = 1
552
554
553 return nrow, ncol
555 return nrow, ncol
554
556
555 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
557 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
556
558
557 self.__showprofile = showprofile
559 self.__showprofile = showprofile
558 self.nplots = nplots
560 self.nplots = nplots
559
561
560 ncolspan = 7
562 ncolspan = 7
561 colspan = 6
563 colspan = 6
562 self.__nsubplots = 2
564 self.__nsubplots = 2
563
565
564 self.createFigure(id = id,
566 self.createFigure(id = id,
565 wintitle = wintitle,
567 wintitle = wintitle,
566 widthplot = self.WIDTH+self.WIDTHPROF,
568 widthplot = self.WIDTH+self.WIDTHPROF,
567 heightplot = self.HEIGHT+self.HEIGHTPROF,
569 heightplot = self.HEIGHT+self.HEIGHTPROF,
568 show=show)
570 show=show)
569
571
570 nrow, ncol = self.getSubplots()
572 nrow, ncol = self.getSubplots()
571
573
572 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
574 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
573
575
574 def save_phase(self, filename_phase):
576 def save_phase(self, filename_phase):
575 f = open(filename_phase,'w+')
577 f = open(filename_phase,'w+')
576 f.write('\n\n')
578 f.write('\n\n')
577 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
579 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
578 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
580 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
579 f.close()
581 f.close()
580
582
581 def save_data(self, filename_phase, data, data_datetime):
583 def save_data(self, filename_phase, data, data_datetime):
582 f=open(filename_phase,'a')
584 f=open(filename_phase,'a')
583 timetuple_data = data_datetime.timetuple()
585 timetuple_data = data_datetime.timetuple()
584 day = str(timetuple_data.tm_mday)
586 day = str(timetuple_data.tm_mday)
585 month = str(timetuple_data.tm_mon)
587 month = str(timetuple_data.tm_mon)
586 year = str(timetuple_data.tm_year)
588 year = str(timetuple_data.tm_year)
587 hour = str(timetuple_data.tm_hour)
589 hour = str(timetuple_data.tm_hour)
588 minute = str(timetuple_data.tm_min)
590 minute = str(timetuple_data.tm_min)
589 second = str(timetuple_data.tm_sec)
591 second = str(timetuple_data.tm_sec)
590 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
592 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
591 f.close()
593 f.close()
592
594
593 def plot(self):
595 def plot(self):
594 log.warning('TODO: Not yet implemented...')
596 log.warning('TODO: Not yet implemented...')
595
597
596 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
598 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
597 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
599 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
598 timerange=None,
600 timerange=None,
599 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
601 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
600 server=None, folder=None, username=None, password=None,
602 server=None, folder=None, username=None, password=None,
601 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
603 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
602
604
603 if dataOut.flagNoData:
605 if dataOut.flagNoData:
604 return dataOut
606 return dataOut
605
607
606 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
608 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
607 return
609 return
608
610
609 if pairsList == None:
611 if pairsList == None:
610 pairsIndexList = dataOut.pairsIndexList[:10]
612 pairsIndexList = dataOut.pairsIndexList[:10]
611 else:
613 else:
612 pairsIndexList = []
614 pairsIndexList = []
613 for pair in pairsList:
615 for pair in pairsList:
614 if pair not in dataOut.pairsList:
616 if pair not in dataOut.pairsList:
615 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
617 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
616 pairsIndexList.append(dataOut.pairsList.index(pair))
618 pairsIndexList.append(dataOut.pairsList.index(pair))
617
619
618 if pairsIndexList == []:
620 if pairsIndexList == []:
619 return
621 return
620
622
621 # if len(pairsIndexList) > 4:
623 # if len(pairsIndexList) > 4:
622 # pairsIndexList = pairsIndexList[0:4]
624 # pairsIndexList = pairsIndexList[0:4]
623
625
624 hmin_index = None
626 hmin_index = None
625 hmax_index = None
627 hmax_index = None
626
628
627 if hmin != None and hmax != None:
629 if hmin != None and hmax != None:
628 indexes = numpy.arange(dataOut.nHeights)
630 indexes = numpy.arange(dataOut.nHeights)
629 hmin_list = indexes[dataOut.heightList >= hmin]
631 hmin_list = indexes[dataOut.heightList >= hmin]
630 hmax_list = indexes[dataOut.heightList <= hmax]
632 hmax_list = indexes[dataOut.heightList <= hmax]
631
633
632 if hmin_list.any():
634 if hmin_list.any():
633 hmin_index = hmin_list[0]
635 hmin_index = hmin_list[0]
634
636
635 if hmax_list.any():
637 if hmax_list.any():
636 hmax_index = hmax_list[-1]+1
638 hmax_index = hmax_list[-1]+1
637
639
638 x = dataOut.getTimeRange()
640 x = dataOut.getTimeRange()
639
641
640 thisDatetime = dataOut.datatime
642 thisDatetime = dataOut.datatime
641
643
642 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
644 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
643 xlabel = "Local Time"
645 xlabel = "Local Time"
644 ylabel = "Phase (degrees)"
646 ylabel = "Phase (degrees)"
645
647
646 update_figfile = False
648 update_figfile = False
647
649
648 nplots = len(pairsIndexList)
650 nplots = len(pairsIndexList)
649 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
651 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
650 phase_beacon = numpy.zeros(len(pairsIndexList))
652 phase_beacon = numpy.zeros(len(pairsIndexList))
651 for i in range(nplots):
653 for i in range(nplots):
652 pair = dataOut.pairsList[pairsIndexList[i]]
654 pair = dataOut.pairsList[pairsIndexList[i]]
653 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
655 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
654 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
656 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
655 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
657 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
656 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
658 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
657 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
659 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
658
660
659 if dataOut.beacon_heiIndexList:
661 if dataOut.beacon_heiIndexList:
660 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
662 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
661 else:
663 else:
662 phase_beacon[i] = numpy.average(phase)
664 phase_beacon[i] = numpy.average(phase)
663
665
664 if not self.isConfig:
666 if not self.isConfig:
665
667
666 nplots = len(pairsIndexList)
668 nplots = len(pairsIndexList)
667
669
668 self.setup(id=id,
670 self.setup(id=id,
669 nplots=nplots,
671 nplots=nplots,
670 wintitle=wintitle,
672 wintitle=wintitle,
671 showprofile=showprofile,
673 showprofile=showprofile,
672 show=show)
674 show=show)
673
675
674 if timerange != None:
676 if timerange != None:
675 self.timerange = timerange
677 self.timerange = timerange
676
678
677 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
679 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
678
680
679 if ymin == None: ymin = 0
681 if ymin == None: ymin = 0
680 if ymax == None: ymax = 360
682 if ymax == None: ymax = 360
681
683
682 self.FTP_WEI = ftp_wei
684 self.FTP_WEI = ftp_wei
683 self.EXP_CODE = exp_code
685 self.EXP_CODE = exp_code
684 self.SUB_EXP_CODE = sub_exp_code
686 self.SUB_EXP_CODE = sub_exp_code
685 self.PLOT_POS = plot_pos
687 self.PLOT_POS = plot_pos
686
688
687 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
689 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
688 self.isConfig = True
690 self.isConfig = True
689 self.figfile = figfile
691 self.figfile = figfile
690 self.xdata = numpy.array([])
692 self.xdata = numpy.array([])
691 self.ydata = numpy.array([])
693 self.ydata = numpy.array([])
692
694
693 update_figfile = True
695 update_figfile = True
694
696
695 #open file beacon phase
697 #open file beacon phase
696 path = '%s%03d' %(self.PREFIX, self.id)
698 path = '%s%03d' %(self.PREFIX, self.id)
697 beacon_file = os.path.join(path,'%s.txt'%self.name)
699 beacon_file = os.path.join(path,'%s.txt'%self.name)
698 self.filename_phase = os.path.join(figpath,beacon_file)
700 self.filename_phase = os.path.join(figpath,beacon_file)
699 #self.save_phase(self.filename_phase)
701 #self.save_phase(self.filename_phase)
700
702
701
703
702 #store data beacon phase
704 #store data beacon phase
703 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
705 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
704
706
705 self.setWinTitle(title)
707 self.setWinTitle(title)
706
708
707
709
708 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
710 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
709
711
710 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
712 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
711
713
712 axes = self.axesList[0]
714 axes = self.axesList[0]
713
715
714 self.xdata = numpy.hstack((self.xdata, x[0:1]))
716 self.xdata = numpy.hstack((self.xdata, x[0:1]))
715
717
716 if len(self.ydata)==0:
718 if len(self.ydata)==0:
717 self.ydata = phase_beacon.reshape(-1,1)
719 self.ydata = phase_beacon.reshape(-1,1)
718 else:
720 else:
719 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
721 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
720
722
721
723
722 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
724 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
723 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
725 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
724 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
726 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
725 XAxisAsTime=True, grid='both'
727 XAxisAsTime=True, grid='both'
726 )
728 )
727
729
728 self.draw()
730 self.draw()
729
731
730 if dataOut.ltctime >= self.xmax:
732 if dataOut.ltctime >= self.xmax:
731 self.counter_imagwr = wr_period
733 self.counter_imagwr = wr_period
732 self.isConfig = False
734 self.isConfig = False
733 update_figfile = True
735 update_figfile = True
734
736
735 self.save(figpath=figpath,
737 self.save(figpath=figpath,
736 figfile=figfile,
738 figfile=figfile,
737 save=save,
739 save=save,
738 ftp=ftp,
740 ftp=ftp,
739 wr_period=wr_period,
741 wr_period=wr_period,
740 thisDatetime=thisDatetime,
742 thisDatetime=thisDatetime,
741 update_figfile=update_figfile)
743 update_figfile=update_figfile)
742
744
743 return dataOut
745 return dataOut
@@ -1,1575 +1,1609
1 """
1 """
2 Created on Jul 2, 2014
2 Created on Jul 2, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 """
5 """
6 import os
6 import os
7 import sys
7 import sys
8 import glob
8 import glob
9 import time
9 import time
10 import numpy
10 import numpy
11 import fnmatch
11 import fnmatch
12 import inspect
12 import inspect
13 import time
13 import time
14 import datetime
14 import datetime
15 import zmq
15 import zmq
16
16
17 from schainpy.model.proc.jroproc_base import Operation, MPDecorator
17 from schainpy.model.proc.jroproc_base import Operation, MPDecorator
18 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
18 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
19 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
19 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
20 from schainpy.utils import log
20 from schainpy.utils import log
21 import schainpy.admin
21 import schainpy.admin
22
22
23 LOCALTIME = True
23 LOCALTIME = True
24 DT_DIRECTIVES = {
24 DT_DIRECTIVES = {
25 '%Y': 4,
25 '%Y': 4,
26 '%y': 2,
26 '%y': 2,
27 '%m': 2,
27 '%m': 2,
28 '%d': 2,
28 '%d': 2,
29 '%j': 3,
29 '%j': 3,
30 '%H': 2,
30 '%H': 2,
31 '%M': 2,
31 '%M': 2,
32 '%S': 2,
32 '%S': 2,
33 '%f': 6
33 '%f': 6
34 }
34 }
35
35
36
36
37 def isNumber(cad):
37 def isNumber(cad):
38 """
38 """
39 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
39 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
40
40
41 Excepciones:
41 Excepciones:
42 Si un determinado string no puede ser convertido a numero
42 Si un determinado string no puede ser convertido a numero
43 Input:
43 Input:
44 str, string al cual se le analiza para determinar si convertible a un numero o no
44 str, string al cual se le analiza para determinar si convertible a un numero o no
45
45
46 Return:
46 Return:
47 True : si el string es uno numerico
47 True : si el string es uno numerico
48 False : no es un string numerico
48 False : no es un string numerico
49 """
49 """
50 try:
50 try:
51 float(cad)
51 float(cad)
52 return True
52 return True
53 except:
53 except:
54 return False
54 return False
55
55
56
56
57 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
57 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
58 """
58 """
59 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
59 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
60
60
61 Inputs:
61 Inputs:
62 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
62 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
63
63
64 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
64 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
65 segundos contados desde 01/01/1970.
65 segundos contados desde 01/01/1970.
66 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
66 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
67 segundos contados desde 01/01/1970.
67 segundos contados desde 01/01/1970.
68
68
69 Return:
69 Return:
70 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
70 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
71 fecha especificado, de lo contrario retorna False.
71 fecha especificado, de lo contrario retorna False.
72
72
73 Excepciones:
73 Excepciones:
74 Si el archivo no existe o no puede ser abierto
74 Si el archivo no existe o no puede ser abierto
75 Si la cabecera no puede ser leida.
75 Si la cabecera no puede ser leida.
76
76
77 """
77 """
78 basicHeaderObj = BasicHeader(LOCALTIME)
78 basicHeaderObj = BasicHeader(LOCALTIME)
79
79
80 try:
80 try:
81 fp = open(filename, 'rb')
81 fp = open(filename, 'rb')
82 except IOError:
82 except IOError:
83 print("The file %s can't be opened" % (filename))
83 print("The file %s can't be opened" % (filename))
84 return 0
84 return 0
85
85
86 sts = basicHeaderObj.read(fp)
86 sts = basicHeaderObj.read(fp)
87 fp.close()
87 fp.close()
88
88
89 if not(sts):
89 if not(sts):
90 print("Skipping the file %s because it has not a valid header" % (filename))
90 print("Skipping the file %s because it has not a valid header" % (filename))
91 return 0
91 return 0
92
92
93 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
93 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
94 return 0
94 return 0
95
95
96 return 1
96 return 1
97
97
98
98
99 def isTimeInRange(thisTime, startTime, endTime):
99 def isTimeInRange(thisTime, startTime, endTime):
100 if endTime >= startTime:
100 if endTime >= startTime:
101 if (thisTime < startTime) or (thisTime > endTime):
101 if (thisTime < startTime) or (thisTime > endTime):
102 return 0
102 return 0
103 return 1
103 return 1
104 else:
104 else:
105 if (thisTime < startTime) and (thisTime > endTime):
105 if (thisTime < startTime) and (thisTime > endTime):
106 return 0
106 return 0
107 return 1
107 return 1
108
108
109
109
110 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
110 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
111 """
111 """
112 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
112 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
113
113
114 Inputs:
114 Inputs:
115 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
115 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
116
116
117 startDate : fecha inicial del rango seleccionado en formato datetime.date
117 startDate : fecha inicial del rango seleccionado en formato datetime.date
118
118
119 endDate : fecha final del rango seleccionado en formato datetime.date
119 endDate : fecha final del rango seleccionado en formato datetime.date
120
120
121 startTime : tiempo inicial del rango seleccionado en formato datetime.time
121 startTime : tiempo inicial del rango seleccionado en formato datetime.time
122
122
123 endTime : tiempo final del rango seleccionado en formato datetime.time
123 endTime : tiempo final del rango seleccionado en formato datetime.time
124
124
125 Return:
125 Return:
126 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
126 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
127 fecha especificado, de lo contrario retorna False.
127 fecha especificado, de lo contrario retorna False.
128
128
129 Excepciones:
129 Excepciones:
130 Si el archivo no existe o no puede ser abierto
130 Si el archivo no existe o no puede ser abierto
131 Si la cabecera no puede ser leida.
131 Si la cabecera no puede ser leida.
132
132
133 """
133 """
134
134
135 try:
135 try:
136 fp = open(filename, 'rb')
136 fp = open(filename, 'rb')
137 except IOError:
137 except IOError:
138 print("The file %s can't be opened" % (filename))
138 print("The file %s can't be opened" % (filename))
139 return None
139 return None
140
140
141 firstBasicHeaderObj = BasicHeader(LOCALTIME)
141 firstBasicHeaderObj = BasicHeader(LOCALTIME)
142 systemHeaderObj = SystemHeader()
142 systemHeaderObj = SystemHeader()
143 radarControllerHeaderObj = RadarControllerHeader()
143 radarControllerHeaderObj = RadarControllerHeader()
144 processingHeaderObj = ProcessingHeader()
144 processingHeaderObj = ProcessingHeader()
145
145
146 lastBasicHeaderObj = BasicHeader(LOCALTIME)
146 lastBasicHeaderObj = BasicHeader(LOCALTIME)
147
147
148 sts = firstBasicHeaderObj.read(fp)
148 sts = firstBasicHeaderObj.read(fp)
149
149
150 if not(sts):
150 if not(sts):
151 print("[Reading] Skipping the file %s because it has not a valid header" % (filename))
151 print("[Reading] Skipping the file %s because it has not a valid header" % (filename))
152 return None
152 return None
153
153
154 if not systemHeaderObj.read(fp):
154 if not systemHeaderObj.read(fp):
155 return None
155 return None
156
156
157 if not radarControllerHeaderObj.read(fp):
157 if not radarControllerHeaderObj.read(fp):
158 return None
158 return None
159
159
160 if not processingHeaderObj.read(fp):
160 if not processingHeaderObj.read(fp):
161 return None
161 return None
162
162
163 filesize = os.path.getsize(filename)
163 filesize = os.path.getsize(filename)
164
164
165 offset = processingHeaderObj.blockSize + 24 # header size
165 offset = processingHeaderObj.blockSize + 24 # header size
166
166
167 if filesize <= offset:
167 if filesize <= offset:
168 print("[Reading] %s: This file has not enough data" % filename)
168 print("[Reading] %s: This file has not enough data" % filename)
169 return None
169 return None
170
170
171 fp.seek(-offset, 2)
171 fp.seek(-offset, 2)
172
172
173 sts = lastBasicHeaderObj.read(fp)
173 sts = lastBasicHeaderObj.read(fp)
174
174
175 fp.close()
175 fp.close()
176
176
177 thisDatetime = lastBasicHeaderObj.datatime
177 thisDatetime = lastBasicHeaderObj.datatime
178 thisTime_last_block = thisDatetime.time()
178 thisTime_last_block = thisDatetime.time()
179
179
180 thisDatetime = firstBasicHeaderObj.datatime
180 thisDatetime = firstBasicHeaderObj.datatime
181 thisDate = thisDatetime.date()
181 thisDate = thisDatetime.date()
182 thisTime_first_block = thisDatetime.time()
182 thisTime_first_block = thisDatetime.time()
183
183
184 # General case
184 # General case
185 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
185 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
186 #-----------o----------------------------o-----------
186 #-----------o----------------------------o-----------
187 # startTime endTime
187 # startTime endTime
188
188
189 if endTime >= startTime:
189 if endTime >= startTime:
190 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
190 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
191 return None
191 return None
192
192
193 return thisDatetime
193 return thisDatetime
194
194
195 # If endTime < startTime then endTime belongs to the next day
195 # If endTime < startTime then endTime belongs to the next day
196
196
197 #<<<<<<<<<<<o o>>>>>>>>>>>
197 #<<<<<<<<<<<o o>>>>>>>>>>>
198 #-----------o----------------------------o-----------
198 #-----------o----------------------------o-----------
199 # endTime startTime
199 # endTime startTime
200
200
201 if (thisDate == startDate) and (thisTime_last_block < startTime):
201 if (thisDate == startDate) and (thisTime_last_block < startTime):
202 return None
202 return None
203
203
204 if (thisDate == endDate) and (thisTime_first_block > endTime):
204 if (thisDate == endDate) and (thisTime_first_block > endTime):
205 return None
205 return None
206
206
207 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
207 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
208 return None
208 return None
209
209
210 return thisDatetime
210 return thisDatetime
211
211
212
212
213 def isFolderInDateRange(folder, startDate=None, endDate=None):
213 def isFolderInDateRange(folder, startDate=None, endDate=None):
214 """
214 """
215 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
215 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
216
216
217 Inputs:
217 Inputs:
218 folder : nombre completo del directorio.
218 folder : nombre completo del directorio.
219 Su formato deberia ser "/path_root/?YYYYDDD"
219 Su formato deberia ser "/path_root/?YYYYDDD"
220
220
221 siendo:
221 siendo:
222 YYYY : Anio (ejemplo 2015)
222 YYYY : Anio (ejemplo 2015)
223 DDD : Dia del anio (ejemplo 305)
223 DDD : Dia del anio (ejemplo 305)
224
224
225 startDate : fecha inicial del rango seleccionado en formato datetime.date
225 startDate : fecha inicial del rango seleccionado en formato datetime.date
226
226
227 endDate : fecha final del rango seleccionado en formato datetime.date
227 endDate : fecha final del rango seleccionado en formato datetime.date
228
228
229 Return:
229 Return:
230 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
230 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
231 fecha especificado, de lo contrario retorna False.
231 fecha especificado, de lo contrario retorna False.
232 Excepciones:
232 Excepciones:
233 Si el directorio no tiene el formato adecuado
233 Si el directorio no tiene el formato adecuado
234 """
234 """
235
235
236 basename = os.path.basename(folder)
236 basename = os.path.basename(folder)
237
237
238 if not isRadarFolder(basename):
238 if not isRadarFolder(basename):
239 print("The folder %s has not the rigth format" % folder)
239 print("The folder %s has not the rigth format" % folder)
240 return 0
240 return 0
241
241
242 if startDate and endDate:
242 if startDate and endDate:
243 thisDate = getDateFromRadarFolder(basename)
243 thisDate = getDateFromRadarFolder(basename)
244
244
245 if thisDate < startDate:
245 if thisDate < startDate:
246 return 0
246 return 0
247
247
248 if thisDate > endDate:
248 if thisDate > endDate:
249 return 0
249 return 0
250
250
251 return 1
251 return 1
252
252
253
253
254 def isFileInDateRange(filename, startDate=None, endDate=None):
254 def isFileInDateRange(filename, startDate=None, endDate=None):
255 """
255 """
256 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
256 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
257
257
258 Inputs:
258 Inputs:
259 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
259 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
260
260
261 Su formato deberia ser "?YYYYDDDsss"
261 Su formato deberia ser "?YYYYDDDsss"
262
262
263 siendo:
263 siendo:
264 YYYY : Anio (ejemplo 2015)
264 YYYY : Anio (ejemplo 2015)
265 DDD : Dia del anio (ejemplo 305)
265 DDD : Dia del anio (ejemplo 305)
266 sss : set
266 sss : set
267
267
268 startDate : fecha inicial del rango seleccionado en formato datetime.date
268 startDate : fecha inicial del rango seleccionado en formato datetime.date
269
269
270 endDate : fecha final del rango seleccionado en formato datetime.date
270 endDate : fecha final del rango seleccionado en formato datetime.date
271
271
272 Return:
272 Return:
273 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
273 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
274 fecha especificado, de lo contrario retorna False.
274 fecha especificado, de lo contrario retorna False.
275 Excepciones:
275 Excepciones:
276 Si el archivo no tiene el formato adecuado
276 Si el archivo no tiene el formato adecuado
277 """
277 """
278
278
279 basename = os.path.basename(filename)
279 basename = os.path.basename(filename)
280
280
281 if not isRadarFile(basename):
281 if not isRadarFile(basename):
282 print("The filename %s has not the rigth format" % filename)
282 print("The filename %s has not the rigth format" % filename)
283 return 0
283 return 0
284
284
285 if startDate and endDate:
285 if startDate and endDate:
286 thisDate = getDateFromRadarFile(basename)
286 thisDate = getDateFromRadarFile(basename)
287
287
288 if thisDate < startDate:
288 if thisDate < startDate:
289 return 0
289 return 0
290
290
291 if thisDate > endDate:
291 if thisDate > endDate:
292 return 0
292 return 0
293
293
294 return 1
294 return 1
295
295
296
296
297 def getFileFromSet(path, ext, set):
297 def getFileFromSet(path, ext, set):
298 validFilelist = []
298 validFilelist = []
299 fileList = os.listdir(path)
299 fileList = os.listdir(path)
300
300
301 # 0 1234 567 89A BCDE
301 # 0 1234 567 89A BCDE
302 # H YYYY DDD SSS .ext
302 # H YYYY DDD SSS .ext
303
303
304 for thisFile in fileList:
304 for thisFile in fileList:
305 try:
305 try:
306 year = int(thisFile[1:5])
306 year = int(thisFile[1:5])
307 doy = int(thisFile[5:8])
307 doy = int(thisFile[5:8])
308 except:
308 except:
309 continue
309 continue
310
310
311 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
311 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
312 continue
312 continue
313
313
314 validFilelist.append(thisFile)
314 validFilelist.append(thisFile)
315
315
316 myfile = fnmatch.filter(
316 myfile = fnmatch.filter(
317 validFilelist, '*%4.4d%3.3d%3.3d*' % (year, doy, set))
317 validFilelist, '*%4.4d%3.3d%3.3d*' % (year, doy, set))
318
318
319 if len(myfile) != 0:
319 if len(myfile) != 0:
320 return myfile[0]
320 return myfile[0]
321 else:
321 else:
322 filename = '*%4.4d%3.3d%3.3d%s' % (year, doy, set, ext.lower())
322 filename = '*%4.4d%3.3d%3.3d%s' % (year, doy, set, ext.lower())
323 print('the filename %s does not exist' % filename)
323 print('the filename %s does not exist' % filename)
324 print('...going to the last file: ')
324 print('...going to the last file: ')
325
325
326 if validFilelist:
326 if validFilelist:
327 validFilelist = sorted(validFilelist, key=str.lower)
327 validFilelist = sorted(validFilelist, key=str.lower)
328 return validFilelist[-1]
328 return validFilelist[-1]
329
329
330 return None
330 return None
331
331
332
332
333 def getlastFileFromPath(path, ext):
333 def getlastFileFromPath(path, ext):
334 """
334 """
335 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
335 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
336 al final de la depuracion devuelve el ultimo file de la lista que quedo.
336 al final de la depuracion devuelve el ultimo file de la lista que quedo.
337
337
338 Input:
338 Input:
339 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
339 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
340 ext : extension de los files contenidos en una carpeta
340 ext : extension de los files contenidos en una carpeta
341
341
342 Return:
342 Return:
343 El ultimo file de una determinada carpeta, no se considera el path.
343 El ultimo file de una determinada carpeta, no se considera el path.
344 """
344 """
345 validFilelist = []
345 validFilelist = []
346 fileList = os.listdir(path)
346 fileList = os.listdir(path)
347
347
348 # 0 1234 567 89A BCDE
348 # 0 1234 567 89A BCDE
349 # H YYYY DDD SSS .ext
349 # H YYYY DDD SSS .ext
350
350
351 for thisFile in fileList:
351 for thisFile in fileList:
352
352
353 year = thisFile[1:5]
353 year = thisFile[1:5]
354 if not isNumber(year):
354 if not isNumber(year):
355 continue
355 continue
356
356
357 doy = thisFile[5:8]
357 doy = thisFile[5:8]
358 if not isNumber(doy):
358 if not isNumber(doy):
359 continue
359 continue
360
360
361 year = int(year)
361 year = int(year)
362 doy = int(doy)
362 doy = int(doy)
363
363
364 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
364 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
365 continue
365 continue
366
366
367 validFilelist.append(thisFile)
367 validFilelist.append(thisFile)
368
368
369 if validFilelist:
369 if validFilelist:
370 validFilelist = sorted(validFilelist, key=str.lower)
370 validFilelist = sorted(validFilelist, key=str.lower)
371 return validFilelist[-1]
371 return validFilelist[-1]
372
372
373 return None
373 return None
374
374
375
375
376 def isRadarFolder(folder):
376 def isRadarFolder(folder):
377 try:
377 try:
378 year = int(folder[1:5])
378 year = int(folder[1:5])
379 doy = int(folder[5:8])
379 doy = int(folder[5:8])
380 except:
380 except:
381 return 0
381 return 0
382
382
383 return 1
383 return 1
384
384
385
385
386 def isRadarFile(file):
386 def isRadarFile(file):
387 try:
387 try:
388 year = int(file[1:5])
388 year = int(file[1:5])
389 doy = int(file[5:8])
389 doy = int(file[5:8])
390 set = int(file[8:11])
390 set = int(file[8:11])
391 except:
391 except:
392 return 0
392 return 0
393
393
394 return 1
394 return 1
395
395
396
396
397 def getDateFromRadarFile(file):
397 def getDateFromRadarFile(file):
398 try:
398 try:
399 year = int(file[1:5])
399 year = int(file[1:5])
400 doy = int(file[5:8])
400 doy = int(file[5:8])
401 set = int(file[8:11])
401 set = int(file[8:11])
402 except:
402 except:
403 return None
403 return None
404
404
405 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
405 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
406 return thisDate
406 return thisDate
407
407
408
408
409 def getDateFromRadarFolder(folder):
409 def getDateFromRadarFolder(folder):
410 try:
410 try:
411 year = int(folder[1:5])
411 year = int(folder[1:5])
412 doy = int(folder[5:8])
412 doy = int(folder[5:8])
413 except:
413 except:
414 return None
414 return None
415
415
416 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
416 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
417 return thisDate
417 return thisDate
418
418
419 def parse_format(s, fmt):
419 def parse_format(s, fmt):
420
420
421 for i in range(fmt.count('%')):
421 for i in range(fmt.count('%')):
422 x = fmt.index('%')
422 x = fmt.index('%')
423 d = DT_DIRECTIVES[fmt[x:x+2]]
423 d = DT_DIRECTIVES[fmt[x:x+2]]
424 fmt = fmt.replace(fmt[x:x+2], s[x:x+d])
424 fmt = fmt.replace(fmt[x:x+2], s[x:x+d])
425 return fmt
425 return fmt
426
426
427 class Reader(object):
427 class Reader(object):
428
428
429 c = 3E8
429 c = 3E8
430 isConfig = False
430 isConfig = False
431 dtype = None
431 dtype = None
432 pathList = []
432 pathList = []
433 filenameList = []
433 filenameList = []
434 datetimeList = []
434 datetimeList = []
435 filename = None
435 filename = None
436 ext = None
436 ext = None
437 flagIsNewFile = 1
437 flagIsNewFile = 1
438 flagDiscontinuousBlock = 0
438 flagDiscontinuousBlock = 0
439 flagIsNewBlock = 0
439 flagIsNewBlock = 0
440 flagNoMoreFiles = 0
440 flagNoMoreFiles = 0
441 fp = None
441 fp = None
442 firstHeaderSize = 0
442 firstHeaderSize = 0
443 basicHeaderSize = 24
443 basicHeaderSize = 24
444 versionFile = 1103
444 versionFile = 1103
445 fileSize = None
445 fileSize = None
446 fileSizeByHeader = None
446 fileSizeByHeader = None
447 fileIndex = -1
447 fileIndex = -1
448 profileIndex = None
448 profileIndex = None
449 blockIndex = 0
449 blockIndex = 0
450 nTotalBlocks = 0
450 nTotalBlocks = 0
451 maxTimeStep = 30
451 maxTimeStep = 30
452 lastUTTime = None
452 lastUTTime = None
453 datablock = None
453 datablock = None
454 dataOut = None
454 dataOut = None
455 getByBlock = False
455 getByBlock = False
456 path = None
456 path = None
457 startDate = None
457 startDate = None
458 endDate = None
458 endDate = None
459 startTime = datetime.time(0, 0, 0)
459 startTime = datetime.time(0, 0, 0)
460 endTime = datetime.time(23, 59, 59)
460 endTime = datetime.time(23, 59, 59)
461 set = None
461 set = None
462 expLabel = ""
462 expLabel = ""
463 online = False
463 online = False
464 delay = 60
464 delay = 60
465 nTries = 3 # quantity tries
465 nTries = 3 # quantity tries
466 nFiles = 3 # number of files for searching
466 nFiles = 3 # number of files for searching
467 walk = True
467 walk = True
468 getblock = False
468 getblock = False
469 nTxs = 1
469 nTxs = 1
470 realtime = False
470 realtime = False
471 blocksize = 0
471 blocksize = 0
472 blocktime = None
472 blocktime = None
473 warnings = True
473 warnings = True
474 verbose = True
474 verbose = True
475 server = None
475 server = None
476 format = None
476 format = None
477 oneDDict = None
477 oneDDict = None
478 twoDDict = None
478 twoDDict = None
479 independentParam = None
479 independentParam = None
480 filefmt = None
480 filefmt = None
481 folderfmt = None
481 folderfmt = None
482 open_file = open
482 open_file = open
483 open_mode = 'rb'
483 open_mode = 'rb'
484
484
485 def run(self):
485 def run(self):
486
486
487 raise NotImplementedError
487 raise NotImplementedError
488
488
489 def getAllowedArgs(self):
489 def getAllowedArgs(self):
490 if hasattr(self, '__attrs__'):
490 if hasattr(self, '__attrs__'):
491 return self.__attrs__
491 return self.__attrs__
492 else:
492 else:
493 return inspect.getargspec(self.run).args
493 return inspect.getargspec(self.run).args
494
494
495 def set_kwargs(self, **kwargs):
495 def set_kwargs(self, **kwargs):
496
496
497 for key, value in kwargs.items():
497 for key, value in kwargs.items():
498 setattr(self, key, value)
498 setattr(self, key, value)
499
499
500 def find_folders(self, path, startDate, endDate, folderfmt, last=False):
500 def find_folders(self, path, startDate, endDate, folderfmt, last=False):
501
501
502 folders = [x for f in path.split(',')
502 folders = [x for f in path.split(',')
503 for x in os.listdir(f) if os.path.isdir(os.path.join(f, x))]
503 for x in os.listdir(f) if os.path.isdir(os.path.join(f, x))]
504 folders.sort()
504 folders.sort()
505
505
506 if last:
506 if last:
507 folders = [folders[-1]]
507 folders = [folders[-1]]
508
508
509 for folder in folders:
509 for folder in folders:
510 try:
510 try:
511 dt = datetime.datetime.strptime(parse_format(folder, folderfmt), folderfmt).date()
511 dt = datetime.datetime.strptime(parse_format(folder, folderfmt), folderfmt).date()
512 if dt >= startDate and dt <= endDate:
512 if dt >= startDate and dt <= endDate:
513 yield os.path.join(path, folder)
513 yield os.path.join(path, folder)
514 else:
514 else:
515 log.log('Skiping folder {}'.format(folder), self.name)
515 log.log('Skiping folder {}'.format(folder), self.name)
516 except Exception as e:
516 except Exception as e:
517 log.log('Skiping folder {}'.format(folder), self.name)
517 log.log('Skiping folder {}'.format(folder), self.name)
518 continue
518 continue
519 return
519 return
520
520
521 def find_files(self, folders, ext, filefmt, startDate=None, endDate=None,
521 def find_files(self, folders, ext, filefmt, startDate=None, endDate=None,
522 expLabel='', last=False):
522 expLabel='', last=False):
523
523
524 for path in folders:
524 for path in folders:
525 files = glob.glob1(path, '*{}'.format(ext))
525 files = glob.glob1(path, '*{}'.format(ext))
526 files.sort()
526 files.sort()
527 if last:
527 if last:
528 if files:
528 if files:
529 fo = files[-1]
529 fo = files[-1]
530 try:
530 try:
531 dt = datetime.datetime.strptime(parse_format(fo, filefmt), filefmt).date()
531 dt = datetime.datetime.strptime(parse_format(fo, filefmt), filefmt).date()
532 yield os.path.join(path, expLabel, fo)
532 yield os.path.join(path, expLabel, fo)
533 except Exception as e:
533 except Exception as e:
534 pass
534 pass
535 return
535 return
536 else:
536 else:
537 return
537 return
538
538
539 for fo in files:
539 for fo in files:
540 try:
540 try:
541 dt = datetime.datetime.strptime(parse_format(fo, filefmt), filefmt).date()
541 dt = datetime.datetime.strptime(parse_format(fo, filefmt), filefmt).date()
542 if dt >= startDate and dt <= endDate:
542 if dt >= startDate and dt <= endDate:
543 yield os.path.join(path, expLabel, fo)
543 yield os.path.join(path, expLabel, fo)
544 else:
544 else:
545 log.log('Skiping file {}'.format(fo), self.name)
545 log.log('Skiping file {}'.format(fo), self.name)
546 except Exception as e:
546 except Exception as e:
547 log.log('Skiping file {}'.format(fo), self.name)
547 log.log('Skiping file {}'.format(fo), self.name)
548 continue
548 continue
549
549
550 def searchFilesOffLine(self, path, startDate, endDate,
550 def searchFilesOffLine(self, path, startDate, endDate,
551 expLabel, ext, walk,
551 expLabel, ext, walk,
552 filefmt, folderfmt):
552 filefmt, folderfmt):
553 """Search files in offline mode for the given arguments
553 """Search files in offline mode for the given arguments
554
554
555 Return:
555 Return:
556 Generator of files
556 Generator of files
557 """
557 """
558
558
559 if walk:
559 if walk:
560 folders = self.find_folders(
560 folders = self.find_folders(
561 path, startDate, endDate, folderfmt)
561 path, startDate, endDate, folderfmt)
562 else:
562 else:
563 folders = path.split(',')
563 folders = path.split(',')
564
564
565 return self.find_files(
565 return self.find_files(
566 folders, ext, filefmt, startDate, endDate, expLabel)
566 folders, ext, filefmt, startDate, endDate, expLabel)
567
567
568 def searchFilesOnLine(self, path, startDate, endDate,
568 def searchFilesOnLine(self, path, startDate, endDate,
569 expLabel, ext, walk,
569 expLabel, ext, walk,
570 filefmt, folderfmt):
570 filefmt, folderfmt):
571 """Search for the last file of the last folder
571 """Search for the last file of the last folder
572
572
573 Arguments:
573 Arguments:
574 path : carpeta donde estan contenidos los files que contiene data
574 path : carpeta donde estan contenidos los files que contiene data
575 expLabel : Nombre del subexperimento (subfolder)
575 expLabel : Nombre del subexperimento (subfolder)
576 ext : extension de los files
576 ext : extension de los files
577 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
577 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
578
578
579 Return:
579 Return:
580 generator with the full path of last filename
580 generator with the full path of last filename
581 """
581 """
582
582
583 if walk:
583 if walk:
584 folders = self.find_folders(
584 folders = self.find_folders(
585 path, startDate, endDate, folderfmt, last=True)
585 path, startDate, endDate, folderfmt, last=True)
586 else:
586 else:
587 folders = path.split(',')
587 folders = path.split(',')
588
588
589 return self.find_files(
589 return self.find_files(
590 folders, ext, filefmt, startDate, endDate, expLabel, last=True)
590 folders, ext, filefmt, startDate, endDate, expLabel, last=True)
591
591
592 def setNextFile(self):
592 def setNextFile(self):
593 """Set the next file to be readed open it and parse de file header"""
593 """Set the next file to be readed open it and parse de file header"""
594
594
595 while True:
595 while True:
596 if self.fp != None:
596 if self.fp != None:
597 self.fp.close()
597 self.fp.close()
598
598
599 if self.online:
599 if self.online:
600 newFile = self.setNextFileOnline()
600 newFile = self.setNextFileOnline()
601 else:
601 else:
602 newFile = self.setNextFileOffline()
602 newFile = self.setNextFileOffline()
603
603
604 if not(newFile):
604 if not(newFile):
605 if self.online:
605 if self.online:
606 raise schainpy.admin.SchainError('Time to wait for new files reach')
606 raise schainpy.admin.SchainError('Time to wait for new files reach')
607 else:
607 else:
608 if self.fileIndex == -1:
608 if self.fileIndex == -1:
609 raise schainpy.admin.SchainWarning('No files found in the given path')
609 raise schainpy.admin.SchainWarning('No files found in the given path')
610 else:
610 else:
611 raise schainpy.admin.SchainWarning('No more files to read')
611 raise schainpy.admin.SchainWarning('No more files to read')
612
612
613 if self.verifyFile(self.filename):
613 if self.verifyFile(self.filename):
614 break
614 break
615
615
616 log.log('Opening file: %s' % self.filename, self.name)
616 log.log('Opening file: %s' % self.filename, self.name)
617
617
618 self.readFirstHeader()
618 self.readFirstHeader()
619 self.nReadBlocks = 0
619 self.nReadBlocks = 0
620
620
621 def setNextFileOnline(self):
621 def setNextFileOnline(self):
622 """Check for the next file to be readed in online mode.
622 """Check for the next file to be readed in online mode.
623
623
624 Set:
624 Set:
625 self.filename
625 self.filename
626 self.fp
626 self.fp
627 self.filesize
627 self.filesize
628
628
629 Return:
629 Return:
630 boolean
630 boolean
631
631
632 """
632 """
633 nextFile = True
633 nextFile = True
634 nextDay = False
634 nextDay = False
635
635
636 for nFiles in range(self.nFiles+1):
636 for nFiles in range(self.nFiles+1):
637 for nTries in range(self.nTries):
637 for nTries in range(self.nTries):
638 fullfilename, filename = self.checkForRealPath(nextFile, nextDay)
638 fullfilename, filename = self.checkForRealPath(nextFile, nextDay)
639 if fullfilename is not None:
639 if fullfilename is not None:
640 break
640 break
641 log.warning(
641 log.warning(
642 "Waiting %0.2f sec for the next file: \"%s\" , try %02d ..." % (self.delay, filename, nTries + 1),
642 "Waiting %0.2f sec for the next file: \"%s\" , try %02d ..." % (self.delay, filename, nTries + 1),
643 self.name)
643 self.name)
644 time.sleep(self.delay)
644 time.sleep(self.delay)
645 nextFile = False
645 nextFile = False
646 continue
646 continue
647
647
648 if fullfilename is not None:
648 if fullfilename is not None:
649 break
649 break
650
650
651 self.nTries = 1
651 self.nTries = 1
652 nextFile = True
652 nextFile = True
653
653
654 if nFiles == (self.nFiles - 1):
654 if nFiles == (self.nFiles - 1):
655 log.log('Trying with next day...', self.name)
655 log.log('Trying with next day...', self.name)
656 nextDay = True
656 nextDay = True
657 self.nTries = 3
657 self.nTries = 3
658
658
659 if fullfilename:
659 if fullfilename:
660 self.fileSize = os.path.getsize(fullfilename)
660 self.fileSize = os.path.getsize(fullfilename)
661 self.filename = fullfilename
661 self.filename = fullfilename
662 self.flagIsNewFile = 1
662 self.flagIsNewFile = 1
663 if self.fp != None:
663 if self.fp != None:
664 self.fp.close()
664 self.fp.close()
665 self.fp = self.open_file(fullfilename, self.open_mode)
665 self.fp = self.open_file(fullfilename, self.open_mode)
666 self.flagNoMoreFiles = 0
666 self.flagNoMoreFiles = 0
667 self.fileIndex += 1
667 self.fileIndex += 1
668 return 1
668 return 1
669 else:
669 else:
670 return 0
670 return 0
671
671
672 def setNextFileOffline(self):
672 def setNextFileOffline(self):
673 """Open the next file to be readed in offline mode"""
673 """Open the next file to be readed in offline mode"""
674
674
675 try:
675 try:
676 filename = next(self.filenameList)
676 filename = next(self.filenameList)
677 self.fileIndex +=1
677 self.fileIndex +=1
678 except StopIteration:
678 except StopIteration:
679 self.flagNoMoreFiles = 1
679 self.flagNoMoreFiles = 1
680 return 0
680 return 0
681
681
682 self.filename = filename
682 self.filename = filename
683 self.fileSize = os.path.getsize(filename)
683 self.fileSize = os.path.getsize(filename)
684 self.fp = self.open_file(filename, self.open_mode)
684 self.fp = self.open_file(filename, self.open_mode)
685 self.flagIsNewFile = 1
685 self.flagIsNewFile = 1
686
686
687 return 1
687 return 1
688
688
689 @staticmethod
689 @staticmethod
690 def isDateTimeInRange(dt, startDate, endDate, startTime, endTime):
690 def isDateTimeInRange(dt, startDate, endDate, startTime, endTime):
691 """Check if the given datetime is in range"""
691 """Check if the given datetime is in range"""
692
692
693 if startDate <= dt.date() <= endDate:
693 if startDate <= dt.date() <= endDate:
694 if startTime <= dt.time() <= endTime:
694 if startTime <= dt.time() <= endTime:
695 return True
695 return True
696 return False
696 return False
697
697
698 def verifyFile(self, filename):
698 def verifyFile(self, filename):
699 """Check for a valid file
699 """Check for a valid file
700
700
701 Arguments:
701 Arguments:
702 filename -- full path filename
702 filename -- full path filename
703
703
704 Return:
704 Return:
705 boolean
705 boolean
706 """
706 """
707
707
708 return True
708 return True
709
709
710 def checkForRealPath(self, nextFile, nextDay):
710 def checkForRealPath(self, nextFile, nextDay):
711 """Check if the next file to be readed exists"""
711 """Check if the next file to be readed exists"""
712 if nextFile:
713 self.set += 1
714 if nextDay:
715 self.set = 0
716 self.doy += 1
717 foldercounter = 0
718 prefixDirList = [None, 'd', 'D']
719 if self.ext.lower() == ".r": # voltage
720 prefixFileList = ['d', 'D']
721 elif self.ext.lower() == ".pdata": # spectra
722 prefixFileList = ['p', 'P']
723 elif self.ext.lower() == ".hdf5": # HDF5
724 prefixFileList = ['D', 'P'] # HDF5
712
725
713 raise NotImplementedError
726 # barrido por las combinaciones posibles
727 for prefixDir in prefixDirList:
728 thispath = self.path
729 if prefixDir != None:
730 # formo el nombre del directorio xYYYYDDD (x=d o x=D)
731 if foldercounter == 0:
732 thispath = os.path.join(self.path, "%s%04d%03d" %
733 (prefixDir, self.year, self.doy))
734 else:
735 thispath = os.path.join(self.path, "%s%04d%03d_%02d" % (
736 prefixDir, self.year, self.doy, foldercounter))
737 for prefixFile in prefixFileList: # barrido por las dos combinaciones posibles de "D"
738 # formo el nombre del file xYYYYDDDSSS.ext
739 filename = "%s%04d%03d%03d%s" % (prefixFile, self.year, self.doy, self.set, self.ext)
740 fullfilename = os.path.join(
741 thispath, filename)
742
743 if os.path.exists(fullfilename):
744 return fullfilename, filename
745
746 return None, filename
747 #raise NotImplementedError
714
748
715 def readFirstHeader(self):
749 def readFirstHeader(self):
716 """Parse the file header"""
750 """Parse the file header"""
717
751
718 pass
752 pass
719
753
720 def waitDataBlock(self, pointer_location, blocksize=None):
754 def waitDataBlock(self, pointer_location, blocksize=None):
721 """
755 """
722 """
756 """
723
757
724 currentPointer = pointer_location
758 currentPointer = pointer_location
725 if blocksize is None:
759 if blocksize is None:
726 neededSize = self.processingHeaderObj.blockSize # + self.basicHeaderSize
760 neededSize = self.processingHeaderObj.blockSize # + self.basicHeaderSize
727 else:
761 else:
728 neededSize = blocksize
762 neededSize = blocksize
729
763
730 for nTries in range(self.nTries):
764 for nTries in range(self.nTries):
731 self.fp.close()
765 self.fp.close()
732 self.fp = open(self.filename, 'rb')
766 self.fp = open(self.filename, 'rb')
733 self.fp.seek(currentPointer)
767 self.fp.seek(currentPointer)
734
768
735 self.fileSize = os.path.getsize(self.filename)
769 self.fileSize = os.path.getsize(self.filename)
736 currentSize = self.fileSize - currentPointer
770 currentSize = self.fileSize - currentPointer
737
771
738 if (currentSize >= neededSize):
772 if (currentSize >= neededSize):
739 return 1
773 return 1
740
774
741 log.warning(
775 log.warning(
742 "Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1),
776 "Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1),
743 self.name
777 self.name
744 )
778 )
745 time.sleep(self.delay)
779 time.sleep(self.delay)
746
780
747 return 0
781 return 0
748
782
749 class JRODataReader(Reader):
783 class JRODataReader(Reader):
750
784
751 utc = 0
785 utc = 0
752 nReadBlocks = 0
786 nReadBlocks = 0
753 foldercounter = 0
787 foldercounter = 0
754 firstHeaderSize = 0
788 firstHeaderSize = 0
755 basicHeaderSize = 24
789 basicHeaderSize = 24
756 __isFirstTimeOnline = 1
790 __isFirstTimeOnline = 1
757 filefmt = "*%Y%j***"
791 filefmt = "*%Y%j***"
758 folderfmt = "*%Y%j"
792 folderfmt = "*%Y%j"
759 __attrs__ = ['path', 'startDate', 'endDate', 'startTime', 'endTime', 'online', 'delay', 'walk']
793 __attrs__ = ['path', 'startDate', 'endDate', 'startTime', 'endTime', 'online', 'delay', 'walk']
760
794
761 def getDtypeWidth(self):
795 def getDtypeWidth(self):
762
796
763 dtype_index = get_dtype_index(self.dtype)
797 dtype_index = get_dtype_index(self.dtype)
764 dtype_width = get_dtype_width(dtype_index)
798 dtype_width = get_dtype_width(dtype_index)
765
799
766 return dtype_width
800 return dtype_width
767
801
768 def checkForRealPath(self, nextFile, nextDay):
802 def checkForRealPath(self, nextFile, nextDay):
769 """Check if the next file to be readed exists.
803 """Check if the next file to be readed exists.
770
804
771 Example :
805 Example :
772 nombre correcto del file es .../.../D2009307/P2009307367.ext
806 nombre correcto del file es .../.../D2009307/P2009307367.ext
773
807
774 Entonces la funcion prueba con las siguientes combinaciones
808 Entonces la funcion prueba con las siguientes combinaciones
775 .../.../y2009307367.ext
809 .../.../y2009307367.ext
776 .../.../Y2009307367.ext
810 .../.../Y2009307367.ext
777 .../.../x2009307/y2009307367.ext
811 .../.../x2009307/y2009307367.ext
778 .../.../x2009307/Y2009307367.ext
812 .../.../x2009307/Y2009307367.ext
779 .../.../X2009307/y2009307367.ext
813 .../.../X2009307/y2009307367.ext
780 .../.../X2009307/Y2009307367.ext
814 .../.../X2009307/Y2009307367.ext
781 siendo para este caso, la ultima combinacion de letras, identica al file buscado
815 siendo para este caso, la ultima combinacion de letras, identica al file buscado
782
816
783 Return:
817 Return:
784 str -- fullpath of the file
818 str -- fullpath of the file
785 """
819 """
786
820
787
821
788 if nextFile:
822 if nextFile:
789 self.set += 1
823 self.set += 1
790 if nextDay:
824 if nextDay:
791 self.set = 0
825 self.set = 0
792 self.doy += 1
826 self.doy += 1
793 foldercounter = 0
827 foldercounter = 0
794 prefixDirList = [None, 'd', 'D']
828 prefixDirList = [None, 'd', 'D']
795 if self.ext.lower() == ".r": # voltage
829 if self.ext.lower() == ".r": # voltage
796 prefixFileList = ['d', 'D']
830 prefixFileList = ['d', 'D']
797 elif self.ext.lower() == ".pdata": # spectra
831 elif self.ext.lower() == ".pdata": # spectra
798 prefixFileList = ['p', 'P']
832 prefixFileList = ['p', 'P']
799
833
800 # barrido por las combinaciones posibles
834 # barrido por las combinaciones posibles
801 for prefixDir in prefixDirList:
835 for prefixDir in prefixDirList:
802 thispath = self.path
836 thispath = self.path
803 if prefixDir != None:
837 if prefixDir != None:
804 # formo el nombre del directorio xYYYYDDD (x=d o x=D)
838 # formo el nombre del directorio xYYYYDDD (x=d o x=D)
805 if foldercounter == 0:
839 if foldercounter == 0:
806 thispath = os.path.join(self.path, "%s%04d%03d" %
840 thispath = os.path.join(self.path, "%s%04d%03d" %
807 (prefixDir, self.year, self.doy))
841 (prefixDir, self.year, self.doy))
808 else:
842 else:
809 thispath = os.path.join(self.path, "%s%04d%03d_%02d" % (
843 thispath = os.path.join(self.path, "%s%04d%03d_%02d" % (
810 prefixDir, self.year, self.doy, foldercounter))
844 prefixDir, self.year, self.doy, foldercounter))
811 for prefixFile in prefixFileList: # barrido por las dos combinaciones posibles de "D"
845 for prefixFile in prefixFileList: # barrido por las dos combinaciones posibles de "D"
812 # formo el nombre del file xYYYYDDDSSS.ext
846 # formo el nombre del file xYYYYDDDSSS.ext
813 filename = "%s%04d%03d%03d%s" % (prefixFile, self.year, self.doy, self.set, self.ext)
847 filename = "%s%04d%03d%03d%s" % (prefixFile, self.year, self.doy, self.set, self.ext)
814 fullfilename = os.path.join(
848 fullfilename = os.path.join(
815 thispath, filename)
849 thispath, filename)
816
850
817 if os.path.exists(fullfilename):
851 if os.path.exists(fullfilename):
818 return fullfilename, filename
852 return fullfilename, filename
819
853
820 return None, filename
854 return None, filename
821
855
822 def __waitNewBlock(self):
856 def __waitNewBlock(self):
823 """
857 """
824 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
858 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
825
859
826 Si el modo de lectura es OffLine siempre retorn 0
860 Si el modo de lectura es OffLine siempre retorn 0
827 """
861 """
828 if not self.online:
862 if not self.online:
829 return 0
863 return 0
830
864
831 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
865 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
832 return 0
866 return 0
833
867
834 currentPointer = self.fp.tell()
868 currentPointer = self.fp.tell()
835
869
836 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
870 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
837
871
838 for nTries in range(self.nTries):
872 for nTries in range(self.nTries):
839
873
840 self.fp.close()
874 self.fp.close()
841 self.fp = open(self.filename, 'rb')
875 self.fp = open(self.filename, 'rb')
842 self.fp.seek(currentPointer)
876 self.fp.seek(currentPointer)
843
877
844 self.fileSize = os.path.getsize(self.filename)
878 self.fileSize = os.path.getsize(self.filename)
845 currentSize = self.fileSize - currentPointer
879 currentSize = self.fileSize - currentPointer
846
880
847 if (currentSize >= neededSize):
881 if (currentSize >= neededSize):
848 self.basicHeaderObj.read(self.fp)
882 self.basicHeaderObj.read(self.fp)
849 return 1
883 return 1
850
884
851 if self.fileSize == self.fileSizeByHeader:
885 if self.fileSize == self.fileSizeByHeader:
852 # self.flagEoF = True
886 # self.flagEoF = True
853 return 0
887 return 0
854
888
855 print("[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1))
889 print("[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1))
856 time.sleep(self.delay)
890 time.sleep(self.delay)
857
891
858 return 0
892 return 0
859
893
860 def __setNewBlock(self):
894 def __setNewBlock(self):
861
895
862 if self.fp == None:
896 if self.fp == None:
863 return 0
897 return 0
864
898
865 if self.flagIsNewFile:
899 if self.flagIsNewFile:
866 self.lastUTTime = self.basicHeaderObj.utc
900 self.lastUTTime = self.basicHeaderObj.utc
867 return 1
901 return 1
868
902
869 if self.realtime:
903 if self.realtime:
870 self.flagDiscontinuousBlock = 1
904 self.flagDiscontinuousBlock = 1
871 if not(self.setNextFile()):
905 if not(self.setNextFile()):
872 return 0
906 return 0
873 else:
907 else:
874 return 1
908 return 1
875
909
876 currentSize = self.fileSize - self.fp.tell()
910 currentSize = self.fileSize - self.fp.tell()
877 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
911 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
878
912
879 if (currentSize >= neededSize):
913 if (currentSize >= neededSize):
880 self.basicHeaderObj.read(self.fp)
914 self.basicHeaderObj.read(self.fp)
881 self.lastUTTime = self.basicHeaderObj.utc
915 self.lastUTTime = self.basicHeaderObj.utc
882 return 1
916 return 1
883
917
884 if self.__waitNewBlock():
918 if self.__waitNewBlock():
885 self.lastUTTime = self.basicHeaderObj.utc
919 self.lastUTTime = self.basicHeaderObj.utc
886 return 1
920 return 1
887
921
888 if not(self.setNextFile()):
922 if not(self.setNextFile()):
889 return 0
923 return 0
890
924
891 deltaTime = self.basicHeaderObj.utc - self.lastUTTime
925 deltaTime = self.basicHeaderObj.utc - self.lastUTTime
892 self.lastUTTime = self.basicHeaderObj.utc
926 self.lastUTTime = self.basicHeaderObj.utc
893
927
894 self.flagDiscontinuousBlock = 0
928 self.flagDiscontinuousBlock = 0
895
929
896 if deltaTime > self.maxTimeStep:
930 if deltaTime > self.maxTimeStep:
897 self.flagDiscontinuousBlock = 1
931 self.flagDiscontinuousBlock = 1
898
932
899 return 1
933 return 1
900
934
901 def readNextBlock(self):
935 def readNextBlock(self):
902
936
903 while True:
937 while True:
904 if not(self.__setNewBlock()):
938 if not(self.__setNewBlock()):
905 continue
939 continue
906
940
907 if not(self.readBlock()):
941 if not(self.readBlock()):
908 return 0
942 return 0
909
943
910 self.getBasicHeader()
944 self.getBasicHeader()
911
945
912 if not self.isDateTimeInRange(self.dataOut.datatime, self.startDate, self.endDate, self.startTime, self.endTime):
946 if not self.isDateTimeInRange(self.dataOut.datatime, self.startDate, self.endDate, self.startTime, self.endTime):
913 print("[Reading] Block No. %d/%d -> %s [Skipping]" % (self.nReadBlocks,
947 print("[Reading] Block No. %d/%d -> %s [Skipping]" % (self.nReadBlocks,
914 self.processingHeaderObj.dataBlocksPerFile,
948 self.processingHeaderObj.dataBlocksPerFile,
915 self.dataOut.datatime.ctime()))
949 self.dataOut.datatime.ctime()))
916 continue
950 continue
917
951
918 break
952 break
919
953
920 if self.verbose:
954 if self.verbose:
921 print("[Reading] Block No. %d/%d -> %s" % (self.nReadBlocks,
955 print("[Reading] Block No. %d/%d -> %s" % (self.nReadBlocks,
922 self.processingHeaderObj.dataBlocksPerFile,
956 self.processingHeaderObj.dataBlocksPerFile,
923 self.dataOut.datatime.ctime()))
957 self.dataOut.datatime.ctime()))
924 return 1
958 return 1
925
959
926 def readFirstHeader(self):
960 def readFirstHeader(self):
927
961
928 self.basicHeaderObj.read(self.fp)
962 self.basicHeaderObj.read(self.fp)
929 self.systemHeaderObj.read(self.fp)
963 self.systemHeaderObj.read(self.fp)
930 self.radarControllerHeaderObj.read(self.fp)
964 self.radarControllerHeaderObj.read(self.fp)
931 self.processingHeaderObj.read(self.fp)
965 self.processingHeaderObj.read(self.fp)
932 self.firstHeaderSize = self.basicHeaderObj.size
966 self.firstHeaderSize = self.basicHeaderObj.size
933
967
934 datatype = int(numpy.log2((self.processingHeaderObj.processFlags &
968 datatype = int(numpy.log2((self.processingHeaderObj.processFlags &
935 PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR))
969 PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR))
936 if datatype == 0:
970 if datatype == 0:
937 datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
971 datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
938 elif datatype == 1:
972 elif datatype == 1:
939 datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
973 datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
940 elif datatype == 2:
974 elif datatype == 2:
941 datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
975 datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
942 elif datatype == 3:
976 elif datatype == 3:
943 datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
977 datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
944 elif datatype == 4:
978 elif datatype == 4:
945 datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
979 datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
946 elif datatype == 5:
980 elif datatype == 5:
947 datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
981 datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
948 else:
982 else:
949 raise ValueError('Data type was not defined')
983 raise ValueError('Data type was not defined')
950
984
951 self.dtype = datatype_str
985 self.dtype = datatype_str
952 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
986 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
953 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \
987 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \
954 self.firstHeaderSize + self.basicHeaderSize * \
988 self.firstHeaderSize + self.basicHeaderSize * \
955 (self.processingHeaderObj.dataBlocksPerFile - 1)
989 (self.processingHeaderObj.dataBlocksPerFile - 1)
956 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
990 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
957 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
991 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
958 self.getBlockDimension()
992 self.getBlockDimension()
959
993
960 def verifyFile(self, filename):
994 def verifyFile(self, filename):
961
995
962 flag = True
996 flag = True
963
997
964 try:
998 try:
965 fp = open(filename, 'rb')
999 fp = open(filename, 'rb')
966 except IOError:
1000 except IOError:
967 log.error("File {} can't be opened".format(filename), self.name)
1001 log.error("File {} can't be opened".format(filename), self.name)
968 return False
1002 return False
969
1003
970 if self.online and self.waitDataBlock(0):
1004 if self.online and self.waitDataBlock(0):
971 pass
1005 pass
972
1006
973 basicHeaderObj = BasicHeader(LOCALTIME)
1007 basicHeaderObj = BasicHeader(LOCALTIME)
974 systemHeaderObj = SystemHeader()
1008 systemHeaderObj = SystemHeader()
975 radarControllerHeaderObj = RadarControllerHeader()
1009 radarControllerHeaderObj = RadarControllerHeader()
976 processingHeaderObj = ProcessingHeader()
1010 processingHeaderObj = ProcessingHeader()
977
1011
978 if not(basicHeaderObj.read(fp)):
1012 if not(basicHeaderObj.read(fp)):
979 flag = False
1013 flag = False
980 if not(systemHeaderObj.read(fp)):
1014 if not(systemHeaderObj.read(fp)):
981 flag = False
1015 flag = False
982 if not(radarControllerHeaderObj.read(fp)):
1016 if not(radarControllerHeaderObj.read(fp)):
983 flag = False
1017 flag = False
984 if not(processingHeaderObj.read(fp)):
1018 if not(processingHeaderObj.read(fp)):
985 flag = False
1019 flag = False
986 if not self.online:
1020 if not self.online:
987 dt1 = basicHeaderObj.datatime
1021 dt1 = basicHeaderObj.datatime
988 pos = self.fileSize-processingHeaderObj.blockSize-24
1022 pos = self.fileSize-processingHeaderObj.blockSize-24
989 if pos<0:
1023 if pos<0:
990 flag = False
1024 flag = False
991 log.error('Invalid size for file: {}'.format(self.filename), self.name)
1025 log.error('Invalid size for file: {}'.format(self.filename), self.name)
992 else:
1026 else:
993 fp.seek(pos)
1027 fp.seek(pos)
994 if not(basicHeaderObj.read(fp)):
1028 if not(basicHeaderObj.read(fp)):
995 flag = False
1029 flag = False
996 dt2 = basicHeaderObj.datatime
1030 dt2 = basicHeaderObj.datatime
997 if not self.isDateTimeInRange(dt1, self.startDate, self.endDate, self.startTime, self.endTime) and not \
1031 if not self.isDateTimeInRange(dt1, self.startDate, self.endDate, self.startTime, self.endTime) and not \
998 self.isDateTimeInRange(dt2, self.startDate, self.endDate, self.startTime, self.endTime):
1032 self.isDateTimeInRange(dt2, self.startDate, self.endDate, self.startTime, self.endTime):
999 flag = False
1033 flag = False
1000
1034
1001 fp.close()
1035 fp.close()
1002 return flag
1036 return flag
1003
1037
1004 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1038 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1005
1039
1006 path_empty = True
1040 path_empty = True
1007
1041
1008 dateList = []
1042 dateList = []
1009 pathList = []
1043 pathList = []
1010
1044
1011 multi_path = path.split(',')
1045 multi_path = path.split(',')
1012
1046
1013 if not walk:
1047 if not walk:
1014
1048
1015 for single_path in multi_path:
1049 for single_path in multi_path:
1016
1050
1017 if not os.path.isdir(single_path):
1051 if not os.path.isdir(single_path):
1018 continue
1052 continue
1019
1053
1020 fileList = glob.glob1(single_path, "*" + ext)
1054 fileList = glob.glob1(single_path, "*" + ext)
1021
1055
1022 if not fileList:
1056 if not fileList:
1023 continue
1057 continue
1024
1058
1025 path_empty = False
1059 path_empty = False
1026
1060
1027 fileList.sort()
1061 fileList.sort()
1028
1062
1029 for thisFile in fileList:
1063 for thisFile in fileList:
1030
1064
1031 if not os.path.isfile(os.path.join(single_path, thisFile)):
1065 if not os.path.isfile(os.path.join(single_path, thisFile)):
1032 continue
1066 continue
1033
1067
1034 if not isRadarFile(thisFile):
1068 if not isRadarFile(thisFile):
1035 continue
1069 continue
1036
1070
1037 if not isFileInDateRange(thisFile, startDate, endDate):
1071 if not isFileInDateRange(thisFile, startDate, endDate):
1038 continue
1072 continue
1039
1073
1040 thisDate = getDateFromRadarFile(thisFile)
1074 thisDate = getDateFromRadarFile(thisFile)
1041
1075
1042 if thisDate in dateList or single_path in pathList:
1076 if thisDate in dateList or single_path in pathList:
1043 continue
1077 continue
1044
1078
1045 dateList.append(thisDate)
1079 dateList.append(thisDate)
1046 pathList.append(single_path)
1080 pathList.append(single_path)
1047
1081
1048 else:
1082 else:
1049 for single_path in multi_path:
1083 for single_path in multi_path:
1050
1084
1051 if not os.path.isdir(single_path):
1085 if not os.path.isdir(single_path):
1052 continue
1086 continue
1053
1087
1054 dirList = []
1088 dirList = []
1055
1089
1056 for thisPath in os.listdir(single_path):
1090 for thisPath in os.listdir(single_path):
1057
1091
1058 if not os.path.isdir(os.path.join(single_path, thisPath)):
1092 if not os.path.isdir(os.path.join(single_path, thisPath)):
1059 continue
1093 continue
1060
1094
1061 if not isRadarFolder(thisPath):
1095 if not isRadarFolder(thisPath):
1062 continue
1096 continue
1063
1097
1064 if not isFolderInDateRange(thisPath, startDate, endDate):
1098 if not isFolderInDateRange(thisPath, startDate, endDate):
1065 continue
1099 continue
1066
1100
1067 dirList.append(thisPath)
1101 dirList.append(thisPath)
1068
1102
1069 if not dirList:
1103 if not dirList:
1070 continue
1104 continue
1071
1105
1072 dirList.sort()
1106 dirList.sort()
1073
1107
1074 for thisDir in dirList:
1108 for thisDir in dirList:
1075
1109
1076 datapath = os.path.join(single_path, thisDir, expLabel)
1110 datapath = os.path.join(single_path, thisDir, expLabel)
1077 fileList = glob.glob1(datapath, "*" + ext)
1111 fileList = glob.glob1(datapath, "*" + ext)
1078
1112
1079 if not fileList:
1113 if not fileList:
1080 continue
1114 continue
1081
1115
1082 path_empty = False
1116 path_empty = False
1083
1117
1084 thisDate = getDateFromRadarFolder(thisDir)
1118 thisDate = getDateFromRadarFolder(thisDir)
1085
1119
1086 pathList.append(datapath)
1120 pathList.append(datapath)
1087 dateList.append(thisDate)
1121 dateList.append(thisDate)
1088
1122
1089 dateList.sort()
1123 dateList.sort()
1090
1124
1091 if walk:
1125 if walk:
1092 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1126 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1093 else:
1127 else:
1094 pattern_path = multi_path[0]
1128 pattern_path = multi_path[0]
1095
1129
1096 if path_empty:
1130 if path_empty:
1097 raise schainpy.admin.SchainError("[Reading] No *%s files in %s for %s to %s" % (ext, pattern_path, startDate, endDate))
1131 raise schainpy.admin.SchainError("[Reading] No *%s files in %s for %s to %s" % (ext, pattern_path, startDate, endDate))
1098 else:
1132 else:
1099 if not dateList:
1133 if not dateList:
1100 raise schainpy.admin.SchainError("[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" % (startDate, endDate, ext, path))
1134 raise schainpy.admin.SchainError("[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" % (startDate, endDate, ext, path))
1101
1135
1102 if include_path:
1136 if include_path:
1103 return dateList, pathList
1137 return dateList, pathList
1104
1138
1105 return dateList
1139 return dateList
1106
1140
1107 def setup(self, **kwargs):
1141 def setup(self, **kwargs):
1108
1142
1109 self.set_kwargs(**kwargs)
1143 self.set_kwargs(**kwargs)
1110 if not self.ext.startswith('.'):
1144 if not self.ext.startswith('.'):
1111 self.ext = '.{}'.format(self.ext)
1145 self.ext = '.{}'.format(self.ext)
1112
1146
1113 if self.server is not None:
1147 if self.server is not None:
1114 if 'tcp://' in self.server:
1148 if 'tcp://' in self.server:
1115 address = server
1149 address = server
1116 else:
1150 else:
1117 address = 'ipc:///tmp/%s' % self.server
1151 address = 'ipc:///tmp/%s' % self.server
1118 self.server = address
1152 self.server = address
1119 self.context = zmq.Context()
1153 self.context = zmq.Context()
1120 self.receiver = self.context.socket(zmq.PULL)
1154 self.receiver = self.context.socket(zmq.PULL)
1121 self.receiver.connect(self.server)
1155 self.receiver.connect(self.server)
1122 time.sleep(0.5)
1156 time.sleep(0.5)
1123 print('[Starting] ReceiverData from {}'.format(self.server))
1157 print('[Starting] ReceiverData from {}'.format(self.server))
1124 else:
1158 else:
1125 self.server = None
1159 self.server = None
1126 if self.path == None:
1160 if self.path == None:
1127 raise ValueError("[Reading] The path is not valid")
1161 raise ValueError("[Reading] The path is not valid")
1128
1162
1129 if self.online:
1163 if self.online:
1130 log.log("[Reading] Searching files in online mode...", self.name)
1164 log.log("[Reading] Searching files in online mode...", self.name)
1131
1165
1132 for nTries in range(self.nTries):
1166 for nTries in range(self.nTries):
1133 fullpath = self.searchFilesOnLine(self.path, self.startDate,
1167 fullpath = self.searchFilesOnLine(self.path, self.startDate,
1134 self.endDate, self.expLabel, self.ext, self.walk,
1168 self.endDate, self.expLabel, self.ext, self.walk,
1135 self.filefmt, self.folderfmt)
1169 self.filefmt, self.folderfmt)
1136
1170
1137 try:
1171 try:
1138 fullpath = next(fullpath)
1172 fullpath = next(fullpath)
1139 except:
1173 except:
1140 fullpath = None
1174 fullpath = None
1141
1175
1142 if fullpath:
1176 if fullpath:
1143 break
1177 break
1144
1178
1145 log.warning(
1179 log.warning(
1146 'Waiting {} sec for a valid file in {}: try {} ...'.format(
1180 'Waiting {} sec for a valid file in {}: try {} ...'.format(
1147 self.delay, self.path, nTries + 1),
1181 self.delay, self.path, nTries + 1),
1148 self.name)
1182 self.name)
1149 time.sleep(self.delay)
1183 time.sleep(self.delay)
1150
1184
1151 if not(fullpath):
1185 if not(fullpath):
1152 raise schainpy.admin.SchainError(
1186 raise schainpy.admin.SchainError(
1153 'There isn\'t any valid file in {}'.format(self.path))
1187 'There isn\'t any valid file in {}'.format(self.path))
1154
1188
1155 pathname, filename = os.path.split(fullpath)
1189 pathname, filename = os.path.split(fullpath)
1156 self.year = int(filename[1:5])
1190 self.year = int(filename[1:5])
1157 self.doy = int(filename[5:8])
1191 self.doy = int(filename[5:8])
1158 self.set = int(filename[8:11]) - 1
1192 self.set = int(filename[8:11]) - 1
1159 else:
1193 else:
1160 log.log("Searching files in {}".format(self.path), self.name)
1194 log.log("Searching files in {}".format(self.path), self.name)
1161 self.filenameList = self.searchFilesOffLine(self.path, self.startDate,
1195 self.filenameList = self.searchFilesOffLine(self.path, self.startDate,
1162 self.endDate, self.expLabel, self.ext, self.walk, self.filefmt, self.folderfmt)
1196 self.endDate, self.expLabel, self.ext, self.walk, self.filefmt, self.folderfmt)
1163
1197
1164 self.setNextFile()
1198 self.setNextFile()
1165
1199
1166 return
1200 return
1167
1201
1168 def getBasicHeader(self):
1202 def getBasicHeader(self):
1169
1203
1170 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond / \
1204 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond / \
1171 1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1205 1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1172
1206
1173 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1207 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1174
1208
1175 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1209 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1176
1210
1177 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1211 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1178
1212
1179 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1213 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1180
1214
1181 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1215 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1182
1216
1183 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
1217 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
1184
1218
1185 def getFirstHeader(self):
1219 def getFirstHeader(self):
1186
1220
1187 raise NotImplementedError
1221 raise NotImplementedError
1188
1222
1189 def getData(self):
1223 def getData(self):
1190
1224
1191 raise NotImplementedError
1225 raise NotImplementedError
1192
1226
1193 def hasNotDataInBuffer(self):
1227 def hasNotDataInBuffer(self):
1194
1228
1195 raise NotImplementedError
1229 raise NotImplementedError
1196
1230
1197 def readBlock(self):
1231 def readBlock(self):
1198
1232
1199 raise NotImplementedError
1233 raise NotImplementedError
1200
1234
1201 def isEndProcess(self):
1235 def isEndProcess(self):
1202
1236
1203 return self.flagNoMoreFiles
1237 return self.flagNoMoreFiles
1204
1238
1205 def printReadBlocks(self):
1239 def printReadBlocks(self):
1206
1240
1207 print("[Reading] Number of read blocks per file %04d" % self.nReadBlocks)
1241 print("[Reading] Number of read blocks per file %04d" % self.nReadBlocks)
1208
1242
1209 def printTotalBlocks(self):
1243 def printTotalBlocks(self):
1210
1244
1211 print("[Reading] Number of read blocks %04d" % self.nTotalBlocks)
1245 print("[Reading] Number of read blocks %04d" % self.nTotalBlocks)
1212
1246
1213 def run(self, **kwargs):
1247 def run(self, **kwargs):
1214 """
1248 """
1215
1249
1216 Arguments:
1250 Arguments:
1217 path :
1251 path :
1218 startDate :
1252 startDate :
1219 endDate :
1253 endDate :
1220 startTime :
1254 startTime :
1221 endTime :
1255 endTime :
1222 set :
1256 set :
1223 expLabel :
1257 expLabel :
1224 ext :
1258 ext :
1225 online :
1259 online :
1226 delay :
1260 delay :
1227 walk :
1261 walk :
1228 getblock :
1262 getblock :
1229 nTxs :
1263 nTxs :
1230 realtime :
1264 realtime :
1231 blocksize :
1265 blocksize :
1232 blocktime :
1266 blocktime :
1233 skip :
1267 skip :
1234 cursor :
1268 cursor :
1235 warnings :
1269 warnings :
1236 server :
1270 server :
1237 verbose :
1271 verbose :
1238 format :
1272 format :
1239 oneDDict :
1273 oneDDict :
1240 twoDDict :
1274 twoDDict :
1241 independentParam :
1275 independentParam :
1242 """
1276 """
1243
1277
1244 if not(self.isConfig):
1278 if not(self.isConfig):
1245 self.setup(**kwargs)
1279 self.setup(**kwargs)
1246 self.isConfig = True
1280 self.isConfig = True
1247 if self.server is None:
1281 if self.server is None:
1248 self.getData()
1282 self.getData()
1249 else:
1283 else:
1250 self.getFromServer()
1284 self.getFromServer()
1251
1285
1252
1286
1253 class JRODataWriter(Reader):
1287 class JRODataWriter(Reader):
1254
1288
1255 """
1289 """
1256 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1290 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1257 de los datos siempre se realiza por bloques.
1291 de los datos siempre se realiza por bloques.
1258 """
1292 """
1259
1293
1260 setFile = None
1294 setFile = None
1261 profilesPerBlock = None
1295 profilesPerBlock = None
1262 blocksPerFile = None
1296 blocksPerFile = None
1263 nWriteBlocks = 0
1297 nWriteBlocks = 0
1264 fileDate = None
1298 fileDate = None
1265
1299
1266 def __init__(self, dataOut=None):
1300 def __init__(self, dataOut=None):
1267 raise NotImplementedError
1301 raise NotImplementedError
1268
1302
1269 def hasAllDataInBuffer(self):
1303 def hasAllDataInBuffer(self):
1270 raise NotImplementedError
1304 raise NotImplementedError
1271
1305
1272 def setBlockDimension(self):
1306 def setBlockDimension(self):
1273 raise NotImplementedError
1307 raise NotImplementedError
1274
1308
1275 def writeBlock(self):
1309 def writeBlock(self):
1276 raise NotImplementedError
1310 raise NotImplementedError
1277
1311
1278 def putData(self):
1312 def putData(self):
1279 raise NotImplementedError
1313 raise NotImplementedError
1280
1314
1281 def getDtypeWidth(self):
1315 def getDtypeWidth(self):
1282
1316
1283 dtype_index = get_dtype_index(self.dtype)
1317 dtype_index = get_dtype_index(self.dtype)
1284 dtype_width = get_dtype_width(dtype_index)
1318 dtype_width = get_dtype_width(dtype_index)
1285
1319
1286 return dtype_width
1320 return dtype_width
1287
1321
1288 def getProcessFlags(self):
1322 def getProcessFlags(self):
1289
1323
1290 processFlags = 0
1324 processFlags = 0
1291
1325
1292 dtype_index = get_dtype_index(self.dtype)
1326 dtype_index = get_dtype_index(self.dtype)
1293 procflag_dtype = get_procflag_dtype(dtype_index)
1327 procflag_dtype = get_procflag_dtype(dtype_index)
1294
1328
1295 processFlags += procflag_dtype
1329 processFlags += procflag_dtype
1296
1330
1297 if self.dataOut.flagDecodeData:
1331 if self.dataOut.flagDecodeData:
1298 processFlags += PROCFLAG.DECODE_DATA
1332 processFlags += PROCFLAG.DECODE_DATA
1299
1333
1300 if self.dataOut.flagDeflipData:
1334 if self.dataOut.flagDeflipData:
1301 processFlags += PROCFLAG.DEFLIP_DATA
1335 processFlags += PROCFLAG.DEFLIP_DATA
1302
1336
1303 if self.dataOut.code is not None:
1337 if self.dataOut.code is not None:
1304 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1338 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1305
1339
1306 if self.dataOut.nCohInt > 1:
1340 if self.dataOut.nCohInt > 1:
1307 processFlags += PROCFLAG.COHERENT_INTEGRATION
1341 processFlags += PROCFLAG.COHERENT_INTEGRATION
1308
1342
1309 if self.dataOut.type == "Spectra":
1343 if self.dataOut.type == "Spectra":
1310 if self.dataOut.nIncohInt > 1:
1344 if self.dataOut.nIncohInt > 1:
1311 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1345 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1312
1346
1313 if self.dataOut.data_dc is not None:
1347 if self.dataOut.data_dc is not None:
1314 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1348 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1315
1349
1316 if self.dataOut.flagShiftFFT:
1350 if self.dataOut.flagShiftFFT:
1317 processFlags += PROCFLAG.SHIFT_FFT_DATA
1351 processFlags += PROCFLAG.SHIFT_FFT_DATA
1318
1352
1319 return processFlags
1353 return processFlags
1320
1354
1321 def setBasicHeader(self):
1355 def setBasicHeader(self):
1322
1356
1323 self.basicHeaderObj.size = self.basicHeaderSize # bytes
1357 self.basicHeaderObj.size = self.basicHeaderSize # bytes
1324 self.basicHeaderObj.version = self.versionFile
1358 self.basicHeaderObj.version = self.versionFile
1325 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1359 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1326 utc = numpy.floor(self.dataOut.utctime)
1360 utc = numpy.floor(self.dataOut.utctime)
1327 milisecond = (self.dataOut.utctime - utc) * 1000.0
1361 milisecond = (self.dataOut.utctime - utc) * 1000.0
1328 self.basicHeaderObj.utc = utc
1362 self.basicHeaderObj.utc = utc
1329 self.basicHeaderObj.miliSecond = milisecond
1363 self.basicHeaderObj.miliSecond = milisecond
1330 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1364 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1331 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1365 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1332 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1366 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1333
1367
1334 def setFirstHeader(self):
1368 def setFirstHeader(self):
1335 """
1369 """
1336 Obtiene una copia del First Header
1370 Obtiene una copia del First Header
1337
1371
1338 Affected:
1372 Affected:
1339
1373
1340 self.basicHeaderObj
1374 self.basicHeaderObj
1341 self.systemHeaderObj
1375 self.systemHeaderObj
1342 self.radarControllerHeaderObj
1376 self.radarControllerHeaderObj
1343 self.processingHeaderObj self.
1377 self.processingHeaderObj self.
1344
1378
1345 Return:
1379 Return:
1346 None
1380 None
1347 """
1381 """
1348
1382
1349 raise NotImplementedError
1383 raise NotImplementedError
1350
1384
1351 def __writeFirstHeader(self):
1385 def __writeFirstHeader(self):
1352 """
1386 """
1353 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1387 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1354
1388
1355 Affected:
1389 Affected:
1356 __dataType
1390 __dataType
1357
1391
1358 Return:
1392 Return:
1359 None
1393 None
1360 """
1394 """
1361
1395
1362 # CALCULAR PARAMETROS
1396 # CALCULAR PARAMETROS
1363
1397
1364 sizeLongHeader = self.systemHeaderObj.size + \
1398 sizeLongHeader = self.systemHeaderObj.size + \
1365 self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1399 self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1366 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1400 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1367
1401
1368 self.basicHeaderObj.write(self.fp)
1402 self.basicHeaderObj.write(self.fp)
1369 self.systemHeaderObj.write(self.fp)
1403 self.systemHeaderObj.write(self.fp)
1370 self.radarControllerHeaderObj.write(self.fp)
1404 self.radarControllerHeaderObj.write(self.fp)
1371 self.processingHeaderObj.write(self.fp)
1405 self.processingHeaderObj.write(self.fp)
1372
1406
1373 def __setNewBlock(self):
1407 def __setNewBlock(self):
1374 """
1408 """
1375 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1409 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1376
1410
1377 Return:
1411 Return:
1378 0 : si no pudo escribir nada
1412 0 : si no pudo escribir nada
1379 1 : Si escribio el Basic el First Header
1413 1 : Si escribio el Basic el First Header
1380 """
1414 """
1381 if self.fp == None:
1415 if self.fp == None:
1382 self.setNextFile()
1416 self.setNextFile()
1383
1417
1384 if self.flagIsNewFile:
1418 if self.flagIsNewFile:
1385 return 1
1419 return 1
1386
1420
1387 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1421 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1388 self.basicHeaderObj.write(self.fp)
1422 self.basicHeaderObj.write(self.fp)
1389 return 1
1423 return 1
1390
1424
1391 if not(self.setNextFile()):
1425 if not(self.setNextFile()):
1392 return 0
1426 return 0
1393
1427
1394 return 1
1428 return 1
1395
1429
1396 def writeNextBlock(self):
1430 def writeNextBlock(self):
1397 """
1431 """
1398 Selecciona el bloque siguiente de datos y los escribe en un file
1432 Selecciona el bloque siguiente de datos y los escribe en un file
1399
1433
1400 Return:
1434 Return:
1401 0 : Si no hizo pudo escribir el bloque de datos
1435 0 : Si no hizo pudo escribir el bloque de datos
1402 1 : Si no pudo escribir el bloque de datos
1436 1 : Si no pudo escribir el bloque de datos
1403 """
1437 """
1404 if not(self.__setNewBlock()):
1438 if not(self.__setNewBlock()):
1405 return 0
1439 return 0
1406
1440
1407 self.writeBlock()
1441 self.writeBlock()
1408
1442
1409 print("[Writing] Block No. %d/%d" % (self.blockIndex,
1443 print("[Writing] Block No. %d/%d" % (self.blockIndex,
1410 self.processingHeaderObj.dataBlocksPerFile))
1444 self.processingHeaderObj.dataBlocksPerFile))
1411
1445
1412 return 1
1446 return 1
1413
1447
1414 def setNextFile(self):
1448 def setNextFile(self):
1415 """Determina el siguiente file que sera escrito
1449 """Determina el siguiente file que sera escrito
1416
1450
1417 Affected:
1451 Affected:
1418 self.filename
1452 self.filename
1419 self.subfolder
1453 self.subfolder
1420 self.fp
1454 self.fp
1421 self.setFile
1455 self.setFile
1422 self.flagIsNewFile
1456 self.flagIsNewFile
1423
1457
1424 Return:
1458 Return:
1425 0 : Si el archivo no puede ser escrito
1459 0 : Si el archivo no puede ser escrito
1426 1 : Si el archivo esta listo para ser escrito
1460 1 : Si el archivo esta listo para ser escrito
1427 """
1461 """
1428 ext = self.ext
1462 ext = self.ext
1429 path = self.path
1463 path = self.path
1430
1464
1431 if self.fp != None:
1465 if self.fp != None:
1432 self.fp.close()
1466 self.fp.close()
1433
1467
1434 if not os.path.exists(path):
1468 if not os.path.exists(path):
1435 os.mkdir(path)
1469 os.mkdir(path)
1436
1470
1437 timeTuple = time.localtime(self.dataOut.utctime)
1471 timeTuple = time.localtime(self.dataOut.utctime)
1438 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year, timeTuple.tm_yday)
1472 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year, timeTuple.tm_yday)
1439
1473
1440 fullpath = os.path.join(path, subfolder)
1474 fullpath = os.path.join(path, subfolder)
1441 setFile = self.setFile
1475 setFile = self.setFile
1442
1476
1443 if not(os.path.exists(fullpath)):
1477 if not(os.path.exists(fullpath)):
1444 os.mkdir(fullpath)
1478 os.mkdir(fullpath)
1445 setFile = -1 # inicializo mi contador de seteo
1479 setFile = -1 # inicializo mi contador de seteo
1446 else:
1480 else:
1447 filesList = os.listdir(fullpath)
1481 filesList = os.listdir(fullpath)
1448 if len(filesList) > 0:
1482 if len(filesList) > 0:
1449 filesList = sorted(filesList, key=str.lower)
1483 filesList = sorted(filesList, key=str.lower)
1450 filen = filesList[-1]
1484 filen = filesList[-1]
1451 # el filename debera tener el siguiente formato
1485 # el filename debera tener el siguiente formato
1452 # 0 1234 567 89A BCDE (hex)
1486 # 0 1234 567 89A BCDE (hex)
1453 # x YYYY DDD SSS .ext
1487 # x YYYY DDD SSS .ext
1454 if isNumber(filen[8:11]):
1488 if isNumber(filen[8:11]):
1455 # inicializo mi contador de seteo al seteo del ultimo file
1489 # inicializo mi contador de seteo al seteo del ultimo file
1456 setFile = int(filen[8:11])
1490 setFile = int(filen[8:11])
1457 else:
1491 else:
1458 setFile = -1
1492 setFile = -1
1459 else:
1493 else:
1460 setFile = -1 # inicializo mi contador de seteo
1494 setFile = -1 # inicializo mi contador de seteo
1461
1495
1462 setFile += 1
1496 setFile += 1
1463
1497
1464 # If this is a new day it resets some values
1498 # If this is a new day it resets some values
1465 if self.dataOut.datatime.date() > self.fileDate:
1499 if self.dataOut.datatime.date() > self.fileDate:
1466 setFile = 0
1500 setFile = 0
1467 self.nTotalBlocks = 0
1501 self.nTotalBlocks = 0
1468
1502
1469 filen = '{}{:04d}{:03d}{:03d}{}'.format(
1503 filen = '{}{:04d}{:03d}{:03d}{}'.format(
1470 self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext)
1504 self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext)
1471
1505
1472 filename = os.path.join(path, subfolder, filen)
1506 filename = os.path.join(path, subfolder, filen)
1473
1507
1474 fp = open(filename, 'wb')
1508 fp = open(filename, 'wb')
1475
1509
1476 self.blockIndex = 0
1510 self.blockIndex = 0
1477 self.filename = filename
1511 self.filename = filename
1478 self.subfolder = subfolder
1512 self.subfolder = subfolder
1479 self.fp = fp
1513 self.fp = fp
1480 self.setFile = setFile
1514 self.setFile = setFile
1481 self.flagIsNewFile = 1
1515 self.flagIsNewFile = 1
1482 self.fileDate = self.dataOut.datatime.date()
1516 self.fileDate = self.dataOut.datatime.date()
1483 self.setFirstHeader()
1517 self.setFirstHeader()
1484
1518
1485 print('[Writing] Opening file: %s' % self.filename)
1519 print('[Writing] Opening file: %s' % self.filename)
1486
1520
1487 self.__writeFirstHeader()
1521 self.__writeFirstHeader()
1488
1522
1489 return 1
1523 return 1
1490
1524
1491 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1525 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1492 """
1526 """
1493 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1527 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1494
1528
1495 Inputs:
1529 Inputs:
1496 path : directory where data will be saved
1530 path : directory where data will be saved
1497 profilesPerBlock : number of profiles per block
1531 profilesPerBlock : number of profiles per block
1498 set : initial file set
1532 set : initial file set
1499 datatype : An integer number that defines data type:
1533 datatype : An integer number that defines data type:
1500 0 : int8 (1 byte)
1534 0 : int8 (1 byte)
1501 1 : int16 (2 bytes)
1535 1 : int16 (2 bytes)
1502 2 : int32 (4 bytes)
1536 2 : int32 (4 bytes)
1503 3 : int64 (8 bytes)
1537 3 : int64 (8 bytes)
1504 4 : float32 (4 bytes)
1538 4 : float32 (4 bytes)
1505 5 : double64 (8 bytes)
1539 5 : double64 (8 bytes)
1506
1540
1507 Return:
1541 Return:
1508 0 : Si no realizo un buen seteo
1542 0 : Si no realizo un buen seteo
1509 1 : Si realizo un buen seteo
1543 1 : Si realizo un buen seteo
1510 """
1544 """
1511
1545
1512 if ext == None:
1546 if ext == None:
1513 ext = self.ext
1547 ext = self.ext
1514
1548
1515 self.ext = ext.lower()
1549 self.ext = ext.lower()
1516
1550
1517 self.path = path
1551 self.path = path
1518
1552
1519 if set is None:
1553 if set is None:
1520 self.setFile = -1
1554 self.setFile = -1
1521 else:
1555 else:
1522 self.setFile = set - 1
1556 self.setFile = set - 1
1523
1557
1524 self.blocksPerFile = blocksPerFile
1558 self.blocksPerFile = blocksPerFile
1525 self.profilesPerBlock = profilesPerBlock
1559 self.profilesPerBlock = profilesPerBlock
1526 self.dataOut = dataOut
1560 self.dataOut = dataOut
1527 self.fileDate = self.dataOut.datatime.date()
1561 self.fileDate = self.dataOut.datatime.date()
1528 self.dtype = self.dataOut.dtype
1562 self.dtype = self.dataOut.dtype
1529
1563
1530 if datatype is not None:
1564 if datatype is not None:
1531 self.dtype = get_numpy_dtype(datatype)
1565 self.dtype = get_numpy_dtype(datatype)
1532
1566
1533 if not(self.setNextFile()):
1567 if not(self.setNextFile()):
1534 print("[Writing] There isn't a next file")
1568 print("[Writing] There isn't a next file")
1535 return 0
1569 return 0
1536
1570
1537 self.setBlockDimension()
1571 self.setBlockDimension()
1538
1572
1539 return 1
1573 return 1
1540
1574
1541 def run(self, dataOut, path, blocksPerFile=100, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1575 def run(self, dataOut, path, blocksPerFile=100, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1542
1576
1543 if not(self.isConfig):
1577 if not(self.isConfig):
1544
1578
1545 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock,
1579 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock,
1546 set=set, ext=ext, datatype=datatype, **kwargs)
1580 set=set, ext=ext, datatype=datatype, **kwargs)
1547 self.isConfig = True
1581 self.isConfig = True
1548
1582
1549 self.dataOut = dataOut
1583 self.dataOut = dataOut
1550 self.putData()
1584 self.putData()
1551 return self.dataOut
1585 return self.dataOut
1552
1586
1553 @MPDecorator
1587 @MPDecorator
1554 class printInfo(Operation):
1588 class printInfo(Operation):
1555
1589
1556 def __init__(self):
1590 def __init__(self):
1557
1591
1558 Operation.__init__(self)
1592 Operation.__init__(self)
1559 self.__printInfo = True
1593 self.__printInfo = True
1560
1594
1561 def run(self, dataOut, headers = ['systemHeaderObj', 'radarControllerHeaderObj', 'processingHeaderObj']):
1595 def run(self, dataOut, headers = ['systemHeaderObj', 'radarControllerHeaderObj', 'processingHeaderObj']):
1562 if self.__printInfo == False:
1596 if self.__printInfo == False:
1563 return
1597 return
1564
1598
1565 for header in headers:
1599 for header in headers:
1566 if hasattr(dataOut, header):
1600 if hasattr(dataOut, header):
1567 obj = getattr(dataOut, header)
1601 obj = getattr(dataOut, header)
1568 if hasattr(obj, 'printInfo'):
1602 if hasattr(obj, 'printInfo'):
1569 obj.printInfo()
1603 obj.printInfo()
1570 else:
1604 else:
1571 print(obj)
1605 print(obj)
1572 else:
1606 else:
1573 log.warning('Header {} Not found in object'.format(header))
1607 log.warning('Header {} Not found in object'.format(header))
1574
1608
1575 self.__printInfo = False
1609 self.__printInfo = False
@@ -1,793 +1,798
1 '''
1 '''
2 Created on Jul 3, 2014
2 Created on Jul 3, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 # SUBCHANNELS EN VEZ DE CHANNELS
6 # SUBCHANNELS EN VEZ DE CHANNELS
7 # BENCHMARKS -> PROBLEMAS CON ARCHIVOS GRANDES -> INCONSTANTE EN EL TIEMPO
7 # BENCHMARKS -> PROBLEMAS CON ARCHIVOS GRANDES -> INCONSTANTE EN EL TIEMPO
8 # ACTUALIZACION DE VERSION
8 # ACTUALIZACION DE VERSION
9 # HEADERS
9 # HEADERS
10 # MODULO DE ESCRITURA
10 # MODULO DE ESCRITURA
11 # METADATA
11 # METADATA
12
12
13 import os
13 import os
14 import time
14 import time
15 import datetime
15 import datetime
16 import numpy
16 import numpy
17 import timeit
17 import timeit
18 from fractions import Fraction
18 from fractions import Fraction
19 from time import time
19 from time import time
20 from time import sleep
20 from time import sleep
21
21
22 import schainpy.admin
22 import schainpy.admin
23 from schainpy.model.data.jroheaderIO import RadarControllerHeader, SystemHeader
23 from schainpy.model.data.jroheaderIO import RadarControllerHeader, SystemHeader
24 from schainpy.model.data.jrodata import Voltage
24 from schainpy.model.data.jrodata import Voltage
25 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
25 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
26
26
27 import pickle
27 import pickle
28 try:
28 try:
29 import digital_rf
29 import digital_rf
30 except:
30 except:
31 pass
31 pass
32
32
33
33
34 class DigitalRFReader(ProcessingUnit):
34 class DigitalRFReader(ProcessingUnit):
35 '''
35 '''
36 classdocs
36 classdocs
37 '''
37 '''
38
38
39 def __init__(self):
39 def __init__(self):
40 '''
40 '''
41 Constructor
41 Constructor
42 '''
42 '''
43
43
44 ProcessingUnit.__init__(self)
44 ProcessingUnit.__init__(self)
45
45
46 self.dataOut = Voltage()
46 self.dataOut = Voltage()
47 self.__printInfo = True
47 self.__printInfo = True
48 self.__flagDiscontinuousBlock = False
48 self.__flagDiscontinuousBlock = False
49 self.__bufferIndex = 9999999
49 self.__bufferIndex = 9999999
50 self.__codeType = 0
50 self.__codeType = 0
51 self.__ippKm = None
51 self.__ippKm = None
52 self.__nCode = None
52 self.__nCode = None
53 self.__nBaud = None
53 self.__nBaud = None
54 self.__code = None
54 self.__code = None
55 self.dtype = None
55 self.dtype = None
56 self.oldAverage = None
56 self.oldAverage = None
57 self.path = None
57 self.path = None
58
58
59 def close(self):
59 def close(self):
60 print('Average of writing to digital rf format is ', self.oldAverage * 1000)
60 print('Average of writing to digital rf format is ', self.oldAverage * 1000)
61 return
61 return
62
62
63 def __getCurrentSecond(self):
63 def __getCurrentSecond(self):
64
64
65 return self.__thisUnixSample / self.__sample_rate
65 return self.__thisUnixSample / self.__sample_rate
66
66
67 thisSecond = property(__getCurrentSecond, "I'm the 'thisSecond' property.")
67 thisSecond = property(__getCurrentSecond, "I'm the 'thisSecond' property.")
68
68
69 def __setFileHeader(self):
69 def __setFileHeader(self):
70 '''
70 '''
71 In this method will be initialized every parameter of dataOut object (header, no data)
71 In this method will be initialized every parameter of dataOut object (header, no data)
72 '''
72 '''
73 ippSeconds = 1.0 * self.__nSamples / self.__sample_rate
73 ippSeconds = 1.0 * self.__nSamples / self.__sample_rate
74
74
75 nProfiles = 1.0 / ippSeconds # Number of profiles in one second
75 nProfiles = 1.0 / ippSeconds # Number of profiles in one second
76
76
77 try:
77 try:
78 self.dataOut.radarControllerHeaderObj = RadarControllerHeader(
78 self.dataOut.radarControllerHeaderObj = RadarControllerHeader(
79 self.__radarControllerHeader)
79 self.__radarControllerHeader)
80 except:
80 except:
81 self.dataOut.radarControllerHeaderObj = RadarControllerHeader(
81 self.dataOut.radarControllerHeaderObj = RadarControllerHeader(
82 txA=0,
82 txA=0,
83 txB=0,
83 txB=0,
84 nWindows=1,
84 nWindows=1,
85 nHeights=self.__nSamples,
85 nHeights=self.__nSamples,
86 firstHeight=self.__firstHeigth,
86 firstHeight=self.__firstHeigth,
87 deltaHeight=self.__deltaHeigth,
87 deltaHeight=self.__deltaHeigth,
88 codeType=self.__codeType,
88 codeType=self.__codeType,
89 nCode=self.__nCode, nBaud=self.__nBaud,
89 nCode=self.__nCode, nBaud=self.__nBaud,
90 code=self.__code)
90 code=self.__code)
91
91
92 try:
92 try:
93 self.dataOut.systemHeaderObj = SystemHeader(self.__systemHeader)
93 self.dataOut.systemHeaderObj = SystemHeader(self.__systemHeader)
94 except:
94 except:
95 self.dataOut.systemHeaderObj = SystemHeader(nSamples=self.__nSamples,
95 self.dataOut.systemHeaderObj = SystemHeader(nSamples=self.__nSamples,
96 nProfiles=nProfiles,
96 nProfiles=nProfiles,
97 nChannels=len(
97 nChannels=len(
98 self.__channelList),
98 self.__channelList),
99 adcResolution=14)
99 adcResolution=14)
100 self.dataOut.type = "Voltage"
100 self.dataOut.type = "Voltage"
101
101
102 self.dataOut.data = None
102 self.dataOut.data = None
103
103
104 self.dataOut.dtype = self.dtype
104 self.dataOut.dtype = self.dtype
105
105
106 # self.dataOut.nChannels = 0
106 # self.dataOut.nChannels = 0
107
107
108 # self.dataOut.nHeights = 0
108 # self.dataOut.nHeights = 0
109
109
110 self.dataOut.nProfiles = int(nProfiles)
110 self.dataOut.nProfiles = int(nProfiles)
111
111
112 self.dataOut.heightList = self.__firstHeigth + \
112 self.dataOut.heightList = self.__firstHeigth + \
113 numpy.arange(self.__nSamples, dtype=numpy.float) * \
113 numpy.arange(self.__nSamples, dtype=numpy.float) * \
114 self.__deltaHeigth
114 self.__deltaHeigth
115
115
116 self.dataOut.channelList = list(range(self.__num_subchannels))
116 #self.dataOut.channelList = list(range(self.__num_subchannels))
117
117 self.dataOut.channelList = list(range(len(self.__channelList)))
118 self.dataOut.blocksize = self.dataOut.nChannels * self.dataOut.nHeights
118 self.dataOut.blocksize = self.dataOut.nChannels * self.dataOut.nHeights
119
119
120 # self.dataOut.channelIndexList = None
120 # self.dataOut.channelIndexList = None
121
121
122 self.dataOut.flagNoData = True
122 self.dataOut.flagNoData = True
123
123
124 self.dataOut.flagDataAsBlock = False
124 self.dataOut.flagDataAsBlock = False
125 # Set to TRUE if the data is discontinuous
125 # Set to TRUE if the data is discontinuous
126 self.dataOut.flagDiscontinuousBlock = False
126 self.dataOut.flagDiscontinuousBlock = False
127
127
128 self.dataOut.utctime = None
128 self.dataOut.utctime = None
129
129
130 # timezone like jroheader, difference in minutes between UTC and localtime
130 # timezone like jroheader, difference in minutes between UTC and localtime
131 self.dataOut.timeZone = self.__timezone / 60
131 self.dataOut.timeZone = self.__timezone / 60
132
132
133 self.dataOut.dstFlag = 0
133 self.dataOut.dstFlag = 0
134
134
135 self.dataOut.errorCount = 0
135 self.dataOut.errorCount = 0
136
136
137 try:
137 try:
138 self.dataOut.nCohInt = self.fixed_metadata_dict.get(
138 self.dataOut.nCohInt = self.fixed_metadata_dict.get(
139 'nCohInt', self.nCohInt)
139 'nCohInt', self.nCohInt)
140
140
141 # asumo que la data esta decodificada
141 # asumo que la data esta decodificada
142 self.dataOut.flagDecodeData = self.fixed_metadata_dict.get(
142 self.dataOut.flagDecodeData = self.fixed_metadata_dict.get(
143 'flagDecodeData', self.flagDecodeData)
143 'flagDecodeData', self.flagDecodeData)
144
144
145 # asumo que la data esta sin flip
145 # asumo que la data esta sin flip
146 self.dataOut.flagDeflipData = self.fixed_metadata_dict['flagDeflipData']
146 self.dataOut.flagDeflipData = self.fixed_metadata_dict['flagDeflipData']
147
147
148 self.dataOut.flagShiftFFT = self.fixed_metadata_dict['flagShiftFFT']
148 self.dataOut.flagShiftFFT = self.fixed_metadata_dict['flagShiftFFT']
149
149
150 self.dataOut.useLocalTime = self.fixed_metadata_dict['useLocalTime']
150 self.dataOut.useLocalTime = self.fixed_metadata_dict['useLocalTime']
151 except:
151 except:
152 pass
152 pass
153
153
154 self.dataOut.ippSeconds = ippSeconds
154 self.dataOut.ippSeconds = ippSeconds
155
155
156 # Time interval between profiles
156 # Time interval between profiles
157 # self.dataOut.timeInterval = self.dataOut.ippSeconds * self.dataOut.nCohInt
157 # self.dataOut.timeInterval = self.dataOut.ippSeconds * self.dataOut.nCohInt
158
158
159 self.dataOut.frequency = self.__frequency
159 self.dataOut.frequency = self.__frequency
160
160
161 self.dataOut.realtime = self.__online
161 self.dataOut.realtime = self.__online
162
162
163 def findDatafiles(self, path, startDate=None, endDate=None):
163 def findDatafiles(self, path, startDate=None, endDate=None):
164
164
165 if not os.path.isdir(path):
165 if not os.path.isdir(path):
166 return []
166 return []
167
167
168 try:
168 try:
169 digitalReadObj = digital_rf.DigitalRFReader(
169 digitalReadObj = digital_rf.DigitalRFReader(
170 path, load_all_metadata=True)
170 path, load_all_metadata=True)
171 except:
171 except:
172 digitalReadObj = digital_rf.DigitalRFReader(path)
172 digitalReadObj = digital_rf.DigitalRFReader(path)
173
173
174 channelNameList = digitalReadObj.get_channels()
174 channelNameList = digitalReadObj.get_channels()
175
175
176 if not channelNameList:
176 if not channelNameList:
177 return []
177 return []
178
178
179 metadata_dict = digitalReadObj.get_rf_file_metadata(channelNameList[0])
179 metadata_dict = digitalReadObj.get_rf_file_metadata(channelNameList[0])
180
180
181 sample_rate = metadata_dict['sample_rate'][0]
181 sample_rate = metadata_dict['sample_rate'][0]
182
182
183 this_metadata_file = digitalReadObj.get_metadata(channelNameList[0])
183 this_metadata_file = digitalReadObj.get_metadata(channelNameList[0])
184
184
185 try:
185 try:
186 timezone = this_metadata_file['timezone'].value
186 timezone = this_metadata_file['timezone'].value
187 except:
187 except:
188 timezone = 0
188 timezone = 0
189
189
190 startUTCSecond, endUTCSecond = digitalReadObj.get_bounds(
190 startUTCSecond, endUTCSecond = digitalReadObj.get_bounds(
191 channelNameList[0]) / sample_rate - timezone
191 channelNameList[0]) / sample_rate - timezone
192
192
193 startDatetime = datetime.datetime.utcfromtimestamp(startUTCSecond)
193 startDatetime = datetime.datetime.utcfromtimestamp(startUTCSecond)
194 endDatatime = datetime.datetime.utcfromtimestamp(endUTCSecond)
194 endDatatime = datetime.datetime.utcfromtimestamp(endUTCSecond)
195
195
196 if not startDate:
196 if not startDate:
197 startDate = startDatetime.date()
197 startDate = startDatetime.date()
198
198
199 if not endDate:
199 if not endDate:
200 endDate = endDatatime.date()
200 endDate = endDatatime.date()
201
201
202 dateList = []
202 dateList = []
203
203
204 thisDatetime = startDatetime
204 thisDatetime = startDatetime
205
205
206 while(thisDatetime <= endDatatime):
206 while(thisDatetime <= endDatatime):
207
207
208 thisDate = thisDatetime.date()
208 thisDate = thisDatetime.date()
209
209
210 if thisDate < startDate:
210 if thisDate < startDate:
211 continue
211 continue
212
212
213 if thisDate > endDate:
213 if thisDate > endDate:
214 break
214 break
215
215
216 dateList.append(thisDate)
216 dateList.append(thisDate)
217 thisDatetime += datetime.timedelta(1)
217 thisDatetime += datetime.timedelta(1)
218
218
219 return dateList
219 return dateList
220
220
221 def setup(self, path=None,
221 def setup(self, path=None,
222 startDate=None,
222 startDate=None,
223 endDate=None,
223 endDate=None,
224 startTime=datetime.time(0, 0, 0),
224 startTime=datetime.time(0, 0, 0),
225 endTime=datetime.time(23, 59, 59),
225 endTime=datetime.time(23, 59, 59),
226 channelList=None,
226 channelList=None,
227 nSamples=None,
227 nSamples=None,
228 online=False,
228 online=False,
229 delay=60,
229 delay=60,
230 buffer_size=1024,
230 buffer_size=1024,
231 ippKm=None,
231 ippKm=None,
232 nCohInt=1,
232 nCohInt=1,
233 nCode=1,
233 nCode=1,
234 nBaud=1,
234 nBaud=1,
235 flagDecodeData=False,
235 flagDecodeData=False,
236 code=numpy.ones((1, 1), dtype=numpy.int),
236 code=numpy.ones((1, 1), dtype=numpy.int),
237 **kwargs):
237 **kwargs):
238 '''
238 '''
239 In this method we should set all initial parameters.
239 In this method we should set all initial parameters.
240
240
241 Inputs:
241 Inputs:
242 path
242 path
243 startDate
243 startDate
244 endDate
244 endDate
245 startTime
245 startTime
246 endTime
246 endTime
247 set
247 set
248 expLabel
248 expLabel
249 ext
249 ext
250 online
250 online
251 delay
251 delay
252 '''
252 '''
253 self.path = path
253 self.path = path
254 self.nCohInt = nCohInt
254 self.nCohInt = nCohInt
255 self.flagDecodeData = flagDecodeData
255 self.flagDecodeData = flagDecodeData
256 self.i = 0
256 self.i = 0
257 if not os.path.isdir(path):
257 if not os.path.isdir(path):
258 raise ValueError("[Reading] Directory %s does not exist" % path)
258 raise ValueError("[Reading] Directory %s does not exist" % path)
259
259
260 try:
260 try:
261 self.digitalReadObj = digital_rf.DigitalRFReader(
261 self.digitalReadObj = digital_rf.DigitalRFReader(
262 path, load_all_metadata=True)
262 path, load_all_metadata=True)
263 except:
263 except:
264 self.digitalReadObj = digital_rf.DigitalRFReader(path)
264 self.digitalReadObj = digital_rf.DigitalRFReader(path)
265
265
266 channelNameList = self.digitalReadObj.get_channels()
266 channelNameList = self.digitalReadObj.get_channels()
267
267
268 if not channelNameList:
268 if not channelNameList:
269 raise ValueError("[Reading] Directory %s does not have any files" % path)
269 raise ValueError("[Reading] Directory %s does not have any files" % path)
270
270
271 if not channelList:
271 if not channelList:
272 channelList = list(range(len(channelNameList)))
272 channelList = list(range(len(channelNameList)))
273
273
274 ########## Reading metadata ######################
274 ########## Reading metadata ######################
275
275
276 top_properties = self.digitalReadObj.get_properties(
276 top_properties = self.digitalReadObj.get_properties(
277 channelNameList[channelList[0]])
277 channelNameList[channelList[0]])
278
278
279 self.__num_subchannels = top_properties['num_subchannels']
279 self.__num_subchannels = top_properties['num_subchannels']
280 self.__sample_rate = 1.0 * \
280 self.__sample_rate = 1.0 * \
281 top_properties['sample_rate_numerator'] / \
281 top_properties['sample_rate_numerator'] / \
282 top_properties['sample_rate_denominator']
282 top_properties['sample_rate_denominator']
283 # self.__samples_per_file = top_properties['samples_per_file'][0]
283 # self.__samples_per_file = top_properties['samples_per_file'][0]
284 self.__deltaHeigth = 1e6 * 0.15 / self.__sample_rate # why 0.15?
284 self.__deltaHeigth = 1e6 * 0.15 / self.__sample_rate # why 0.15?
285
285
286 this_metadata_file = self.digitalReadObj.get_digital_metadata(
286 this_metadata_file = self.digitalReadObj.get_digital_metadata(
287 channelNameList[channelList[0]])
287 channelNameList[channelList[0]])
288 metadata_bounds = this_metadata_file.get_bounds()
288 metadata_bounds = this_metadata_file.get_bounds()
289 self.fixed_metadata_dict = this_metadata_file.read(
289 self.fixed_metadata_dict = this_metadata_file.read(
290 metadata_bounds[0])[metadata_bounds[0]] # GET FIRST HEADER
290 metadata_bounds[0])[metadata_bounds[0]] # GET FIRST HEADER
291
291
292 try:
292 try:
293 self.__processingHeader = self.fixed_metadata_dict['processingHeader']
293 self.__processingHeader = self.fixed_metadata_dict['processingHeader']
294 self.__radarControllerHeader = self.fixed_metadata_dict['radarControllerHeader']
294 self.__radarControllerHeader = self.fixed_metadata_dict['radarControllerHeader']
295 self.__systemHeader = self.fixed_metadata_dict['systemHeader']
295 self.__systemHeader = self.fixed_metadata_dict['systemHeader']
296 self.dtype = pickle.loads(self.fixed_metadata_dict['dtype'])
296 self.dtype = pickle.loads(self.fixed_metadata_dict['dtype'])
297 except:
297 except:
298 pass
298 pass
299
299
300 self.__frequency = None
300 self.__frequency = None
301
301
302 self.__frequency = self.fixed_metadata_dict.get('frequency', 1)
302 self.__frequency = self.fixed_metadata_dict.get('frequency', 1)
303
303
304 self.__timezone = self.fixed_metadata_dict.get('timezone', 18000)
304 self.__timezone = self.fixed_metadata_dict.get('timezone', 18000)
305
305
306 try:
306 try:
307 nSamples = self.fixed_metadata_dict['nSamples']
307 nSamples = self.fixed_metadata_dict['nSamples']
308 except:
308 except:
309 nSamples = None
309 nSamples = None
310
310
311 self.__firstHeigth = 0
311 self.__firstHeigth = 0
312
312
313 try:
313 try:
314 codeType = self.__radarControllerHeader['codeType']
314 codeType = self.__radarControllerHeader['codeType']
315 except:
315 except:
316 codeType = 0
316 codeType = 0
317
317
318 try:
318 try:
319 if codeType:
319 if codeType:
320 nCode = self.__radarControllerHeader['nCode']
320 nCode = self.__radarControllerHeader['nCode']
321 nBaud = self.__radarControllerHeader['nBaud']
321 nBaud = self.__radarControllerHeader['nBaud']
322 code = self.__radarControllerHeader['code']
322 code = self.__radarControllerHeader['code']
323 except:
323 except:
324 pass
324 pass
325
325
326 if not ippKm:
326 if not ippKm:
327 try:
327 try:
328 # seconds to km
328 # seconds to km
329 ippKm = self.__radarControllerHeader['ipp']
329 ippKm = self.__radarControllerHeader['ipp']
330 except:
330 except:
331 ippKm = None
331 ippKm = None
332 ####################################################
332 ####################################################
333 self.__ippKm = ippKm
333 self.__ippKm = ippKm
334 startUTCSecond = None
334 startUTCSecond = None
335 endUTCSecond = None
335 endUTCSecond = None
336
336
337 if startDate:
337 if startDate:
338 startDatetime = datetime.datetime.combine(startDate, startTime)
338 startDatetime = datetime.datetime.combine(startDate, startTime)
339 startUTCSecond = (
339 startUTCSecond = (
340 startDatetime - datetime.datetime(1970, 1, 1)).total_seconds() + self.__timezone
340 startDatetime - datetime.datetime(1970, 1, 1)).total_seconds() + self.__timezone
341
341
342 if endDate:
342 if endDate:
343 endDatetime = datetime.datetime.combine(endDate, endTime)
343 endDatetime = datetime.datetime.combine(endDate, endTime)
344 endUTCSecond = (endDatetime - datetime.datetime(1970,
344 endUTCSecond = (endDatetime - datetime.datetime(1970,
345 1, 1)).total_seconds() + self.__timezone
345 1, 1)).total_seconds() + self.__timezone
346
346
347
348 print(startUTCSecond,endUTCSecond)
347 start_index, end_index = self.digitalReadObj.get_bounds(
349 start_index, end_index = self.digitalReadObj.get_bounds(
348 channelNameList[channelList[0]])
350 channelNameList[channelList[0]])
349
351
352 print("*****",start_index,end_index)
350 if not startUTCSecond:
353 if not startUTCSecond:
351 startUTCSecond = start_index / self.__sample_rate
354 startUTCSecond = start_index / self.__sample_rate
352
355
353 if start_index > startUTCSecond * self.__sample_rate:
356 if start_index > startUTCSecond * self.__sample_rate:
354 startUTCSecond = start_index / self.__sample_rate
357 startUTCSecond = start_index / self.__sample_rate
355
358
356 if not endUTCSecond:
359 if not endUTCSecond:
357 endUTCSecond = end_index / self.__sample_rate
360 endUTCSecond = end_index / self.__sample_rate
358
361
359 if end_index < endUTCSecond * self.__sample_rate:
362 if end_index < endUTCSecond * self.__sample_rate:
360 endUTCSecond = end_index / self.__sample_rate
363 endUTCSecond = end_index / self.__sample_rate
361 if not nSamples:
364 if not nSamples:
362 if not ippKm:
365 if not ippKm:
363 raise ValueError("[Reading] nSamples or ippKm should be defined")
366 raise ValueError("[Reading] nSamples or ippKm should be defined")
364 nSamples = int(ippKm / (1e6 * 0.15 / self.__sample_rate))
367 nSamples = int(ippKm / (1e6 * 0.15 / self.__sample_rate))
365 channelBoundList = []
368 channelBoundList = []
366 channelNameListFiltered = []
369 channelNameListFiltered = []
367
370
368 for thisIndexChannel in channelList:
371 for thisIndexChannel in channelList:
369 thisChannelName = channelNameList[thisIndexChannel]
372 thisChannelName = channelNameList[thisIndexChannel]
370 start_index, end_index = self.digitalReadObj.get_bounds(
373 start_index, end_index = self.digitalReadObj.get_bounds(
371 thisChannelName)
374 thisChannelName)
372 channelBoundList.append((start_index, end_index))
375 channelBoundList.append((start_index, end_index))
373 channelNameListFiltered.append(thisChannelName)
376 channelNameListFiltered.append(thisChannelName)
374
377
375 self.profileIndex = 0
378 self.profileIndex = 0
376 self.i = 0
379 self.i = 0
377 self.__delay = delay
380 self.__delay = delay
378
381
379 self.__codeType = codeType
382 self.__codeType = codeType
380 self.__nCode = nCode
383 self.__nCode = nCode
381 self.__nBaud = nBaud
384 self.__nBaud = nBaud
382 self.__code = code
385 self.__code = code
383
386
384 self.__datapath = path
387 self.__datapath = path
385 self.__online = online
388 self.__online = online
386 self.__channelList = channelList
389 self.__channelList = channelList
387 self.__channelNameList = channelNameListFiltered
390 self.__channelNameList = channelNameListFiltered
388 self.__channelBoundList = channelBoundList
391 self.__channelBoundList = channelBoundList
389 self.__nSamples = nSamples
392 self.__nSamples = nSamples
390 self.__samples_to_read = int(nSamples) # FIJO: AHORA 40
393 self.__samples_to_read = int(nSamples) # FIJO: AHORA 40
391 self.__nChannels = len(self.__channelList)
394 self.__nChannels = len(self.__channelList)
392
395
393 self.__startUTCSecond = startUTCSecond
396 self.__startUTCSecond = startUTCSecond
394 self.__endUTCSecond = endUTCSecond
397 self.__endUTCSecond = endUTCSecond
395
398
396 self.__timeInterval = 1.0 * self.__samples_to_read / \
399 self.__timeInterval = 1.0 * self.__samples_to_read / \
397 self.__sample_rate # Time interval
400 self.__sample_rate # Time interval
398
401
399 if online:
402 if online:
400 # self.__thisUnixSample = int(endUTCSecond*self.__sample_rate - 4*self.__samples_to_read)
403 # self.__thisUnixSample = int(endUTCSecond*self.__sample_rate - 4*self.__samples_to_read)
401 startUTCSecond = numpy.floor(endUTCSecond)
404 startUTCSecond = numpy.floor(endUTCSecond)
402
405
403 # por que en el otro metodo lo primero q se hace es sumar samplestoread
406 # por que en el otro metodo lo primero q se hace es sumar samplestoread
404 self.__thisUnixSample = int(startUTCSecond * self.__sample_rate) - self.__samples_to_read
407 self.__thisUnixSample = int(startUTCSecond * self.__sample_rate) - self.__samples_to_read
405
408
406 self.__data_buffer = numpy.zeros(
409 #self.__data_buffer = numpy.zeros(
407 (self.__num_subchannels, self.__samples_to_read), dtype=numpy.complex)
410 # (self.__num_subchannels, self.__samples_to_read), dtype=numpy.complex)
411 self.__data_buffer = numpy.zeros((int(len(channelList)), self.__samples_to_read), dtype=numpy.complex)
412
408
413
409 self.__setFileHeader()
414 self.__setFileHeader()
410 self.isConfig = True
415 self.isConfig = True
411
416
412 print("[Reading] Digital RF Data was found from %s to %s " % (
417 print("[Reading] Digital RF Data was found from %s to %s " % (
413 datetime.datetime.utcfromtimestamp(
418 datetime.datetime.utcfromtimestamp(
414 self.__startUTCSecond - self.__timezone),
419 self.__startUTCSecond - self.__timezone),
415 datetime.datetime.utcfromtimestamp(
420 datetime.datetime.utcfromtimestamp(
416 self.__endUTCSecond - self.__timezone)
421 self.__endUTCSecond - self.__timezone)
417 ))
422 ))
418
423
419 print("[Reading] Starting process from %s to %s" % (datetime.datetime.utcfromtimestamp(startUTCSecond - self.__timezone),
424 print("[Reading] Starting process from %s to %s" % (datetime.datetime.utcfromtimestamp(startUTCSecond - self.__timezone),
420 datetime.datetime.utcfromtimestamp(
425 datetime.datetime.utcfromtimestamp(
421 endUTCSecond - self.__timezone)
426 endUTCSecond - self.__timezone)
422 ))
427 ))
423 self.oldAverage = None
428 self.oldAverage = None
424 self.count = 0
429 self.count = 0
425 self.executionTime = 0
430 self.executionTime = 0
426
431
427 def __reload(self):
432 def __reload(self):
428 # print
433 # print
429 # print "%s not in range [%s, %s]" %(
434 # print "%s not in range [%s, %s]" %(
430 # datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
435 # datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
431 # datetime.datetime.utcfromtimestamp(self.__startUTCSecond - self.__timezone),
436 # datetime.datetime.utcfromtimestamp(self.__startUTCSecond - self.__timezone),
432 # datetime.datetime.utcfromtimestamp(self.__endUTCSecond - self.__timezone)
437 # datetime.datetime.utcfromtimestamp(self.__endUTCSecond - self.__timezone)
433 # )
438 # )
434 print("[Reading] reloading metadata ...")
439 print("[Reading] reloading metadata ...")
435
440
436 try:
441 try:
437 self.digitalReadObj.reload(complete_update=True)
442 self.digitalReadObj.reload(complete_update=True)
438 except:
443 except:
439 self.digitalReadObj = digital_rf.DigitalRFReader(self.path)
444 self.digitalReadObj = digital_rf.DigitalRFReader(self.path)
440
445
441 start_index, end_index = self.digitalReadObj.get_bounds(
446 start_index, end_index = self.digitalReadObj.get_bounds(
442 self.__channelNameList[self.__channelList[0]])
447 self.__channelNameList[self.__channelList[0]])
443
448
444 if start_index > self.__startUTCSecond * self.__sample_rate:
449 if start_index > self.__startUTCSecond * self.__sample_rate:
445 self.__startUTCSecond = 1.0 * start_index / self.__sample_rate
450 self.__startUTCSecond = 1.0 * start_index / self.__sample_rate
446
451
447 if end_index > self.__endUTCSecond * self.__sample_rate:
452 if end_index > self.__endUTCSecond * self.__sample_rate:
448 self.__endUTCSecond = 1.0 * end_index / self.__sample_rate
453 self.__endUTCSecond = 1.0 * end_index / self.__sample_rate
449 print()
454 print()
450 print("[Reading] New timerange found [%s, %s] " % (
455 print("[Reading] New timerange found [%s, %s] " % (
451 datetime.datetime.utcfromtimestamp(
456 datetime.datetime.utcfromtimestamp(
452 self.__startUTCSecond - self.__timezone),
457 self.__startUTCSecond - self.__timezone),
453 datetime.datetime.utcfromtimestamp(
458 datetime.datetime.utcfromtimestamp(
454 self.__endUTCSecond - self.__timezone)
459 self.__endUTCSecond - self.__timezone)
455 ))
460 ))
456
461
457 return True
462 return True
458
463
459 return False
464 return False
460
465
461 def timeit(self, toExecute):
466 def timeit(self, toExecute):
462 t0 = time.time()
467 t0 = time.time()
463 toExecute()
468 toExecute()
464 self.executionTime = time.time() - t0
469 self.executionTime = time.time() - t0
465 if self.oldAverage is None:
470 if self.oldAverage is None:
466 self.oldAverage = self.executionTime
471 self.oldAverage = self.executionTime
467 self.oldAverage = (self.executionTime + self.count *
472 self.oldAverage = (self.executionTime + self.count *
468 self.oldAverage) / (self.count + 1.0)
473 self.oldAverage) / (self.count + 1.0)
469 self.count = self.count + 1.0
474 self.count = self.count + 1.0
470 return
475 return
471
476
472 def __readNextBlock(self, seconds=30, volt_scale=1):
477 def __readNextBlock(self, seconds=30, volt_scale=1):
473 '''
478 '''
474 '''
479 '''
475
480
476 # Set the next data
481 # Set the next data
477 self.__flagDiscontinuousBlock = False
482 self.__flagDiscontinuousBlock = False
478 self.__thisUnixSample += self.__samples_to_read
483 self.__thisUnixSample += self.__samples_to_read
479
484
480 if self.__thisUnixSample + 2 * self.__samples_to_read > self.__endUTCSecond * self.__sample_rate:
485 if self.__thisUnixSample + 2 * self.__samples_to_read > self.__endUTCSecond * self.__sample_rate:
481 print ("[Reading] There are no more data into selected time-range")
486 print ("[Reading] There are no more data into selected time-range")
482 if self.__online:
487 if self.__online:
483 sleep(3)
488 sleep(3)
484 self.__reload()
489 self.__reload()
485 else:
490 else:
486 return False
491 return False
487
492
488 if self.__thisUnixSample + 2 * self.__samples_to_read > self.__endUTCSecond * self.__sample_rate:
493 if self.__thisUnixSample + 2 * self.__samples_to_read > self.__endUTCSecond * self.__sample_rate:
489 return False
494 return False
490 self.__thisUnixSample -= self.__samples_to_read
495 self.__thisUnixSample -= self.__samples_to_read
491
496
492 indexChannel = 0
497 indexChannel = 0
493
498
494 dataOk = False
499 dataOk = False
495
500
496 for thisChannelName in self.__channelNameList: # TODO VARIOS CHANNELS?
501 for thisChannelName in self.__channelNameList: # TODO VARIOS CHANNELS?
497 for indexSubchannel in range(self.__num_subchannels):
502 for indexSubchannel in range(self.__num_subchannels):
498 try:
503 try:
499 t0 = time()
504 t0 = time()
500 result = self.digitalReadObj.read_vector_c81d(self.__thisUnixSample,
505 result = self.digitalReadObj.read_vector_c81d(self.__thisUnixSample,
501 self.__samples_to_read,
506 self.__samples_to_read,
502 thisChannelName, sub_channel=indexSubchannel)
507 thisChannelName, sub_channel=indexSubchannel)
503 self.executionTime = time() - t0
508 self.executionTime = time() - t0
504 if self.oldAverage is None:
509 if self.oldAverage is None:
505 self.oldAverage = self.executionTime
510 self.oldAverage = self.executionTime
506 self.oldAverage = (
511 self.oldAverage = (
507 self.executionTime + self.count * self.oldAverage) / (self.count + 1.0)
512 self.executionTime + self.count * self.oldAverage) / (self.count + 1.0)
508 self.count = self.count + 1.0
513 self.count = self.count + 1.0
509
514
510 except IOError as e:
515 except IOError as e:
511 # read next profile
516 # read next profile
512 self.__flagDiscontinuousBlock = True
517 self.__flagDiscontinuousBlock = True
513 print("[Reading] %s" % datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone), e)
518 print("[Reading] %s" % datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone), e)
514 break
519 break
515
520
516 if result.shape[0] != self.__samples_to_read:
521 if result.shape[0] != self.__samples_to_read:
517 self.__flagDiscontinuousBlock = True
522 self.__flagDiscontinuousBlock = True
518 print("[Reading] %s: Too few samples were found, just %d/%d samples" % (datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
523 print("[Reading] %s: Too few samples were found, just %d/%d samples" % (datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
519 result.shape[0],
524 result.shape[0],
520 self.__samples_to_read))
525 self.__samples_to_read))
521 break
526 break
522
527
523 self.__data_buffer[indexSubchannel, :] = result * volt_scale
528 self.__data_buffer[indexChannel, :] = result * volt_scale
524 indexChannel+=1
529 indexChannel+=1
525
530
526 dataOk = True
531 dataOk = True
527
532
528 self.__utctime = self.__thisUnixSample / self.__sample_rate
533 self.__utctime = self.__thisUnixSample / self.__sample_rate
529
534
530 if not dataOk:
535 if not dataOk:
531 return False
536 return False
532
537
533 print("[Reading] %s: %d samples <> %f sec" % (datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
538 print("[Reading] %s: %d samples <> %f sec" % (datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
534 self.__samples_to_read,
539 self.__samples_to_read,
535 self.__timeInterval))
540 self.__timeInterval))
536
541
537 self.__bufferIndex = 0
542 self.__bufferIndex = 0
538
543
539 return True
544 return True
540
545
541 def __isBufferEmpty(self):
546 def __isBufferEmpty(self):
542 return self.__bufferIndex > self.__samples_to_read - self.__nSamples # 40960 - 40
547 return self.__bufferIndex > self.__samples_to_read - self.__nSamples # 40960 - 40
543
548
544 def getData(self, seconds=30, nTries=5):
549 def getData(self, seconds=30, nTries=5):
545 '''
550 '''
546 This method gets the data from files and put the data into the dataOut object
551 This method gets the data from files and put the data into the dataOut object
547
552
548 In addition, increase el the buffer counter in one.
553 In addition, increase el the buffer counter in one.
549
554
550 Return:
555 Return:
551 data : retorna un perfil de voltages (alturas * canales) copiados desde el
556 data : retorna un perfil de voltages (alturas * canales) copiados desde el
552 buffer. Si no hay mas archivos a leer retorna None.
557 buffer. Si no hay mas archivos a leer retorna None.
553
558
554 Affected:
559 Affected:
555 self.dataOut
560 self.dataOut
556 self.profileIndex
561 self.profileIndex
557 self.flagDiscontinuousBlock
562 self.flagDiscontinuousBlock
558 self.flagIsNewBlock
563 self.flagIsNewBlock
559 '''
564 '''
560 #print("getdata")
565 #print("getdata")
561 err_counter = 0
566 err_counter = 0
562 self.dataOut.flagNoData = True
567 self.dataOut.flagNoData = True
563
568
564 if self.__isBufferEmpty():
569 if self.__isBufferEmpty():
565 #print("hi")
570 #print("hi")
566 self.__flagDiscontinuousBlock = False
571 self.__flagDiscontinuousBlock = False
567
572
568 while True:
573 while True:
569 #print ("q ha pasado")
574 #print ("q ha pasado")
570 if self.__readNextBlock():
575 if self.__readNextBlock():
571 break
576 break
572 if self.__thisUnixSample > self.__endUTCSecond * self.__sample_rate:
577 if self.__thisUnixSample > self.__endUTCSecond * self.__sample_rate:
573 raise schainpy.admin.SchainError('Error')
578 raise schainpy.admin.SchainError('Error')
574 return
579 return
575
580
576 if self.__flagDiscontinuousBlock:
581 if self.__flagDiscontinuousBlock:
577 raise schainpy.admin.SchainError('discontinuous block found')
582 raise schainpy.admin.SchainError('discontinuous block found')
578 return
583 return
579
584
580 if not self.__online:
585 if not self.__online:
581 raise schainpy.admin.SchainError('Online?')
586 raise schainpy.admin.SchainError('Online?')
582 return
587 return
583
588
584 err_counter += 1
589 err_counter += 1
585 if err_counter > nTries:
590 if err_counter > nTries:
586 raise schainpy.admin.SchainError('Max retrys reach')
591 raise schainpy.admin.SchainError('Max retrys reach')
587 return
592 return
588
593
589 print('[Reading] waiting %d seconds to read a new block' % seconds)
594 print('[Reading] waiting %d seconds to read a new block' % seconds)
590 time.sleep(seconds)
595 sleep(seconds)
591
596
592 self.dataOut.data = self.__data_buffer[:, self.__bufferIndex:self.__bufferIndex + self.__nSamples]
597 self.dataOut.data = self.__data_buffer[:, self.__bufferIndex:self.__bufferIndex + self.__nSamples]
593 self.dataOut.utctime = ( self.__thisUnixSample + self.__bufferIndex) / self.__sample_rate
598 self.dataOut.utctime = ( self.__thisUnixSample + self.__bufferIndex) / self.__sample_rate
594 self.dataOut.flagNoData = False
599 self.dataOut.flagNoData = False
595 self.dataOut.flagDiscontinuousBlock = self.__flagDiscontinuousBlock
600 self.dataOut.flagDiscontinuousBlock = self.__flagDiscontinuousBlock
596 self.dataOut.profileIndex = self.profileIndex
601 self.dataOut.profileIndex = self.profileIndex
597
602
598 self.__bufferIndex += self.__nSamples
603 self.__bufferIndex += self.__nSamples
599 self.profileIndex += 1
604 self.profileIndex += 1
600
605
601 if self.profileIndex == self.dataOut.nProfiles:
606 if self.profileIndex == self.dataOut.nProfiles:
602 self.profileIndex = 0
607 self.profileIndex = 0
603
608
604 return True
609 return True
605
610
606 def printInfo(self):
611 def printInfo(self):
607 '''
612 '''
608 '''
613 '''
609 if self.__printInfo == False:
614 if self.__printInfo == False:
610 return
615 return
611
616
612 # self.systemHeaderObj.printInfo()
617 # self.systemHeaderObj.printInfo()
613 # self.radarControllerHeaderObj.printInfo()
618 # self.radarControllerHeaderObj.printInfo()
614
619
615 self.__printInfo = False
620 self.__printInfo = False
616
621
617 def printNumberOfBlock(self):
622 def printNumberOfBlock(self):
618 '''
623 '''
619 '''
624 '''
620 return
625 return
621 # print self.profileIndex
626 # print self.profileIndex
622
627
623 def run(self, **kwargs):
628 def run(self, **kwargs):
624 '''
629 '''
625 This method will be called many times so here you should put all your code
630 This method will be called many times so here you should put all your code
626 '''
631 '''
627
632
628 if not self.isConfig:
633 if not self.isConfig:
629 self.setup(**kwargs)
634 self.setup(**kwargs)
630 #self.i = self.i+1
635 #self.i = self.i+1
631 self.getData(seconds=self.__delay)
636 self.getData(seconds=self.__delay)
632
637
633 return
638 return
634
639
635 @MPDecorator
640 @MPDecorator
636 class DigitalRFWriter(Operation):
641 class DigitalRFWriter(Operation):
637 '''
642 '''
638 classdocs
643 classdocs
639 '''
644 '''
640
645
641 def __init__(self, **kwargs):
646 def __init__(self, **kwargs):
642 '''
647 '''
643 Constructor
648 Constructor
644 '''
649 '''
645 Operation.__init__(self, **kwargs)
650 Operation.__init__(self, **kwargs)
646 self.metadata_dict = {}
651 self.metadata_dict = {}
647 self.dataOut = None
652 self.dataOut = None
648 self.dtype = None
653 self.dtype = None
649 self.oldAverage = 0
654 self.oldAverage = 0
650
655
651 def setHeader(self):
656 def setHeader(self):
652
657
653 self.metadata_dict['frequency'] = self.dataOut.frequency
658 self.metadata_dict['frequency'] = self.dataOut.frequency
654 self.metadata_dict['timezone'] = self.dataOut.timeZone
659 self.metadata_dict['timezone'] = self.dataOut.timeZone
655 self.metadata_dict['dtype'] = pickle.dumps(self.dataOut.dtype)
660 self.metadata_dict['dtype'] = pickle.dumps(self.dataOut.dtype)
656 self.metadata_dict['nProfiles'] = self.dataOut.nProfiles
661 self.metadata_dict['nProfiles'] = self.dataOut.nProfiles
657 self.metadata_dict['heightList'] = self.dataOut.heightList
662 self.metadata_dict['heightList'] = self.dataOut.heightList
658 self.metadata_dict['channelList'] = self.dataOut.channelList
663 self.metadata_dict['channelList'] = self.dataOut.channelList
659 self.metadata_dict['flagDecodeData'] = self.dataOut.flagDecodeData
664 self.metadata_dict['flagDecodeData'] = self.dataOut.flagDecodeData
660 self.metadata_dict['flagDeflipData'] = self.dataOut.flagDeflipData
665 self.metadata_dict['flagDeflipData'] = self.dataOut.flagDeflipData
661 self.metadata_dict['flagShiftFFT'] = self.dataOut.flagShiftFFT
666 self.metadata_dict['flagShiftFFT'] = self.dataOut.flagShiftFFT
662 self.metadata_dict['useLocalTime'] = self.dataOut.useLocalTime
667 self.metadata_dict['useLocalTime'] = self.dataOut.useLocalTime
663 self.metadata_dict['nCohInt'] = self.dataOut.nCohInt
668 self.metadata_dict['nCohInt'] = self.dataOut.nCohInt
664 self.metadata_dict['type'] = self.dataOut.type
669 self.metadata_dict['type'] = self.dataOut.type
665 self.metadata_dict['flagDataAsBlock']= getattr(
670 self.metadata_dict['flagDataAsBlock']= getattr(
666 self.dataOut, 'flagDataAsBlock', None) # chequear
671 self.dataOut, 'flagDataAsBlock', None) # chequear
667
672
668 def setup(self, dataOut, path, frequency, fileCadence, dirCadence, metadataCadence, set=0, metadataFile='metadata', ext='.h5'):
673 def setup(self, dataOut, path, frequency, fileCadence, dirCadence, metadataCadence, set=0, metadataFile='metadata', ext='.h5'):
669 '''
674 '''
670 In this method we should set all initial parameters.
675 In this method we should set all initial parameters.
671 Input:
676 Input:
672 dataOut: Input data will also be outputa data
677 dataOut: Input data will also be outputa data
673 '''
678 '''
674 self.setHeader()
679 self.setHeader()
675 self.__ippSeconds = dataOut.ippSeconds
680 self.__ippSeconds = dataOut.ippSeconds
676 self.__deltaH = dataOut.getDeltaH()
681 self.__deltaH = dataOut.getDeltaH()
677 self.__sample_rate = 1e6 * 0.15 / self.__deltaH
682 self.__sample_rate = 1e6 * 0.15 / self.__deltaH
678 self.__dtype = dataOut.dtype
683 self.__dtype = dataOut.dtype
679 if len(dataOut.dtype) == 2:
684 if len(dataOut.dtype) == 2:
680 self.__dtype = dataOut.dtype[0]
685 self.__dtype = dataOut.dtype[0]
681 self.__nSamples = dataOut.systemHeaderObj.nSamples
686 self.__nSamples = dataOut.systemHeaderObj.nSamples
682 self.__nProfiles = dataOut.nProfiles
687 self.__nProfiles = dataOut.nProfiles
683
688
684 if self.dataOut.type != 'Voltage':
689 if self.dataOut.type != 'Voltage':
685 raise 'Digital RF cannot be used with this data type'
690 raise 'Digital RF cannot be used with this data type'
686 self.arr_data = numpy.ones((1, dataOut.nFFTPoints * len(
691 self.arr_data = numpy.ones((1, dataOut.nFFTPoints * len(
687 self.dataOut.channelList)), dtype=[('r', self.__dtype), ('i', self.__dtype)])
692 self.dataOut.channelList)), dtype=[('r', self.__dtype), ('i', self.__dtype)])
688 else:
693 else:
689 self.arr_data = numpy.ones((self.__nSamples, len(
694 self.arr_data = numpy.ones((self.__nSamples, len(
690 self.dataOut.channelList)), dtype=[('r', self.__dtype), ('i', self.__dtype)])
695 self.dataOut.channelList)), dtype=[('r', self.__dtype), ('i', self.__dtype)])
691
696
692 file_cadence_millisecs = 1000
697 file_cadence_millisecs = 1000
693
698
694 sample_rate_fraction = Fraction(self.__sample_rate).limit_denominator()
699 sample_rate_fraction = Fraction(self.__sample_rate).limit_denominator()
695 sample_rate_numerator = int(sample_rate_fraction.numerator)
700 sample_rate_numerator = int(sample_rate_fraction.numerator)
696 sample_rate_denominator = int(sample_rate_fraction.denominator)
701 sample_rate_denominator = int(sample_rate_fraction.denominator)
697 start_global_index = dataOut.utctime * self.__sample_rate
702 start_global_index = dataOut.utctime * self.__sample_rate
698
703
699 uuid = 'prueba'
704 uuid = 'prueba'
700 compression_level = 0
705 compression_level = 0
701 checksum = False
706 checksum = False
702 is_complex = True
707 is_complex = True
703 num_subchannels = len(dataOut.channelList)
708 num_subchannels = len(dataOut.channelList)
704 is_continuous = True
709 is_continuous = True
705 marching_periods = False
710 marching_periods = False
706
711
707 self.digitalWriteObj = digital_rf.DigitalRFWriter(path, self.__dtype, dirCadence,
712 self.digitalWriteObj = digital_rf.DigitalRFWriter(path, self.__dtype, dirCadence,
708 fileCadence, start_global_index,
713 fileCadence, start_global_index,
709 sample_rate_numerator, sample_rate_denominator, uuid, compression_level, checksum,
714 sample_rate_numerator, sample_rate_denominator, uuid, compression_level, checksum,
710 is_complex, num_subchannels, is_continuous, marching_periods)
715 is_complex, num_subchannels, is_continuous, marching_periods)
711 metadata_dir = os.path.join(path, 'metadata')
716 metadata_dir = os.path.join(path, 'metadata')
712 os.system('mkdir %s' % (metadata_dir))
717 os.system('mkdir %s' % (metadata_dir))
713 self.digitalMetadataWriteObj = digital_rf.DigitalMetadataWriter(metadata_dir, dirCadence, 1, # 236, file_cadence_millisecs / 1000
718 self.digitalMetadataWriteObj = digital_rf.DigitalMetadataWriter(metadata_dir, dirCadence, 1, # 236, file_cadence_millisecs / 1000
714 sample_rate_numerator, sample_rate_denominator,
719 sample_rate_numerator, sample_rate_denominator,
715 metadataFile)
720 metadataFile)
716 self.isConfig = True
721 self.isConfig = True
717 self.currentSample = 0
722 self.currentSample = 0
718 self.oldAverage = 0
723 self.oldAverage = 0
719 self.count = 0
724 self.count = 0
720 return
725 return
721
726
722 def writeMetadata(self):
727 def writeMetadata(self):
723 start_idx = self.__sample_rate * self.dataOut.utctime
728 start_idx = self.__sample_rate * self.dataOut.utctime
724
729
725 self.metadata_dict['processingHeader'] = self.dataOut.processingHeaderObj.getAsDict(
730 self.metadata_dict['processingHeader'] = self.dataOut.processingHeaderObj.getAsDict(
726 )
731 )
727 self.metadata_dict['radarControllerHeader'] = self.dataOut.radarControllerHeaderObj.getAsDict(
732 self.metadata_dict['radarControllerHeader'] = self.dataOut.radarControllerHeaderObj.getAsDict(
728 )
733 )
729 self.metadata_dict['systemHeader'] = self.dataOut.systemHeaderObj.getAsDict(
734 self.metadata_dict['systemHeader'] = self.dataOut.systemHeaderObj.getAsDict(
730 )
735 )
731 self.digitalMetadataWriteObj.write(start_idx, self.metadata_dict)
736 self.digitalMetadataWriteObj.write(start_idx, self.metadata_dict)
732 return
737 return
733
738
734 def timeit(self, toExecute):
739 def timeit(self, toExecute):
735 t0 = time()
740 t0 = time()
736 toExecute()
741 toExecute()
737 self.executionTime = time() - t0
742 self.executionTime = time() - t0
738 if self.oldAverage is None:
743 if self.oldAverage is None:
739 self.oldAverage = self.executionTime
744 self.oldAverage = self.executionTime
740 self.oldAverage = (self.executionTime + self.count *
745 self.oldAverage = (self.executionTime + self.count *
741 self.oldAverage) / (self.count + 1.0)
746 self.oldAverage) / (self.count + 1.0)
742 self.count = self.count + 1.0
747 self.count = self.count + 1.0
743 return
748 return
744
749
745 def writeData(self):
750 def writeData(self):
746 if self.dataOut.type != 'Voltage':
751 if self.dataOut.type != 'Voltage':
747 raise 'Digital RF cannot be used with this data type'
752 raise 'Digital RF cannot be used with this data type'
748 for channel in self.dataOut.channelList:
753 for channel in self.dataOut.channelList:
749 for i in range(self.dataOut.nFFTPoints):
754 for i in range(self.dataOut.nFFTPoints):
750 self.arr_data[1][channel * self.dataOut.nFFTPoints +
755 self.arr_data[1][channel * self.dataOut.nFFTPoints +
751 i]['r'] = self.dataOut.data[channel][i].real
756 i]['r'] = self.dataOut.data[channel][i].real
752 self.arr_data[1][channel * self.dataOut.nFFTPoints +
757 self.arr_data[1][channel * self.dataOut.nFFTPoints +
753 i]['i'] = self.dataOut.data[channel][i].imag
758 i]['i'] = self.dataOut.data[channel][i].imag
754 else:
759 else:
755 for i in range(self.dataOut.systemHeaderObj.nSamples):
760 for i in range(self.dataOut.systemHeaderObj.nSamples):
756 for channel in self.dataOut.channelList:
761 for channel in self.dataOut.channelList:
757 self.arr_data[i][channel]['r'] = self.dataOut.data[channel][i].real
762 self.arr_data[i][channel]['r'] = self.dataOut.data[channel][i].real
758 self.arr_data[i][channel]['i'] = self.dataOut.data[channel][i].imag
763 self.arr_data[i][channel]['i'] = self.dataOut.data[channel][i].imag
759
764
760 def f(): return self.digitalWriteObj.rf_write(self.arr_data)
765 def f(): return self.digitalWriteObj.rf_write(self.arr_data)
761 self.timeit(f)
766 self.timeit(f)
762
767
763 return
768 return
764
769
765 def run(self, dataOut, frequency=49.92e6, path=None, fileCadence=1000, dirCadence=36000, metadataCadence=1, **kwargs):
770 def run(self, dataOut, frequency=49.92e6, path=None, fileCadence=1000, dirCadence=36000, metadataCadence=1, **kwargs):
766 '''
771 '''
767 This method will be called many times so here you should put all your code
772 This method will be called many times so here you should put all your code
768 Inputs:
773 Inputs:
769 dataOut: object with the data
774 dataOut: object with the data
770 '''
775 '''
771 # print dataOut.__dict__
776 # print dataOut.__dict__
772 self.dataOut = dataOut
777 self.dataOut = dataOut
773 if not self.isConfig:
778 if not self.isConfig:
774 self.setup(dataOut, path, frequency, fileCadence,
779 self.setup(dataOut, path, frequency, fileCadence,
775 dirCadence, metadataCadence, **kwargs)
780 dirCadence, metadataCadence, **kwargs)
776 self.writeMetadata()
781 self.writeMetadata()
777
782
778 self.writeData()
783 self.writeData()
779
784
780 ## self.currentSample += 1
785 ## self.currentSample += 1
781 # if self.dataOut.flagDataAsBlock or self.currentSample == 1:
786 # if self.dataOut.flagDataAsBlock or self.currentSample == 1:
782 # self.writeMetadata()
787 # self.writeMetadata()
783 ## if self.currentSample == self.__nProfiles: self.currentSample = 0
788 ## if self.currentSample == self.__nProfiles: self.currentSample = 0
784
789
785 return dataOut# en la version 2.7 no aparece este return
790 return dataOut# en la version 2.7 no aparece este return
786
791
787 def close(self):
792 def close(self):
788 print('[Writing] - Closing files ')
793 print('[Writing] - Closing files ')
789 print('Average of writing to digital rf format is ', self.oldAverage * 1000)
794 print('Average of writing to digital rf format is ', self.oldAverage * 1000)
790 try:
795 try:
791 self.digitalWriteObj.close()
796 self.digitalWriteObj.close()
792 except:
797 except:
793 pass
798 pass
@@ -1,347 +1,351
1 import numpy
1 import numpy
2
2
3 from .jroproc_base import ProcessingUnit, Operation, MPDecorator
3 from .jroproc_base import ProcessingUnit, Operation, MPDecorator
4 from schainpy.model.data.jrodata import SpectraHeis
4 from schainpy.model.data.jrodata import SpectraHeis
5 from schainpy.utils import log
5 from schainpy.utils import log
6
6
7
7
8
8
9 class SpectraHeisProc(ProcessingUnit):
9 class SpectraHeisProc(ProcessingUnit):
10
10
11 def __init__(self):#, **kwargs):
11 def __init__(self):#, **kwargs):
12
12
13 ProcessingUnit.__init__(self)#, **kwargs)
13 ProcessingUnit.__init__(self)#, **kwargs)
14
14
15 # self.buffer = None
15 # self.buffer = None
16 # self.firstdatatime = None
16 # self.firstdatatime = None
17 # self.profIndex = 0
17 # self.profIndex = 0
18 self.dataOut = SpectraHeis()
18 self.dataOut = SpectraHeis()
19
19
20 def __updateObjFromVoltage(self):
20 def __updateObjFromVoltage(self):
21
21
22 self.dataOut.timeZone = self.dataIn.timeZone
22 self.dataOut.timeZone = self.dataIn.timeZone
23 self.dataOut.dstFlag = self.dataIn.dstFlag
23 self.dataOut.dstFlag = self.dataIn.dstFlag
24 self.dataOut.errorCount = self.dataIn.errorCount
24 self.dataOut.errorCount = self.dataIn.errorCount
25 self.dataOut.useLocalTime = self.dataIn.useLocalTime
25 self.dataOut.useLocalTime = self.dataIn.useLocalTime
26
26
27 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()#
27 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()#
28 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()#
28 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()#
29 self.dataOut.channelList = self.dataIn.channelList
29 self.dataOut.channelList = self.dataIn.channelList
30 self.dataOut.heightList = self.dataIn.heightList
30 self.dataOut.heightList = self.dataIn.heightList
31 # self.dataOut.dtype = self.dataIn.dtype
31 # self.dataOut.dtype = self.dataIn.dtype
32 self.dataOut.dtype = numpy.dtype([('real','<f4'),('imag','<f4')])
32 self.dataOut.dtype = numpy.dtype([('real','<f4'),('imag','<f4')])
33 # self.dataOut.nHeights = self.dataIn.nHeights
33 # self.dataOut.nHeights = self.dataIn.nHeights
34 # self.dataOut.nChannels = self.dataIn.nChannels
34 # self.dataOut.nChannels = self.dataIn.nChannels
35 self.dataOut.nBaud = self.dataIn.nBaud
35 self.dataOut.nBaud = self.dataIn.nBaud
36 self.dataOut.nCode = self.dataIn.nCode
36 self.dataOut.nCode = self.dataIn.nCode
37 self.dataOut.code = self.dataIn.code
37 self.dataOut.code = self.dataIn.code
38 # self.dataOut.nProfiles = 1
38 # self.dataOut.nProfiles = 1
39 self.dataOut.ippFactor = 1
39 self.dataOut.ippFactor = 1
40 self.dataOut.noise_estimation = None
40 self.dataOut.noise_estimation = None
41 # self.dataOut.nProfiles = self.dataOut.nFFTPoints
41 # self.dataOut.nProfiles = self.dataOut.nFFTPoints
42 self.dataOut.nFFTPoints = self.dataIn.nHeights
42 self.dataOut.nFFTPoints = self.dataIn.nHeights
43 # self.dataOut.channelIndexList = self.dataIn.channelIndexList
43 # self.dataOut.channelIndexList = self.dataIn.channelIndexList
44 # self.dataOut.flagNoData = self.dataIn.flagNoData
44 # self.dataOut.flagNoData = self.dataIn.flagNoData
45 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
45 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
46 self.dataOut.utctime = self.dataIn.utctime
46 self.dataOut.utctime = self.dataIn.utctime
47 # self.dataOut.utctime = self.firstdatatime
47 # self.dataOut.utctime = self.firstdatatime
48 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
48 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
49 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
49 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
50 # self.dataOut.flagShiftFFT = self.dataIn.flagShiftFFT
50 # self.dataOut.flagShiftFFT = self.dataIn.flagShiftFFT
51 self.dataOut.nCohInt = self.dataIn.nCohInt
51 self.dataOut.nCohInt = self.dataIn.nCohInt
52 self.dataOut.nIncohInt = 1
52 self.dataOut.nIncohInt = 1
53 # self.dataOut.ippSeconds= self.dataIn.ippSeconds
53 # self.dataOut.ippSeconds= self.dataIn.ippSeconds
54 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
54 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
55
55
56 # self.dataOut.timeInterval = self.dataIn.timeInterval*self.dataOut.nIncohInt
56 # self.dataOut.timeInterval = self.dataIn.timeInterval*self.dataOut.nIncohInt
57 # self.dataOut.set=self.dataIn.set
57 # self.dataOut.set=self.dataIn.set
58 # self.dataOut.deltaHeight=self.dataIn.deltaHeight
58 # self.dataOut.deltaHeight=self.dataIn.deltaHeight
59
59
60
60
61 def __updateObjFromFits(self):
61 def __updateObjFromFits(self):
62
62
63 self.dataOut.utctime = self.dataIn.utctime
63 self.dataOut.utctime = self.dataIn.utctime
64 # self.dataOut.channelIndexList = self.dataIn.channelIndexList
64 # self.dataOut.channelIndexList = self.dataIn.channelIndexList
65
65
66 self.dataOut.channelList = self.dataIn.channelList
66 self.dataOut.channelList = self.dataIn.channelList
67 self.dataOut.heightList = self.dataIn.heightList
67 self.dataOut.heightList = self.dataIn.heightList
68 self.dataOut.data_spc = self.dataIn.data
68 self.dataOut.data_spc = self.dataIn.data
69 self.dataOut.ippSeconds = self.dataIn.ippSeconds
69 self.dataOut.ippSeconds = self.dataIn.ippSeconds
70 self.dataOut.nCohInt = self.dataIn.nCohInt
70 self.dataOut.nCohInt = self.dataIn.nCohInt
71 self.dataOut.nIncohInt = self.dataIn.nIncohInt
71 self.dataOut.nIncohInt = self.dataIn.nIncohInt
72 # self.dataOut.timeInterval = self.dataIn.timeInterval
72 # self.dataOut.timeInterval = self.dataIn.timeInterval
73 self.dataOut.timeZone = self.dataIn.timeZone
73 self.dataOut.timeZone = self.dataIn.timeZone
74 self.dataOut.useLocalTime = True
74 self.dataOut.useLocalTime = True
75 # self.dataOut.
75 # self.dataOut.
76 # self.dataOut.
76 # self.dataOut.
77
77
78 def __getFft(self):
78 def __getFft(self):
79
79
80 fft_volt = numpy.fft.fft(self.dataIn.data, axis=1)
80 fft_volt = numpy.fft.fft(self.dataIn.data, axis=1)
81 fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,))
81 fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,))
82 spc = numpy.abs(fft_volt * numpy.conjugate(fft_volt))/(self.dataOut.nFFTPoints)
82 spc = numpy.abs(fft_volt * numpy.conjugate(fft_volt))/(self.dataOut.nFFTPoints)
83 self.dataOut.data_spc = spc
83 self.dataOut.data_spc = spc
84
84
85 def run(self):
85 def run(self):
86
86
87 self.dataOut.flagNoData = True
87 self.dataOut.flagNoData = True
88
88
89 if self.dataIn.type == "Fits":
89 if self.dataIn.type == "Fits":
90 self.__updateObjFromFits()
90 self.__updateObjFromFits()
91 self.dataOut.flagNoData = False
91 self.dataOut.flagNoData = False
92 return
92 return
93
93
94 if self.dataIn.type == "SpectraHeis":
94 if self.dataIn.type == "SpectraHeis":
95 self.dataOut.copy(self.dataIn)
95 self.dataOut.copy(self.dataIn)
96 return
96 return
97
97
98 if self.dataIn.type == "Voltage":
98 if self.dataIn.type == "Voltage":
99 self.__updateObjFromVoltage()
99 self.__updateObjFromVoltage()
100 self.__getFft()
100 self.__getFft()
101 self.dataOut.flagNoData = False
101 self.dataOut.flagNoData = False
102
102
103 return
103 return
104
104
105 raise ValueError("The type object %s is not valid"%(self.dataIn.type))
105 raise ValueError("The type object %s is not valid"%(self.dataIn.type))
106
106
107
107
108 def selectChannels(self, channelList):
108 def selectChannels(self, channelList):
109
109
110 channelIndexList = []
110 channelIndexList = []
111
111
112 for channel in channelList:
112 for channel in channelList:
113 index = self.dataOut.channelList.index(channel)
113 index = self.dataOut.channelList.index(channel)
114 channelIndexList.append(index)
114 channelIndexList.append(index)
115
115
116 self.selectChannelsByIndex(channelIndexList)
116 self.selectChannelsByIndex(channelIndexList)
117
117
118 def selectChannelsByIndex(self, channelIndexList):
118 def selectChannelsByIndex(self, channelIndexList):
119 """
119 """
120 Selecciona un bloque de datos en base a canales segun el channelIndexList
120 Selecciona un bloque de datos en base a canales segun el channelIndexList
121
121
122 Input:
122 Input:
123 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
123 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
124
124
125 Affected:
125 Affected:
126 self.dataOut.data
126 self.dataOut.data
127 self.dataOut.channelIndexList
127 self.dataOut.channelIndexList
128 self.dataOut.nChannels
128 self.dataOut.nChannels
129 self.dataOut.m_ProcessingHeader.totalSpectra
129 self.dataOut.m_ProcessingHeader.totalSpectra
130 self.dataOut.systemHeaderObj.numChannels
130 self.dataOut.systemHeaderObj.numChannels
131 self.dataOut.m_ProcessingHeader.blockSize
131 self.dataOut.m_ProcessingHeader.blockSize
132
132
133 Return:
133 Return:
134 None
134 None
135 """
135 """
136
136
137 for channelIndex in channelIndexList:
137 for channelIndex in channelIndexList:
138 if channelIndex not in self.dataOut.channelIndexList:
138 if channelIndex not in self.dataOut.channelIndexList:
139 raise ValueError("The value %d in channelIndexList is not valid" %channelIndex)
139 raise ValueError("The value %d in channelIndexList is not valid" %channelIndex)
140
140
141 data_spc = self.dataOut.data_spc[channelIndexList,:]
141 data_spc = self.dataOut.data_spc[channelIndexList,:]
142
142
143 self.dataOut.data_spc = data_spc
143 self.dataOut.data_spc = data_spc
144 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
144 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
145
145
146 return 1
146 return 1
147
147
148
148
149 class IncohInt4SpectraHeis(Operation):
149 class IncohInt4SpectraHeis(Operation):
150
150
151 isConfig = False
151 isConfig = False
152
152
153 __profIndex = 0
153 __profIndex = 0
154 __withOverapping = False
154 __withOverapping = False
155
155
156 __byTime = False
156 __byTime = False
157 __initime = None
157 __initime = None
158 __lastdatatime = None
158 __lastdatatime = None
159 __integrationtime = None
159 __integrationtime = None
160
160
161 __buffer = None
161 __buffer = None
162
162
163 __dataReady = False
163 __dataReady = False
164
164
165 n = None
165 n = None
166
166
167 def __init__(self):#, **kwargs):
167 def __init__(self):#, **kwargs):
168
168
169 Operation.__init__(self)#, **kwargs)
169 Operation.__init__(self)#, **kwargs)
170 # self.isConfig = False
170 # self.isConfig = False
171
171
172 def setup(self, n=None, timeInterval=None, overlapping=False):
172 def setup(self, n=None, timeInterval=None, overlapping=False):
173 """
173 """
174 Set the parameters of the integration class.
174 Set the parameters of the integration class.
175
175
176 Inputs:
176 Inputs:
177
177
178 n : Number of coherent integrations
178 n : Number of coherent integrations
179 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
179 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
180 overlapping :
180 overlapping :
181
181
182 """
182 """
183
183
184 self.__initime = None
184 self.__initime = None
185 self.__lastdatatime = 0
185 self.__lastdatatime = 0
186 self.__buffer = None
186 self.__buffer = None
187 self.__dataReady = False
187 self.__dataReady = False
188
188
189
189
190 if n == None and timeInterval == None:
190 if n == None and timeInterval == None:
191 raise ValueError("n or timeInterval should be specified ...")
191 raise ValueError("n or timeInterval should be specified ...")
192
192
193 if n != None:
193 if n != None:
194 self.n = n
194 self.n = n
195 self.__byTime = False
195 self.__byTime = False
196 else:
196 else:
197 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
197 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
198 self.n = 9999
198 self.n = 9999
199 self.__byTime = True
199 self.__byTime = True
200
200
201 if overlapping:
201 if overlapping:
202 self.__withOverapping = True
202 self.__withOverapping = True
203 self.__buffer = None
203 self.__buffer = None
204 else:
204 else:
205 self.__withOverapping = False
205 self.__withOverapping = False
206 self.__buffer = 0
206 self.__buffer = 0
207
207
208 self.__profIndex = 0
208 self.__profIndex = 0
209
209
210 def putData(self, data):
210 def putData(self, data):
211
211
212 """
212 """
213 Add a profile to the __buffer and increase in one the __profileIndex
213 Add a profile to the __buffer and increase in one the __profileIndex
214
214
215 """
215 """
216
216
217 if not self.__withOverapping:
217 if not self.__withOverapping:
218 self.__buffer += data.copy()
218 self.__buffer += data.copy()
219 self.__profIndex += 1
219 self.__profIndex += 1
220 return
220 return
221
221
222 #Overlapping data
222 #Overlapping data
223 nChannels, nHeis = data.shape
223 nChannels, nHeis = data.shape
224 data = numpy.reshape(data, (1, nChannels, nHeis))
224 data = numpy.reshape(data, (1, nChannels, nHeis))
225
225
226 #If the buffer is empty then it takes the data value
226 #If the buffer is empty then it takes the data value
227 if self.__buffer is None:
227 if self.__buffer is None:
228 self.__buffer = data
228 self.__buffer = data
229 self.__profIndex += 1
229 self.__profIndex += 1
230 return
230 return
231
231
232 #If the buffer length is lower than n then stakcing the data value
232 #If the buffer length is lower than n then stakcing the data value
233 if self.__profIndex < self.n:
233 if self.__profIndex < self.n:
234 self.__buffer = numpy.vstack((self.__buffer, data))
234 self.__buffer = numpy.vstack((self.__buffer, data))
235 self.__profIndex += 1
235 self.__profIndex += 1
236 return
236 return
237
237
238 #If the buffer length is equal to n then replacing the last buffer value with the data value
238 #If the buffer length is equal to n then replacing the last buffer value with the data value
239 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
239 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
240 self.__buffer[self.n-1] = data
240 self.__buffer[self.n-1] = data
241 self.__profIndex = self.n
241 self.__profIndex = self.n
242 return
242 return
243
243
244
244
245 def pushData(self):
245 def pushData(self):
246 """
246 """
247 Return the sum of the last profiles and the profiles used in the sum.
247 Return the sum of the last profiles and the profiles used in the sum.
248
248
249 Affected:
249 Affected:
250
250
251 self.__profileIndex
251 self.__profileIndex
252
252
253 """
253 """
254
254
255 if not self.__withOverapping:
255 if not self.__withOverapping:
256 data = self.__buffer
256 data = self.__buffer
257 n = self.__profIndex
257 n = self.__profIndex
258
258
259 self.__buffer = 0
259 self.__buffer = 0
260 self.__profIndex = 0
260 self.__profIndex = 0
261
261
262 return data, n
262 return data, n
263
263
264 #Integration with Overlapping
264 #Integration with Overlapping
265 data = numpy.sum(self.__buffer, axis=0)
265 data = numpy.sum(self.__buffer, axis=0)
266 n = self.__profIndex
266 n = self.__profIndex
267
267
268 return data, n
268 return data, n
269
269
270 def byProfiles(self, data):
270 def byProfiles(self, data):
271
271
272 self.__dataReady = False
272 self.__dataReady = False
273 avgdata = None
273 avgdata = None
274 # n = None
274 # n = None
275
275
276 self.putData(data)
276 self.putData(data)
277
277
278 if self.__profIndex == self.n:
278 if self.__profIndex == self.n:
279
279
280 avgdata, n = self.pushData()
280 avgdata, n = self.pushData()
281 self.__dataReady = True
281 self.__dataReady = True
282
282
283 return avgdata
283 return avgdata
284
284
285 def byTime(self, data, datatime):
285 def byTime(self, data, datatime):
286
286
287 self.__dataReady = False
287 self.__dataReady = False
288 avgdata = None
288 avgdata = None
289 n = None
289 n = None
290
290
291 self.putData(data)
291 self.putData(data)
292
292
293 if (datatime - self.__initime) >= self.__integrationtime:
293 if (datatime - self.__initime) >= self.__integrationtime:
294 avgdata, n = self.pushData()
294 avgdata, n = self.pushData()
295 self.n = n
295 self.n = n
296 self.__dataReady = True
296 self.__dataReady = True
297
297
298 return avgdata
298 return avgdata
299
299
300 def integrate(self, data, datatime=None):
300 def integrate(self, data, datatime=None):
301
301
302 if self.__initime == None:
302 if self.__initime == None:
303 self.__initime = datatime
303 self.__initime = datatime
304
304
305 #if self.__profIndex == 0:
306 # self.__initime = datatime
307
305 if self.__byTime:
308 if self.__byTime:
306 avgdata = self.byTime(data, datatime)
309 avgdata = self.byTime(data, datatime)
307 else:
310 else:
308 avgdata = self.byProfiles(data)
311 avgdata = self.byProfiles(data)
309
312
310
313
311 self.__lastdatatime = datatime
314 self.__lastdatatime = datatime
312
315
313 if avgdata is None:
316 if avgdata is None:
314 return None, None
317 return None, None
315
318
316 avgdatatime = self.__initime
319 avgdatatime = self.__initime
317
320
318 deltatime = datatime -self.__lastdatatime
321 deltatime = datatime -self.__lastdatatime
319
322
320 if not self.__withOverapping:
323 if not self.__withOverapping:
321 self.__initime = datatime
324 self.__initime = datatime
322 else:
325 else:
323 self.__initime += deltatime
326 self.__initime += deltatime
324
327
325 return avgdata, avgdatatime
328 return avgdata, avgdatatime
326
329
327 def run(self, dataOut, n=None, timeInterval=None, overlapping=False, **kwargs):
330 def run(self, dataOut, n=None, timeInterval=None, overlapping=False, **kwargs):
328
331
329 if not self.isConfig:
332 if not self.isConfig:
330 self.setup(n=n, timeInterval=timeInterval, overlapping=overlapping)
333 self.setup(n=n, timeInterval=timeInterval, overlapping=overlapping)
331 self.isConfig = True
334 self.isConfig = True
332
335
336 #print("utc_time",dataOut.utctime)
333 avgdata, avgdatatime = self.integrate(dataOut.data_spc, dataOut.utctime)
337 avgdata, avgdatatime = self.integrate(dataOut.data_spc, dataOut.utctime)
334
338
335 # dataOut.timeInterval *= n
339 # dataOut.timeInterval *= n
336 dataOut.flagNoData = True
340 dataOut.flagNoData = True
337
341
338 if self.__dataReady:
342 if self.__dataReady:
339 dataOut.data_spc = avgdata
343 dataOut.data_spc = avgdata
340 dataOut.nIncohInt *= self.n
344 dataOut.nIncohInt *= self.n
341 # dataOut.nCohInt *= self.n
345 # dataOut.nCohInt *= self.n
342 dataOut.utctime = avgdatatime
346 dataOut.utctime = avgdatatime
343 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nIncohInt
347 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nIncohInt
344 # dataOut.timeInterval = self.__timeInterval*self.n
348 # dataOut.timeInterval = self.__timeInterval*self.n
345 dataOut.flagNoData = False
349 dataOut.flagNoData = False
346
350
347 return dataOut
351 return dataOut
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,1625 +1,1627
1 import sys
1 import sys
2 import numpy,math
2 import numpy,math
3 from scipy import interpolate
3 from scipy import interpolate
4 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
4 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
5 from schainpy.model.data.jrodata import Voltage,hildebrand_sekhon
5 from schainpy.model.data.jrodata import Voltage,hildebrand_sekhon
6 from schainpy.utils import log
6 from schainpy.utils import log
7 from time import time
7 from time import time
8
8
9
9
10
10
11 class VoltageProc(ProcessingUnit):
11 class VoltageProc(ProcessingUnit):
12
12
13 def __init__(self):
13 def __init__(self):
14
14
15 ProcessingUnit.__init__(self)
15 ProcessingUnit.__init__(self)
16
16
17 self.dataOut = Voltage()
17 self.dataOut = Voltage()
18 self.flip = 1
18 self.flip = 1
19 self.setupReq = False
19 self.setupReq = False
20
20
21 def run(self):
21 def run(self):
22
22
23 if self.dataIn.type == 'AMISR':
23 if self.dataIn.type == 'AMISR':
24 self.__updateObjFromAmisrInput()
24 self.__updateObjFromAmisrInput()
25
25
26 if self.dataIn.type == 'Voltage':
26 if self.dataIn.type == 'Voltage':
27 self.dataOut.copy(self.dataIn)
27 self.dataOut.copy(self.dataIn)
28
28
29 def __updateObjFromAmisrInput(self):
29 def __updateObjFromAmisrInput(self):
30
30
31 self.dataOut.timeZone = self.dataIn.timeZone
31 self.dataOut.timeZone = self.dataIn.timeZone
32 self.dataOut.dstFlag = self.dataIn.dstFlag
32 self.dataOut.dstFlag = self.dataIn.dstFlag
33 self.dataOut.errorCount = self.dataIn.errorCount
33 self.dataOut.errorCount = self.dataIn.errorCount
34 self.dataOut.useLocalTime = self.dataIn.useLocalTime
34 self.dataOut.useLocalTime = self.dataIn.useLocalTime
35
35
36 self.dataOut.flagNoData = self.dataIn.flagNoData
36 self.dataOut.flagNoData = self.dataIn.flagNoData
37 self.dataOut.data = self.dataIn.data
37 self.dataOut.data = self.dataIn.data
38 self.dataOut.utctime = self.dataIn.utctime
38 self.dataOut.utctime = self.dataIn.utctime
39 self.dataOut.channelList = self.dataIn.channelList
39 self.dataOut.channelList = self.dataIn.channelList
40 #self.dataOut.timeInterval = self.dataIn.timeInterval
40 #self.dataOut.timeInterval = self.dataIn.timeInterval
41 self.dataOut.heightList = self.dataIn.heightList
41 self.dataOut.heightList = self.dataIn.heightList
42 self.dataOut.nProfiles = self.dataIn.nProfiles
42 self.dataOut.nProfiles = self.dataIn.nProfiles
43
43
44 self.dataOut.nCohInt = self.dataIn.nCohInt
44 self.dataOut.nCohInt = self.dataIn.nCohInt
45 self.dataOut.ippSeconds = self.dataIn.ippSeconds
45 self.dataOut.ippSeconds = self.dataIn.ippSeconds
46 self.dataOut.frequency = self.dataIn.frequency
46 self.dataOut.frequency = self.dataIn.frequency
47
47
48 self.dataOut.azimuth = self.dataIn.azimuth
48 self.dataOut.azimuth = self.dataIn.azimuth
49 self.dataOut.zenith = self.dataIn.zenith
49 self.dataOut.zenith = self.dataIn.zenith
50
50
51 self.dataOut.beam.codeList = self.dataIn.beam.codeList
51 self.dataOut.beam.codeList = self.dataIn.beam.codeList
52 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
52 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
53 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
53 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
54
54
55
55
56 class selectChannels(Operation):
56 class selectChannels(Operation):
57
57
58 def run(self, dataOut, channelList):
58 def run(self, dataOut, channelList):
59
59
60 channelIndexList = []
60 channelIndexList = []
61 self.dataOut = dataOut
61 self.dataOut = dataOut
62 for channel in channelList:
62 for channel in channelList:
63 if channel not in self.dataOut.channelList:
63 if channel not in self.dataOut.channelList:
64 raise ValueError("Channel %d is not in %s" %(channel, str(self.dataOut.channelList)))
64 raise ValueError("Channel %d is not in %s" %(channel, str(self.dataOut.channelList)))
65
65
66 index = self.dataOut.channelList.index(channel)
66 index = self.dataOut.channelList.index(channel)
67 channelIndexList.append(index)
67 channelIndexList.append(index)
68 self.selectChannelsByIndex(channelIndexList)
68 self.selectChannelsByIndex(channelIndexList)
69 return self.dataOut
69 return self.dataOut
70
70
71 def selectChannelsByIndex(self, channelIndexList):
71 def selectChannelsByIndex(self, channelIndexList):
72 """
72 """
73 Selecciona un bloque de datos en base a canales segun el channelIndexList
73 Selecciona un bloque de datos en base a canales segun el channelIndexList
74
74
75 Input:
75 Input:
76 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
76 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
77
77
78 Affected:
78 Affected:
79 self.dataOut.data
79 self.dataOut.data
80 self.dataOut.channelIndexList
80 self.dataOut.channelIndexList
81 self.dataOut.nChannels
81 self.dataOut.nChannels
82 self.dataOut.m_ProcessingHeader.totalSpectra
82 self.dataOut.m_ProcessingHeader.totalSpectra
83 self.dataOut.systemHeaderObj.numChannels
83 self.dataOut.systemHeaderObj.numChannels
84 self.dataOut.m_ProcessingHeader.blockSize
84 self.dataOut.m_ProcessingHeader.blockSize
85
85
86 Return:
86 Return:
87 None
87 None
88 """
88 """
89
89
90 for channelIndex in channelIndexList:
90 for channelIndex in channelIndexList:
91 if channelIndex not in self.dataOut.channelIndexList:
91 if channelIndex not in self.dataOut.channelIndexList:
92 raise ValueError("The value %d in channelIndexList is not valid" %channelIndex)
92 raise ValueError("The value %d in channelIndexList is not valid" %channelIndex)
93
93
94 if self.dataOut.type == 'Voltage':
94 if self.dataOut.type == 'Voltage':
95 if self.dataOut.flagDataAsBlock:
95 if self.dataOut.flagDataAsBlock:
96 """
96 """
97 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
97 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
98 """
98 """
99 data = self.dataOut.data[channelIndexList,:,:]
99 data = self.dataOut.data[channelIndexList,:,:]
100 else:
100 else:
101 data = self.dataOut.data[channelIndexList,:]
101 data = self.dataOut.data[channelIndexList,:]
102
102
103 self.dataOut.data = data
103 self.dataOut.data = data
104 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
104 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
105 self.dataOut.channelList = range(len(channelIndexList))
105 self.dataOut.channelList = range(len(channelIndexList))
106
106
107 elif self.dataOut.type == 'Spectra':
107 elif self.dataOut.type == 'Spectra':
108 data_spc = self.dataOut.data_spc[channelIndexList, :]
108 data_spc = self.dataOut.data_spc[channelIndexList, :]
109 data_dc = self.dataOut.data_dc[channelIndexList, :]
109 data_dc = self.dataOut.data_dc[channelIndexList, :]
110
110
111 self.dataOut.data_spc = data_spc
111 self.dataOut.data_spc = data_spc
112 self.dataOut.data_dc = data_dc
112 self.dataOut.data_dc = data_dc
113
113
114 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
114 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
115 self.dataOut.channelList = range(len(channelIndexList))
115 self.dataOut.channelList = range(len(channelIndexList))
116 self.__selectPairsByChannel(channelIndexList)
116 self.__selectPairsByChannel(channelIndexList)
117
117
118 return 1
118 return 1
119
119
120 def __selectPairsByChannel(self, channelList=None):
120 def __selectPairsByChannel(self, channelList=None):
121
121
122 if channelList == None:
122 if channelList == None:
123 return
123 return
124
124
125 pairsIndexListSelected = []
125 pairsIndexListSelected = []
126 for pairIndex in self.dataOut.pairsIndexList:
126 for pairIndex in self.dataOut.pairsIndexList:
127 # First pair
127 # First pair
128 if self.dataOut.pairsList[pairIndex][0] not in channelList:
128 if self.dataOut.pairsList[pairIndex][0] not in channelList:
129 continue
129 continue
130 # Second pair
130 # Second pair
131 if self.dataOut.pairsList[pairIndex][1] not in channelList:
131 if self.dataOut.pairsList[pairIndex][1] not in channelList:
132 continue
132 continue
133
133
134 pairsIndexListSelected.append(pairIndex)
134 pairsIndexListSelected.append(pairIndex)
135
135
136 if not pairsIndexListSelected:
136 if not pairsIndexListSelected:
137 self.dataOut.data_cspc = None
137 self.dataOut.data_cspc = None
138 self.dataOut.pairsList = []
138 self.dataOut.pairsList = []
139 return
139 return
140
140
141 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
141 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
142 self.dataOut.pairsList = [self.dataOut.pairsList[i]
142 self.dataOut.pairsList = [self.dataOut.pairsList[i]
143 for i in pairsIndexListSelected]
143 for i in pairsIndexListSelected]
144
144
145 return
145 return
146
146
147 class selectHeights(Operation):
147 class selectHeights(Operation):
148
148
149 def run(self, dataOut, minHei=None, maxHei=None, minIndex=None, maxIndex=None):
149 def run(self, dataOut, minHei=None, maxHei=None, minIndex=None, maxIndex=None):
150 """
150 """
151 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
151 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
152 minHei <= height <= maxHei
152 minHei <= height <= maxHei
153
153
154 Input:
154 Input:
155 minHei : valor minimo de altura a considerar
155 minHei : valor minimo de altura a considerar
156 maxHei : valor maximo de altura a considerar
156 maxHei : valor maximo de altura a considerar
157
157
158 Affected:
158 Affected:
159 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
159 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
160
160
161 Return:
161 Return:
162 1 si el metodo se ejecuto con exito caso contrario devuelve 0
162 1 si el metodo se ejecuto con exito caso contrario devuelve 0
163 """
163 """
164
164
165 self.dataOut = dataOut
165 self.dataOut = dataOut
166
166
167 if minHei and maxHei:
167 if minHei and maxHei:
168
168
169 if (minHei < self.dataOut.heightList[0]):
169 if (minHei < self.dataOut.heightList[0]):
170 minHei = self.dataOut.heightList[0]
170 minHei = self.dataOut.heightList[0]
171
171
172 if (maxHei > self.dataOut.heightList[-1]):
172 if (maxHei > self.dataOut.heightList[-1]):
173 maxHei = self.dataOut.heightList[-1]
173 maxHei = self.dataOut.heightList[-1]
174
174
175 minIndex = 0
175 minIndex = 0
176 maxIndex = 0
176 maxIndex = 0
177 heights = self.dataOut.heightList
177 heights = self.dataOut.heightList
178
178
179 inda = numpy.where(heights >= minHei)
179 inda = numpy.where(heights >= minHei)
180 indb = numpy.where(heights <= maxHei)
180 indb = numpy.where(heights <= maxHei)
181
181
182 try:
182 try:
183 minIndex = inda[0][0]
183 minIndex = inda[0][0]
184 except:
184 except:
185 minIndex = 0
185 minIndex = 0
186
186
187 try:
187 try:
188 maxIndex = indb[0][-1]
188 maxIndex = indb[0][-1]
189 except:
189 except:
190 maxIndex = len(heights)
190 maxIndex = len(heights)
191
191
192 self.selectHeightsByIndex(minIndex, maxIndex)
192 self.selectHeightsByIndex(minIndex, maxIndex)
193
193
194 return self.dataOut
194 return self.dataOut
195
195
196 def selectHeightsByIndex(self, minIndex, maxIndex):
196 def selectHeightsByIndex(self, minIndex, maxIndex):
197 """
197 """
198 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
198 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
199 minIndex <= index <= maxIndex
199 minIndex <= index <= maxIndex
200
200
201 Input:
201 Input:
202 minIndex : valor de indice minimo de altura a considerar
202 minIndex : valor de indice minimo de altura a considerar
203 maxIndex : valor de indice maximo de altura a considerar
203 maxIndex : valor de indice maximo de altura a considerar
204
204
205 Affected:
205 Affected:
206 self.dataOut.data
206 self.dataOut.data
207 self.dataOut.heightList
207 self.dataOut.heightList
208
208
209 Return:
209 Return:
210 1 si el metodo se ejecuto con exito caso contrario devuelve 0
210 1 si el metodo se ejecuto con exito caso contrario devuelve 0
211 """
211 """
212
212
213 if self.dataOut.type == 'Voltage':
213 if self.dataOut.type == 'Voltage':
214 if (minIndex < 0) or (minIndex > maxIndex):
214 if (minIndex < 0) or (minIndex > maxIndex):
215 raise ValueError("Height index range (%d,%d) is not valid" % (minIndex, maxIndex))
215 raise ValueError("Height index range (%d,%d) is not valid" % (minIndex, maxIndex))
216
216
217 if (maxIndex >= self.dataOut.nHeights):
217 if (maxIndex >= self.dataOut.nHeights):
218 maxIndex = self.dataOut.nHeights
218 maxIndex = self.dataOut.nHeights
219
219
220 #voltage
220 #voltage
221 if self.dataOut.flagDataAsBlock:
221 if self.dataOut.flagDataAsBlock:
222 """
222 """
223 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
223 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
224 """
224 """
225 data = self.dataOut.data[:,:, minIndex:maxIndex]
225 data = self.dataOut.data[:,:, minIndex:maxIndex]
226 else:
226 else:
227 data = self.dataOut.data[:, minIndex:maxIndex]
227 data = self.dataOut.data[:, minIndex:maxIndex]
228
228
229 # firstHeight = self.dataOut.heightList[minIndex]
229 # firstHeight = self.dataOut.heightList[minIndex]
230
230
231 self.dataOut.data = data
231 self.dataOut.data = data
232 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex]
232 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex]
233
233
234 if self.dataOut.nHeights <= 1:
234 if self.dataOut.nHeights <= 1:
235 raise ValueError("selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights))
235 raise ValueError("selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights))
236 elif self.dataOut.type == 'Spectra':
236 elif self.dataOut.type == 'Spectra':
237 if (minIndex < 0) or (minIndex > maxIndex):
237 if (minIndex < 0) or (minIndex > maxIndex):
238 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (
238 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (
239 minIndex, maxIndex))
239 minIndex, maxIndex))
240
240
241 if (maxIndex >= self.dataOut.nHeights):
241 if (maxIndex >= self.dataOut.nHeights):
242 maxIndex = self.dataOut.nHeights - 1
242 maxIndex = self.dataOut.nHeights - 1
243
243
244 # Spectra
244 # Spectra
245 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
245 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
246
246
247 data_cspc = None
247 data_cspc = None
248 if self.dataOut.data_cspc is not None:
248 if self.dataOut.data_cspc is not None:
249 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
249 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
250
250
251 data_dc = None
251 data_dc = None
252 if self.dataOut.data_dc is not None:
252 if self.dataOut.data_dc is not None:
253 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
253 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
254
254
255 self.dataOut.data_spc = data_spc
255 self.dataOut.data_spc = data_spc
256 self.dataOut.data_cspc = data_cspc
256 self.dataOut.data_cspc = data_cspc
257 self.dataOut.data_dc = data_dc
257 self.dataOut.data_dc = data_dc
258
258
259 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
259 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
260
260
261 return 1
261 return 1
262
262
263
263
264 class filterByHeights(Operation):
264 class filterByHeights(Operation):
265
265
266 def run(self, dataOut, window):
266 def run(self, dataOut, window):
267
267
268 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
268 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
269
269
270 if window == None:
270 if window == None:
271 window = (dataOut.radarControllerHeaderObj.txA/dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
271 window = (dataOut.radarControllerHeaderObj.txA/dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
272
272
273 newdelta = deltaHeight * window
273 newdelta = deltaHeight * window
274 r = dataOut.nHeights % window
274 r = dataOut.nHeights % window
275 newheights = (dataOut.nHeights-r)/window
275 newheights = (dataOut.nHeights-r)/window
276
276
277 if newheights <= 1:
277 if newheights <= 1:
278 raise ValueError("filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(dataOut.nHeights, window))
278 raise ValueError("filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(dataOut.nHeights, window))
279
279
280 if dataOut.flagDataAsBlock:
280 if dataOut.flagDataAsBlock:
281 """
281 """
282 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
282 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
283 """
283 """
284 buffer = dataOut.data[:, :, 0:int(dataOut.nHeights-r)]
284 buffer = dataOut.data[:, :, 0:int(dataOut.nHeights-r)]
285 buffer = buffer.reshape(dataOut.nChannels, dataOut.nProfiles, int(dataOut.nHeights/window), window)
285 buffer = buffer.reshape(dataOut.nChannels, dataOut.nProfiles, int(dataOut.nHeights/window), window)
286 buffer = numpy.sum(buffer,3)
286 buffer = numpy.sum(buffer,3)
287
287
288 else:
288 else:
289 buffer = dataOut.data[:,0:int(dataOut.nHeights-r)]
289 buffer = dataOut.data[:,0:int(dataOut.nHeights-r)]
290 buffer = buffer.reshape(dataOut.nChannels,int(dataOut.nHeights/window),int(window))
290 buffer = buffer.reshape(dataOut.nChannels,int(dataOut.nHeights/window),int(window))
291 buffer = numpy.sum(buffer,2)
291 buffer = numpy.sum(buffer,2)
292
292
293 dataOut.data = buffer
293 dataOut.data = buffer
294 dataOut.heightList = dataOut.heightList[0] + numpy.arange( newheights )*newdelta
294 dataOut.heightList = dataOut.heightList[0] + numpy.arange( newheights )*newdelta
295 dataOut.windowOfFilter = window
295 dataOut.windowOfFilter = window
296
296
297 return dataOut
297 return dataOut
298
298
299
299
300 class setH0(Operation):
300 class setH0(Operation):
301
301
302 def run(self, dataOut, h0, deltaHeight = None):
302 def run(self, dataOut, h0, deltaHeight = None):
303
303
304 if not deltaHeight:
304 if not deltaHeight:
305 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
305 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
306
306
307 nHeights = dataOut.nHeights
307 nHeights = dataOut.nHeights
308
308
309 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
309 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
310
310
311 dataOut.heightList = newHeiRange
311 dataOut.heightList = newHeiRange
312
312
313 return dataOut
313 return dataOut
314
314
315
315
316 class deFlip(Operation):
316 class deFlip(Operation):
317
317
318 def run(self, dataOut, channelList = []):
318 def run(self, dataOut, channelList = []):
319
319
320 data = dataOut.data.copy()
320 data = dataOut.data.copy()
321
321
322 if dataOut.flagDataAsBlock:
322 if dataOut.flagDataAsBlock:
323 flip = self.flip
323 flip = self.flip
324 profileList = list(range(dataOut.nProfiles))
324 profileList = list(range(dataOut.nProfiles))
325
325
326 if not channelList:
326 if not channelList:
327 for thisProfile in profileList:
327 for thisProfile in profileList:
328 data[:,thisProfile,:] = data[:,thisProfile,:]*flip
328 data[:,thisProfile,:] = data[:,thisProfile,:]*flip
329 flip *= -1.0
329 flip *= -1.0
330 else:
330 else:
331 for thisChannel in channelList:
331 for thisChannel in channelList:
332 if thisChannel not in dataOut.channelList:
332 if thisChannel not in dataOut.channelList:
333 continue
333 continue
334
334
335 for thisProfile in profileList:
335 for thisProfile in profileList:
336 data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip
336 data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip
337 flip *= -1.0
337 flip *= -1.0
338
338
339 self.flip = flip
339 self.flip = flip
340
340
341 else:
341 else:
342 if not channelList:
342 if not channelList:
343 data[:,:] = data[:,:]*self.flip
343 data[:,:] = data[:,:]*self.flip
344 else:
344 else:
345 for thisChannel in channelList:
345 for thisChannel in channelList:
346 if thisChannel not in dataOut.channelList:
346 if thisChannel not in dataOut.channelList:
347 continue
347 continue
348
348
349 data[thisChannel,:] = data[thisChannel,:]*self.flip
349 data[thisChannel,:] = data[thisChannel,:]*self.flip
350
350
351 self.flip *= -1.
351 self.flip *= -1.
352
352
353 dataOut.data = data
353 dataOut.data = data
354
354
355 return dataOut
355 return dataOut
356
356
357
357
358 class setAttribute(Operation):
358 class setAttribute(Operation):
359 '''
359 '''
360 Set an arbitrary attribute(s) to dataOut
360 Set an arbitrary attribute(s) to dataOut
361 '''
361 '''
362
362
363 def __init__(self):
363 def __init__(self):
364
364
365 Operation.__init__(self)
365 Operation.__init__(self)
366 self._ready = False
366 self._ready = False
367
367
368 def run(self, dataOut, **kwargs):
368 def run(self, dataOut, **kwargs):
369
369
370 for key, value in kwargs.items():
370 for key, value in kwargs.items():
371 setattr(dataOut, key, value)
371 setattr(dataOut, key, value)
372
372
373 return dataOut
373 return dataOut
374
374
375
375
376 @MPDecorator
376 @MPDecorator
377 class printAttribute(Operation):
377 class printAttribute(Operation):
378 '''
378 '''
379 Print an arbitrary attribute of dataOut
379 Print an arbitrary attribute of dataOut
380 '''
380 '''
381
381
382 def __init__(self):
382 def __init__(self):
383
383
384 Operation.__init__(self)
384 Operation.__init__(self)
385
385
386 def run(self, dataOut, attributes):
386 def run(self, dataOut, attributes):
387
387
388 if isinstance(attributes, str):
388 if isinstance(attributes, str):
389 attributes = [attributes]
389 attributes = [attributes]
390 for attr in attributes:
390 for attr in attributes:
391 if hasattr(dataOut, attr):
391 if hasattr(dataOut, attr):
392 log.log(getattr(dataOut, attr), attr)
392 log.log(getattr(dataOut, attr), attr)
393
393
394
394
395 class interpolateHeights(Operation):
395 class interpolateHeights(Operation):
396
396
397 def run(self, dataOut, topLim, botLim):
397 def run(self, dataOut, topLim, botLim):
398 #69 al 72 para julia
398 #69 al 72 para julia
399 #82-84 para meteoros
399 #82-84 para meteoros
400 if len(numpy.shape(dataOut.data))==2:
400 if len(numpy.shape(dataOut.data))==2:
401 sampInterp = (dataOut.data[:,botLim-1] + dataOut.data[:,topLim+1])/2
401 sampInterp = (dataOut.data[:,botLim-1] + dataOut.data[:,topLim+1])/2
402 sampInterp = numpy.transpose(numpy.tile(sampInterp,(topLim-botLim + 1,1)))
402 sampInterp = numpy.transpose(numpy.tile(sampInterp,(topLim-botLim + 1,1)))
403 #dataOut.data[:,botLim:limSup+1] = sampInterp
403 #dataOut.data[:,botLim:limSup+1] = sampInterp
404 dataOut.data[:,botLim:topLim+1] = sampInterp
404 dataOut.data[:,botLim:topLim+1] = sampInterp
405 else:
405 else:
406 nHeights = dataOut.data.shape[2]
406 nHeights = dataOut.data.shape[2]
407 x = numpy.hstack((numpy.arange(botLim),numpy.arange(topLim+1,nHeights)))
407 x = numpy.hstack((numpy.arange(botLim),numpy.arange(topLim+1,nHeights)))
408 y = dataOut.data[:,:,list(range(botLim))+list(range(topLim+1,nHeights))]
408 y = dataOut.data[:,:,list(range(botLim))+list(range(topLim+1,nHeights))]
409 f = interpolate.interp1d(x, y, axis = 2)
409 f = interpolate.interp1d(x, y, axis = 2)
410 xnew = numpy.arange(botLim,topLim+1)
410 xnew = numpy.arange(botLim,topLim+1)
411 ynew = f(xnew)
411 ynew = f(xnew)
412 dataOut.data[:,:,botLim:topLim+1] = ynew
412 dataOut.data[:,:,botLim:topLim+1] = ynew
413
413
414 return dataOut
414 return dataOut
415
415
416
416
417 class CohInt(Operation):
417 class CohInt(Operation):
418
418
419 isConfig = False
419 isConfig = False
420 __profIndex = 0
420 __profIndex = 0
421 __byTime = False
421 __byTime = False
422 __initime = None
422 __initime = None
423 __lastdatatime = None
423 __lastdatatime = None
424 __integrationtime = None
424 __integrationtime = None
425 __buffer = None
425 __buffer = None
426 __bufferStride = []
426 __bufferStride = []
427 __dataReady = False
427 __dataReady = False
428 __profIndexStride = 0
428 __profIndexStride = 0
429 __dataToPutStride = False
429 __dataToPutStride = False
430 n = None
430 n = None
431
431
432 def __init__(self, **kwargs):
432 def __init__(self, **kwargs):
433
433
434 Operation.__init__(self, **kwargs)
434 Operation.__init__(self, **kwargs)
435
435
436 def setup(self, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False):
436 def setup(self, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False):
437 """
437 """
438 Set the parameters of the integration class.
438 Set the parameters of the integration class.
439
439
440 Inputs:
440 Inputs:
441
441
442 n : Number of coherent integrations
442 n : Number of coherent integrations
443 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
443 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
444 overlapping :
444 overlapping :
445 """
445 """
446
446
447 self.__initime = None
447 self.__initime = None
448 self.__lastdatatime = 0
448 self.__lastdatatime = 0
449 self.__buffer = None
449 self.__buffer = None
450 self.__dataReady = False
450 self.__dataReady = False
451 self.byblock = byblock
451 self.byblock = byblock
452 self.stride = stride
452 self.stride = stride
453
453
454 if n == None and timeInterval == None:
454 if n == None and timeInterval == None:
455 raise ValueError("n or timeInterval should be specified ...")
455 raise ValueError("n or timeInterval should be specified ...")
456
456
457 if n != None:
457 if n != None:
458 self.n = n
458 self.n = n
459 self.__byTime = False
459 self.__byTime = False
460 else:
460 else:
461 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
461 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
462 self.n = 9999
462 self.n = 9999
463 self.__byTime = True
463 self.__byTime = True
464
464
465 if overlapping:
465 if overlapping:
466 self.__withOverlapping = True
466 self.__withOverlapping = True
467 self.__buffer = None
467 self.__buffer = None
468 else:
468 else:
469 self.__withOverlapping = False
469 self.__withOverlapping = False
470 self.__buffer = 0
470 self.__buffer = 0
471
471
472 self.__profIndex = 0
472 self.__profIndex = 0
473
473
474 def putData(self, data):
474 def putData(self, data):
475
475
476 """
476 """
477 Add a profile to the __buffer and increase in one the __profileIndex
477 Add a profile to the __buffer and increase in one the __profileIndex
478
478
479 """
479 """
480
480
481 if not self.__withOverlapping:
481 if not self.__withOverlapping:
482 self.__buffer += data.copy()
482 self.__buffer += data.copy()
483 self.__profIndex += 1
483 self.__profIndex += 1
484 return
484 return
485
485
486 #Overlapping data
486 #Overlapping data
487 nChannels, nHeis = data.shape
487 nChannels, nHeis = data.shape
488 data = numpy.reshape(data, (1, nChannels, nHeis))
488 data = numpy.reshape(data, (1, nChannels, nHeis))
489
489
490 #If the buffer is empty then it takes the data value
490 #If the buffer is empty then it takes the data value
491 if self.__buffer is None:
491 if self.__buffer is None:
492 self.__buffer = data
492 self.__buffer = data
493 self.__profIndex += 1
493 self.__profIndex += 1
494 return
494 return
495
495
496 #If the buffer length is lower than n then stakcing the data value
496 #If the buffer length is lower than n then stakcing the data value
497 if self.__profIndex < self.n:
497 if self.__profIndex < self.n:
498 self.__buffer = numpy.vstack((self.__buffer, data))
498 self.__buffer = numpy.vstack((self.__buffer, data))
499 self.__profIndex += 1
499 self.__profIndex += 1
500 return
500 return
501
501
502 #If the buffer length is equal to n then replacing the last buffer value with the data value
502 #If the buffer length is equal to n then replacing the last buffer value with the data value
503 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
503 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
504 self.__buffer[self.n-1] = data
504 self.__buffer[self.n-1] = data
505 self.__profIndex = self.n
505 self.__profIndex = self.n
506 return
506 return
507
507
508
508
509 def pushData(self):
509 def pushData(self):
510 """
510 """
511 Return the sum of the last profiles and the profiles used in the sum.
511 Return the sum of the last profiles and the profiles used in the sum.
512
512
513 Affected:
513 Affected:
514
514
515 self.__profileIndex
515 self.__profileIndex
516
516
517 """
517 """
518
518
519 if not self.__withOverlapping:
519 if not self.__withOverlapping:
520 data = self.__buffer
520 data = self.__buffer
521 n = self.__profIndex
521 n = self.__profIndex
522
522
523 self.__buffer = 0
523 self.__buffer = 0
524 self.__profIndex = 0
524 self.__profIndex = 0
525
525
526 return data, n
526 return data, n
527
527
528 #Integration with Overlapping
528 #Integration with Overlapping
529 data = numpy.sum(self.__buffer, axis=0)
529 data = numpy.sum(self.__buffer, axis=0)
530 # print data
530 # print data
531 # raise
531 # raise
532 n = self.__profIndex
532 n = self.__profIndex
533
533
534 return data, n
534 return data, n
535
535
536 def byProfiles(self, data):
536 def byProfiles(self, data):
537
537
538 self.__dataReady = False
538 self.__dataReady = False
539 avgdata = None
539 avgdata = None
540 # n = None
540 # n = None
541 # print data
541 # print data
542 # raise
542 # raise
543 self.putData(data)
543 self.putData(data)
544
544
545 if self.__profIndex == self.n:
545 if self.__profIndex == self.n:
546 avgdata, n = self.pushData()
546 avgdata, n = self.pushData()
547 self.__dataReady = True
547 self.__dataReady = True
548
548
549 return avgdata
549 return avgdata
550
550
551 def byTime(self, data, datatime):
551 def byTime(self, data, datatime):
552
552
553 self.__dataReady = False
553 self.__dataReady = False
554 avgdata = None
554 avgdata = None
555 n = None
555 n = None
556
556
557 self.putData(data)
557 self.putData(data)
558
558
559 if (datatime - self.__initime) >= self.__integrationtime:
559 if (datatime - self.__initime) >= self.__integrationtime:
560 avgdata, n = self.pushData()
560 avgdata, n = self.pushData()
561 self.n = n
561 self.n = n
562 self.__dataReady = True
562 self.__dataReady = True
563
563
564 return avgdata
564 return avgdata
565
565
566 def integrateByStride(self, data, datatime):
566 def integrateByStride(self, data, datatime):
567 # print data
567 # print data
568 if self.__profIndex == 0:
568 if self.__profIndex == 0:
569 self.__buffer = [[data.copy(), datatime]]
569 self.__buffer = [[data.copy(), datatime]]
570 else:
570 else:
571 self.__buffer.append([data.copy(),datatime])
571 self.__buffer.append([data.copy(),datatime])
572 self.__profIndex += 1
572 self.__profIndex += 1
573 self.__dataReady = False
573 self.__dataReady = False
574
574
575 if self.__profIndex == self.n * self.stride :
575 if self.__profIndex == self.n * self.stride :
576 self.__dataToPutStride = True
576 self.__dataToPutStride = True
577 self.__profIndexStride = 0
577 self.__profIndexStride = 0
578 self.__profIndex = 0
578 self.__profIndex = 0
579 self.__bufferStride = []
579 self.__bufferStride = []
580 for i in range(self.stride):
580 for i in range(self.stride):
581 current = self.__buffer[i::self.stride]
581 current = self.__buffer[i::self.stride]
582 data = numpy.sum([t[0] for t in current], axis=0)
582 data = numpy.sum([t[0] for t in current], axis=0)
583 avgdatatime = numpy.average([t[1] for t in current])
583 avgdatatime = numpy.average([t[1] for t in current])
584 # print data
584 # print data
585 self.__bufferStride.append((data, avgdatatime))
585 self.__bufferStride.append((data, avgdatatime))
586
586
587 if self.__dataToPutStride:
587 if self.__dataToPutStride:
588 self.__dataReady = True
588 self.__dataReady = True
589 self.__profIndexStride += 1
589 self.__profIndexStride += 1
590 if self.__profIndexStride == self.stride:
590 if self.__profIndexStride == self.stride:
591 self.__dataToPutStride = False
591 self.__dataToPutStride = False
592 # print self.__bufferStride[self.__profIndexStride - 1]
592 # print self.__bufferStride[self.__profIndexStride - 1]
593 # raise
593 # raise
594 return self.__bufferStride[self.__profIndexStride - 1]
594 return self.__bufferStride[self.__profIndexStride - 1]
595
595
596
596
597 return None, None
597 return None, None
598
598
599 def integrate(self, data, datatime=None):
599 def integrate(self, data, datatime=None):
600
600
601 if self.__initime == None:
601 if self.__initime == None:
602 self.__initime = datatime
602 self.__initime = datatime
603
603
604 if self.__byTime:
604 if self.__byTime:
605 avgdata = self.byTime(data, datatime)
605 avgdata = self.byTime(data, datatime)
606 else:
606 else:
607 avgdata = self.byProfiles(data)
607 avgdata = self.byProfiles(data)
608
608
609
609
610 self.__lastdatatime = datatime
610 self.__lastdatatime = datatime
611
611
612 if avgdata is None:
612 if avgdata is None:
613 return None, None
613 return None, None
614
614
615 avgdatatime = self.__initime
615 avgdatatime = self.__initime
616
616
617 deltatime = datatime - self.__lastdatatime
617 deltatime = datatime - self.__lastdatatime
618
618
619 if not self.__withOverlapping:
619 if not self.__withOverlapping:
620 self.__initime = datatime
620 self.__initime = datatime
621 else:
621 else:
622 self.__initime += deltatime
622 self.__initime += deltatime
623
623
624 return avgdata, avgdatatime
624 return avgdata, avgdatatime
625
625
626 def integrateByBlock(self, dataOut):
626 def integrateByBlock(self, dataOut):
627
627
628 times = int(dataOut.data.shape[1]/self.n)
628 times = int(dataOut.data.shape[1]/self.n)
629 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex)
629 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex)
630
630
631 id_min = 0
631 id_min = 0
632 id_max = self.n
632 id_max = self.n
633
633
634 for i in range(times):
634 for i in range(times):
635 junk = dataOut.data[:,id_min:id_max,:]
635 junk = dataOut.data[:,id_min:id_max,:]
636 avgdata[:,i,:] = junk.sum(axis=1)
636 avgdata[:,i,:] = junk.sum(axis=1)
637 id_min += self.n
637 id_min += self.n
638 id_max += self.n
638 id_max += self.n
639
639
640 timeInterval = dataOut.ippSeconds*self.n
640 timeInterval = dataOut.ippSeconds*self.n
641 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
641 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
642 self.__dataReady = True
642 self.__dataReady = True
643 return avgdata, avgdatatime
643 return avgdata, avgdatatime
644
644
645 def run(self, dataOut, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False, **kwargs):
645 def run(self, dataOut, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False, **kwargs):
646
646
647 if not self.isConfig:
647 if not self.isConfig:
648 self.setup(n=n, stride=stride, timeInterval=timeInterval, overlapping=overlapping, byblock=byblock, **kwargs)
648 self.setup(n=n, stride=stride, timeInterval=timeInterval, overlapping=overlapping, byblock=byblock, **kwargs)
649 self.isConfig = True
649 self.isConfig = True
650
650
651 if dataOut.flagDataAsBlock:
651 if dataOut.flagDataAsBlock:
652 """
652 """
653 Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis]
653 Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis]
654 """
654 """
655 avgdata, avgdatatime = self.integrateByBlock(dataOut)
655 avgdata, avgdatatime = self.integrateByBlock(dataOut)
656 dataOut.nProfiles /= self.n
656 dataOut.nProfiles /= self.n
657 else:
657 else:
658 if stride is None:
658 if stride is None:
659 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
659 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
660 else:
660 else:
661 avgdata, avgdatatime = self.integrateByStride(dataOut.data, dataOut.utctime)
661 avgdata, avgdatatime = self.integrateByStride(dataOut.data, dataOut.utctime)
662
662
663
663
664 # dataOut.timeInterval *= n
664 # dataOut.timeInterval *= n
665 dataOut.flagNoData = True
665 dataOut.flagNoData = True
666
666
667 if self.__dataReady:
667 if self.__dataReady:
668 dataOut.data = avgdata
668 dataOut.data = avgdata
669 if not dataOut.flagCohInt:
669 if not dataOut.flagCohInt:
670 dataOut.nCohInt *= self.n
670 dataOut.nCohInt *= self.n
671 dataOut.flagCohInt = True
671 dataOut.flagCohInt = True
672 dataOut.utctime = avgdatatime
672 dataOut.utctime = avgdatatime
673 # print avgdata, avgdatatime
673 # print avgdata, avgdatatime
674 # raise
674 # raise
675 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
675 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
676 dataOut.flagNoData = False
676 dataOut.flagNoData = False
677 return dataOut
677 return dataOut
678
678
679 class Decoder(Operation):
679 class Decoder(Operation):
680
680
681 isConfig = False
681 isConfig = False
682 __profIndex = 0
682 __profIndex = 0
683
683
684 code = None
684 code = None
685
685
686 nCode = None
686 nCode = None
687 nBaud = None
687 nBaud = None
688
688
689 def __init__(self, **kwargs):
689 def __init__(self, **kwargs):
690
690
691 Operation.__init__(self, **kwargs)
691 Operation.__init__(self, **kwargs)
692
692
693 self.times = None
693 self.times = None
694 self.osamp = None
694 self.osamp = None
695 # self.__setValues = False
695 # self.__setValues = False
696 self.isConfig = False
696 self.isConfig = False
697 self.setupReq = False
697 self.setupReq = False
698 def setup(self, code, osamp, dataOut):
698 def setup(self, code, osamp, dataOut):
699
699
700 self.__profIndex = 0
700 self.__profIndex = 0
701
701
702 self.code = code
702 self.code = code
703
703
704 self.nCode = len(code)
704 self.nCode = len(code)
705 self.nBaud = len(code[0])
705 self.nBaud = len(code[0])
706
706
707 if (osamp != None) and (osamp >1):
707 if (osamp != None) and (osamp >1):
708 self.osamp = osamp
708 self.osamp = osamp
709 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
709 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
710 self.nBaud = self.nBaud*self.osamp
710 self.nBaud = self.nBaud*self.osamp
711
711
712 self.__nChannels = dataOut.nChannels
712 self.__nChannels = dataOut.nChannels
713 self.__nProfiles = dataOut.nProfiles
713 self.__nProfiles = dataOut.nProfiles
714 self.__nHeis = dataOut.nHeights
714 self.__nHeis = dataOut.nHeights
715
715
716 if self.__nHeis < self.nBaud:
716 if self.__nHeis < self.nBaud:
717 raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud))
717 raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud))
718
718
719 #Frequency
719 #Frequency
720 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
720 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
721
721
722 __codeBuffer[:,0:self.nBaud] = self.code
722 __codeBuffer[:,0:self.nBaud] = self.code
723
723
724 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
724 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
725
725
726 if dataOut.flagDataAsBlock:
726 if dataOut.flagDataAsBlock:
727
727
728 self.ndatadec = self.__nHeis #- self.nBaud + 1
728 self.ndatadec = self.__nHeis #- self.nBaud + 1
729
729
730 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex)
730 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex)
731
731
732 else:
732 else:
733
733
734 #Time
734 #Time
735 self.ndatadec = self.__nHeis #- self.nBaud + 1
735 self.ndatadec = self.__nHeis #- self.nBaud + 1
736
736
737 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
737 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
738
738
739 def __convolutionInFreq(self, data):
739 def __convolutionInFreq(self, data):
740
740
741 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
741 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
742
742
743 fft_data = numpy.fft.fft(data, axis=1)
743 fft_data = numpy.fft.fft(data, axis=1)
744
744
745 conv = fft_data*fft_code
745 conv = fft_data*fft_code
746
746
747 data = numpy.fft.ifft(conv,axis=1)
747 data = numpy.fft.ifft(conv,axis=1)
748
748
749 return data
749 return data
750
750
751 def __convolutionInFreqOpt(self, data):
751 def __convolutionInFreqOpt(self, data):
752
752
753 raise NotImplementedError
753 raise NotImplementedError
754
754
755 def __convolutionInTime(self, data):
755 def __convolutionInTime(self, data):
756
756
757 code = self.code[self.__profIndex]
757 code = self.code[self.__profIndex]
758 for i in range(self.__nChannels):
758 for i in range(self.__nChannels):
759 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
759 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
760
760
761 return self.datadecTime
761 return self.datadecTime
762
762
763 def __convolutionByBlockInTime(self, data):
763 def __convolutionByBlockInTime(self, data):
764
764
765 repetitions = int(self.__nProfiles / self.nCode)
765 repetitions = int(self.__nProfiles / self.nCode)
766 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
766 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
767 junk = junk.flatten()
767 junk = junk.flatten()
768 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
768 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
769 profilesList = range(self.__nProfiles)
769 profilesList = range(self.__nProfiles)
770
770
771 for i in range(self.__nChannels):
771 for i in range(self.__nChannels):
772 for j in profilesList:
772 for j in profilesList:
773 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
773 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
774 return self.datadecTime
774 return self.datadecTime
775
775
776 def __convolutionByBlockInFreq(self, data):
776 def __convolutionByBlockInFreq(self, data):
777
777
778 raise NotImplementedError("Decoder by frequency fro Blocks not implemented")
778 raise NotImplementedError("Decoder by frequency fro Blocks not implemented")
779
779
780
780
781 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
781 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
782
782
783 fft_data = numpy.fft.fft(data, axis=2)
783 fft_data = numpy.fft.fft(data, axis=2)
784
784
785 conv = fft_data*fft_code
785 conv = fft_data*fft_code
786
786
787 data = numpy.fft.ifft(conv,axis=2)
787 data = numpy.fft.ifft(conv,axis=2)
788
788
789 return data
789 return data
790
790
791
791
792 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
792 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
793
793
794 if dataOut.flagDecodeData:
794 if dataOut.flagDecodeData:
795 print("This data is already decoded, recoding again ...")
795 print("This data is already decoded, recoding again ...")
796
796
797 if not self.isConfig:
797 if not self.isConfig:
798
798
799 if code is None:
799 if code is None:
800 if dataOut.code is None:
800 if dataOut.code is None:
801 raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type)
801 raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type)
802
802
803 code = dataOut.code
803 code = dataOut.code
804 else:
804 else:
805 code = numpy.array(code).reshape(nCode,nBaud)
805 code = numpy.array(code).reshape(nCode,nBaud)
806 self.setup(code, osamp, dataOut)
806 self.setup(code, osamp, dataOut)
807
807
808 self.isConfig = True
808 self.isConfig = True
809
809
810 if mode == 3:
810 if mode == 3:
811 sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode)
811 sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode)
812
812
813 if times != None:
813 if times != None:
814 sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n")
814 sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n")
815
815
816 if self.code is None:
816 if self.code is None:
817 print("Fail decoding: Code is not defined.")
817 print("Fail decoding: Code is not defined.")
818 return
818 return
819
819
820 self.__nProfiles = dataOut.nProfiles
820 self.__nProfiles = dataOut.nProfiles
821 datadec = None
821 datadec = None
822
822
823 if mode == 3:
823 if mode == 3:
824 mode = 0
824 mode = 0
825
825
826 if dataOut.flagDataAsBlock:
826 if dataOut.flagDataAsBlock:
827 """
827 """
828 Decoding when data have been read as block,
828 Decoding when data have been read as block,
829 """
829 """
830
830
831 if mode == 0:
831 if mode == 0:
832 datadec = self.__convolutionByBlockInTime(dataOut.data)
832 datadec = self.__convolutionByBlockInTime(dataOut.data)
833 if mode == 1:
833 if mode == 1:
834 datadec = self.__convolutionByBlockInFreq(dataOut.data)
834 datadec = self.__convolutionByBlockInFreq(dataOut.data)
835 else:
835 else:
836 """
836 """
837 Decoding when data have been read profile by profile
837 Decoding when data have been read profile by profile
838 """
838 """
839 if mode == 0:
839 if mode == 0:
840 datadec = self.__convolutionInTime(dataOut.data)
840 datadec = self.__convolutionInTime(dataOut.data)
841
841
842 if mode == 1:
842 if mode == 1:
843 datadec = self.__convolutionInFreq(dataOut.data)
843 datadec = self.__convolutionInFreq(dataOut.data)
844
844
845 if mode == 2:
845 if mode == 2:
846 datadec = self.__convolutionInFreqOpt(dataOut.data)
846 datadec = self.__convolutionInFreqOpt(dataOut.data)
847
847
848 if datadec is None:
848 if datadec is None:
849 raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode)
849 raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode)
850
850
851 dataOut.code = self.code
851 dataOut.code = self.code
852 dataOut.nCode = self.nCode
852 dataOut.nCode = self.nCode
853 dataOut.nBaud = self.nBaud
853 dataOut.nBaud = self.nBaud
854
854
855 dataOut.data = datadec
855 dataOut.data = datadec
856
856
857 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
857 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
858
858
859 dataOut.flagDecodeData = True #asumo q la data esta decodificada
859 dataOut.flagDecodeData = True #asumo q la data esta decodificada
860
860
861 if self.__profIndex == self.nCode-1:
861 if self.__profIndex == self.nCode-1:
862 self.__profIndex = 0
862 self.__profIndex = 0
863 return dataOut
863 return dataOut
864
864
865 self.__profIndex += 1
865 self.__profIndex += 1
866
866
867 return dataOut
867 return dataOut
868 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
868 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
869
869
870
870
871 class ProfileConcat(Operation):
871 class ProfileConcat(Operation):
872
872
873 isConfig = False
873 isConfig = False
874 buffer = None
874 buffer = None
875
875
876 def __init__(self, **kwargs):
876 def __init__(self, **kwargs):
877
877
878 Operation.__init__(self, **kwargs)
878 Operation.__init__(self, **kwargs)
879 self.profileIndex = 0
879 self.profileIndex = 0
880
880
881 def reset(self):
881 def reset(self):
882 self.buffer = numpy.zeros_like(self.buffer)
882 self.buffer = numpy.zeros_like(self.buffer)
883 self.start_index = 0
883 self.start_index = 0
884 self.times = 1
884 self.times = 1
885
885
886 def setup(self, data, m, n=1):
886 def setup(self, data, m, n=1):
887 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
887 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
888 self.nHeights = data.shape[1]#.nHeights
888 self.nHeights = data.shape[1]#.nHeights
889 self.start_index = 0
889 self.start_index = 0
890 self.times = 1
890 self.times = 1
891
891
892 def concat(self, data):
892 def concat(self, data):
893
893
894 self.buffer[:,self.start_index:self.nHeights*self.times] = data.copy()
894 self.buffer[:,self.start_index:self.nHeights*self.times] = data.copy()
895 self.start_index = self.start_index + self.nHeights
895 self.start_index = self.start_index + self.nHeights
896
896
897 def run(self, dataOut, m):
897 def run(self, dataOut, m):
898 dataOut.flagNoData = True
898 dataOut.flagNoData = True
899
899
900 if not self.isConfig:
900 if not self.isConfig:
901 self.setup(dataOut.data, m, 1)
901 self.setup(dataOut.data, m, 1)
902 self.isConfig = True
902 self.isConfig = True
903
903
904 if dataOut.flagDataAsBlock:
904 if dataOut.flagDataAsBlock:
905 raise ValueError("ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False")
905 raise ValueError("ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False")
906
906
907 else:
907 else:
908 self.concat(dataOut.data)
908 self.concat(dataOut.data)
909 self.times += 1
909 self.times += 1
910 if self.times > m:
910 if self.times > m:
911 dataOut.data = self.buffer
911 dataOut.data = self.buffer
912 self.reset()
912 self.reset()
913 dataOut.flagNoData = False
913 dataOut.flagNoData = False
914 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
914 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
915 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
915 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
916 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m
916 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m
917 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
917 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
918 dataOut.ippSeconds *= m
918 dataOut.ippSeconds *= m
919 return dataOut
919 return dataOut
920
920
921 class ProfileSelector(Operation):
921 class ProfileSelector(Operation):
922
922
923 profileIndex = None
923 profileIndex = None
924 # Tamanho total de los perfiles
924 # Tamanho total de los perfiles
925 nProfiles = None
925 nProfiles = None
926
926
927 def __init__(self, **kwargs):
927 def __init__(self, **kwargs):
928
928
929 Operation.__init__(self, **kwargs)
929 Operation.__init__(self, **kwargs)
930 self.profileIndex = 0
930 self.profileIndex = 0
931
931
932 def incProfileIndex(self):
932 def incProfileIndex(self):
933
933
934 self.profileIndex += 1
934 self.profileIndex += 1
935
935
936 if self.profileIndex >= self.nProfiles:
936 if self.profileIndex >= self.nProfiles:
937 self.profileIndex = 0
937 self.profileIndex = 0
938
938
939 def isThisProfileInRange(self, profileIndex, minIndex, maxIndex):
939 def isThisProfileInRange(self, profileIndex, minIndex, maxIndex):
940
940
941 if profileIndex < minIndex:
941 if profileIndex < minIndex:
942 return False
942 return False
943
943
944 if profileIndex > maxIndex:
944 if profileIndex > maxIndex:
945 return False
945 return False
946
946
947 return True
947 return True
948
948
949 def isThisProfileInList(self, profileIndex, profileList):
949 def isThisProfileInList(self, profileIndex, profileList):
950
950
951 if profileIndex not in profileList:
951 if profileIndex not in profileList:
952 return False
952 return False
953
953
954 return True
954 return True
955
955
956 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None):
956 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None):
957
957
958 """
958 """
959 ProfileSelector:
959 ProfileSelector:
960
960
961 Inputs:
961 Inputs:
962 profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8)
962 profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8)
963
963
964 profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30)
964 profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30)
965
965
966 rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256))
966 rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256))
967
967
968 """
968 """
969
969
970 if rangeList is not None:
970 if rangeList is not None:
971 if type(rangeList[0]) not in (tuple, list):
971 if type(rangeList[0]) not in (tuple, list):
972 rangeList = [rangeList]
972 rangeList = [rangeList]
973
973
974 dataOut.flagNoData = True
974 dataOut.flagNoData = True
975
975
976 if dataOut.flagDataAsBlock:
976 if dataOut.flagDataAsBlock:
977 """
977 """
978 data dimension = [nChannels, nProfiles, nHeis]
978 data dimension = [nChannels, nProfiles, nHeis]
979 """
979 """
980 if profileList != None:
980 if profileList != None:
981 dataOut.data = dataOut.data[:,profileList,:]
981 dataOut.data = dataOut.data[:,profileList,:]
982
982
983 if profileRangeList != None:
983 if profileRangeList != None:
984 minIndex = profileRangeList[0]
984 minIndex = profileRangeList[0]
985 maxIndex = profileRangeList[1]
985 maxIndex = profileRangeList[1]
986 profileList = list(range(minIndex, maxIndex+1))
986 profileList = list(range(minIndex, maxIndex+1))
987
987
988 dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:]
988 dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:]
989
989
990 if rangeList != None:
990 if rangeList != None:
991
991
992 profileList = []
992 profileList = []
993
993
994 for thisRange in rangeList:
994 for thisRange in rangeList:
995 minIndex = thisRange[0]
995 minIndex = thisRange[0]
996 maxIndex = thisRange[1]
996 maxIndex = thisRange[1]
997
997
998 profileList.extend(list(range(minIndex, maxIndex+1)))
998 profileList.extend(list(range(minIndex, maxIndex+1)))
999
999
1000 dataOut.data = dataOut.data[:,profileList,:]
1000 dataOut.data = dataOut.data[:,profileList,:]
1001
1001
1002 dataOut.nProfiles = len(profileList)
1002 dataOut.nProfiles = len(profileList)
1003 dataOut.profileIndex = dataOut.nProfiles - 1
1003 dataOut.profileIndex = dataOut.nProfiles - 1
1004 dataOut.flagNoData = False
1004 dataOut.flagNoData = False
1005
1005
1006 return dataOut
1006 return dataOut
1007
1007
1008 """
1008 """
1009 data dimension = [nChannels, nHeis]
1009 data dimension = [nChannels, nHeis]
1010 """
1010 """
1011
1011
1012 if profileList != None:
1012 if profileList != None:
1013
1013
1014 if self.isThisProfileInList(dataOut.profileIndex, profileList):
1014 if self.isThisProfileInList(dataOut.profileIndex, profileList):
1015
1015
1016 self.nProfiles = len(profileList)
1016 self.nProfiles = len(profileList)
1017 dataOut.nProfiles = self.nProfiles
1017 dataOut.nProfiles = self.nProfiles
1018 dataOut.profileIndex = self.profileIndex
1018 dataOut.profileIndex = self.profileIndex
1019 dataOut.flagNoData = False
1019 dataOut.flagNoData = False
1020
1020
1021 self.incProfileIndex()
1021 self.incProfileIndex()
1022 return dataOut
1022 return dataOut
1023
1023
1024 if profileRangeList != None:
1024 if profileRangeList != None:
1025
1025
1026 minIndex = profileRangeList[0]
1026 minIndex = profileRangeList[0]
1027 maxIndex = profileRangeList[1]
1027 maxIndex = profileRangeList[1]
1028
1028
1029 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
1029 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
1030
1030
1031 self.nProfiles = maxIndex - minIndex + 1
1031 self.nProfiles = maxIndex - minIndex + 1
1032 dataOut.nProfiles = self.nProfiles
1032 dataOut.nProfiles = self.nProfiles
1033 dataOut.profileIndex = self.profileIndex
1033 dataOut.profileIndex = self.profileIndex
1034 dataOut.flagNoData = False
1034 dataOut.flagNoData = False
1035
1035
1036 self.incProfileIndex()
1036 self.incProfileIndex()
1037 return dataOut
1037 return dataOut
1038
1038
1039 if rangeList != None:
1039 if rangeList != None:
1040
1040
1041 nProfiles = 0
1041 nProfiles = 0
1042
1042
1043 for thisRange in rangeList:
1043 for thisRange in rangeList:
1044 minIndex = thisRange[0]
1044 minIndex = thisRange[0]
1045 maxIndex = thisRange[1]
1045 maxIndex = thisRange[1]
1046
1046
1047 nProfiles += maxIndex - minIndex + 1
1047 nProfiles += maxIndex - minIndex + 1
1048
1048
1049 for thisRange in rangeList:
1049 for thisRange in rangeList:
1050
1050
1051 minIndex = thisRange[0]
1051 minIndex = thisRange[0]
1052 maxIndex = thisRange[1]
1052 maxIndex = thisRange[1]
1053
1053
1054 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
1054 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
1055
1055
1056 self.nProfiles = nProfiles
1056 self.nProfiles = nProfiles
1057 dataOut.nProfiles = self.nProfiles
1057 dataOut.nProfiles = self.nProfiles
1058 dataOut.profileIndex = self.profileIndex
1058 dataOut.profileIndex = self.profileIndex
1059 dataOut.flagNoData = False
1059 dataOut.flagNoData = False
1060
1060
1061 self.incProfileIndex()
1061 self.incProfileIndex()
1062
1062
1063 break
1063 break
1064
1064
1065 return dataOut
1065 return dataOut
1066
1066
1067
1067
1068 if beam != None: #beam is only for AMISR data
1068 if beam != None: #beam is only for AMISR data
1069 if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]):
1069 if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]):
1070 dataOut.flagNoData = False
1070 dataOut.flagNoData = False
1071 dataOut.profileIndex = self.profileIndex
1071 dataOut.profileIndex = self.profileIndex
1072
1072
1073 self.incProfileIndex()
1073 self.incProfileIndex()
1074
1074
1075 return dataOut
1075 return dataOut
1076
1076
1077 raise ValueError("ProfileSelector needs profileList, profileRangeList or rangeList parameter")
1077 raise ValueError("ProfileSelector needs profileList, profileRangeList or rangeList parameter")
1078
1078
1079
1079
1080 class Reshaper(Operation):
1080 class Reshaper(Operation):
1081
1081
1082 def __init__(self, **kwargs):
1082 def __init__(self, **kwargs):
1083
1083
1084 Operation.__init__(self, **kwargs)
1084 Operation.__init__(self, **kwargs)
1085
1085
1086 self.__buffer = None
1086 self.__buffer = None
1087 self.__nitems = 0
1087 self.__nitems = 0
1088
1088
1089 def __appendProfile(self, dataOut, nTxs):
1089 def __appendProfile(self, dataOut, nTxs):
1090
1090
1091 if self.__buffer is None:
1091 if self.__buffer is None:
1092 shape = (dataOut.nChannels, int(dataOut.nHeights/nTxs) )
1092 shape = (dataOut.nChannels, int(dataOut.nHeights/nTxs) )
1093 self.__buffer = numpy.empty(shape, dtype = dataOut.data.dtype)
1093 self.__buffer = numpy.empty(shape, dtype = dataOut.data.dtype)
1094
1094
1095 ini = dataOut.nHeights * self.__nitems
1095 ini = dataOut.nHeights * self.__nitems
1096 end = ini + dataOut.nHeights
1096 end = ini + dataOut.nHeights
1097
1097
1098 self.__buffer[:, ini:end] = dataOut.data
1098 self.__buffer[:, ini:end] = dataOut.data
1099
1099
1100 self.__nitems += 1
1100 self.__nitems += 1
1101
1101
1102 return int(self.__nitems*nTxs)
1102 return int(self.__nitems*nTxs)
1103
1103
1104 def __getBuffer(self):
1104 def __getBuffer(self):
1105
1105
1106 if self.__nitems == int(1./self.__nTxs):
1106 if self.__nitems == int(1./self.__nTxs):
1107
1107
1108 self.__nitems = 0
1108 self.__nitems = 0
1109
1109
1110 return self.__buffer.copy()
1110 return self.__buffer.copy()
1111
1111
1112 return None
1112 return None
1113
1113
1114 def __checkInputs(self, dataOut, shape, nTxs):
1114 def __checkInputs(self, dataOut, shape, nTxs):
1115
1115
1116 if shape is None and nTxs is None:
1116 if shape is None and nTxs is None:
1117 raise ValueError("Reshaper: shape of factor should be defined")
1117 raise ValueError("Reshaper: shape of factor should be defined")
1118
1118
1119 if nTxs:
1119 if nTxs:
1120 if nTxs < 0:
1120 if nTxs < 0:
1121 raise ValueError("nTxs should be greater than 0")
1121 raise ValueError("nTxs should be greater than 0")
1122
1122
1123 if nTxs < 1 and dataOut.nProfiles % (1./nTxs) != 0:
1123 if nTxs < 1 and dataOut.nProfiles % (1./nTxs) != 0:
1124 raise ValueError("nProfiles= %d is not divisibled by (1./nTxs) = %f" %(dataOut.nProfiles, (1./nTxs)))
1124 raise ValueError("nProfiles= %d is not divisibled by (1./nTxs) = %f" %(dataOut.nProfiles, (1./nTxs)))
1125
1125
1126 shape = [dataOut.nChannels, dataOut.nProfiles*nTxs, dataOut.nHeights/nTxs]
1126 shape = [dataOut.nChannels, dataOut.nProfiles*nTxs, dataOut.nHeights/nTxs]
1127
1127
1128 return shape, nTxs
1128 return shape, nTxs
1129
1129
1130 if len(shape) != 2 and len(shape) != 3:
1130 if len(shape) != 2 and len(shape) != 3:
1131 raise ValueError("shape dimension should be equal to 2 or 3. shape = (nProfiles, nHeis) or (nChannels, nProfiles, nHeis). Actually shape = (%d, %d, %d)" %(dataOut.nChannels, dataOut.nProfiles, dataOut.nHeights))
1131 raise ValueError("shape dimension should be equal to 2 or 3. shape = (nProfiles, nHeis) or (nChannels, nProfiles, nHeis). Actually shape = (%d, %d, %d)" %(dataOut.nChannels, dataOut.nProfiles, dataOut.nHeights))
1132
1132
1133 if len(shape) == 2:
1133 if len(shape) == 2:
1134 shape_tuple = [dataOut.nChannels]
1134 shape_tuple = [dataOut.nChannels]
1135 shape_tuple.extend(shape)
1135 shape_tuple.extend(shape)
1136 else:
1136 else:
1137 shape_tuple = list(shape)
1137 shape_tuple = list(shape)
1138
1138
1139 nTxs = 1.0*shape_tuple[1]/dataOut.nProfiles
1139 nTxs = 1.0*shape_tuple[1]/dataOut.nProfiles
1140
1140
1141 return shape_tuple, nTxs
1141 return shape_tuple, nTxs
1142
1142
1143 def run(self, dataOut, shape=None, nTxs=None):
1143 def run(self, dataOut, shape=None, nTxs=None):
1144
1144
1145 shape_tuple, self.__nTxs = self.__checkInputs(dataOut, shape, nTxs)
1145 shape_tuple, self.__nTxs = self.__checkInputs(dataOut, shape, nTxs)
1146
1146
1147 dataOut.flagNoData = True
1147 dataOut.flagNoData = True
1148 profileIndex = None
1148 profileIndex = None
1149
1149
1150 if dataOut.flagDataAsBlock:
1150 if dataOut.flagDataAsBlock:
1151
1151
1152 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
1152 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
1153 dataOut.flagNoData = False
1153 dataOut.flagNoData = False
1154
1154
1155 profileIndex = int(dataOut.nProfiles*self.__nTxs) - 1
1155 profileIndex = int(dataOut.nProfiles*self.__nTxs) - 1
1156
1156
1157 else:
1157 else:
1158
1158
1159 if self.__nTxs < 1:
1159 if self.__nTxs < 1:
1160
1160
1161 self.__appendProfile(dataOut, self.__nTxs)
1161 self.__appendProfile(dataOut, self.__nTxs)
1162 new_data = self.__getBuffer()
1162 new_data = self.__getBuffer()
1163
1163
1164 if new_data is not None:
1164 if new_data is not None:
1165 dataOut.data = new_data
1165 dataOut.data = new_data
1166 dataOut.flagNoData = False
1166 dataOut.flagNoData = False
1167
1167
1168 profileIndex = dataOut.profileIndex*nTxs
1168 profileIndex = dataOut.profileIndex*nTxs
1169
1169
1170 else:
1170 else:
1171 raise ValueError("nTxs should be greater than 0 and lower than 1, or use VoltageReader(..., getblock=True)")
1171 raise ValueError("nTxs should be greater than 0 and lower than 1, or use VoltageReader(..., getblock=True)")
1172
1172
1173 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1173 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1174
1174
1175 dataOut.heightList = numpy.arange(dataOut.nHeights/self.__nTxs) * deltaHeight + dataOut.heightList[0]
1175 dataOut.heightList = numpy.arange(dataOut.nHeights/self.__nTxs) * deltaHeight + dataOut.heightList[0]
1176
1176
1177 dataOut.nProfiles = int(dataOut.nProfiles*self.__nTxs)
1177 dataOut.nProfiles = int(dataOut.nProfiles*self.__nTxs)
1178
1178
1179 dataOut.profileIndex = profileIndex
1179 dataOut.profileIndex = profileIndex
1180
1180
1181 dataOut.ippSeconds /= self.__nTxs
1181 dataOut.ippSeconds /= self.__nTxs
1182
1182
1183 return dataOut
1183 return dataOut
1184
1184
1185 class SplitProfiles(Operation):
1185 class SplitProfiles(Operation):
1186
1186
1187 def __init__(self, **kwargs):
1187 def __init__(self, **kwargs):
1188
1188
1189 Operation.__init__(self, **kwargs)
1189 Operation.__init__(self, **kwargs)
1190
1190
1191 def run(self, dataOut, n):
1191 def run(self, dataOut, n):
1192
1192
1193 dataOut.flagNoData = True
1193 dataOut.flagNoData = True
1194 profileIndex = None
1194 profileIndex = None
1195
1195
1196 if dataOut.flagDataAsBlock:
1196 if dataOut.flagDataAsBlock:
1197
1197
1198 #nchannels, nprofiles, nsamples
1198 #nchannels, nprofiles, nsamples
1199 shape = dataOut.data.shape
1199 shape = dataOut.data.shape
1200
1200
1201 if shape[2] % n != 0:
1201 if shape[2] % n != 0:
1202 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[2]))
1202 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[2]))
1203
1203
1204 new_shape = shape[0], shape[1]*n, int(shape[2]/n)
1204 new_shape = shape[0], shape[1]*n, int(shape[2]/n)
1205
1205
1206 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1206 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1207 dataOut.flagNoData = False
1207 dataOut.flagNoData = False
1208
1208
1209 profileIndex = int(dataOut.nProfiles/n) - 1
1209 profileIndex = int(dataOut.nProfiles/n) - 1
1210
1210
1211 else:
1211 else:
1212
1212
1213 raise ValueError("Could not split the data when is read Profile by Profile. Use VoltageReader(..., getblock=True)")
1213 raise ValueError("Could not split the data when is read Profile by Profile. Use VoltageReader(..., getblock=True)")
1214
1214
1215 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1215 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1216
1216
1217 dataOut.heightList = numpy.arange(dataOut.nHeights/n) * deltaHeight + dataOut.heightList[0]
1217 dataOut.heightList = numpy.arange(dataOut.nHeights/n) * deltaHeight + dataOut.heightList[0]
1218
1218
1219 dataOut.nProfiles = int(dataOut.nProfiles*n)
1219 dataOut.nProfiles = int(dataOut.nProfiles*n)
1220
1220
1221 dataOut.profileIndex = profileIndex
1221 dataOut.profileIndex = profileIndex
1222
1222
1223 dataOut.ippSeconds /= n
1223 dataOut.ippSeconds /= n
1224
1224
1225 return dataOut
1225 return dataOut
1226
1226
1227 class CombineProfiles(Operation):
1227 class CombineProfiles(Operation):
1228 def __init__(self, **kwargs):
1228 def __init__(self, **kwargs):
1229
1229
1230 Operation.__init__(self, **kwargs)
1230 Operation.__init__(self, **kwargs)
1231
1231
1232 self.__remData = None
1232 self.__remData = None
1233 self.__profileIndex = 0
1233 self.__profileIndex = 0
1234
1234
1235 def run(self, dataOut, n):
1235 def run(self, dataOut, n):
1236
1236
1237 dataOut.flagNoData = True
1237 dataOut.flagNoData = True
1238 profileIndex = None
1238 profileIndex = None
1239
1239
1240 if dataOut.flagDataAsBlock:
1240 if dataOut.flagDataAsBlock:
1241
1241
1242 #nchannels, nprofiles, nsamples
1242 #nchannels, nprofiles, nsamples
1243 shape = dataOut.data.shape
1243 shape = dataOut.data.shape
1244 new_shape = shape[0], shape[1]/n, shape[2]*n
1244 new_shape = shape[0], shape[1]/n, shape[2]*n
1245
1245
1246 if shape[1] % n != 0:
1246 if shape[1] % n != 0:
1247 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[1]))
1247 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[1]))
1248
1248
1249 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1249 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1250 dataOut.flagNoData = False
1250 dataOut.flagNoData = False
1251
1251
1252 profileIndex = int(dataOut.nProfiles*n) - 1
1252 profileIndex = int(dataOut.nProfiles*n) - 1
1253
1253
1254 else:
1254 else:
1255
1255
1256 #nchannels, nsamples
1256 #nchannels, nsamples
1257 if self.__remData is None:
1257 if self.__remData is None:
1258 newData = dataOut.data
1258 newData = dataOut.data
1259 else:
1259 else:
1260 newData = numpy.concatenate((self.__remData, dataOut.data), axis=1)
1260 newData = numpy.concatenate((self.__remData, dataOut.data), axis=1)
1261
1261
1262 self.__profileIndex += 1
1262 self.__profileIndex += 1
1263
1263
1264 if self.__profileIndex < n:
1264 if self.__profileIndex < n:
1265 self.__remData = newData
1265 self.__remData = newData
1266 #continue
1266 #continue
1267 return
1267 return
1268
1268
1269 self.__profileIndex = 0
1269 self.__profileIndex = 0
1270 self.__remData = None
1270 self.__remData = None
1271
1271
1272 dataOut.data = newData
1272 dataOut.data = newData
1273 dataOut.flagNoData = False
1273 dataOut.flagNoData = False
1274
1274
1275 profileIndex = dataOut.profileIndex/n
1275 profileIndex = dataOut.profileIndex/n
1276
1276
1277
1277
1278 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1278 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1279
1279
1280 dataOut.heightList = numpy.arange(dataOut.nHeights*n) * deltaHeight + dataOut.heightList[0]
1280 dataOut.heightList = numpy.arange(dataOut.nHeights*n) * deltaHeight + dataOut.heightList[0]
1281
1281
1282 dataOut.nProfiles = int(dataOut.nProfiles/n)
1282 dataOut.nProfiles = int(dataOut.nProfiles/n)
1283
1283
1284 dataOut.profileIndex = profileIndex
1284 dataOut.profileIndex = profileIndex
1285
1285
1286 dataOut.ippSeconds *= n
1286 dataOut.ippSeconds *= n
1287
1287
1288 return dataOut
1288 return dataOut
1289
1289
1290 class PulsePairVoltage(Operation):
1290 class PulsePair(Operation):
1291 '''
1291 '''
1292 Function PulsePair(Signal Power, Velocity)
1292 Function PulsePair(Signal Power, Velocity)
1293 The real component of Lag[0] provides Intensity Information
1293 The real component of Lag[0] provides Intensity Information
1294 The imag component of Lag[1] Phase provides Velocity Information
1294 The imag component of Lag[1] Phase provides Velocity Information
1295
1295
1296 Configuration Parameters:
1296 Configuration Parameters:
1297 nPRF = Number of Several PRF
1297 nPRF = Number of Several PRF
1298 theta = Degree Azimuth angel Boundaries
1298 theta = Degree Azimuth angel Boundaries
1299
1299
1300 Input:
1300 Input:
1301 self.dataOut
1301 self.dataOut
1302 lag[N]
1302 lag[N]
1303 Affected:
1303 Affected:
1304 self.dataOut.spc
1304 self.dataOut.spc
1305 '''
1305 '''
1306 isConfig = False
1306 isConfig = False
1307 __profIndex = 0
1307 __profIndex = 0
1308 __initime = None
1308 __initime = None
1309 __lastdatatime = None
1309 __lastdatatime = None
1310 __buffer = None
1310 __buffer = None
1311 noise = None
1311 noise = None
1312 __dataReady = False
1312 __dataReady = False
1313 n = None
1313 n = None
1314 __nch = 0
1314 __nch = 0
1315 __nHeis = 0
1315 __nHeis = 0
1316 removeDC = False
1316 removeDC = False
1317 ipp = None
1317 ipp = None
1318 lambda_ = 0
1318 lambda_ = 0
1319
1319
1320 def __init__(self,**kwargs):
1320 def __init__(self,**kwargs):
1321 Operation.__init__(self,**kwargs)
1321 Operation.__init__(self,**kwargs)
1322
1322
1323 def setup(self, dataOut, n = None, removeDC=False):
1323 def setup(self, dataOut, n = None, removeDC=False):
1324 '''
1324 '''
1325 n= Numero de PRF's de entrada
1325 n= Numero de PRF's de entrada
1326 '''
1326 '''
1327 print("[INICIO]-setup del METODO PULSE PAIR")
1327 self.__initime = None
1328 self.__initime = None
1328 self.__lastdatatime = 0
1329 self.__lastdatatime = 0
1329 self.__dataReady = False
1330 self.__dataReady = False
1330 self.__buffer = 0
1331 self.__buffer = 0
1331 self.__profIndex = 0
1332 self.__profIndex = 0
1332 self.noise = None
1333 self.noise = None
1333 self.__nch = dataOut.nChannels
1334 self.__nch = dataOut.nChannels
1334 self.__nHeis = dataOut.nHeights
1335 self.__nHeis = dataOut.nHeights
1335 self.removeDC = removeDC
1336 self.removeDC = removeDC
1336 self.lambda_ = 3.0e8/(9345.0e6)
1337 self.lambda_ = 3.0e8/(9345.0e6)
1337 self.ippSec = dataOut.ippSeconds
1338 self.ippSec = dataOut.ippSeconds
1338 self.nCohInt = dataOut.nCohInt
1339 self.nCohInt = dataOut.nCohInt
1339 print("IPPseconds",dataOut.ippSeconds)
1340 print("IPPseconds",dataOut.ippSeconds)
1340
1341
1341 print("ELVALOR DE n es:", n)
1342 print("ELVALOR DE n es:", n)
1342 if n == None:
1343 if n == None:
1343 raise ValueError("n should be specified.")
1344 raise ValueError("n should be specified.")
1344
1345
1345 if n != None:
1346 if n != None:
1346 if n<2:
1347 if n<2:
1347 raise ValueError("n should be greater than 2")
1348 raise ValueError("n should be greater than 2")
1348
1349
1349 self.n = n
1350 self.n = n
1350 self.__nProf = n
1351 self.__nProf = n
1351
1352
1352 self.__buffer = numpy.zeros((dataOut.nChannels,
1353 self.__buffer = numpy.zeros((dataOut.nChannels,
1353 n,
1354 n,
1354 dataOut.nHeights),
1355 dataOut.nHeights),
1355 dtype='complex')
1356 dtype='complex')
1356
1357
1357 def putData(self,data):
1358 def putData(self,data):
1358 '''
1359 '''
1359 Add a profile to he __buffer and increase in one the __profiel Index
1360 Add a profile to he __buffer and increase in one the __profiel Index
1360 '''
1361 '''
1361 self.__buffer[:,self.__profIndex,:]= data
1362 self.__buffer[:,self.__profIndex,:]= data
1362 self.__profIndex += 1
1363 self.__profIndex += 1
1363 return
1364 return
1364
1365
1365 def pushData(self,dataOut):
1366 def pushData(self,dataOut):
1366 '''
1367 '''
1367 Return the PULSEPAIR and the profiles used in the operation
1368 Return the PULSEPAIR and the profiles used in the operation
1368 Affected : self.__profileIndex
1369 Affected : self.__profileIndex
1369 '''
1370 '''
1370 #----------------- Remove DC-----------------------------------
1371 #----------------- Remove DC-----------------------------------
1371 if self.removeDC==True:
1372 if self.removeDC==True:
1372 mean = numpy.mean(self.__buffer,1)
1373 mean = numpy.mean(self.__buffer,1)
1373 tmp = mean.reshape(self.__nch,1,self.__nHeis)
1374 tmp = mean.reshape(self.__nch,1,self.__nHeis)
1374 dc= numpy.tile(tmp,[1,self.__nProf,1])
1375 dc= numpy.tile(tmp,[1,self.__nProf,1])
1375 self.__buffer = self.__buffer - dc
1376 self.__buffer = self.__buffer - dc
1376 #------------------Calculo de Potencia ------------------------
1377 #------------------Calculo de Potencia ------------------------
1377 pair0 = self.__buffer*numpy.conj(self.__buffer)
1378 pair0 = self.__buffer*numpy.conj(self.__buffer)
1378 pair0 = pair0.real
1379 pair0 = pair0.real
1379 lag_0 = numpy.sum(pair0,1)
1380 lag_0 = numpy.sum(pair0,1)
1380 #------------------Calculo de Ruido x canal--------------------
1381 #------------------Calculo de Ruido x canal--------------------
1381 self.noise = numpy.zeros(self.__nch)
1382 self.noise = numpy.zeros(self.__nch)
1382 for i in range(self.__nch):
1383 for i in range(self.__nch):
1383 daux = numpy.sort(pair0[i,:,:],axis= None)
1384 daux = numpy.sort(pair0[i,:,:],axis= None)
1384 self.noise[i]=hildebrand_sekhon( daux ,self.nCohInt)
1385 self.noise[i]=hildebrand_sekhon( daux ,self.nCohInt)
1385
1386
1386 self.noise = self.noise.reshape(self.__nch,1)
1387 self.noise = self.noise.reshape(self.__nch,1)
1387 self.noise = numpy.tile(self.noise,[1,self.__nHeis])
1388 self.noise = numpy.tile(self.noise,[1,self.__nHeis])
1388 noise_buffer = self.noise.reshape(self.__nch,1,self.__nHeis)
1389 noise_buffer = self.noise.reshape(self.__nch,1,self.__nHeis)
1389 noise_buffer = numpy.tile(noise_buffer,[1,self.__nProf,1])
1390 noise_buffer = numpy.tile(noise_buffer,[1,self.__nProf,1])
1390 #------------------ Potencia recibida= P , Potencia senal = S , Ruido= N--
1391 #------------------ Potencia recibida= P , Potencia senal = S , Ruido= N--
1391 #------------------ P= S+N ,P=lag_0/N ---------------------------------
1392 #------------------ P= S+N ,P=lag_0/N ---------------------------------
1392 #-------------------- Power --------------------------------------------------
1393 #-------------------- Power --------------------------------------------------
1393 data_power = lag_0/(self.n*self.nCohInt)
1394 data_power = lag_0/(self.n*self.nCohInt)
1394 #------------------ Senal ---------------------------------------------------
1395 #------------------ Senal ---------------------------------------------------
1395 data_intensity = pair0 - noise_buffer
1396 data_intensity = pair0 - noise_buffer
1396 data_intensity = numpy.sum(data_intensity,axis=1)*(self.n*self.nCohInt)#*self.nCohInt)
1397 data_intensity = numpy.sum(data_intensity,axis=1)*(self.n*self.nCohInt)#*self.nCohInt)
1397 #data_intensity = (lag_0-self.noise*self.n)*(self.n*self.nCohInt)
1398 #data_intensity = (lag_0-self.noise*self.n)*(self.n*self.nCohInt)
1398 for i in range(self.__nch):
1399 for i in range(self.__nch):
1399 for j in range(self.__nHeis):
1400 for j in range(self.__nHeis):
1400 if data_intensity[i][j] < 0:
1401 if data_intensity[i][j] < 0:
1401 data_intensity[i][j] = numpy.min(numpy.absolute(data_intensity[i][j]))
1402 data_intensity[i][j] = numpy.min(numpy.absolute(data_intensity[i][j]))
1402
1403
1403 #----------------- Calculo de Frecuencia y Velocidad doppler--------
1404 #----------------- Calculo de Frecuencia y Velocidad doppler--------
1404 pair1 = self.__buffer[:,:-1,:]*numpy.conjugate(self.__buffer[:,1:,:])
1405 pair1 = self.__buffer[:,:-1,:]*numpy.conjugate(self.__buffer[:,1:,:])
1405 lag_1 = numpy.sum(pair1,1)
1406 lag_1 = numpy.sum(pair1,1)
1406 data_freq = (-1/(2.0*math.pi*self.ippSec*self.nCohInt))*numpy.angle(lag_1)
1407 data_freq = (-1/(2.0*math.pi*self.ippSec*self.nCohInt))*numpy.angle(lag_1)
1407 data_velocity = (self.lambda_/2.0)*data_freq
1408 data_velocity = (self.lambda_/2.0)*data_freq
1408
1409
1409 #---------------- Potencia promedio estimada de la Senal-----------
1410 #---------------- Potencia promedio estimada de la Senal-----------
1410 lag_0 = lag_0/self.n
1411 lag_0 = lag_0/self.n
1411 S = lag_0-self.noise
1412 S = lag_0-self.noise
1412
1413
1413 #---------------- Frecuencia Doppler promedio ---------------------
1414 #---------------- Frecuencia Doppler promedio ---------------------
1414 lag_1 = lag_1/(self.n-1)
1415 lag_1 = lag_1/(self.n-1)
1415 R1 = numpy.abs(lag_1)
1416 R1 = numpy.abs(lag_1)
1416
1417
1417 #---------------- Calculo del SNR----------------------------------
1418 #---------------- Calculo del SNR----------------------------------
1418 data_snrPP = S/self.noise
1419 data_snrPP = S/self.noise
1419 for i in range(self.__nch):
1420 for i in range(self.__nch):
1420 for j in range(self.__nHeis):
1421 for j in range(self.__nHeis):
1421 if data_snrPP[i][j] < 1.e-20:
1422 if data_snrPP[i][j] < 1.e-20:
1422 data_snrPP[i][j] = 1.e-20
1423 data_snrPP[i][j] = 1.e-20
1423
1424
1424 #----------------- Calculo del ancho espectral ----------------------
1425 #----------------- Calculo del ancho espectral ----------------------
1425 L = S/R1
1426 L = S/R1
1426 L = numpy.where(L<0,1,L)
1427 L = numpy.where(L<0,1,L)
1427 L = numpy.log(L)
1428 L = numpy.log(L)
1428 tmp = numpy.sqrt(numpy.absolute(L))
1429 tmp = numpy.sqrt(numpy.absolute(L))
1429 data_specwidth = (self.lambda_/(2*math.sqrt(2)*math.pi*self.ippSec*self.nCohInt))*tmp*numpy.sign(L)
1430 data_specwidth = (self.lambda_/(2*math.sqrt(2)*math.pi*self.ippSec*self.nCohInt))*tmp*numpy.sign(L)
1430 n = self.__profIndex
1431 n = self.__profIndex
1431
1432
1432 self.__buffer = numpy.zeros((self.__nch, self.__nProf,self.__nHeis), dtype='complex')
1433 self.__buffer = numpy.zeros((self.__nch, self.__nProf,self.__nHeis), dtype='complex')
1433 self.__profIndex = 0
1434 self.__profIndex = 0
1434 return data_power,data_intensity,data_velocity,data_snrPP,data_specwidth,n
1435 return data_power,data_intensity,data_velocity,data_snrPP,data_specwidth,n
1435
1436
1436
1437
1437 def pulsePairbyProfiles(self,dataOut):
1438 def pulsePairbyProfiles(self,dataOut):
1438
1439
1439 self.__dataReady = False
1440 self.__dataReady = False
1440 data_power = None
1441 data_power = None
1441 data_intensity = None
1442 data_intensity = None
1442 data_velocity = None
1443 data_velocity = None
1443 data_specwidth = None
1444 data_specwidth = None
1444 data_snrPP = None
1445 data_snrPP = None
1445 self.putData(data=dataOut.data)
1446 self.putData(data=dataOut.data)
1446 if self.__profIndex == self.n:
1447 if self.__profIndex == self.n:
1447 data_power,data_intensity, data_velocity,data_snrPP,data_specwidth, n = self.pushData(dataOut=dataOut)
1448 data_power,data_intensity, data_velocity,data_snrPP,data_specwidth, n = self.pushData(dataOut=dataOut)
1448 self.__dataReady = True
1449 self.__dataReady = True
1449
1450
1450 return data_power, data_intensity, data_velocity, data_snrPP, data_specwidth
1451 return data_power, data_intensity, data_velocity, data_snrPP, data_specwidth
1451
1452
1452
1453
1453 def pulsePairOp(self, dataOut, datatime= None):
1454 def pulsePairOp(self, dataOut, datatime= None):
1454
1455
1455 if self.__initime == None:
1456 if self.__initime == None:
1456 self.__initime = datatime
1457 self.__initime = datatime
1457 data_power, data_intensity, data_velocity, data_snrPP, data_specwidth = self.pulsePairbyProfiles(dataOut)
1458 data_power, data_intensity, data_velocity, data_snrPP, data_specwidth = self.pulsePairbyProfiles(dataOut)
1458 self.__lastdatatime = datatime
1459 self.__lastdatatime = datatime
1459
1460
1460 if data_power is None:
1461 if data_power is None:
1461 return None, None, None,None,None,None
1462 return None, None, None,None,None,None
1462
1463
1463 avgdatatime = self.__initime
1464 avgdatatime = self.__initime
1464 deltatime = datatime - self.__lastdatatime
1465 deltatime = datatime - self.__lastdatatime
1465 self.__initime = datatime
1466 self.__initime = datatime
1466
1467
1467 return data_power, data_intensity, data_velocity, data_snrPP, data_specwidth, avgdatatime
1468 return data_power, data_intensity, data_velocity, data_snrPP, data_specwidth, avgdatatime
1468
1469
1469 def run(self, dataOut,n = None,removeDC= False, overlapping= False,**kwargs):
1470 def run(self, dataOut,n = None,removeDC= False, overlapping= False,**kwargs):
1470
1471
1471 if not self.isConfig:
1472 if not self.isConfig:
1472 self.setup(dataOut = dataOut, n = n , removeDC=removeDC , **kwargs)
1473 self.setup(dataOut = dataOut, n = n , removeDC=removeDC , **kwargs)
1473 self.isConfig = True
1474 self.isConfig = True
1474 data_power, data_intensity, data_velocity,data_snrPP,data_specwidth, avgdatatime = self.pulsePairOp(dataOut, dataOut.utctime)
1475 data_power, data_intensity, data_velocity,data_snrPP,data_specwidth, avgdatatime = self.pulsePairOp(dataOut, dataOut.utctime)
1475 dataOut.flagNoData = True
1476 dataOut.flagNoData = True
1476
1477
1477 if self.__dataReady:
1478 if self.__dataReady:
1478 dataOut.nCohInt *= self.n
1479 dataOut.nCohInt *= self.n
1479 dataOut.dataPP_POW = data_intensity # S
1480 dataOut.dataPP_POW = data_intensity # S
1480 dataOut.dataPP_POWER = data_power # P
1481 dataOut.dataPP_POWER = data_power # P
1481 dataOut.dataPP_DOP = data_velocity
1482 dataOut.dataPP_DOP = data_velocity
1482 dataOut.dataPP_SNR = data_snrPP
1483 dataOut.dataPP_SNR = data_snrPP
1483 dataOut.dataPP_WIDTH = data_specwidth
1484 dataOut.dataPP_WIDTH = data_specwidth
1484 dataOut.PRFbyAngle = self.n #numero de PRF*cada angulo rotado que equivale a un tiempo.
1485 dataOut.PRFbyAngle = self.n #numero de PRF*cada angulo rotado que equivale a un tiempo.
1486 dataOut.nProfiles = int(dataOut.nProfiles/n)
1485 dataOut.utctime = avgdatatime
1487 dataOut.utctime = avgdatatime
1486 dataOut.flagNoData = False
1488 dataOut.flagNoData = False
1487 return dataOut
1489 return dataOut
1488
1490
1489
1491
1490
1492
1491 # import collections
1493 # import collections
1492 # from scipy.stats import mode
1494 # from scipy.stats import mode
1493 #
1495 #
1494 # class Synchronize(Operation):
1496 # class Synchronize(Operation):
1495 #
1497 #
1496 # isConfig = False
1498 # isConfig = False
1497 # __profIndex = 0
1499 # __profIndex = 0
1498 #
1500 #
1499 # def __init__(self, **kwargs):
1501 # def __init__(self, **kwargs):
1500 #
1502 #
1501 # Operation.__init__(self, **kwargs)
1503 # Operation.__init__(self, **kwargs)
1502 # # self.isConfig = False
1504 # # self.isConfig = False
1503 # self.__powBuffer = None
1505 # self.__powBuffer = None
1504 # self.__startIndex = 0
1506 # self.__startIndex = 0
1505 # self.__pulseFound = False
1507 # self.__pulseFound = False
1506 #
1508 #
1507 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
1509 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
1508 #
1510 #
1509 # #Read data
1511 # #Read data
1510 #
1512 #
1511 # powerdB = dataOut.getPower(channel = channel)
1513 # powerdB = dataOut.getPower(channel = channel)
1512 # noisedB = dataOut.getNoise(channel = channel)[0]
1514 # noisedB = dataOut.getNoise(channel = channel)[0]
1513 #
1515 #
1514 # self.__powBuffer.extend(powerdB.flatten())
1516 # self.__powBuffer.extend(powerdB.flatten())
1515 #
1517 #
1516 # dataArray = numpy.array(self.__powBuffer)
1518 # dataArray = numpy.array(self.__powBuffer)
1517 #
1519 #
1518 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
1520 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
1519 #
1521 #
1520 # maxValue = numpy.nanmax(filteredPower)
1522 # maxValue = numpy.nanmax(filteredPower)
1521 #
1523 #
1522 # if maxValue < noisedB + 10:
1524 # if maxValue < noisedB + 10:
1523 # #No se encuentra ningun pulso de transmision
1525 # #No se encuentra ningun pulso de transmision
1524 # return None
1526 # return None
1525 #
1527 #
1526 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
1528 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
1527 #
1529 #
1528 # if len(maxValuesIndex) < 2:
1530 # if len(maxValuesIndex) < 2:
1529 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
1531 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
1530 # return None
1532 # return None
1531 #
1533 #
1532 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
1534 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
1533 #
1535 #
1534 # #Seleccionar solo valores con un espaciamiento de nSamples
1536 # #Seleccionar solo valores con un espaciamiento de nSamples
1535 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
1537 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
1536 #
1538 #
1537 # if len(pulseIndex) < 2:
1539 # if len(pulseIndex) < 2:
1538 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1540 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1539 # return None
1541 # return None
1540 #
1542 #
1541 # spacing = pulseIndex[1:] - pulseIndex[:-1]
1543 # spacing = pulseIndex[1:] - pulseIndex[:-1]
1542 #
1544 #
1543 # #remover senales que se distancien menos de 10 unidades o muestras
1545 # #remover senales que se distancien menos de 10 unidades o muestras
1544 # #(No deberian existir IPP menor a 10 unidades)
1546 # #(No deberian existir IPP menor a 10 unidades)
1545 #
1547 #
1546 # realIndex = numpy.where(spacing > 10 )[0]
1548 # realIndex = numpy.where(spacing > 10 )[0]
1547 #
1549 #
1548 # if len(realIndex) < 2:
1550 # if len(realIndex) < 2:
1549 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1551 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1550 # return None
1552 # return None
1551 #
1553 #
1552 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
1554 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
1553 # realPulseIndex = pulseIndex[realIndex]
1555 # realPulseIndex = pulseIndex[realIndex]
1554 #
1556 #
1555 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
1557 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
1556 #
1558 #
1557 # print "IPP = %d samples" %period
1559 # print "IPP = %d samples" %period
1558 #
1560 #
1559 # self.__newNSamples = dataOut.nHeights #int(period)
1561 # self.__newNSamples = dataOut.nHeights #int(period)
1560 # self.__startIndex = int(realPulseIndex[0])
1562 # self.__startIndex = int(realPulseIndex[0])
1561 #
1563 #
1562 # return 1
1564 # return 1
1563 #
1565 #
1564 #
1566 #
1565 # def setup(self, nSamples, nChannels, buffer_size = 4):
1567 # def setup(self, nSamples, nChannels, buffer_size = 4):
1566 #
1568 #
1567 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
1569 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
1568 # maxlen = buffer_size*nSamples)
1570 # maxlen = buffer_size*nSamples)
1569 #
1571 #
1570 # bufferList = []
1572 # bufferList = []
1571 #
1573 #
1572 # for i in range(nChannels):
1574 # for i in range(nChannels):
1573 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN,
1575 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN,
1574 # maxlen = buffer_size*nSamples)
1576 # maxlen = buffer_size*nSamples)
1575 #
1577 #
1576 # bufferList.append(bufferByChannel)
1578 # bufferList.append(bufferByChannel)
1577 #
1579 #
1578 # self.__nSamples = nSamples
1580 # self.__nSamples = nSamples
1579 # self.__nChannels = nChannels
1581 # self.__nChannels = nChannels
1580 # self.__bufferList = bufferList
1582 # self.__bufferList = bufferList
1581 #
1583 #
1582 # def run(self, dataOut, channel = 0):
1584 # def run(self, dataOut, channel = 0):
1583 #
1585 #
1584 # if not self.isConfig:
1586 # if not self.isConfig:
1585 # nSamples = dataOut.nHeights
1587 # nSamples = dataOut.nHeights
1586 # nChannels = dataOut.nChannels
1588 # nChannels = dataOut.nChannels
1587 # self.setup(nSamples, nChannels)
1589 # self.setup(nSamples, nChannels)
1588 # self.isConfig = True
1590 # self.isConfig = True
1589 #
1591 #
1590 # #Append new data to internal buffer
1592 # #Append new data to internal buffer
1591 # for thisChannel in range(self.__nChannels):
1593 # for thisChannel in range(self.__nChannels):
1592 # bufferByChannel = self.__bufferList[thisChannel]
1594 # bufferByChannel = self.__bufferList[thisChannel]
1593 # bufferByChannel.extend(dataOut.data[thisChannel])
1595 # bufferByChannel.extend(dataOut.data[thisChannel])
1594 #
1596 #
1595 # if self.__pulseFound:
1597 # if self.__pulseFound:
1596 # self.__startIndex -= self.__nSamples
1598 # self.__startIndex -= self.__nSamples
1597 #
1599 #
1598 # #Finding Tx Pulse
1600 # #Finding Tx Pulse
1599 # if not self.__pulseFound:
1601 # if not self.__pulseFound:
1600 # indexFound = self.__findTxPulse(dataOut, channel)
1602 # indexFound = self.__findTxPulse(dataOut, channel)
1601 #
1603 #
1602 # if indexFound == None:
1604 # if indexFound == None:
1603 # dataOut.flagNoData = True
1605 # dataOut.flagNoData = True
1604 # return
1606 # return
1605 #
1607 #
1606 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex)
1608 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex)
1607 # self.__pulseFound = True
1609 # self.__pulseFound = True
1608 # self.__startIndex = indexFound
1610 # self.__startIndex = indexFound
1609 #
1611 #
1610 # #If pulse was found ...
1612 # #If pulse was found ...
1611 # for thisChannel in range(self.__nChannels):
1613 # for thisChannel in range(self.__nChannels):
1612 # bufferByChannel = self.__bufferList[thisChannel]
1614 # bufferByChannel = self.__bufferList[thisChannel]
1613 # #print self.__startIndex
1615 # #print self.__startIndex
1614 # x = numpy.array(bufferByChannel)
1616 # x = numpy.array(bufferByChannel)
1615 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
1617 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
1616 #
1618 #
1617 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1619 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1618 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
1620 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
1619 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
1621 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
1620 #
1622 #
1621 # dataOut.data = self.__arrayBuffer
1623 # dataOut.data = self.__arrayBuffer
1622 #
1624 #
1623 # self.__startIndex += self.__newNSamples
1625 # self.__startIndex += self.__newNSamples
1624 #
1626 #
1625 # return
1627 # return
@@ -1,183 +1,248
1 #!python
1 #!python
2 '''
2 '''
3 '''
3 '''
4
4
5 import os, sys
5 import os, sys
6 import datetime
6 import datetime
7 import time
7 import time
8
8
9 #path = os.path.dirname(os.getcwd())
9 #path = os.path.dirname(os.getcwd())
10 #path = os.path.dirname(path)
10 #path = os.path.dirname(path)
11 #sys.path.insert(0, path)
11 #sys.path.insert(0, path)
12
12
13 from schainpy.controller import Project
13 from schainpy.controller import Project
14
14
15 desc = "USRP_test"
15 desc = "USRP_test"
16 filename = "USRP_processing.xml"
16 filename = "USRP_processing.xml"
17 controllerObj = Project()
17 controllerObj = Project()
18 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
18 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
19
19
20 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
20 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
21
21
22 #######################################################################
22 #######################################################################
23 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
23 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
24 #######################################################################
24 #######################################################################
25 #path = '/media/data/data/vientos/57.2063km/echoes/NCO_Woodman'
25 #path = '/media/data/data/vientos/57.2063km/echoes/NCO_Woodman'
26
26 #path = '/DATA_RM/TEST_INTEGRACION'
27
27 path = '/DATA_RM/TEST_ONLINE'
28 path = '/home/soporte/data_hdf5' #### with clock 35.16 db noise
28 figpath = '/home/soporte/Pictures/TEST_INTEGRACION_IMG'
29
30 figpath = '/home/soporte/data_hdf5_imag'
31 #remotefolder = "/home/wmaster/graficos"
29 #remotefolder = "/home/wmaster/graficos"
32 #######################################################################
30 #######################################################################
33 ################# RANGO DE PLOTEO######################################
31 ################# RANGO DE PLOTEO######################################
34 #######################################################################
32 #######################################################################
35 dBmin = '30'
33 dBmin = '-5'
36 dBmax = '60'
34 dBmax = '20'
37 xmin = '0'
35 xmin = '0'
38 xmax ='24'
36 xmax ='24'
39 ymin = '0'
37 ymin = '0'
40 ymax = '600'
38 ymax = '600'
41 #######################################################################
39 #######################################################################
42 ########################FECHA##########################################
40 ########################FECHA##########################################
43 #######################################################################
41 #######################################################################
44 str = datetime.date.today()
42 str = datetime.date.today()
45 today = str.strftime("%Y/%m/%d")
43 today = str.strftime("%Y/%m/%d")
46 str2 = str - datetime.timedelta(days=1)
44 str2 = str - datetime.timedelta(days=1)
47 yesterday = str2.strftime("%Y/%m/%d")
45 yesterday = str2.strftime("%Y/%m/%d")
48 #######################################################################
46 #######################################################################
49 ######################## UNIDAD DE LECTURA#############################
47 ######################## UNIDAD DE LECTURA#############################
50 #######################################################################
48 #######################################################################
51 readUnitConfObj = controllerObj.addReadUnit(datatype='DigitalRFReader',
49 readUnitConfObj = controllerObj.addReadUnit(datatype='DigitalRFReader',
52 path=path,
50 path=path,
53 startDate="2019/01/01",#today,
51 startDate="2021/01/01",#today,
54 endDate="2109/12/30",#today,
52 endDate="2021/12/30",#today,
55 startTime='00:00:00',
53 startTime='00:00:00',
56 endTime='23:59:59',
54 endTime='23:59:59',
57 delay=0,
55 delay=0,
58 #set=0,
56 #set=0,
59 online=0,
57 online=0,
60 walk=1,
58 walk=1,
61 ippKm = 1000)
59 ippKm = 60)
62
60
63 opObj11 = readUnitConfObj.addOperation(name='printInfo')
61 opObj11 = readUnitConfObj.addOperation(name='printInfo')
64 opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
62 #opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
65 #######################################################################
63 #######################################################################
66 ################ OPERACIONES DOMINIO DEL TIEMPO########################
64 ################ OPERACIONES DOMINIO DEL TIEMPO########################
67 #######################################################################
65 #######################################################################
68
66
69 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
67 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
70 #
68 #
71 # codigo64='1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0,'+\
69 # codigo64='1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0,'+\
72 # '1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1'
70 # '1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1'
73
71
74 #opObj11 = procUnitConfObjA.addOperation(name='setRadarFrequency')
72 #opObj11 = procUnitConfObjA.addOperation(name='setRadarFrequency')
75 #opObj11.addParameter(name='frequency', value='30e6', format='float')
73 #opObj11.addParameter(name='frequency', value='70312500')
74
75 '''
76 opObj11 = procUnitConfObjA.addOperation(name='PulsePair', optype='other')
77 opObj11.addParameter(name='n', value='625', format='int')#10
78 opObj11.addParameter(name='removeDC', value=1, format='int')
79 '''
76
80
77 #opObj10 = procUnitConfObjA.addOperation(name='Scope', optype='external')
81 # Ploteo TEST
82 '''
83 opObj11 = procUnitConfObjA.addOperation(name='PulsepairPowerPlot', optype='other')
84 opObj11 = procUnitConfObjA.addOperation(name='PulsepairSignalPlot', optype='other')
85 opObj11 = procUnitConfObjA.addOperation(name='PulsepairVelocityPlot', optype='other')
86 #opObj11.addParameter(name='xmax', value=8)
87 opObj11 = procUnitConfObjA.addOperation(name='PulsepairSpecwidthPlot', optype='other')
88 '''
89 # OJO SCOPE
90 #opObj10 = procUnitConfObjA.addOperation(name='ScopePlot', optype='external')
78 #opObj10.addParameter(name='id', value='10', format='int')
91 #opObj10.addParameter(name='id', value='10', format='int')
79 ##opObj10.addParameter(name='xmin', value='0', format='int')
92 ##opObj10.addParameter(name='xmin', value='0', format='int')
80 ##opObj10.addParameter(name='xmax', value='50', format='int')
93 ##opObj10.addParameter(name='xmax', value='50', format='int')
81 #opObj10.addParameter(name='type', value='iq')
94 #opObj10.addParameter(name='type', value='iq')
82 #opObj10.addParameter(name='ymin', value='-5000', format='int')
95 ##opObj10.addParameter(name='ymin', value='-5000', format='int')
83 ##opObj10.addParameter(name='ymax', value='8500', format='int')
96 ##opObj10.addParameter(name='ymax', value='8500', format='int')
97 #opObj11.addParameter(name='save', value=figpath, format='str')
98 #opObj11.addParameter(name='save_period', value=10, format='int')
84
99
85 #opObj10 = procUnitConfObjA.addOperation(name='setH0')
100 #opObj10 = procUnitConfObjA.addOperation(name='setH0')
86 #opObj10.addParameter(name='h0', value='-5000', format='float')
101 #opObj10.addParameter(name='h0', value='-5000', format='float')
87
102
88 #opObj11 = procUnitConfObjA.addOperation(name='filterByHeights')
103 #opObj11 = procUnitConfObjA.addOperation(name='filterByHeights')
89 #opObj11.addParameter(name='window', value='1', format='int')
104 #opObj11.addParameter(name='window', value='1', format='int')
90
105
91 #codigo='1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,-1,-1,-1'
106 #codigo='1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,-1,-1,-1'
92 #opObj11 = procUnitConfObjSousy.addOperation(name='Decoder', optype='other')
107 #opObj11 = procUnitConfObjSousy.addOperation(name='Decoder', optype='other')
93 #opObj11.addParameter(name='code', value=codigo, format='floatlist')
108 #opObj11.addParameter(name='code', value=codigo, format='floatlist')
94 #opObj11.addParameter(name='nCode', value='1', format='int')
109 #opObj11.addParameter(name='nCode', value='1', format='int')
95 #opObj11.addParameter(name='nBaud', value='28', format='int')
110 #opObj11.addParameter(name='nBaud', value='28', format='int')
96
111
97 #opObj11 = procUnitConfObjA.addOperation(name='CohInt', optype='other')
112 #opObj11 = procUnitConfObjA.addOperation(name='CohInt', optype='other')
98 #opObj11.addParameter(name='n', value='100', format='int')
113 #opObj11.addParameter(name='n', value='100', format='int')
99
114
100 #######################################################################
115 #######################################################################
116 ########## OPERACIONES ParametersProc########################
117 #######################################################################
118 ###procUnitConfObjB= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjA.getId())
119 '''
120
121 opObj11 = procUnitConfObjA.addOperation(name='PedestalInformation')
122 opObj11.addParameter(name='path_ped', value=path_ped)
123 opObj11.addParameter(name='path_adq', value=path_adq)
124 opObj11.addParameter(name='t_Interval_p', value='0.01', format='float')
125 opObj11.addParameter(name='n_Muestras_p', value='100', format='float')
126 opObj11.addParameter(name='blocksPerfile', value='100', format='int')
127 opObj11.addParameter(name='f_a_p', value='25', format='int')
128 opObj11.addParameter(name='online', value='0', format='int')
129
130 opObj11 = procUnitConfObjA.addOperation(name='Block360')
131 opObj11.addParameter(name='n', value='40', format='int')
132
133 opObj11= procUnitConfObjA.addOperation(name='WeatherPlot',optype='other')
134 opObj11.addParameter(name='save', value=figpath)
135 opObj11.addParameter(name='save_period', value=1)
136
137
138 '''
139
140 #######################################################################
101 ########## OPERACIONES DOMINIO DE LA FRECUENCIA########################
141 ########## OPERACIONES DOMINIO DE LA FRECUENCIA########################
102 #######################################################################
142 #######################################################################
103 procUnitConfObjSousySpectra = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjA.getId())
104 procUnitConfObjSousySpectra.addParameter(name='nFFTPoints', value='100', format='int')
105 procUnitConfObjSousySpectra.addParameter(name='nProfiles', value='100', format='int')
106 #procUnitConfObjSousySpectra.addParameter(name='pairsList', value='(0,0),(1,1),(0,1)', format='pairsList')
107
143
108 #opObj13 = procUnitConfObjSousySpectra.addOperation(name='removeDC')
144 procUnitConfObjB = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjA.getId())
145 procUnitConfObjB.addParameter(name='nFFTPoints', value='32', format='int')
146 procUnitConfObjB.addParameter(name='nProfiles', value='32', format='int')
147
148 procUnitConfObjC = controllerObj.addProcUnit(datatype='SpectraHeisProc', inputId=procUnitConfObjA.getId())
149 #procUnitConfObjB.addParameter(name='nFFTPoints', value='64', format='int')
150 #procUnitConfObjB.addParameter(name='nProfiles', value='64', format='int')
151 opObj11 = procUnitConfObjC.addOperation(name='IncohInt4SpectraHeis', optype='other')
152 opObj11.addParameter(name='timeInterval', value='8', format='int')
153
154
155 #procUnitConfObjB.addParameter(name='pairsList', value='(0,0),(1,1),(0,1)', format='pairsList')
156
157 #opObj13 = procUnitConfObjB.addOperation(name='removeDC')
109 #opObj13.addParameter(name='mode', value='2', format='int')
158 #opObj13.addParameter(name='mode', value='2', format='int')
110
159
111 #opObj11 = procUnitConfObjSousySpectra.addOperation(name='IncohInt', optype='other')
160 opObj11 = procUnitConfObjB.addOperation(name='IncohInt', optype='other')
112 #opObj11.addParameter(name='n', value='60', format='float')
161 opObj11.addParameter(name='n', value='8', format='float')
113 #######################################################################
162 #######################################################################
114 ########## PLOTEO DOMINIO DE LA FRECUENCIA#############################
163 ########## PLOTEO DOMINIO DE LA FRECUENCIA#############################
115 #######################################################################
164 #######################################################################
165 #----
166
167 opObj11 = procUnitConfObjC.addOperation(name='SpectraHeisPlot')
168 opObj11.addParameter(name='id', value='10', format='int')
169 opObj11.addParameter(name='wintitle', value='Spectra_Alturas', format='str')
170 #opObj11.addParameter(name='xmin', value=-100000, format='float')
171 #opObj11.addParameter(name='xmax', value=100000, format='float')
172 #opObj11.addParameter(name='zmin', value=dBmin, format='int')
173 #opObj11.addParameter(name='zmax', value=dBmax, format='int')
174 opObj11.addParameter(name='ymin', value=-20, format='int')
175 opObj11.addParameter(name='ymax', value=50, format='int')
176 opObj11.addParameter(name='showprofile', value='1', format='int')
177 opObj11.addParameter(name='save', value=figpath, format='str')
178 opObj11.addParameter(name='save_period', value=10, format='int')
179
180
116 #SpectraPlot
181 #SpectraPlot
117
182
118 opObj11 = procUnitConfObjSousySpectra.addOperation(name='SpectraPlot', optype='external')
183 opObj11 = procUnitConfObjB.addOperation(name='SpectraPlot', optype='external')
119 opObj11.addParameter(name='id', value='1', format='int')
184 opObj11.addParameter(name='id', value='1', format='int')
120 opObj11.addParameter(name='wintitle', value='Spectra', format='str')
185 opObj11.addParameter(name='wintitle', value='Spectra', format='str')
121 #opObj11.addParameter(name='xmin', value=-0.01, format='float')
186 #opObj11.addParameter(name='xmin', value=-0.01, format='float')
122 #opObj11.addParameter(name='xmax', value=0.01, format='float')
187 #opObj11.addParameter(name='xmax', value=0.01, format='float')
123 #opObj11.addParameter(name='zmin', value=dBmin, format='int')
188 opObj11.addParameter(name='zmin', value=dBmin, format='int')
124 #opObj11.addParameter(name='zmax', value=dBmax, format='int')
189 opObj11.addParameter(name='zmax', value=dBmax, format='int')
125 #opObj11.addParameter(name='ymin', value=ymin, format='int')
190 #opObj11.addParameter(name='ymin', value=ymin, format='int')
126 #opObj11.addParameter(name='ymax', value=ymax, format='int')
191 #opObj11.addParameter(name='ymax', value=ymax, format='int')
127 opObj11.addParameter(name='showprofile', value='1', format='int')
192 opObj11.addParameter(name='showprofile', value='1', format='int')
128 opObj11.addParameter(name='save', value=figpath, format='str')
193 opObj11.addParameter(name='save', value=figpath, format='str')
129 opObj11.addParameter(name='save_period', value=10, format='int')
194 opObj11.addParameter(name='save_period', value=10, format='int')
130
195
131
132 #RTIPLOT
196 #RTIPLOT
133
197
134 opObj11 = procUnitConfObjSousySpectra.addOperation(name='RTIPlot', optype='external')
198 opObj11 = procUnitConfObjB.addOperation(name='RTIPlot', optype='external')
135 opObj11.addParameter(name='id', value='2', format='int')
199 opObj11.addParameter(name='id', value='2', format='int')
136 opObj11.addParameter(name='wintitle', value='RTIPlot', format='str')
200 opObj11.addParameter(name='wintitle', value='RTIPlot', format='str')
137 #opObj11.addParameter(name='zmin', value=dBmin, format='int')
201 opObj11.addParameter(name='zmin', value=dBmin, format='int')
138 #opObj11.addParameter(name='zmax', value=dBmax, format='int')
202 opObj11.addParameter(name='zmax', value=dBmax, format='int')
139 #opObj11.addParameter(name='ymin', value=ymin, format='int')
203 #opObj11.addParameter(name='ymin', value=ymin, format='int')
140 #opObj11.addParameter(name='ymax', value=ymax, format='int')
204 #opObj11.addParameter(name='ymax', value=ymax, format='int')
141 opObj11.addParameter(name='xmin', value=0, format='int')
205 #opObj11.addParameter(name='xmin', value=15, format='int')
142 opObj11.addParameter(name='xmax', value=23, format='int')
206 #opObj11.addParameter(name='xmax', value=16, format='int')
143
207
144 opObj11.addParameter(name='showprofile', value='1', format='int')
208 opObj11.addParameter(name='showprofile', value='1', format='int')
145 opObj11.addParameter(name='save', value=figpath, format='str')
209 opObj11.addParameter(name='save', value=figpath, format='str')
146 opObj11.addParameter(name='save_period', value=10, format='int')
210 opObj11.addParameter(name='save_period', value=10, format='int')
147
211
148
212
149 # opObj11 = procUnitConfObjSousySpectra.addOperation(name='CrossSpectraPlot', optype='other')
213 # opObj11 = procUnitConfObjB.addOperation(name='CrossSpectraPlot', optype='other')
150 # opObj11.addParameter(name='id', value='3', format='int')
214 # opObj11.addParameter(name='id', value='3', format='int')
151 # opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str')
215 # opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str')
152 # opObj11.addParameter(name='ymin', value=ymin, format='int')
216 # opObj11.addParameter(name='ymin', value=ymin, format='int')
153 # opObj11.addParameter(name='ymax', value=ymax, format='int')
217 # opObj11.addParameter(name='ymax', value=ymax, format='int')
154 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
218 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
155 # opObj11.addParameter(name='zmin', value=dBmin, format='int')
219 # opObj11.addParameter(name='zmin', value=dBmin, format='int')
156 # opObj11.addParameter(name='zmax', value=dBmax, format='int')
220 # opObj11.addParameter(name='zmax', value=dBmax, format='int')
157 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
221 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
158 # opObj11.addParameter(name='save', value=0, format='bool')
222 # opObj11.addParameter(name='save', value=0, format='bool')
159 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
223 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
160 # #
224 # #
161 # opObj11 = procUnitConfObjSousySpectra.addOperation(name='CoherenceMap', optype='other')
225 # opObj11 = procUnitConfObjB.addOperation(name='CoherenceMap', optype='other')
162 # opObj11.addParameter(name='id', value='4', format='int')
226 # opObj11.addParameter(name='id', value='4', format='int')
163 # opObj11.addParameter(name='wintitle', value='Coherence', format='str')
227 # opObj11.addParameter(name='wintitle', value='Coherence', format='str')
164 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
228 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
165 # opObj11.addParameter(name='xmin', value=xmin, format='float')
229 # opObj11.addParameter(name='xmin', value=xmin, format='float')
166 # opObj11.addParameter(name='xmax', value=xmax, format='float')
230 # opObj11.addParameter(name='xmax', value=xmax, format='float')
167 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
231 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
168 # opObj11.addParameter(name='save', value=0, format='bool')
232 # opObj11.addParameter(name='save', value=0, format='bool')
169 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
233 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
170 #
234 #
235
236 '''
171 #######################################################################
237 #######################################################################
172 ############### UNIDAD DE ESCRITURA ###################################
238 ############### UNIDAD DE ESCRITURA ###################################
173 #######################################################################
239 #######################################################################
174 #opObj11 = procUnitConfObjSousySpectra.addOperation(name='SpectraWriter', optype='other')
240 #opObj11 = procUnitConfObjB.addOperation(name='SpectraWriter', optype='other')
175 #opObj11.addParameter(name='path', value=wr_path)
241 #opObj11.addParameter(name='path', value=wr_path)
176 #opObj11.addParameter(name='blocksPerFile', value='50', format='int')
242 #opObj11.addParameter(name='blocksPerFile', value='50', format='int')
177 print ("Escribiendo el archivo XML")
243 print ("Escribiendo el archivo XML")
178 print ("Leyendo el archivo XML")
244 print ("Leyendo el archivo XML")
179
245 '''
180
246
181
247
182 controllerObj.start()
248 controllerObj.start()
183
@@ -1,82 +1,93
1 import os, sys
1 import os, sys
2 import datetime
2 import datetime
3 import time
3 import time
4 from schainpy.controller import Project
4 from schainpy.controller import Project
5 '''
6 NOTA:
7 Este script de prueba.
8 - Unidad del lectura 'SimulatorReader'.
9 - Unidad de procesamiento VoltageProc
10 - Unidad de procesamiento SpectraProc (profileIndex no esta en metadata porque se queda en voltage.)
11 - Operacion removeDC.
12 - Unidad de procesamiento ParametersProc
13 - Operacion SpectralMoments
14 - Operacion SpectralMomentsPlot
15 - Unidad de escrituda 'HDFWriter'.
16 '''
5
17
6 desc = "USRP_test"
18 desc = "USRP_test"
7 filename = "USRP_processing.xml"
19 filename = "USRP_processing.xml"
8 controllerObj = Project()
20 controllerObj = Project()
9 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
21 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
10
22
11 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
23 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
12 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
24 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
13 path = '/home/alex/Downloads/test_rawdata'
25 path = '/home/soporte/Downloads/RAWDATA'
14 figpath = '/home/alex/Downloads/hdf5_test'
26 figpath = '/home/soporte/Downloads/IMAGE'
15 ######################## UNIDAD DE LECTURA#############################
27 ######################## UNIDAD DE LECTURA#############################
16 '''
28 '''
17 readUnitConfObj = controllerObj.addReadUnit(datatype='VoltageReader',
29 readUnitConfObj = controllerObj.addReadUnit(datatype='VoltageReader',
18 path=path,
30 path=path,
19 startDate="2020/01/01", #"2020/01/01",#today,
31 startDate="2020/01/01", #"2020/01/01",#today,
20 endDate= "2020/12/01", #"2020/12/30",#today,
32 endDate= "2020/12/01", #"2020/12/30",#today,
21 startTime='00:00:00',
33 startTime='00:00:00',
22 endTime='23:59:59',
34 endTime='23:59:59',
23 delay=0,
35 delay=0,
24 #set=0,
36 #set=0,
25 online=0,
37 online=0,
26 walk=1)
38 walk=1)
27
39
28 '''
40 '''
29 readUnitConfObj = controllerObj.addReadUnit(datatype='SimulatorReader',
41 readUnitConfObj = controllerObj.addReadUnit(datatype='SimulatorReader',
30 frequency=9.345e9,
42 frequency=9.345e9,
31 FixRCP_IPP= 60,
43 FixRCP_IPP= 60,
32 Tau_0 = 30,
44 Tau_0 = 30,
33 AcqH0_0=0,
45 AcqH0_0=0,
34 samples=330,
46 samples=330,
35 AcqDH_0=0.15,
47 AcqDH_0=0.15,
36 FixRCP_TXA=0.15,
48 FixRCP_TXA=0.15,
37 FixRCP_TXB=0.15,
49 FixRCP_TXB=0.15,
38 Fdoppler=600.0,
50 Fdoppler=600.0,
39 Hdoppler=36,
51 Hdoppler=36,
40 Adoppler=300,#300
52 Adoppler=300,#300
41 delay=0,
53 delay=0,
42 online=0,
54 online=0,
43 walk=0,
55 walk=0,
44 profilesPerBlock=625,
56 profilesPerBlock=625,
45 dataBlocksPerFile=100)
57 dataBlocksPerFile=100)
46 #nTotalReadFiles=2)
58 #nTotalReadFiles=2)
47
59
48
60
49 #opObj11 = readUnitConfObj.addOperation(name='printInfo')
61 #opObj11 = readUnitConfObj.addOperation(name='printInfo')
50
62
51 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
63 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
52
64
53 procUnitConfObjB = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjA.getId())
65 procUnitConfObjB = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjA.getId())
54 procUnitConfObjB.addParameter(name='nFFTPoints', value=625, format='int')
66 procUnitConfObjB.addParameter(name='nFFTPoints', value=625, format='int')
55 procUnitConfObjB.addParameter(name='nProfiles', value=625, format='int')
67 procUnitConfObjB.addParameter(name='nProfiles', value=625, format='int')
56
68
57 opObj11 = procUnitConfObjB.addOperation(name='removeDC')
69 opObj11 = procUnitConfObjB.addOperation(name='removeDC')
58 opObj11.addParameter(name='mode', value=2)
70 opObj11.addParameter(name='mode', value=2)
59 #opObj11 = procUnitConfObjB.addOperation(name='SpectraPlot')
71 #opObj11 = procUnitConfObjB.addOperation(name='SpectraPlot')
60 #opObj11 = procUnitConfObjB.addOperation(name='PowerProfilePlot')
72 #opObj11 = procUnitConfObjB.addOperation(name='PowerProfilePlot')
61
73
62 procUnitConfObjC= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjB.getId())
74 procUnitConfObjC= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjB.getId())
63 procUnitConfObjC.addOperation(name='SpectralMoments')
75 procUnitConfObjC.addOperation(name='SpectralMoments')
64 #opObj11 = procUnitConfObjC.addOperation(name='PowerPlot')
76 #opObj11 = procUnitConfObjC.addOperation(name='PowerPlot')
65
77
66 '''
78
67 opObj11 = procUnitConfObjC.addOperation(name='SpectralMomentsPlot')
79 opObj11 = procUnitConfObjC.addOperation(name='SpectralMomentsPlot')
68 #opObj11.addParameter(name='xmin', value=14)
80 #opObj11.addParameter(name='xmin', value=14)
69 #opObj11.addParameter(name='xmax', value=15)
81 #opObj11.addParameter(name='xmax', value=15)
70 #opObj11.addParameter(name='save', value=figpath)
82 opObj11.addParameter(name='save', value=figpath)
71 opObj11.addParameter(name='showprofile', value=1)
83 opObj11.addParameter(name='showprofile', value=1)
72 #opObj11.addParameter(name='save_period', value=10)
84 opObj11.addParameter(name='save_period', value=10)
73 '''
74
85
75 opObj10 = procUnitConfObjC.addOperation(name='ParameterWriter')
86 opObj10 = procUnitConfObjC.addOperation(name='HDFWriter')
76 opObj10.addParameter(name='path',value=figpath)
87 opObj10.addParameter(name='path',value=path)
77 #opObj10.addParameter(name='mode',value=0)
88 #opObj10.addParameter(name='mode',value=0)
78 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
89 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
79 opObj10.addParameter(name='metadataList',value='utctimeInit,timeInterval',format='list')
90 opObj10.addParameter(name='metadataList',value='utctimeInit,heightList,nIncohInt,nCohInt,nProfiles,channelList',format='list')#profileIndex
80 opObj10.addParameter(name='dataList',value='data_POW,data_DOP,data_WIDTH,data_SNR')#,format='list'
91 opObj10.addParameter(name='dataList',value='data_pow,data_dop,utctime',format='list')#,format='list'
81
92
82 controllerObj.start()
93 controllerObj.start()
@@ -1,73 +1,73
1 import os,sys
1 import os,sys
2 import datetime
2 import datetime
3 import time
3 import time
4 from schainpy.controller import Project
4 from schainpy.controller import Project
5 path = '/home/alex/Downloads/NEW_WR2/spc16removeDC'
5 path = '/home/soporte/Downloads/RAWDATA_PP'
6 figpath = path
6 figpath = path
7 desc = "Simulator Test"
7 desc = "Simulator Test"
8
8
9 controllerObj = Project()
9 controllerObj = Project()
10
10
11 controllerObj.setup(id='10',name='Test Simulator',description=desc)
11 controllerObj.setup(id='10',name='Test Simulator',description=desc)
12
12
13 readUnitConfObj = controllerObj.addReadUnit(datatype='SimulatorReader',
13 readUnitConfObj = controllerObj.addReadUnit(datatype='SimulatorReader',
14 frequency=9.345e9,
14 frequency=9.345e9,
15 FixRCP_IPP= 60,
15 FixRCP_IPP= 60,
16 Tau_0 = 30,
16 Tau_0 = 30,
17 AcqH0_0=0,
17 AcqH0_0=0,
18 samples=330,
18 samples=330,
19 AcqDH_0=0.15,
19 AcqDH_0=0.15,
20 FixRCP_TXA=0.15,
20 FixRCP_TXA=0.15,
21 FixRCP_TXB=0.15,
21 FixRCP_TXB=0.15,
22 Fdoppler=600.0,
22 Fdoppler=600.0,
23 Hdoppler=36,
23 Hdoppler=36,
24 Adoppler=300,#300
24 Adoppler=300,#300
25 delay=0,
25 delay=0,
26 online=0,
26 online=0,
27 walk=0,
27 walk=0,
28 profilesPerBlock=625,
28 profilesPerBlock=625,
29 dataBlocksPerFile=100)#,#nTotalReadFiles=2)
29 dataBlocksPerFile=100)#,#nTotalReadFiles=2)
30 '''
30 '''
31 readUnitConfObj = controllerObj.addReadUnit(datatype='VoltageReader',
31 readUnitConfObj = controllerObj.addReadUnit(datatype='VoltageReader',
32 path=path,
32 path=path,
33 startDate="2020/01/01", #"2020/01/01",#today,
33 startDate="2020/01/01", #"2020/01/01",#today,
34 endDate= "2020/12/01", #"2020/12/30",#today,
34 endDate= "2020/12/01", #"2020/12/30",#today,
35 startTime='00:00:00',
35 startTime='00:00:00',
36 endTime='23:59:59',
36 endTime='23:59:59',
37 delay=0,
37 delay=0,
38 #set=0,
38 #set=0,
39 online=0,
39 online=0,
40 walk=1)
40 walk=1)
41 '''
41 '''
42 opObj11 = readUnitConfObj.addOperation(name='printInfo')
42 opObj11 = readUnitConfObj.addOperation(name='printInfo')
43
43
44 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
44 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
45 #opObj11 = procUnitConfObjA.addOperation(name='CohInt', optype='other')
45 #opObj11 = procUnitConfObjA.addOperation(name='CohInt', optype='other')
46 #opObj11.addParameter(name='n', value='10', format='int')
46 #opObj11.addParameter(name='n', value='10', format='int')
47
47
48 #opObj10 = procUnitConfObjA.addOperation(name='selectChannels')
48 #opObj10 = procUnitConfObjA.addOperation(name='selectChannels')
49 #opObj10.addParameter(name='channelList', value=[0])
49 #opObj10.addParameter(name='channelList', value=[0])
50 opObj11 = procUnitConfObjA.addOperation(name='PulsePairVoltage', optype='other')
50 opObj11 = procUnitConfObjA.addOperation(name='PulsePairVoltage', optype='other')
51 opObj11.addParameter(name='n', value='625', format='int')#10
51 opObj11.addParameter(name='n', value='625', format='int')#10
52 opObj11.addParameter(name='removeDC', value=1, format='int')
52 opObj11.addParameter(name='removeDC', value=1, format='int')
53
53
54 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairPowerPlot', optype='other')
54 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairPowerPlot', optype='other')
55 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairSignalPlot', optype='other')
55 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairSignalPlot', optype='other')
56
56
57
57
58 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairVelocityPlot', optype='other')
58 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairVelocityPlot', optype='other')
59 #opObj11.addParameter(name='xmax', value=8)
59 #opObj11.addParameter(name='xmax', value=8)
60
60
61 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairSpecwidthPlot', optype='other')
61 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairSpecwidthPlot', optype='other')
62
62
63 procUnitConfObjB= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjA.getId())
63 procUnitConfObjB= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjA.getId())
64
64
65
65
66 opObj10 = procUnitConfObjB.addOperation(name='ParameterWriter')
66 opObj10 = procUnitConfObjB.addOperation(name='HDFWriter')
67 opObj10.addParameter(name='path',value=figpath)
67 opObj10.addParameter(name='path',value=figpath)
68 #opObj10.addParameter(name='mode',value=0)
68 #opObj10.addParameter(name='mode',value=0)
69 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
69 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
70 opObj10.addParameter(name='metadataList',value='utctimeInit,timeInterval',format='list')
70 opObj10.addParameter(name='metadataList',value='utctimeInit,paramInterval,profileIndex,heightList,flagDataAsBlock',format='list')
71 opObj10.addParameter(name='dataList',value='dataPP_POW,dataPP_DOP,dataPP_SNR,dataPP_WIDTH')#,format='list'
71 opObj10.addParameter(name='dataList',value='dataPP_POW,dataPP_DOP,dataPP_SNR,dataPP_WIDTH,utctime',format='list')#,format='list'
72
72
73 controllerObj.start()
73 controllerObj.start()
General Comments 0
You need to be logged in to leave comments. Login now