##// END OF EJS Templates
Reading and doing Operation in Blocks to processing radar data from MST_ISR_EEJ Experiment
Daniel Valdez -
r495:4f47402d085c
parent child
Show More
@@ -0,0 +1,217
1 import os, sys
2 import timeit
3
4 path = os.path.split(os.getcwd())[0]
5 sys.path.append(path)
6
7 from controller import *
8
9 desc = "MST-ISR-EEJ Experiment Test"
10 filename = "mst_isr_eej_blocks.xml"
11
12 controllerObj = Project()
13
14 controllerObj.setup(id = '191', name='test01', description=desc)
15
16 path='/remote/ewdrifts/RAW_EXP/EW_DRIFT_FARADAY/EW_Drift'
17
18 path = '/media/administrator/New Volume/DATA/MST_ISR'
19
20 path = '/home/administrator/Documents/mst_isr_eej'
21
22 readUnitConfObj = controllerObj.addReadUnit(datatype='VoltageReader',
23 path=path,
24 startDate='2014/01/09',
25 endDate='2014/01/09',
26 startTime='00:00:00',
27 endTime='23:59:59',
28 online=0,
29 delay=10,
30 walk=0,
31 getblock=1)
32
33 opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
34 # ################ EEJ ####################################
35 procUnitConfObjEEJ = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
36
37 opObj11 = procUnitConfObjEEJ.addOperation(name='ProfileSelector', optype='other')
38 opObj11.addParameter(name='profileRangeList', value='120,183', format='intlist')
39 opObj11.addParameter(name='byblock', value='1', format='bool')
40
41 opObj11 = procUnitConfObjEEJ.addOperation(name='Decoder', optype='other')
42 opObj11.addParameter(name='code', value='1,-1', format='floatlist')
43 opObj11.addParameter(name='nCode', value='2', format='int')
44 opObj11.addParameter(name='nBaud', value='1', format='int')
45 opObj11.addParameter(name='mode', value='3', format='int')
46 opObj11.addParameter(name='times', value='32', format='int')
47
48 # opObj11 = procUnitConfObjEEJ.addOperation(name='CohInt', optype='other')
49 # opObj11.addParameter(name='n', value='2', format='int')
50
51 procUnitConfObjEEJSpecta = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjEEJ.getId())
52 procUnitConfObjEEJSpecta.addParameter(name='nFFTPoints', value='64', format='int')
53 procUnitConfObjEEJSpecta.addParameter(name='nProfiles', value='64', format='int')
54
55 opObj11 = procUnitConfObjEEJSpecta.addOperation(name='IncohInt', optype='other')
56 #opObj11.addParameter(name='timeInterval', value='10', format='float')
57 opObj11.addParameter(name='n', value='36', format='float')
58
59 opObj11 = procUnitConfObjEEJSpecta.addOperation(name='SpectraPlot', optype='other')
60 opObj11.addParameter(name='id', value='100', format='int')
61 opObj11.addParameter(name='wintitle', value='EEJ', format='str')
62 # opObj11.addParameter(name='zmin', value='20', format='int')
63 # opObj11.addParameter(name='zmax', value='60', format='int')# opObj11.addParameter(name='ftp', value='1', format='int')
64 # opObj11.addParameter(name='save', value='1', format='int')
65 # opObj11.addParameter(name='figpath', value='/home/operaciones/Pictures/MST-ISR', format='str')
66 # opObj11.addParameter(name='wr_period', value='15', format='int')
67 # opObj11.addParameter(name='ftp', value='1', format='int')
68 # opObj11.addParameter(name='server', value='jro-app.igp.gob.pe', format='str')
69 # opObj11.addParameter(name='folder', value='/home/wmaster/graficos', format='str')
70 # opObj11.addParameter(name='username', value='wmaster', format='str')
71 # opObj11.addParameter(name='password', value='mst2010vhf', format='str')
72 # opObj11.addParameter(name='ftp_wei', value='0', format='int')
73 # opObj11.addParameter(name='exp_code', value='22', format='int')
74 # opObj11.addParameter(name='sub_exp_code', value='0', format='int')
75 # opObj11.addParameter(name='plot_pos', value='0', format='int')
76
77
78 # opObj11 = procUnitConfObjEEJSpecta.addOperation(name='RTIPlot', optype='other')
79 # opObj11.addParameter(name='id', value='101', format='int')
80 # opObj11.addParameter(name='wintitle', value='EEJ', format='str')
81 # opObj11.addParameter(name='showprofile', value='0', format='int')
82 # opObj11.addParameter(name='xmin', value='0', format='int')
83 # opObj11.addParameter(name='xmax', value='24', format='int')
84 # opObj11.addParameter(name='save', value='1', format='int')
85 # opObj11.addParameter(name='figpath', value='/home/operaciones/Pictures/MST-ISR', format='str')
86 # opObj11.addParameter(name='wr_period', value='15', format='int')
87 # opObj11.addParameter(name='ftp', value='1', format='int')
88 # opObj11.addParameter(name='server', value='jro-app.igp.gob.pe', format='str')
89 # opObj11.addParameter(name='folder', value='/home/wmaster/graficos', format='str')
90 # opObj11.addParameter(name='username', value='wmaster', format='str')
91 # opObj11.addParameter(name='password', value='mst2010vhf', format='str')
92 # opObj11.addParameter(name='ftp_wei', value='0', format='int')
93 # opObj11.addParameter(name='exp_code', value='22', format='int')
94 # opObj11.addParameter(name='sub_exp_code', value='0', format='int')
95 # opObj11.addParameter(name='plot_pos', value='0', format='int')
96
97 ################ MST ####################################
98 procUnitConfObjMST = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
99
100 opObj11 = procUnitConfObjMST.addOperation(name='ProfileSelector', optype='other')
101 profileIndex = '0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119'
102 #profileIndex = '0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19'
103 opObj11.addParameter(name='profileList', value=profileIndex, format='intlist')
104 opObj11.addParameter(name='byblock', value='1', format='bool')
105
106 opObj11 = procUnitConfObjMST.addOperation(name='Decoder', optype='other')
107 opObj11.addParameter(name='mode',value='3',format='int')
108 opObj11.addParameter(name='times',value='10',format='int')
109
110 opObj11 = procUnitConfObjMST.addOperation(name='CohInt', optype='other')
111 opObj11.addParameter(name='n', value='20', format='int')
112 opObj11.addParameter(name='byblock', value='1', format='bool')
113
114 procUnitConfObjMSTSpectra = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjMST.getId())
115 procUnitConfObjMSTSpectra.addParameter(name='nFFTPoints', value='64', format='int')
116 procUnitConfObjMSTSpectra.addParameter(name='nProfiles', value='64', format='int')
117
118 opObj11 = procUnitConfObjMSTSpectra.addOperation(name='IncohInt', optype='other')
119 opObj11.addParameter(name='n', value='2', format='float')
120
121 opObj11 = procUnitConfObjMSTSpectra.addOperation(name='SpectraPlot', optype='other')
122 opObj11.addParameter(name='id', value='200', format='int')
123 opObj11.addParameter(name='wintitle', value='MST', format='str')
124 # opObj11.addParameter(name='zmin', value='35', format='int')
125 # opObj11.addParameter(name='zmax', value='60', format='int')
126 # opObj11.addParameter(name='save', value='1', format='int')
127 # opObj11.addParameter(name='figpath', value='/home/operaciones/Pictures/MST-ISR', format='str')
128 # opObj11.addParameter(name='wr_period', value='5', format='int')
129 # opObj11.addParameter(name='ftp', value='1', format='int')
130 # opObj11.addParameter(name='server', value='jro-app.igp.gob.pe', format='str')
131 # opObj11.addParameter(name='folder', value='/home/wmaster/graficos', format='str')
132 # opObj11.addParameter(name='username', value='wmaster', format='str')
133 # opObj11.addParameter(name='password', value='mst2010vhf', format='str')
134 # opObj11.addParameter(name='ftp_wei', value='0', format='int')
135 # opObj11.addParameter(name='exp_code', value='19', format='int')
136 # opObj11.addParameter(name='sub_exp_code', value='0', format='int')
137 # opObj11.addParameter(name='plot_pos', value='0', format='int')
138 #
139 # opObj11 = procUnitConfObjMSTSpectra.addOperation(name='RTIPlot', optype='other')
140 # opObj11.addParameter(name='id', value='201', format='int')
141 # opObj11.addParameter(name='wintitle', value='MST', format='str')
142 # opObj11.addParameter(name='showprofile', value='0', format='int')
143 # opObj11.addParameter(name='xmin', value='0', format='int')
144 # opObj11.addParameter(name='xmax', value='24', format='int')
145 # opObj11.addParameter(name='zmin', value='35', format='int')
146 # opObj11.addParameter(name='zmax', value='60', format='int')
147 # opObj11.addParameter(name='save', value='1', format='int')
148 # opObj11.addParameter(name='figpath', value='/home/operaciones/Pictures/MST-ISR', format='str')
149 # opObj11.addParameter(name='wr_period', value='5', format='int')
150 # opObj11.addParameter(name='ftp', value='1', format='int')
151 # opObj11.addParameter(name='server', value='jro-app.igp.gob.pe', format='str')
152 # opObj11.addParameter(name='folder', value='/home/wmaster/graficos', format='str')
153 # opObj11.addParameter(name='username', value='wmaster', format='str')
154 # opObj11.addParameter(name='password', value='mst2010vhf', format='str')
155 # opObj11.addParameter(name='ftp_wei', value='0', format='int')
156 # opObj11.addParameter(name='exp_code', value='19', format='int')
157 # opObj11.addParameter(name='sub_exp_code', value='0', format='int')
158 # opObj11.addParameter(name='plot_pos', value='0', format='int')
159
160 # ################ ISR ####################################
161 procUnitConfObjISR = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
162
163 opObj11 = procUnitConfObjISR.addOperation(name='ProfileSelector', optype='other')
164 # profileIndex = '20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99'
165 # opObj11.addParameter(name='profileList', value=profileIndex, format='intlist')
166 opObj11.addParameter(name='profileRangeList', value='20,99', format='intlist')
167 opObj11.addParameter(name='byblock', value='1', format='bool')
168
169 # opObj11 = procUnitConfObjISR.addOperation(name='ProfileConcat', optype='other')
170 # opObj11.addParameter(name='m', value='5', format='int')
171
172 opObj11 = procUnitConfObjISR.addOperation(name='Reshaper', optype='other') #Esta Operacion opera sobre bloques y reemplaza el ProfileConcat que opera sobre perfiles
173 opObj11.addParameter(name='shape', value='4,16,6750', format='intlist')
174
175 opObj11 = procUnitConfObjISR.addOperation(name='filterByHeights')
176 opObj11.addParameter(name='window', value='20', format='int')
177 opObj11.addParameter(name='axis', value='2', format='int')
178
179 barker3x1 = '1,1,-1,-1,-1,1'
180 #barker3x5 = '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,1,1'
181
182 opObj11 = procUnitConfObjISR.addOperation(name='Decoder', optype='other')
183 opObj11.addParameter(name='code', value=barker3x1, format='floatlist')
184 opObj11.addParameter(name='nCode', value='2', format='int')
185 #opObj11.addParameter(name='nBaud', value='15', format='int')
186 opObj11.addParameter(name='nBaud', value='3', format='int')
187 opObj11.addParameter(name='mode', value='3', format='int')
188 opObj11.addParameter(name='times', value='8', format='int')
189 opObj11.addParameter(name='osamp', value='5', format='int')
190
191
192 procUnitConfObjISRSpectra = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjISR.getId())
193 procUnitConfObjISRSpectra.addParameter(name='nFFTPoints', value='16', format='int')
194 procUnitConfObjISRSpectra.addParameter(name='nProfiles', value='16', format='int')
195
196 opObj11 = procUnitConfObjISRSpectra.addOperation(name='IncohInt', optype='other')
197 opObj11.addParameter(name='n', value='36', format='float')
198
199 opObj11 = procUnitConfObjISRSpectra.addOperation(name='SpectraPlot', optype='other')
200 opObj11.addParameter(name='id', value='300', format='int')
201 opObj11.addParameter(name='wintitle', value='ISR', format='str')
202 # opObj11.addParameter(name='save', value='1', format='bool')
203 # opObj11.addParameter(name='figpath', value='/home/administrator/Pictures/mst_isr_eej', format='str')
204
205
206 print "Escribiendo el archivo XML"
207 controllerObj.writeXml(filename)
208 print "Leyendo el archivo XML"
209 controllerObj.readXml(filename)
210
211 controllerObj.createObjects()
212 controllerObj.connectObjects()
213
214 #timeit.timeit('controllerObj.run()', number=2)
215
216 controllerObj.run()
217 #print fib(5) No newline at end of file
@@ -1,1334 +1,1337
1 1 '''
2 2
3 3 '''
4 4 import os
5 5 import sys
6 6 import glob
7 7 import time
8 8 import numpy
9 9 import fnmatch
10 10 import time, datetime
11 11 #import h5py
12 12 import traceback
13 13
14 14 #try:
15 15 # import pyfits
16 16 #except:
17 17 # print "pyfits module has not been imported, it should be installed to save files in fits format"
18 18
19 19 #from jrodata import *
20 20 #from jroheaderIO import *
21 21 #from jroprocessing import *
22 22
23 23 #import re
24 24 #from xml.etree.ElementTree import Element, SubElement, ElementTree
25 25
26 26
27 27 LOCALTIME = True #-18000
28 28
29 29 from model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
30 30
31 31 def isNumber(str):
32 32 """
33 33 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
34 34
35 35 Excepciones:
36 36 Si un determinado string no puede ser convertido a numero
37 37 Input:
38 38 str, string al cual se le analiza para determinar si convertible a un numero o no
39 39
40 40 Return:
41 41 True : si el string es uno numerico
42 42 False : no es un string numerico
43 43 """
44 44 try:
45 45 float( str )
46 46 return True
47 47 except:
48 48 return False
49 49
50 50 def isThisFileinRange(filename, startUTSeconds, endUTSeconds):
51 51 """
52 52 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
53 53
54 54 Inputs:
55 55 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
56 56
57 57 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
58 58 segundos contados desde 01/01/1970.
59 59 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
60 60 segundos contados desde 01/01/1970.
61 61
62 62 Return:
63 63 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
64 64 fecha especificado, de lo contrario retorna False.
65 65
66 66 Excepciones:
67 67 Si el archivo no existe o no puede ser abierto
68 68 Si la cabecera no puede ser leida.
69 69
70 70 """
71 71 basicHeaderObj = BasicHeader(LOCALTIME)
72 72
73 73 try:
74 74 fp = open(filename,'rb')
75 75 except IOError:
76 76 traceback.print_exc()
77 77 raise IOError, "The file %s can't be opened" %(filename)
78 78
79 79 sts = basicHeaderObj.read(fp)
80 80 fp.close()
81 81
82 82 if not(sts):
83 83 print "Skipping the file %s because it has not a valid header" %(filename)
84 84 return 0
85 85
86 86 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
87 87 return 0
88 88
89 89 return 1
90 90
91 91 def isFileinThisTime(filename, startTime, endTime):
92 92 """
93 93 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
94 94
95 95 Inputs:
96 96 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
97 97
98 98 startTime : tiempo inicial del rango seleccionado en formato datetime.time
99 99
100 100 endTime : tiempo final del rango seleccionado en formato datetime.time
101 101
102 102 Return:
103 103 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
104 104 fecha especificado, de lo contrario retorna False.
105 105
106 106 Excepciones:
107 107 Si el archivo no existe o no puede ser abierto
108 108 Si la cabecera no puede ser leida.
109 109
110 110 """
111 111
112 112
113 113 try:
114 114 fp = open(filename,'rb')
115 115 except IOError:
116 116 traceback.print_exc()
117 117 raise IOError, "The file %s can't be opened" %(filename)
118 118
119 119 basicHeaderObj = BasicHeader(LOCALTIME)
120 120 sts = basicHeaderObj.read(fp)
121 121 fp.close()
122 122
123 123 thisDatetime = basicHeaderObj.datatime
124 124 thisTime = thisDatetime.time()
125 125
126 126 if not(sts):
127 127 print "Skipping the file %s because it has not a valid header" %(filename)
128 128 return None
129 129
130 130 if not ((startTime <= thisTime) and (endTime > thisTime)):
131 131 return None
132 132
133 133 return thisDatetime
134 134
135 135 def getFileFromSet(path, ext, set):
136 136 validFilelist = []
137 137 fileList = os.listdir(path)
138 138
139 139 # 0 1234 567 89A BCDE
140 140 # H YYYY DDD SSS .ext
141 141
142 142 for thisFile in fileList:
143 143 try:
144 144 year = int(thisFile[1:5])
145 145 doy = int(thisFile[5:8])
146 146 except:
147 147 continue
148 148
149 149 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
150 150 continue
151 151
152 152 validFilelist.append(thisFile)
153 153
154 154 myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set))
155 155
156 156 if len(myfile)!= 0:
157 157 return myfile[0]
158 158 else:
159 159 filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower())
160 160 print 'the filename %s does not exist'%filename
161 161 print '...going to the last file: '
162 162
163 163 if validFilelist:
164 164 validFilelist = sorted( validFilelist, key=str.lower )
165 165 return validFilelist[-1]
166 166
167 167 return None
168 168
169 169 def getlastFileFromPath(path, ext):
170 170 """
171 171 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
172 172 al final de la depuracion devuelve el ultimo file de la lista que quedo.
173 173
174 174 Input:
175 175 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
176 176 ext : extension de los files contenidos en una carpeta
177 177
178 178 Return:
179 179 El ultimo file de una determinada carpeta, no se considera el path.
180 180 """
181 181 validFilelist = []
182 182 fileList = os.listdir(path)
183 183
184 184 # 0 1234 567 89A BCDE
185 185 # H YYYY DDD SSS .ext
186 186
187 187 for thisFile in fileList:
188 188
189 189 year = thisFile[1:5]
190 190 if not isNumber(year):
191 191 continue
192 192
193 193 doy = thisFile[5:8]
194 194 if not isNumber(doy):
195 195 continue
196 196
197 197 year = int(year)
198 198 doy = int(doy)
199 199
200 200 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
201 201 continue
202 202
203 203 validFilelist.append(thisFile)
204 204
205 205 if validFilelist:
206 206 validFilelist = sorted( validFilelist, key=str.lower )
207 207 return validFilelist[-1]
208 208
209 209 return None
210 210
211 211 def checkForRealPath(path, foldercounter, year, doy, set, ext):
212 212 """
213 213 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
214 214 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
215 215 el path exacto de un determinado file.
216 216
217 217 Example :
218 218 nombre correcto del file es .../.../D2009307/P2009307367.ext
219 219
220 220 Entonces la funcion prueba con las siguientes combinaciones
221 221 .../.../y2009307367.ext
222 222 .../.../Y2009307367.ext
223 223 .../.../x2009307/y2009307367.ext
224 224 .../.../x2009307/Y2009307367.ext
225 225 .../.../X2009307/y2009307367.ext
226 226 .../.../X2009307/Y2009307367.ext
227 227 siendo para este caso, la ultima combinacion de letras, identica al file buscado
228 228
229 229 Return:
230 230 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
231 231 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
232 232 para el filename
233 233 """
234 234 fullfilename = None
235 235 find_flag = False
236 236 filename = None
237 237
238 238 prefixDirList = [None,'d','D']
239 239 if ext.lower() == ".r": #voltage
240 240 prefixFileList = ['d','D']
241 241 elif ext.lower() == ".pdata": #spectra
242 242 prefixFileList = ['p','P']
243 243 else:
244 244 return None, filename
245 245
246 246 #barrido por las combinaciones posibles
247 247 for prefixDir in prefixDirList:
248 248 thispath = path
249 249 if prefixDir != None:
250 250 #formo el nombre del directorio xYYYYDDD (x=d o x=D)
251 251 if foldercounter == 0:
252 252 thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy ))
253 253 else:
254 254 thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter))
255 255 for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D"
256 256 filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
257 257 fullfilename = os.path.join( thispath, filename ) #formo el path completo
258 258
259 259 if os.path.exists( fullfilename ): #verifico que exista
260 260 find_flag = True
261 261 break
262 262 if find_flag:
263 263 break
264 264
265 265 if not(find_flag):
266 266 return None, filename
267 267
268 268 return fullfilename, filename
269 269
270 270 def isDoyFolder(folder):
271 271 try:
272 272 year = int(folder[1:5])
273 273 except:
274 274 return 0
275 275
276 276 try:
277 277 doy = int(folder[5:8])
278 278 except:
279 279 return 0
280 280
281 281 return 1
282 282
283 283 class JRODataIO:
284 284
285 285 c = 3E8
286 286
287 287 isConfig = False
288 288
289 289 basicHeaderObj = None
290 290
291 291 systemHeaderObj = None
292 292
293 293 radarControllerHeaderObj = None
294 294
295 295 processingHeaderObj = None
296 296
297 297 online = 0
298 298
299 299 dtype = None
300 300
301 301 pathList = []
302 302
303 303 filenameList = []
304 304
305 305 filename = None
306 306
307 307 ext = None
308 308
309 309 flagIsNewFile = 1
310 310
311 311 flagTimeBlock = 0
312 312
313 313 flagIsNewBlock = 0
314 314
315 315 fp = None
316 316
317 317 firstHeaderSize = 0
318 318
319 319 basicHeaderSize = 24
320 320
321 321 versionFile = 1103
322 322
323 323 fileSize = None
324 324
325 325 # ippSeconds = None
326 326
327 327 fileSizeByHeader = None
328 328
329 329 fileIndex = None
330 330
331 331 profileIndex = None
332 332
333 333 blockIndex = None
334 334
335 335 nTotalBlocks = None
336 336
337 337 maxTimeStep = 30
338 338
339 339 lastUTTime = None
340 340
341 341 datablock = None
342 342
343 343 dataOut = None
344 344
345 345 blocksize = None
346 346
347 getblock = False
348
347 349 def __init__(self):
348 350
349 351 raise ValueError, "Not implemented"
350 352
351 353 def run(self):
352 354
353 355 raise ValueError, "Not implemented"
354 356
355 357 class JRODataReader(JRODataIO):
356 358
357 359 nReadBlocks = 0
358 360
359 361 delay = 10 #number of seconds waiting a new file
360 362
361 363 nTries = 3 #quantity tries
362 364
363 365 nFiles = 3 #number of files for searching
364 366
365 367 path = None
366 368
367 369 foldercounter = 0
368 370
369 371 flagNoMoreFiles = 0
370 372
371 373 datetimeList = []
372 374
373 375 __isFirstTimeOnline = 1
374 376
375 377 __printInfo = True
376 378
377 379 profileIndex = None
378 380
379 381 def __init__(self):
380 382
381 383 """
382 384
383 385 """
384 386
385 387 raise ValueError, "This method has not been implemented"
386 388
387 389
388 390 def createObjByDefault(self):
389 391 """
390 392
391 393 """
392 394 raise ValueError, "This method has not been implemented"
393 395
394 396 def getBlockDimension(self):
395 397
396 398 raise ValueError, "No implemented"
397 399
398 400 def __searchFilesOffLine(self,
399 401 path,
400 402 startDate,
401 403 endDate,
402 404 startTime=datetime.time(0,0,0),
403 405 endTime=datetime.time(23,59,59),
404 406 set=None,
405 407 expLabel='',
406 408 ext='.r',
407 409 walk=True):
408 410
409 411 pathList = []
410 412
411 413 if not walk:
412 414 #pathList.append(path)
413 415 multi_path = path.split(',')
414 416 for single_path in multi_path:
415 417 pathList.append(single_path)
416 418
417 419 else:
418 420 #dirList = []
419 421 multi_path = path.split(',')
420 422 for single_path in multi_path:
421 423 dirList = []
422 424 for thisPath in os.listdir(single_path):
423 425 if not os.path.isdir(os.path.join(single_path,thisPath)):
424 426 continue
425 427 if not isDoyFolder(thisPath):
426 428 continue
427 429
428 430 dirList.append(thisPath)
429 431
430 432 if not(dirList):
431 433 return None, None
432 434
433 435 thisDate = startDate
434 436
435 437 while(thisDate <= endDate):
436 438 year = thisDate.timetuple().tm_year
437 439 doy = thisDate.timetuple().tm_yday
438 440
439 441 matchlist = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy) + '*')
440 442 if len(matchlist) == 0:
441 443 thisDate += datetime.timedelta(1)
442 444 continue
443 445 for match in matchlist:
444 446 pathList.append(os.path.join(single_path,match,expLabel))
445 447
446 448 thisDate += datetime.timedelta(1)
447 449
448 450 if pathList == []:
449 451 print "Any folder was found for the date range: %s-%s" %(startDate, endDate)
450 452 return None, None
451 453
452 454 print "%d folder(s) was(were) found for the date range: %s - %s" %(len(pathList), startDate, endDate)
453 455
454 456 filenameList = []
455 457 datetimeList = []
456 458 pathDict = {}
457 459 filenameList_to_sort = []
458 460
459 461 for i in range(len(pathList)):
460 462
461 463 thisPath = pathList[i]
462 464
463 465 fileList = glob.glob1(thisPath, "*%s" %ext)
464 466 fileList.sort()
465 467 pathDict.setdefault(fileList[0])
466 468 pathDict[fileList[0]] = i
467 469 filenameList_to_sort.append(fileList[0])
468 470
469 471 filenameList_to_sort.sort()
470 472
471 473 for file in filenameList_to_sort:
472 474 thisPath = pathList[pathDict[file]]
473 475
474 476 fileList = glob.glob1(thisPath, "*%s" %ext)
475 477 fileList.sort()
476 478
477 479 for file in fileList:
478 480
479 481 filename = os.path.join(thisPath,file)
480 482 thisDatetime = isFileinThisTime(filename, startTime, endTime)
481 483
482 484 if not(thisDatetime):
483 485 continue
484 486
485 487 filenameList.append(filename)
486 488 datetimeList.append(thisDatetime)
487 489
488 490 if not(filenameList):
489 491 print "Any file was found for the time range %s - %s" %(startTime, endTime)
490 492 return None, None
491 493
492 494 print "%d file(s) was(were) found for the time range: %s - %s" %(len(filenameList), startTime, endTime)
493 495 print
494 496
495 497 for i in range(len(filenameList)):
496 498 print "%s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
497 499
498 500 self.filenameList = filenameList
499 501 self.datetimeList = datetimeList
500 502
501 503 return pathList, filenameList
502 504
503 505 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
504 506
505 507 """
506 508 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
507 509 devuelve el archivo encontrado ademas de otros datos.
508 510
509 511 Input:
510 512 path : carpeta donde estan contenidos los files que contiene data
511 513
512 514 expLabel : Nombre del subexperimento (subfolder)
513 515
514 516 ext : extension de los files
515 517
516 518 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
517 519
518 520 Return:
519 521 directory : eL directorio donde esta el file encontrado
520 522 filename : el ultimo file de una determinada carpeta
521 523 year : el anho
522 524 doy : el numero de dia del anho
523 525 set : el set del archivo
524 526
525 527
526 528 """
527 529 dirList = []
528 530
529 531 if not walk:
530 532 fullpath = path
531 533 foldercounter = 0
532 534 else:
533 535 #Filtra solo los directorios
534 536 for thisPath in os.listdir(path):
535 537 if not os.path.isdir(os.path.join(path,thisPath)):
536 538 continue
537 539 if not isDoyFolder(thisPath):
538 540 continue
539 541
540 542 dirList.append(thisPath)
541 543
542 544 if not(dirList):
543 545 return None, None, None, None, None, None
544 546
545 547 dirList = sorted( dirList, key=str.lower )
546 548
547 549 doypath = dirList[-1]
548 550 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
549 551 fullpath = os.path.join(path, doypath, expLabel)
550 552
551 553
552 554 print "%s folder was found: " %(fullpath )
553 555
554 556 if set == None:
555 557 filename = getlastFileFromPath(fullpath, ext)
556 558 else:
557 559 filename = getFileFromSet(fullpath, ext, set)
558 560
559 561 if not(filename):
560 562 return None, None, None, None, None, None
561 563
562 564 print "%s file was found" %(filename)
563 565
564 566 if not(self.__verifyFile(os.path.join(fullpath, filename))):
565 567 return None, None, None, None, None, None
566 568
567 569 year = int( filename[1:5] )
568 570 doy = int( filename[5:8] )
569 571 set = int( filename[8:11] )
570 572
571 573 return fullpath, foldercounter, filename, year, doy, set
572 574
573 575 def __setNextFileOffline(self):
574 576
575 577 idFile = self.fileIndex
576 578
577 579 while (True):
578 580 idFile += 1
579 581 if not(idFile < len(self.filenameList)):
580 582 self.flagNoMoreFiles = 1
581 583 print "No more Files"
582 584 return 0
583 585
584 586 filename = self.filenameList[idFile]
585 587
586 588 if not(self.__verifyFile(filename)):
587 589 continue
588 590
589 591 fileSize = os.path.getsize(filename)
590 592 fp = open(filename,'rb')
591 593 break
592 594
593 595 self.flagIsNewFile = 1
594 596 self.fileIndex = idFile
595 597 self.filename = filename
596 598 self.fileSize = fileSize
597 599 self.fp = fp
598 600
599 601 print "Setting the file: %s"%self.filename
600 602
601 603 return 1
602 604
603 605 def __setNextFileOnline(self):
604 606 """
605 607 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
606 608 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
607 609 siguientes.
608 610
609 611 Affected:
610 612 self.flagIsNewFile
611 613 self.filename
612 614 self.fileSize
613 615 self.fp
614 616 self.set
615 617 self.flagNoMoreFiles
616 618
617 619 Return:
618 620 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
619 621 1 : si el file fue abierto con exito y esta listo a ser leido
620 622
621 623 Excepciones:
622 624 Si un determinado file no puede ser abierto
623 625 """
624 626 nFiles = 0
625 627 fileOk_flag = False
626 628 firstTime_flag = True
627 629
628 630 self.set += 1
629 631
630 632 if self.set > 999:
631 633 self.set = 0
632 634 self.foldercounter += 1
633 635
634 636 #busca el 1er file disponible
635 637 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
636 638 if fullfilename:
637 639 if self.__verifyFile(fullfilename, False):
638 640 fileOk_flag = True
639 641
640 642 #si no encuentra un file entonces espera y vuelve a buscar
641 643 if not(fileOk_flag):
642 644 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
643 645
644 646 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
645 647 tries = self.nTries
646 648 else:
647 649 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
648 650
649 651 for nTries in range( tries ):
650 652 if firstTime_flag:
651 653 print "\tWaiting %0.2f sec for the file \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
652 654 time.sleep( self.delay )
653 655 else:
654 656 print "\tSearching next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
655 657
656 658 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
657 659 if fullfilename:
658 660 if self.__verifyFile(fullfilename):
659 661 fileOk_flag = True
660 662 break
661 663
662 664 if fileOk_flag:
663 665 break
664 666
665 667 firstTime_flag = False
666 668
667 669 print "\tSkipping the file \"%s\" due to this file doesn't exist" % filename
668 670 self.set += 1
669 671
670 672 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
671 673 self.set = 0
672 674 self.doy += 1
673 675 self.foldercounter = 0
674 676
675 677 if fileOk_flag:
676 678 self.fileSize = os.path.getsize( fullfilename )
677 679 self.filename = fullfilename
678 680 self.flagIsNewFile = 1
679 681 if self.fp != None: self.fp.close()
680 682 self.fp = open(fullfilename, 'rb')
681 683 self.flagNoMoreFiles = 0
682 684 print 'Setting the file: %s' % fullfilename
683 685 else:
684 686 self.fileSize = 0
685 687 self.filename = None
686 688 self.flagIsNewFile = 0
687 689 self.fp = None
688 690 self.flagNoMoreFiles = 1
689 691 print 'No more Files'
690 692
691 693 return fileOk_flag
692 694
693 695 def setNextFile(self):
694 696 if self.fp != None:
695 697 self.fp.close()
696 698
697 699 if self.online:
698 700 newFile = self.__setNextFileOnline()
699 701 else:
700 702 newFile = self.__setNextFileOffline()
701 703
702 704 if not(newFile):
703 705 return 0
704 706
705 707 self.__readFirstHeader()
706 708 self.nReadBlocks = 0
707 709 return 1
708 710
709 711 def __waitNewBlock(self):
710 712 """
711 713 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
712 714
713 715 Si el modo de lectura es OffLine siempre retorn 0
714 716 """
715 717 if not self.online:
716 718 return 0
717 719
718 720 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
719 721 return 0
720 722
721 723 currentPointer = self.fp.tell()
722 724
723 725 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
724 726
725 727 for nTries in range( self.nTries ):
726 728
727 729 self.fp.close()
728 730 self.fp = open( self.filename, 'rb' )
729 731 self.fp.seek( currentPointer )
730 732
731 733 self.fileSize = os.path.getsize( self.filename )
732 734 currentSize = self.fileSize - currentPointer
733 735
734 736 if ( currentSize >= neededSize ):
735 737 self.basicHeaderObj.read(self.fp)
736 738 return 1
737 739
738 740 if self.fileSize == self.fileSizeByHeader:
739 741 # self.flagEoF = True
740 742 return 0
741 743
742 744 print "\tWaiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
743 745 time.sleep( self.delay )
744 746
745 747
746 748 return 0
747 749
748 750 def waitDataBlock(self,pointer_location):
749 751
750 752 currentPointer = pointer_location
751 753
752 754 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
753 755
754 756 for nTries in range( self.nTries ):
755 757 self.fp.close()
756 758 self.fp = open( self.filename, 'rb' )
757 759 self.fp.seek( currentPointer )
758 760
759 761 self.fileSize = os.path.getsize( self.filename )
760 762 currentSize = self.fileSize - currentPointer
761 763
762 764 if ( currentSize >= neededSize ):
763 765 return 1
764 766
765 767 print "\tWaiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
766 768 time.sleep( self.delay )
767 769
768 770 return 0
769 771
770 772 def __jumpToLastBlock(self):
771 773
772 774 if not(self.__isFirstTimeOnline):
773 775 return
774 776
775 777 csize = self.fileSize - self.fp.tell()
776 778 blocksize = self.processingHeaderObj.blockSize
777 779
778 780 #salta el primer bloque de datos
779 781 if csize > self.processingHeaderObj.blockSize:
780 782 self.fp.seek(self.fp.tell() + blocksize)
781 783 else:
782 784 return
783 785
784 786 csize = self.fileSize - self.fp.tell()
785 787 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
786 788 while True:
787 789
788 790 if self.fp.tell()<self.fileSize:
789 791 self.fp.seek(self.fp.tell() + neededsize)
790 792 else:
791 793 self.fp.seek(self.fp.tell() - neededsize)
792 794 break
793 795
794 796 # csize = self.fileSize - self.fp.tell()
795 797 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
796 798 # factor = int(csize/neededsize)
797 799 # if factor > 0:
798 800 # self.fp.seek(self.fp.tell() + factor*neededsize)
799 801
800 802 self.flagIsNewFile = 0
801 803 self.__isFirstTimeOnline = 0
802 804
803 805 def __setNewBlock(self):
804 806
805 807 if self.fp == None:
806 808 return 0
807 809
808 810 if self.online:
809 811 self.__jumpToLastBlock()
810 812
811 813 if self.flagIsNewFile:
812 814 return 1
813 815
814 816 self.lastUTTime = self.basicHeaderObj.utc
815 817 currentSize = self.fileSize - self.fp.tell()
816 818 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
817 819
818 820 if (currentSize >= neededSize):
819 821 self.basicHeaderObj.read(self.fp)
820 822 return 1
821 823
822 824 if self.__waitNewBlock():
823 825 return 1
824 826
825 827 if not(self.setNextFile()):
826 828 return 0
827 829
828 830 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
829 831
830 832 self.flagTimeBlock = 0
831 833
832 834 if deltaTime > self.maxTimeStep:
833 835 self.flagTimeBlock = 1
834 836
835 837 return 1
836 838
837 839 def readNextBlock(self):
838 840 if not(self.__setNewBlock()):
839 841 return 0
840 842
841 843 if not(self.readBlock()):
842 844 return 0
843 845
844 846 return 1
845 847
846 848 def __readFirstHeader(self):
847 849
848 850 self.basicHeaderObj.read(self.fp)
849 851 self.systemHeaderObj.read(self.fp)
850 852 self.radarControllerHeaderObj.read(self.fp)
851 853 self.processingHeaderObj.read(self.fp)
852 854
853 855 self.firstHeaderSize = self.basicHeaderObj.size
854 856
855 857 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
856 858 if datatype == 0:
857 859 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
858 860 elif datatype == 1:
859 861 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
860 862 elif datatype == 2:
861 863 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
862 864 elif datatype == 3:
863 865 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
864 866 elif datatype == 4:
865 867 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
866 868 elif datatype == 5:
867 869 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
868 870 else:
869 871 raise ValueError, 'Data type was not defined'
870 872
871 873 self.dtype = datatype_str
872 874 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
873 875 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
874 876 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
875 877 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
876 878 self.getBlockDimension()
877 879
878 880 def __verifyFile(self, filename, msgFlag=True):
879 881 msg = None
880 882 try:
881 883 fp = open(filename, 'rb')
882 884 currentPosition = fp.tell()
883 885 except IOError:
884 886 traceback.print_exc()
885 887 if msgFlag:
886 888 print "The file %s can't be opened" % (filename)
887 889 return False
888 890
889 891 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
890 892
891 893 if neededSize == 0:
892 894 basicHeaderObj = BasicHeader(LOCALTIME)
893 895 systemHeaderObj = SystemHeader()
894 896 radarControllerHeaderObj = RadarControllerHeader()
895 897 processingHeaderObj = ProcessingHeader()
896 898
897 899 try:
898 900 if not( basicHeaderObj.read(fp) ): raise IOError
899 901 if not( systemHeaderObj.read(fp) ): raise IOError
900 902 if not( radarControllerHeaderObj.read(fp) ): raise IOError
901 903 if not( processingHeaderObj.read(fp) ): raise IOError
902 904 # data_type = int(numpy.log2((processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
903 905
904 906 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
905 907
906 908 except IOError:
907 909 traceback.print_exc()
908 910 if msgFlag:
909 911 print "\tThe file %s is empty or it hasn't enough data" % filename
910 912
911 913 fp.close()
912 914 return False
913 915 else:
914 916 msg = "\tSkipping the file %s due to it hasn't enough data" %filename
915 917
916 918 fp.close()
917 919 fileSize = os.path.getsize(filename)
918 920 currentSize = fileSize - currentPosition
919 921 if currentSize < neededSize:
920 922 if msgFlag and (msg != None):
921 923 print msg #print"\tSkipping the file %s due to it hasn't enough data" %filename
922 924 return False
923 925
924 926 return True
925 927
926 928 def setup(self,
927 929 path=None,
928 930 startDate=None,
929 931 endDate=None,
930 932 startTime=datetime.time(0,0,0),
931 933 endTime=datetime.time(23,59,59),
932 934 set=None,
933 935 expLabel = "",
934 936 ext = None,
935 937 online = False,
936 938 delay = 60,
937 walk = True):
939 walk = True,
940 getblock = False):
938 941
939 942 if path == None:
940 943 raise ValueError, "The path is not valid"
941 944
942 945 if ext == None:
943 946 ext = self.ext
944 947
945 948 if online:
946 949 print "Searching files in online mode..."
947 950
948 951 for nTries in range( self.nTries ):
949 952 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
950 953
951 954 if fullpath:
952 955 break
953 956
954 957 print '\tWaiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
955 958 time.sleep( self.delay )
956 959
957 960 if not(fullpath):
958 961 print "There 'isn't valied files in %s" % path
959 962 return None
960 963
961 964 self.year = year
962 965 self.doy = doy
963 966 self.set = set - 1
964 967 self.path = path
965 968 self.foldercounter = foldercounter
966 969 last_set = None
967 970
968 971 else:
969 972 print "Searching files in offline mode ..."
970 973 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
971 974 startTime=startTime, endTime=endTime,
972 975 set=set, expLabel=expLabel, ext=ext,
973 976 walk=walk)
974 977
975 978 if not(pathList):
976 979 print "No *%s files into the folder %s \nfor the range: %s - %s"%(ext, path,
977 980 datetime.datetime.combine(startDate,startTime).ctime(),
978 981 datetime.datetime.combine(endDate,endTime).ctime())
979 982
980 983 sys.exit(-1)
981 984
982 985
983 986 self.fileIndex = -1
984 987 self.pathList = pathList
985 988 self.filenameList = filenameList
986 989 file_name = os.path.basename(filenameList[-1])
987 990 basename, ext = os.path.splitext(file_name)
988 991 last_set = int(basename[-3:])
989 992
990 993 self.online = online
991 994 self.delay = delay
992 995 ext = ext.lower()
993 996 self.ext = ext
994
997 self.getblock = getblock
995 998 if not(self.setNextFile()):
996 999 if (startDate!=None) and (endDate!=None):
997 1000 print "No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
998 1001 elif startDate != None:
999 1002 print "No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1000 1003 else:
1001 1004 print "No files"
1002 1005
1003 1006 sys.exit(-1)
1004 1007
1005 1008 # self.updateDataHeader()
1006 1009 if last_set != None:
1007 1010 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1008 1011 return
1009 1012
1010 1013 def getBasicHeader(self):
1011 1014
1012 1015 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1013 1016
1014 1017 self.dataOut.flagTimeBlock = self.flagTimeBlock
1015 1018
1016 1019 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1017 1020
1018 1021 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1019 1022
1020 1023 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1021 1024
1022 1025 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1023 1026
1024 1027 def getFirstHeader(self):
1025 1028
1026 1029 raise ValueError, "This method has not been implemented"
1027 1030
1028 1031 def getData(self):
1029 1032
1030 1033 raise ValueError, "This method has not been implemented"
1031 1034
1032 1035 def hasNotDataInBuffer(self):
1033 1036
1034 1037 raise ValueError, "This method has not been implemented"
1035 1038
1036 1039 def readBlock(self):
1037 1040
1038 1041 raise ValueError, "This method has not been implemented"
1039 1042
1040 1043 def isEndProcess(self):
1041 1044
1042 1045 return self.flagNoMoreFiles
1043 1046
1044 1047 def printReadBlocks(self):
1045 1048
1046 1049 print "Number of read blocks per file %04d" %self.nReadBlocks
1047 1050
1048 1051 def printTotalBlocks(self):
1049 1052
1050 1053 print "Number of read blocks %04d" %self.nTotalBlocks
1051 1054
1052 1055 def printNumberOfBlock(self):
1053 1056
1054 1057 if self.flagIsNewBlock:
1055 1058 print "Block No. %04d, Total blocks %04d -> %s" %(self.basicHeaderObj.dataBlock, self.nTotalBlocks, self.dataOut.datatime.ctime())
1056 1059 self.dataOut.blocknow = self.basicHeaderObj.dataBlock
1057 1060
1058 1061 def printInfo(self):
1059 1062
1060 1063 if self.__printInfo == False:
1061 1064 return
1062 1065
1063 1066 self.basicHeaderObj.printInfo()
1064 1067 self.systemHeaderObj.printInfo()
1065 1068 self.radarControllerHeaderObj.printInfo()
1066 1069 self.processingHeaderObj.printInfo()
1067 1070
1068 1071 self.__printInfo = False
1069 1072
1070 1073
1071 1074 def run(self, **kwargs):
1072 1075
1073 1076 if not(self.isConfig):
1074 1077
1075 1078 # self.dataOut = dataOut
1076 1079 self.setup(**kwargs)
1077 1080 self.isConfig = True
1078 1081
1079 1082 self.getData()
1080 1083
1081 1084 class JRODataWriter(JRODataIO):
1082 1085
1083 1086 """
1084 1087 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1085 1088 de los datos siempre se realiza por bloques.
1086 1089 """
1087 1090
1088 1091 blockIndex = 0
1089 1092
1090 1093 path = None
1091 1094
1092 1095 setFile = None
1093 1096
1094 1097 profilesPerBlock = None
1095 1098
1096 1099 blocksPerFile = None
1097 1100
1098 1101 nWriteBlocks = 0
1099 1102
1100 1103 def __init__(self, dataOut=None):
1101 1104 raise ValueError, "Not implemented"
1102 1105
1103 1106
1104 1107 def hasAllDataInBuffer(self):
1105 1108 raise ValueError, "Not implemented"
1106 1109
1107 1110
1108 1111 def setBlockDimension(self):
1109 1112 raise ValueError, "Not implemented"
1110 1113
1111 1114
1112 1115 def writeBlock(self):
1113 1116 raise ValueError, "No implemented"
1114 1117
1115 1118
1116 1119 def putData(self):
1117 1120 raise ValueError, "No implemented"
1118 1121
1119 1122
1120 1123 def setBasicHeader(self):
1121 1124
1122 1125 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1123 1126 self.basicHeaderObj.version = self.versionFile
1124 1127 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1125 1128
1126 1129 utc = numpy.floor(self.dataOut.utctime)
1127 1130 milisecond = (self.dataOut.utctime - utc)* 1000.0
1128 1131
1129 1132 self.basicHeaderObj.utc = utc
1130 1133 self.basicHeaderObj.miliSecond = milisecond
1131 1134 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1132 1135 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1133 1136 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1134 1137
1135 1138 def setFirstHeader(self):
1136 1139 """
1137 1140 Obtiene una copia del First Header
1138 1141
1139 1142 Affected:
1140 1143
1141 1144 self.basicHeaderObj
1142 1145 self.systemHeaderObj
1143 1146 self.radarControllerHeaderObj
1144 1147 self.processingHeaderObj self.
1145 1148
1146 1149 Return:
1147 1150 None
1148 1151 """
1149 1152
1150 1153 raise ValueError, "No implemented"
1151 1154
1152 1155 def __writeFirstHeader(self):
1153 1156 """
1154 1157 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1155 1158
1156 1159 Affected:
1157 1160 __dataType
1158 1161
1159 1162 Return:
1160 1163 None
1161 1164 """
1162 1165
1163 1166 # CALCULAR PARAMETROS
1164 1167
1165 1168 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1166 1169 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1167 1170
1168 1171 self.basicHeaderObj.write(self.fp)
1169 1172 self.systemHeaderObj.write(self.fp)
1170 1173 self.radarControllerHeaderObj.write(self.fp)
1171 1174 self.processingHeaderObj.write(self.fp)
1172 1175
1173 1176 self.dtype = self.dataOut.dtype
1174 1177
1175 1178 def __setNewBlock(self):
1176 1179 """
1177 1180 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1178 1181
1179 1182 Return:
1180 1183 0 : si no pudo escribir nada
1181 1184 1 : Si escribio el Basic el First Header
1182 1185 """
1183 1186 if self.fp == None:
1184 1187 self.setNextFile()
1185 1188
1186 1189 if self.flagIsNewFile:
1187 1190 return 1
1188 1191
1189 1192 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1190 1193 self.basicHeaderObj.write(self.fp)
1191 1194 return 1
1192 1195
1193 1196 if not( self.setNextFile() ):
1194 1197 return 0
1195 1198
1196 1199 return 1
1197 1200
1198 1201
1199 1202 def writeNextBlock(self):
1200 1203 """
1201 1204 Selecciona el bloque siguiente de datos y los escribe en un file
1202 1205
1203 1206 Return:
1204 1207 0 : Si no hizo pudo escribir el bloque de datos
1205 1208 1 : Si no pudo escribir el bloque de datos
1206 1209 """
1207 1210 if not( self.__setNewBlock() ):
1208 1211 return 0
1209 1212
1210 1213 self.writeBlock()
1211 1214
1212 1215 return 1
1213 1216
1214 1217 def setNextFile(self):
1215 1218 """
1216 1219 Determina el siguiente file que sera escrito
1217 1220
1218 1221 Affected:
1219 1222 self.filename
1220 1223 self.subfolder
1221 1224 self.fp
1222 1225 self.setFile
1223 1226 self.flagIsNewFile
1224 1227
1225 1228 Return:
1226 1229 0 : Si el archivo no puede ser escrito
1227 1230 1 : Si el archivo esta listo para ser escrito
1228 1231 """
1229 1232 ext = self.ext
1230 1233 path = self.path
1231 1234
1232 1235 if self.fp != None:
1233 1236 self.fp.close()
1234 1237
1235 1238 timeTuple = time.localtime( self.dataOut.utctime)
1236 1239 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1237 1240
1238 1241 fullpath = os.path.join( path, subfolder )
1239 1242 if not( os.path.exists(fullpath) ):
1240 1243 os.mkdir(fullpath)
1241 1244 self.setFile = -1 #inicializo mi contador de seteo
1242 1245 else:
1243 1246 filesList = os.listdir( fullpath )
1244 1247 if len( filesList ) > 0:
1245 1248 filesList = sorted( filesList, key=str.lower )
1246 1249 filen = filesList[-1]
1247 1250 # el filename debera tener el siguiente formato
1248 1251 # 0 1234 567 89A BCDE (hex)
1249 1252 # x YYYY DDD SSS .ext
1250 1253 if isNumber( filen[8:11] ):
1251 1254 self.setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1252 1255 else:
1253 1256 self.setFile = -1
1254 1257 else:
1255 1258 self.setFile = -1 #inicializo mi contador de seteo
1256 1259
1257 1260 setFile = self.setFile
1258 1261 setFile += 1
1259 1262
1260 1263 file = '%s%4.4d%3.3d%3.3d%s' % (self.optchar,
1261 1264 timeTuple.tm_year,
1262 1265 timeTuple.tm_yday,
1263 1266 setFile,
1264 1267 ext )
1265 1268
1266 1269 filename = os.path.join( path, subfolder, file )
1267 1270
1268 1271 fp = open( filename,'wb' )
1269 1272
1270 1273 self.blockIndex = 0
1271 1274
1272 1275 #guardando atributos
1273 1276 self.filename = filename
1274 1277 self.subfolder = subfolder
1275 1278 self.fp = fp
1276 1279 self.setFile = setFile
1277 1280 self.flagIsNewFile = 1
1278 1281
1279 1282 self.setFirstHeader()
1280 1283
1281 1284 print 'Writing the file: %s'%self.filename
1282 1285
1283 1286 self.__writeFirstHeader()
1284 1287
1285 1288 return 1
1286 1289
1287 1290 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=0, ext=None):
1288 1291 """
1289 1292 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1290 1293
1291 1294 Inputs:
1292 1295 path : el path destino en el cual se escribiran los files a crear
1293 1296 format : formato en el cual sera salvado un file
1294 1297 set : el setebo del file
1295 1298
1296 1299 Return:
1297 1300 0 : Si no realizo un buen seteo
1298 1301 1 : Si realizo un buen seteo
1299 1302 """
1300 1303
1301 1304 if ext == None:
1302 1305 ext = self.ext
1303 1306
1304 1307 ext = ext.lower()
1305 1308
1306 1309 self.ext = ext
1307 1310
1308 1311 self.path = path
1309 1312
1310 1313 self.setFile = set - 1
1311 1314
1312 1315 self.blocksPerFile = blocksPerFile
1313 1316
1314 1317 self.profilesPerBlock = profilesPerBlock
1315 1318
1316 1319 self.dataOut = dataOut
1317 1320
1318 1321 if not(self.setNextFile()):
1319 1322 print "There isn't a next file"
1320 1323 return 0
1321 1324
1322 1325 self.setBlockDimension()
1323 1326
1324 1327 return 1
1325 1328
1326 1329 def run(self, dataOut, **kwargs):
1327 1330
1328 1331 if not(self.isConfig):
1329 1332
1330 1333 self.setup(dataOut, **kwargs)
1331 1334 self.isConfig = True
1332 1335
1333 1336 self.putData()
1334 1337
@@ -1,588 +1,593
1 1 '''
2 2
3 3 '''
4 4 import numpy
5 5
6 6 from jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
7 7 from model.proc.jroproc_base import ProcessingUnit, Operation
8 8 from model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
9 9 from model.data.jrodata import Voltage
10 10
11 11 class VoltageReader(JRODataReader, ProcessingUnit):
12 12 """
13 13 Esta clase permite leer datos de voltage desde archivos en formato rawdata (.r). La lectura
14 14 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones:
15 15 perfiles*alturas*canales) son almacenados en la variable "buffer".
16 16
17 17 perfiles * alturas * canales
18 18
19 19 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
20 20 RadarControllerHeader y Voltage. Los tres primeros se usan para almacenar informacion de la
21 21 cabecera de datos (metadata), y el cuarto (Voltage) para obtener y almacenar un perfil de
22 22 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
23 23
24 24 Example:
25 25
26 26 dpath = "/home/myuser/data"
27 27
28 28 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
29 29
30 30 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
31 31
32 32 readerObj = VoltageReader()
33 33
34 34 readerObj.setup(dpath, startTime, endTime)
35 35
36 36 while(True):
37 37
38 38 #to get one profile
39 39 profile = readerObj.getData()
40 40
41 41 #print the profile
42 42 print profile
43 43
44 44 #If you want to see all datablock
45 45 print readerObj.datablock
46 46
47 47 if readerObj.flagNoMoreFiles:
48 48 break
49 49
50 50 """
51 51
52 52 ext = ".r"
53 53
54 54 optchar = "D"
55 55 dataOut = None
56 56
57 57
58 58 def __init__(self):
59 59 """
60 60 Inicializador de la clase VoltageReader para la lectura de datos de voltage.
61 61
62 62 Input:
63 63 dataOut : Objeto de la clase Voltage. Este objeto sera utilizado para
64 64 almacenar un perfil de datos cada vez que se haga un requerimiento
65 65 (getData). El perfil sera obtenido a partir del buffer de datos,
66 66 si el buffer esta vacio se hara un nuevo proceso de lectura de un
67 67 bloque de datos.
68 68 Si este parametro no es pasado se creara uno internamente.
69 69
70 70 Variables afectadas:
71 71 self.dataOut
72 72
73 73 Return:
74 74 None
75 75 """
76 76
77 77 ProcessingUnit.__init__(self)
78 78
79 79 self.isConfig = False
80 80
81 81 self.datablock = None
82 82
83 83 self.utc = 0
84 84
85 85 self.ext = ".r"
86 86
87 87 self.optchar = "D"
88 88
89 89 self.basicHeaderObj = BasicHeader(LOCALTIME)
90 90
91 91 self.systemHeaderObj = SystemHeader()
92 92
93 93 self.radarControllerHeaderObj = RadarControllerHeader()
94 94
95 95 self.processingHeaderObj = ProcessingHeader()
96 96
97 97 self.online = 0
98 98
99 99 self.fp = None
100 100
101 101 self.idFile = None
102 102
103 103 self.dtype = None
104 104
105 105 self.fileSizeByHeader = None
106 106
107 107 self.filenameList = []
108 108
109 109 self.filename = None
110 110
111 111 self.fileSize = None
112 112
113 113 self.firstHeaderSize = 0
114 114
115 115 self.basicHeaderSize = 24
116 116
117 117 self.pathList = []
118 118
119 119 self.filenameList = []
120 120
121 121 self.lastUTTime = 0
122 122
123 123 self.maxTimeStep = 30
124 124
125 125 self.flagNoMoreFiles = 0
126 126
127 127 self.set = 0
128 128
129 129 self.path = None
130 130
131 131 self.profileIndex = 2**32-1
132 132
133 133 self.delay = 3 #seconds
134 134
135 135 self.nTries = 3 #quantity tries
136 136
137 137 self.nFiles = 3 #number of files for searching
138 138
139 139 self.nReadBlocks = 0
140 140
141 141 self.flagIsNewFile = 1
142 142
143 143 self.__isFirstTimeOnline = 1
144 144
145 145 # self.ippSeconds = 0
146 146
147 147 self.flagTimeBlock = 0
148 148
149 149 self.flagIsNewBlock = 0
150 150
151 151 self.nTotalBlocks = 0
152 152
153 153 self.blocksize = 0
154 154
155 155 self.dataOut = self.createObjByDefault()
156 156
157 157 def createObjByDefault(self):
158 158
159 159 dataObj = Voltage()
160 160
161 161 return dataObj
162 162
163 163 def __hasNotDataInBuffer(self):
164 164 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock:
165 165 return 1
166 166 return 0
167 167
168 168
169 169 def getBlockDimension(self):
170 170 """
171 171 Obtiene la cantidad de puntos a leer por cada bloque de datos
172 172
173 173 Affected:
174 174 self.blocksize
175 175
176 176 Return:
177 177 None
178 178 """
179 179 pts2read = self.processingHeaderObj.profilesPerBlock * self.processingHeaderObj.nHeights * self.systemHeaderObj.nChannels
180 180 self.blocksize = pts2read
181 181
182 182
183 183 def readBlock(self):
184 184 """
185 185 readBlock lee el bloque de datos desde la posicion actual del puntero del archivo
186 186 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
187 187 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
188 188 es seteado a 0
189 189
190 190 Inputs:
191 191 None
192 192
193 193 Return:
194 194 None
195 195
196 196 Affected:
197 197 self.profileIndex
198 198 self.datablock
199 199 self.flagIsNewFile
200 200 self.flagIsNewBlock
201 201 self.nTotalBlocks
202 202
203 203 Exceptions:
204 204 Si un bloque leido no es un bloque valido
205 205 """
206 206 current_pointer_location = self.fp.tell()
207 207 junk = numpy.fromfile( self.fp, self.dtype, self.blocksize )
208 208
209 209 try:
210 210 junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) )
211 211 except:
212 212 #print "The read block (%3d) has not enough data" %self.nReadBlocks
213 213
214 214 if self.waitDataBlock(pointer_location=current_pointer_location):
215 215 junk = numpy.fromfile( self.fp, self.dtype, self.blocksize )
216 216 junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) )
217 217 # return 0
218 218
219 219 junk = numpy.transpose(junk, (2,0,1))
220 220 self.datablock = junk['real'] + junk['imag']*1j
221 221
222 222 self.profileIndex = 0
223 223
224 224 self.flagIsNewFile = 0
225 225 self.flagIsNewBlock = 1
226 226
227 227 self.nTotalBlocks += 1
228 228 self.nReadBlocks += 1
229 229
230 230 return 1
231 231
232 232 def getFirstHeader(self):
233 233
234 234 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
235 235
236 236 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
237 237
238 238 # self.dataOut.ippSeconds = self.ippSeconds
239 239
240 240 self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt
241 241
242 242 if self.radarControllerHeaderObj.code != None:
243 243
244 244 self.dataOut.nCode = self.radarControllerHeaderObj.nCode
245 245
246 246 self.dataOut.nBaud = self.radarControllerHeaderObj.nBaud
247 247
248 248 self.dataOut.code = self.radarControllerHeaderObj.code
249 249
250 250 self.dataOut.dtype = self.dtype
251 251
252 252 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
253 253
254 254 xf = self.processingHeaderObj.firstHeight + self.processingHeaderObj.nHeights*self.processingHeaderObj.deltaHeight
255 255
256 256 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight)
257 257
258 258 self.dataOut.channelList = range(self.systemHeaderObj.nChannels)
259 259
260 260 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
261 261
262 262 self.dataOut.flagShiftFFT = False
263 263
264 264 self.dataOut.flagDecodeData = False #asumo q la data no esta decodificada
265 265
266 266 self.dataOut.flagDeflipData = False #asumo q la data no esta sin flip
267 267
268 268 self.dataOut.flagShiftFFT = False
269 269
270 270 def getData(self):
271 271 """
272 272 getData obtiene una unidad de datos del buffer de lectura y la copia a la clase "Voltage"
273 273 con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de
274 274 lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock"
275 275
276 276 Ademas incrementa el contador del buffer en 1.
277 277
278 278 Return:
279 279 data : retorna un perfil de voltages (alturas * canales) copiados desde el
280 280 buffer. Si no hay mas archivos a leer retorna None.
281 281
282 282 Variables afectadas:
283 283 self.dataOut
284 284 self.profileIndex
285 285
286 286 Affected:
287 287 self.dataOut
288 288 self.profileIndex
289 289 self.flagTimeBlock
290 290 self.flagIsNewBlock
291 291 """
292 292
293 293 if self.flagNoMoreFiles:
294 294 self.dataOut.flagNoData = True
295 295 print 'Process finished'
296 296 return 0
297 297
298 298 self.flagTimeBlock = 0
299 299 self.flagIsNewBlock = 0
300 300
301 301 if self.__hasNotDataInBuffer():
302 302
303 303 if not( self.readNextBlock() ):
304 304 return 0
305 305
306 306 self.getFirstHeader()
307 307
308 308 if self.datablock == None:
309 309 self.dataOut.flagNoData = True
310 310 return 0
311 311
312 self.dataOut.data = self.datablock[:,self.profileIndex,:]
312 if self.getblock:
313 self.dataOut.data = self.datablock
314 self.profileIndex = self.processingHeaderObj.profilesPerBlock
315 else:
316 self.dataOut.data = self.datablock[:,self.profileIndex,:]
317 self.profileIndex += 1
313 318
314 319 self.dataOut.flagNoData = False
315 320
316 321 self.getBasicHeader()
317 322
318 self.profileIndex += 1
323
319 324
320 325 self.dataOut.realtime = self.online
321 326
322 327 return self.dataOut.data
323 328
324 329 class VoltageWriter(JRODataWriter, Operation):
325 330 """
326 331 Esta clase permite escribir datos de voltajes a archivos procesados (.r). La escritura
327 332 de los datos siempre se realiza por bloques.
328 333 """
329 334
330 335 ext = ".r"
331 336
332 337 optchar = "D"
333 338
334 339 shapeBuffer = None
335 340
336 341
337 342 def __init__(self):
338 343 """
339 344 Inicializador de la clase VoltageWriter para la escritura de datos de espectros.
340 345
341 346 Affected:
342 347 self.dataOut
343 348
344 349 Return: None
345 350 """
346 351 Operation.__init__(self)
347 352
348 353 self.nTotalBlocks = 0
349 354
350 355 self.profileIndex = 0
351 356
352 357 self.isConfig = False
353 358
354 359 self.fp = None
355 360
356 361 self.flagIsNewFile = 1
357 362
358 363 self.nTotalBlocks = 0
359 364
360 365 self.flagIsNewBlock = 0
361 366
362 367 self.setFile = None
363 368
364 369 self.dtype = None
365 370
366 371 self.path = None
367 372
368 373 self.filename = None
369 374
370 375 self.basicHeaderObj = BasicHeader(LOCALTIME)
371 376
372 377 self.systemHeaderObj = SystemHeader()
373 378
374 379 self.radarControllerHeaderObj = RadarControllerHeader()
375 380
376 381 self.processingHeaderObj = ProcessingHeader()
377 382
378 383 def hasAllDataInBuffer(self):
379 384 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock:
380 385 return 1
381 386 return 0
382 387
383 388
384 389 def setBlockDimension(self):
385 390 """
386 391 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
387 392
388 393 Affected:
389 394 self.shape_spc_Buffer
390 395 self.shape_cspc_Buffer
391 396 self.shape_dc_Buffer
392 397
393 398 Return: None
394 399 """
395 400 self.shapeBuffer = (self.processingHeaderObj.profilesPerBlock,
396 401 self.processingHeaderObj.nHeights,
397 402 self.systemHeaderObj.nChannels)
398 403
399 404 self.datablock = numpy.zeros((self.systemHeaderObj.nChannels,
400 405 self.processingHeaderObj.profilesPerBlock,
401 406 self.processingHeaderObj.nHeights),
402 407 dtype=numpy.dtype('complex64'))
403 408
404 409
405 410 def writeBlock(self):
406 411 """
407 412 Escribe el buffer en el file designado
408 413
409 414 Affected:
410 415 self.profileIndex
411 416 self.flagIsNewFile
412 417 self.flagIsNewBlock
413 418 self.nTotalBlocks
414 419 self.blockIndex
415 420
416 421 Return: None
417 422 """
418 423 data = numpy.zeros( self.shapeBuffer, self.dtype )
419 424
420 425 junk = numpy.transpose(self.datablock, (1,2,0))
421 426
422 427 data['real'] = junk.real
423 428 data['imag'] = junk.imag
424 429
425 430 data = data.reshape( (-1) )
426 431
427 432 data.tofile( self.fp )
428 433
429 434 self.datablock.fill(0)
430 435
431 436 self.profileIndex = 0
432 437 self.flagIsNewFile = 0
433 438 self.flagIsNewBlock = 1
434 439
435 440 self.blockIndex += 1
436 441 self.nTotalBlocks += 1
437 442
438 443 def putData(self):
439 444 """
440 445 Setea un bloque de datos y luego los escribe en un file
441 446
442 447 Affected:
443 448 self.flagIsNewBlock
444 449 self.profileIndex
445 450
446 451 Return:
447 452 0 : Si no hay data o no hay mas files que puedan escribirse
448 453 1 : Si se escribio la data de un bloque en un file
449 454 """
450 455 if self.dataOut.flagNoData:
451 456 return 0
452 457
453 458 self.flagIsNewBlock = 0
454 459
455 460 if self.dataOut.flagTimeBlock:
456 461
457 462 self.datablock.fill(0)
458 463 self.profileIndex = 0
459 464 self.setNextFile()
460 465
461 466 if self.profileIndex == 0:
462 467 self.setBasicHeader()
463 468
464 469 self.datablock[:,self.profileIndex,:] = self.dataOut.data
465 470
466 471 self.profileIndex += 1
467 472
468 473 if self.hasAllDataInBuffer():
469 474 #if self.flagIsNewFile:
470 475 self.writeNextBlock()
471 476 # self.setFirstHeader()
472 477
473 478 return 1
474 479
475 480 def __getProcessFlags(self):
476 481
477 482 processFlags = 0
478 483
479 484 dtype0 = numpy.dtype([('real','<i1'),('imag','<i1')])
480 485 dtype1 = numpy.dtype([('real','<i2'),('imag','<i2')])
481 486 dtype2 = numpy.dtype([('real','<i4'),('imag','<i4')])
482 487 dtype3 = numpy.dtype([('real','<i8'),('imag','<i8')])
483 488 dtype4 = numpy.dtype([('real','<f4'),('imag','<f4')])
484 489 dtype5 = numpy.dtype([('real','<f8'),('imag','<f8')])
485 490
486 491 dtypeList = [dtype0, dtype1, dtype2, dtype3, dtype4, dtype5]
487 492
488 493
489 494
490 495 datatypeValueList = [PROCFLAG.DATATYPE_CHAR,
491 496 PROCFLAG.DATATYPE_SHORT,
492 497 PROCFLAG.DATATYPE_LONG,
493 498 PROCFLAG.DATATYPE_INT64,
494 499 PROCFLAG.DATATYPE_FLOAT,
495 500 PROCFLAG.DATATYPE_DOUBLE]
496 501
497 502
498 503 for index in range(len(dtypeList)):
499 504 if self.dataOut.dtype == dtypeList[index]:
500 505 dtypeValue = datatypeValueList[index]
501 506 break
502 507
503 508 processFlags += dtypeValue
504 509
505 510 if self.dataOut.flagDecodeData:
506 511 processFlags += PROCFLAG.DECODE_DATA
507 512
508 513 if self.dataOut.flagDeflipData:
509 514 processFlags += PROCFLAG.DEFLIP_DATA
510 515
511 516 if self.dataOut.code != None:
512 517 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
513 518
514 519 if self.dataOut.nCohInt > 1:
515 520 processFlags += PROCFLAG.COHERENT_INTEGRATION
516 521
517 522 return processFlags
518 523
519 524
520 525 def __getBlockSize(self):
521 526 '''
522 527 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Voltage
523 528 '''
524 529
525 530 dtype0 = numpy.dtype([('real','<i1'),('imag','<i1')])
526 531 dtype1 = numpy.dtype([('real','<i2'),('imag','<i2')])
527 532 dtype2 = numpy.dtype([('real','<i4'),('imag','<i4')])
528 533 dtype3 = numpy.dtype([('real','<i8'),('imag','<i8')])
529 534 dtype4 = numpy.dtype([('real','<f4'),('imag','<f4')])
530 535 dtype5 = numpy.dtype([('real','<f8'),('imag','<f8')])
531 536
532 537 dtypeList = [dtype0, dtype1, dtype2, dtype3, dtype4, dtype5]
533 538 datatypeValueList = [1,2,4,8,4,8]
534 539 for index in range(len(dtypeList)):
535 540 if self.dataOut.dtype == dtypeList[index]:
536 541 datatypeValue = datatypeValueList[index]
537 542 break
538 543
539 544 blocksize = int(self.dataOut.nHeights * self.dataOut.nChannels * self.profilesPerBlock * datatypeValue * 2)
540 545
541 546 return blocksize
542 547
543 548 def setFirstHeader(self):
544 549
545 550 """
546 551 Obtiene una copia del First Header
547 552
548 553 Affected:
549 554 self.systemHeaderObj
550 555 self.radarControllerHeaderObj
551 556 self.dtype
552 557
553 558 Return:
554 559 None
555 560 """
556 561
557 562 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
558 563 self.systemHeaderObj.nChannels = self.dataOut.nChannels
559 564 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
560 565
561 566 self.setBasicHeader()
562 567
563 568 processingHeaderSize = 40 # bytes
564 569 self.processingHeaderObj.dtype = 0 # Voltage
565 570 self.processingHeaderObj.blockSize = self.__getBlockSize()
566 571 self.processingHeaderObj.profilesPerBlock = self.profilesPerBlock
567 572 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
568 573 self.processingHeaderObj.nWindows = 1 #podria ser 1 o self.dataOut.processingHeaderObj.nWindows
569 574 self.processingHeaderObj.processFlags = self.__getProcessFlags()
570 575 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt
571 576 self.processingHeaderObj.nIncohInt = 1 # Cuando la data de origen es de tipo Voltage
572 577 self.processingHeaderObj.totalSpectra = 0 # Cuando la data de origen es de tipo Voltage
573 578
574 579 # if self.dataOut.code != None:
575 580 # self.processingHeaderObj.code = self.dataOut.code
576 581 # self.processingHeaderObj.nCode = self.dataOut.nCode
577 582 # self.processingHeaderObj.nBaud = self.dataOut.nBaud
578 583 # codesize = int(8 + 4 * self.dataOut.nCode * self.dataOut.nBaud)
579 584 # processingHeaderSize += codesize
580 585
581 586 if self.processingHeaderObj.nWindows != 0:
582 587 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
583 588 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
584 589 self.processingHeaderObj.nHeights = self.dataOut.nHeights
585 590 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
586 591 processingHeaderSize += 12
587 592
588 593 self.processingHeaderObj.size = processingHeaderSize No newline at end of file
@@ -1,1025 +1,927
1 1 import numpy
2 2
3 3 from jroproc_base import ProcessingUnit, Operation
4 4 from model.data.jrodata import Spectra
5 5 from model.data.jrodata import hildebrand_sekhon
6 6
7 7 class SpectraProc(ProcessingUnit):
8 8
9 9 def __init__(self):
10 10
11 11 ProcessingUnit.__init__(self)
12 12
13 13 self.buffer = None
14 14 self.firstdatatime = None
15 15 self.profIndex = 0
16 16 self.dataOut = Spectra()
17 self.id_min = None
18 self.id_max = None
17 19
18 20 def __updateObjFromInput(self):
19 21
20 22 self.dataOut.timeZone = self.dataIn.timeZone
21 23 self.dataOut.dstFlag = self.dataIn.dstFlag
22 24 self.dataOut.errorCount = self.dataIn.errorCount
23 25 self.dataOut.useLocalTime = self.dataIn.useLocalTime
24 26
25 27 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
26 28 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
27 29 self.dataOut.channelList = self.dataIn.channelList
28 30 self.dataOut.heightList = self.dataIn.heightList
29 31 self.dataOut.dtype = numpy.dtype([('real','<f4'),('imag','<f4')])
30 32 # self.dataOut.nHeights = self.dataIn.nHeights
31 33 # self.dataOut.nChannels = self.dataIn.nChannels
32 34 self.dataOut.nBaud = self.dataIn.nBaud
33 35 self.dataOut.nCode = self.dataIn.nCode
34 36 self.dataOut.code = self.dataIn.code
35 37 self.dataOut.nProfiles = self.dataOut.nFFTPoints
36 38 # self.dataOut.channelIndexList = self.dataIn.channelIndexList
37 39 self.dataOut.flagTimeBlock = self.dataIn.flagTimeBlock
38 40 self.dataOut.utctime = self.firstdatatime
39 41 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
40 42 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
41 43 # self.dataOut.flagShiftFFT = self.dataIn.flagShiftFFT
42 44 self.dataOut.nCohInt = self.dataIn.nCohInt
43 45 self.dataOut.nIncohInt = 1
44 46 # self.dataOut.ippSeconds = self.dataIn.ippSeconds
45 47 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
46 48
47 49 self.dataOut.timeInterval = self.dataIn.timeInterval*self.dataOut.nFFTPoints*self.dataOut.nIncohInt
48 50 self.dataOut.frequency = self.dataIn.frequency
49 51 self.dataOut.realtime = self.dataIn.realtime
50 52
51 53 def __getFft(self):
52 54 """
53 55 Convierte valores de Voltaje a Spectra
54 56
55 57 Affected:
56 58 self.dataOut.data_spc
57 59 self.dataOut.data_cspc
58 60 self.dataOut.data_dc
59 61 self.dataOut.heightList
60 62 self.profIndex
61 63 self.buffer
62 64 self.dataOut.flagNoData
63 65 """
64 66 fft_volt = numpy.fft.fft(self.buffer,n=self.dataOut.nFFTPoints,axis=1)
65 67 fft_volt = fft_volt.astype(numpy.dtype('complex'))
66 68 dc = fft_volt[:,0,:]
67 69
68 70 #calculo de self-spectra
69 71 fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,))
70 72 spc = fft_volt * numpy.conjugate(fft_volt)
71 73 spc = spc.real
72 74
73 75 blocksize = 0
74 76 blocksize += dc.size
75 77 blocksize += spc.size
76 78
77 79 cspc = None
78 80 pairIndex = 0
79 81 if self.dataOut.pairsList != None:
80 82 #calculo de cross-spectra
81 83 cspc = numpy.zeros((self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
82 84 for pair in self.dataOut.pairsList:
83 85 cspc[pairIndex,:,:] = fft_volt[pair[0],:,:] * numpy.conjugate(fft_volt[pair[1],:,:])
84 86 pairIndex += 1
85 87 blocksize += cspc.size
86 88
87 89 self.dataOut.data_spc = spc
88 90 self.dataOut.data_cspc = cspc
89 91 self.dataOut.data_dc = dc
90 92 self.dataOut.blockSize = blocksize
91 93 self.dataOut.flagShiftFFT = False
92 94
93 95 def run(self, nProfiles=None, nFFTPoints=None, pairsList=[], ippFactor=None):
94 96
95 97 self.dataOut.flagNoData = True
96 98
97 99 if self.dataIn.type == "Spectra":
98 100 self.dataOut.copy(self.dataIn)
99 101 return True
100 102
101 103 if self.dataIn.type == "Voltage":
102 104
103 105 if nFFTPoints == None:
104 106 raise ValueError, "This SpectraProc.run() need nFFTPoints input variable"
105 107
106 nProfiles = nFFTPoints
107
108 # if pairsList == None:
109 # nPairs = 0
110 # else:
111 # nPairs = len(pairsList)
108 if nProfiles == None:
109 raise ValueError, "This SpectraProc.run() need nProfiles input variable"
110
112 111
113 112 if ippFactor == None:
114 113 ippFactor = 1
115 114 self.dataOut.ippFactor = ippFactor
116 115
117 116 self.dataOut.nFFTPoints = nFFTPoints
118 117 self.dataOut.pairsList = pairsList
119 # self.dataOut.nPairs = nPairs
120
118
121 119 if self.buffer == None:
122 120 self.buffer = numpy.zeros((self.dataIn.nChannels,
123 121 nProfiles,
124 122 self.dataIn.nHeights),
125 dtype='complex')
123 dtype='complex')
124 self.id_min = 0
125 self.id_max = self.dataIn.data.shape[1]
126 126
127
128 self.buffer[:,self.profIndex,:] = self.dataIn.data.copy()
129 self.profIndex += 1
127 if len(self.dataIn.data.shape) == 2:
128 self.buffer[:,self.profIndex,:] = self.dataIn.data.copy()
129 self.profIndex += 1
130 else:
131 if self.dataIn.data.shape[1] == nProfiles:
132 self.buffer = self.dataIn.data.copy()
133 self.profIndex = nProfiles
134 elif self.dataIn.data.shape[1] < nProfiles:
135 self.buffer[:,self.id_min:self.id_max,:] = self.dataIn.data
136 self.profIndex += self.dataIn.data.shape[1]
137 self.id_min += self.dataIn.data.shape[1]
138 self.id_max += self.dataIn.data.shape[1]
139 else:
140 raise ValueError, "The type object %s has %d profiles, it should be equal to %d profiles"%(self.dataIn.type,self.dataIn.data.shape[1],nProfiles)
141 self.dataOut.flagNoData = True
142 return 0
143
130 144
131 145 if self.firstdatatime == None:
132 146 self.firstdatatime = self.dataIn.utctime
133 147
134 148 if self.profIndex == nProfiles:
135 149 self.__updateObjFromInput()
136 150 self.__getFft()
137 151
138 152 self.dataOut.flagNoData = False
139 153
140 154 self.buffer = None
141 155 self.firstdatatime = None
142 156 self.profIndex = 0
143 157
144 158 return True
145 159
146 160 raise ValueError, "The type object %s is not valid"%(self.dataIn.type)
147 161
148 162 def selectChannels(self, channelList):
149 163
150 164 channelIndexList = []
151 165
152 166 for channel in channelList:
153 167 index = self.dataOut.channelList.index(channel)
154 168 channelIndexList.append(index)
155 169
156 170 self.selectChannelsByIndex(channelIndexList)
157 171
158 172 def selectChannelsByIndex(self, channelIndexList):
159 173 """
160 174 Selecciona un bloque de datos en base a canales segun el channelIndexList
161 175
162 176 Input:
163 177 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
164 178
165 179 Affected:
166 180 self.dataOut.data_spc
167 181 self.dataOut.channelIndexList
168 182 self.dataOut.nChannels
169 183
170 184 Return:
171 185 None
172 186 """
173 187
174 188 for channelIndex in channelIndexList:
175 189 if channelIndex not in self.dataOut.channelIndexList:
176 190 print channelIndexList
177 191 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
178 192
179 193 # nChannels = len(channelIndexList)
180 194
181 195 data_spc = self.dataOut.data_spc[channelIndexList,:]
182 196
183 197 self.dataOut.data_spc = data_spc
184 198 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
185 199 # self.dataOut.nChannels = nChannels
186 200
187 201 return 1
188 202
189 203 def selectHeights(self, minHei, maxHei):
190 204 """
191 205 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
192 206 minHei <= height <= maxHei
193 207
194 208 Input:
195 209 minHei : valor minimo de altura a considerar
196 210 maxHei : valor maximo de altura a considerar
197 211
198 212 Affected:
199 213 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
200 214
201 215 Return:
202 216 1 si el metodo se ejecuto con exito caso contrario devuelve 0
203 217 """
204 218 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
205 219 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
206 220
207 221 if (maxHei > self.dataOut.heightList[-1]):
208 222 maxHei = self.dataOut.heightList[-1]
209 223 # raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
210 224
211 225 minIndex = 0
212 226 maxIndex = 0
213 227 heights = self.dataOut.heightList
214 228
215 229 inda = numpy.where(heights >= minHei)
216 230 indb = numpy.where(heights <= maxHei)
217 231
218 232 try:
219 233 minIndex = inda[0][0]
220 234 except:
221 235 minIndex = 0
222 236
223 237 try:
224 238 maxIndex = indb[0][-1]
225 239 except:
226 240 maxIndex = len(heights)
227 241
228 242 self.selectHeightsByIndex(minIndex, maxIndex)
229 243
230 244 return 1
231 245
232 246 def getBeaconSignal(self, tauindex = 0, channelindex = 0, hei_ref=None):
233 247 newheis = numpy.where(self.dataOut.heightList>self.dataOut.radarControllerHeaderObj.Taus[tauindex])
234 248
235 249 if hei_ref != None:
236 250 newheis = numpy.where(self.dataOut.heightList>hei_ref)
237 251
238 252 minIndex = min(newheis[0])
239 253 maxIndex = max(newheis[0])
240 254 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
241 255 heightList = self.dataOut.heightList[minIndex:maxIndex+1]
242 256
243 257 # determina indices
244 258 nheis = int(self.dataOut.radarControllerHeaderObj.txB/(self.dataOut.heightList[1]-self.dataOut.heightList[0]))
245 259 avg_dB = 10*numpy.log10(numpy.sum(data_spc[channelindex,:,:],axis=0))
246 260 beacon_dB = numpy.sort(avg_dB)[-nheis:]
247 261 beacon_heiIndexList = []
248 262 for val in avg_dB.tolist():
249 263 if val >= beacon_dB[0]:
250 264 beacon_heiIndexList.append(avg_dB.tolist().index(val))
251 265
252 266 #data_spc = data_spc[:,:,beacon_heiIndexList]
253 267 data_cspc = None
254 268 if self.dataOut.data_cspc != None:
255 269 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
256 270 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
257 271
258 272 data_dc = None
259 273 if self.dataOut.data_dc != None:
260 274 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
261 275 #data_dc = data_dc[:,beacon_heiIndexList]
262 276
263 277 self.dataOut.data_spc = data_spc
264 278 self.dataOut.data_cspc = data_cspc
265 279 self.dataOut.data_dc = data_dc
266 280 self.dataOut.heightList = heightList
267 281 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
268 282
269 283 return 1
270 284
271 285
272 286 def selectHeightsByIndex(self, minIndex, maxIndex):
273 287 """
274 288 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
275 289 minIndex <= index <= maxIndex
276 290
277 291 Input:
278 292 minIndex : valor de indice minimo de altura a considerar
279 293 maxIndex : valor de indice maximo de altura a considerar
280 294
281 295 Affected:
282 296 self.dataOut.data_spc
283 297 self.dataOut.data_cspc
284 298 self.dataOut.data_dc
285 299 self.dataOut.heightList
286 300
287 301 Return:
288 302 1 si el metodo se ejecuto con exito caso contrario devuelve 0
289 303 """
290 304
291 305 if (minIndex < 0) or (minIndex > maxIndex):
292 306 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
293 307
294 308 if (maxIndex >= self.dataOut.nHeights):
295 309 maxIndex = self.dataOut.nHeights-1
296 310 # raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
297 311
298 312 # nHeights = maxIndex - minIndex + 1
299 313
300 314 #Spectra
301 315 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
302 316
303 317 data_cspc = None
304 318 if self.dataOut.data_cspc != None:
305 319 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
306 320
307 321 data_dc = None
308 322 if self.dataOut.data_dc != None:
309 323 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
310 324
311 325 self.dataOut.data_spc = data_spc
312 326 self.dataOut.data_cspc = data_cspc
313 327 self.dataOut.data_dc = data_dc
314 328
315 329 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
316 330
317 331 return 1
318 332
319 333 def removeDC(self, mode = 2):
320 334 jspectra = self.dataOut.data_spc
321 335 jcspectra = self.dataOut.data_cspc
322 336
323 337
324 338 num_chan = jspectra.shape[0]
325 339 num_hei = jspectra.shape[2]
326 340
327 341 if jcspectra != None:
328 342 jcspectraExist = True
329 343 num_pairs = jcspectra.shape[0]
330 344 else: jcspectraExist = False
331 345
332 346 freq_dc = jspectra.shape[1]/2
333 347 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
334 348
335 349 if ind_vel[0]<0:
336 350 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
337 351
338 352 if mode == 1:
339 353 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
340 354
341 355 if jcspectraExist:
342 356 jcspectra[:,freq_dc,:] = (jcspectra[:,ind_vel[1],:] + jcspectra[:,ind_vel[2],:])/2
343 357
344 358 if mode == 2:
345 359
346 360 vel = numpy.array([-2,-1,1,2])
347 361 xx = numpy.zeros([4,4])
348 362
349 363 for fil in range(4):
350 364 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
351 365
352 366 xx_inv = numpy.linalg.inv(xx)
353 367 xx_aux = xx_inv[0,:]
354 368
355 369 for ich in range(num_chan):
356 370 yy = jspectra[ich,ind_vel,:]
357 371 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
358 372
359 373 junkid = jspectra[ich,freq_dc,:]<=0
360 374 cjunkid = sum(junkid)
361 375
362 376 if cjunkid.any():
363 377 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
364 378
365 379 if jcspectraExist:
366 380 for ip in range(num_pairs):
367 381 yy = jcspectra[ip,ind_vel,:]
368 382 jcspectra[ip,freq_dc,:] = numpy.dot(xx_aux,yy)
369 383
370 384
371 385 self.dataOut.data_spc = jspectra
372 386 self.dataOut.data_cspc = jcspectra
373 387
374 388 return 1
375 389
376 390 def removeInterference(self, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None):
377 391
378 392 jspectra = self.dataOut.data_spc
379 393 jcspectra = self.dataOut.data_cspc
380 394 jnoise = self.dataOut.getNoise()
381 395 num_incoh = self.dataOut.nIncohInt
382 396
383 397 num_channel = jspectra.shape[0]
384 398 num_prof = jspectra.shape[1]
385 399 num_hei = jspectra.shape[2]
386 400
387 401 #hei_interf
388 402 if hei_interf == None:
389 403 count_hei = num_hei/2 #Como es entero no importa
390 404 hei_interf = numpy.asmatrix(range(count_hei)) + num_hei - count_hei
391 405 hei_interf = numpy.asarray(hei_interf)[0]
392 406 #nhei_interf
393 407 if (nhei_interf == None):
394 408 nhei_interf = 5
395 409 if (nhei_interf < 1):
396 410 nhei_interf = 1
397 411 if (nhei_interf > count_hei):
398 412 nhei_interf = count_hei
399 413 if (offhei_interf == None):
400 414 offhei_interf = 0
401 415
402 416 ind_hei = range(num_hei)
403 417 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
404 418 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
405 419 mask_prof = numpy.asarray(range(num_prof))
406 420 num_mask_prof = mask_prof.size
407 421 comp_mask_prof = [0, num_prof/2]
408 422
409 423
410 424 #noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
411 425 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
412 426 jnoise = numpy.nan
413 427 noise_exist = jnoise[0] < numpy.Inf
414 428
415 429 #Subrutina de Remocion de la Interferencia
416 430 for ich in range(num_channel):
417 431 #Se ordena los espectros segun su potencia (menor a mayor)
418 432 power = jspectra[ich,mask_prof,:]
419 433 power = power[:,hei_interf]
420 434 power = power.sum(axis = 0)
421 435 psort = power.ravel().argsort()
422 436
423 437 #Se estima la interferencia promedio en los Espectros de Potencia empleando
424 438 junkspc_interf = jspectra[ich,:,hei_interf[psort[range(offhei_interf, nhei_interf + offhei_interf)]]]
425 439
426 440 if noise_exist:
427 441 # tmp_noise = jnoise[ich] / num_prof
428 442 tmp_noise = jnoise[ich]
429 443 junkspc_interf = junkspc_interf - tmp_noise
430 444 #junkspc_interf[:,comp_mask_prof] = 0
431 445
432 446 jspc_interf = junkspc_interf.sum(axis = 0) / nhei_interf
433 447 jspc_interf = jspc_interf.transpose()
434 448 #Calculando el espectro de interferencia promedio
435 449 noiseid = numpy.where(jspc_interf <= tmp_noise/ math.sqrt(num_incoh))
436 450 noiseid = noiseid[0]
437 451 cnoiseid = noiseid.size
438 452 interfid = numpy.where(jspc_interf > tmp_noise/ math.sqrt(num_incoh))
439 453 interfid = interfid[0]
440 454 cinterfid = interfid.size
441 455
442 456 if (cnoiseid > 0): jspc_interf[noiseid] = 0
443 457
444 458 #Expandiendo los perfiles a limpiar
445 459 if (cinterfid > 0):
446 460 new_interfid = (numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof)%num_prof
447 461 new_interfid = numpy.asarray(new_interfid)
448 462 new_interfid = {x for x in new_interfid}
449 463 new_interfid = numpy.array(list(new_interfid))
450 464 new_cinterfid = new_interfid.size
451 465 else: new_cinterfid = 0
452 466
453 467 for ip in range(new_cinterfid):
454 468 ind = junkspc_interf[:,new_interfid[ip]].ravel().argsort()
455 469 jspc_interf[new_interfid[ip]] = junkspc_interf[ind[nhei_interf/2],new_interfid[ip]]
456 470
457 471
458 472 jspectra[ich,:,ind_hei] = jspectra[ich,:,ind_hei] - jspc_interf #Corregir indices
459 473
460 474 #Removiendo la interferencia del punto de mayor interferencia
461 475 ListAux = jspc_interf[mask_prof].tolist()
462 476 maxid = ListAux.index(max(ListAux))
463 477
464 478
465 479 if cinterfid > 0:
466 480 for ip in range(cinterfid*(interf == 2) - 1):
467 481 ind = (jspectra[ich,interfid[ip],:] < tmp_noise*(1 + 1/math.sqrt(num_incoh))).nonzero()
468 482 cind = len(ind)
469 483
470 484 if (cind > 0):
471 485 jspectra[ich,interfid[ip],ind] = tmp_noise*(1 + (numpy.random.uniform(cind) - 0.5)/math.sqrt(num_incoh))
472 486
473 487 ind = numpy.array([-2,-1,1,2])
474 488 xx = numpy.zeros([4,4])
475 489
476 490 for id1 in range(4):
477 491 xx[:,id1] = ind[id1]**numpy.asarray(range(4))
478 492
479 493 xx_inv = numpy.linalg.inv(xx)
480 494 xx = xx_inv[:,0]
481 495 ind = (ind + maxid + num_mask_prof)%num_mask_prof
482 496 yy = jspectra[ich,mask_prof[ind],:]
483 497 jspectra[ich,mask_prof[maxid],:] = numpy.dot(yy.transpose(),xx)
484 498
485 499
486 500 indAux = (jspectra[ich,:,:] < tmp_noise*(1-1/math.sqrt(num_incoh))).nonzero()
487 501 jspectra[ich,indAux[0],indAux[1]] = tmp_noise * (1 - 1/math.sqrt(num_incoh))
488 502
489 503 #Remocion de Interferencia en el Cross Spectra
490 504 if jcspectra == None: return jspectra, jcspectra
491 505 num_pairs = jcspectra.size/(num_prof*num_hei)
492 506 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
493 507
494 508 for ip in range(num_pairs):
495 509
496 510 #-------------------------------------------
497 511
498 512 cspower = numpy.abs(jcspectra[ip,mask_prof,:])
499 513 cspower = cspower[:,hei_interf]
500 514 cspower = cspower.sum(axis = 0)
501 515
502 516 cspsort = cspower.ravel().argsort()
503 517 junkcspc_interf = jcspectra[ip,:,hei_interf[cspsort[range(offhei_interf, nhei_interf + offhei_interf)]]]
504 518 junkcspc_interf = junkcspc_interf.transpose()
505 519 jcspc_interf = junkcspc_interf.sum(axis = 1)/nhei_interf
506 520
507 521 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
508 522
509 523 median_real = numpy.median(numpy.real(junkcspc_interf[mask_prof[ind[range(3*num_prof/4)]],:]))
510 524 median_imag = numpy.median(numpy.imag(junkcspc_interf[mask_prof[ind[range(3*num_prof/4)]],:]))
511 525 junkcspc_interf[comp_mask_prof,:] = numpy.complex(median_real, median_imag)
512 526
513 527 for iprof in range(num_prof):
514 528 ind = numpy.abs(junkcspc_interf[iprof,:]).ravel().argsort()
515 529 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf/2]]
516 530
517 531 #Removiendo la Interferencia
518 532 jcspectra[ip,:,ind_hei] = jcspectra[ip,:,ind_hei] - jcspc_interf
519 533
520 534 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
521 535 maxid = ListAux.index(max(ListAux))
522 536
523 537 ind = numpy.array([-2,-1,1,2])
524 538 xx = numpy.zeros([4,4])
525 539
526 540 for id1 in range(4):
527 541 xx[:,id1] = ind[id1]**numpy.asarray(range(4))
528 542
529 543 xx_inv = numpy.linalg.inv(xx)
530 544 xx = xx_inv[:,0]
531 545
532 546 ind = (ind + maxid + num_mask_prof)%num_mask_prof
533 547 yy = jcspectra[ip,mask_prof[ind],:]
534 548 jcspectra[ip,mask_prof[maxid],:] = numpy.dot(yy.transpose(),xx)
535 549
536 550 #Guardar Resultados
537 551 self.dataOut.data_spc = jspectra
538 552 self.dataOut.data_cspc = jcspectra
539 553
540 554 return 1
541 555
542 556 def setRadarFrequency(self, frequency=None):
543 557 if frequency != None:
544 558 self.dataOut.frequency = frequency
545 559
546 560 return 1
547 561
548 562 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
549 563 #validacion de rango
550 564 if minHei == None:
551 565 minHei = self.dataOut.heightList[0]
552 566
553 567 if maxHei == None:
554 568 maxHei = self.dataOut.heightList[-1]
555 569
556 570 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
557 571 print 'minHei: %.2f is out of the heights range'%(minHei)
558 572 print 'minHei is setting to %.2f'%(self.dataOut.heightList[0])
559 573 minHei = self.dataOut.heightList[0]
560 574
561 575 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
562 576 print 'maxHei: %.2f is out of the heights range'%(maxHei)
563 577 print 'maxHei is setting to %.2f'%(self.dataOut.heightList[-1])
564 578 maxHei = self.dataOut.heightList[-1]
565 579
566 580 # validacion de velocidades
567 581 velrange = self.dataOut.getVelRange(1)
568 582
569 583 if minVel == None:
570 584 minVel = velrange[0]
571 585
572 586 if maxVel == None:
573 587 maxVel = velrange[-1]
574 588
575 589 if (minVel < velrange[0]) or (minVel > maxVel):
576 590 print 'minVel: %.2f is out of the velocity range'%(minVel)
577 591 print 'minVel is setting to %.2f'%(velrange[0])
578 592 minVel = velrange[0]
579 593
580 594 if (maxVel > velrange[-1]) or (maxVel < minVel):
581 595 print 'maxVel: %.2f is out of the velocity range'%(maxVel)
582 596 print 'maxVel is setting to %.2f'%(velrange[-1])
583 597 maxVel = velrange[-1]
584 598
585 599 # seleccion de indices para rango
586 600 minIndex = 0
587 601 maxIndex = 0
588 602 heights = self.dataOut.heightList
589 603
590 604 inda = numpy.where(heights >= minHei)
591 605 indb = numpy.where(heights <= maxHei)
592 606
593 607 try:
594 608 minIndex = inda[0][0]
595 609 except:
596 610 minIndex = 0
597 611
598 612 try:
599 613 maxIndex = indb[0][-1]
600 614 except:
601 615 maxIndex = len(heights)
602 616
603 617 if (minIndex < 0) or (minIndex > maxIndex):
604 618 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
605 619
606 620 if (maxIndex >= self.dataOut.nHeights):
607 621 maxIndex = self.dataOut.nHeights-1
608 622
609 623 # seleccion de indices para velocidades
610 624 indminvel = numpy.where(velrange >= minVel)
611 625 indmaxvel = numpy.where(velrange <= maxVel)
612 626 try:
613 627 minIndexVel = indminvel[0][0]
614 628 except:
615 629 minIndexVel = 0
616 630
617 631 try:
618 632 maxIndexVel = indmaxvel[0][-1]
619 633 except:
620 634 maxIndexVel = len(velrange)
621 635
622 636 #seleccion del espectro
623 637 data_spc = self.dataOut.data_spc[:,minIndexVel:maxIndexVel+1,minIndex:maxIndex+1]
624 638 #estimacion de ruido
625 639 noise = numpy.zeros(self.dataOut.nChannels)
626 640
627 641 for channel in range(self.dataOut.nChannels):
628 642 daux = data_spc[channel,:,:]
629 643 noise[channel] = hildebrand_sekhon(daux, self.dataOut.nIncohInt)
630 644
631 645 self.dataOut.noise_estimation = noise.copy()
632 646
633 647 return 1
634 648
635 649 class IncohInt(Operation):
636 650
637 651
638 652 __profIndex = 0
639 653 __withOverapping = False
640 654
641 655 __byTime = False
642 656 __initime = None
643 657 __lastdatatime = None
644 658 __integrationtime = None
645 659
646 660 __buffer_spc = None
647 661 __buffer_cspc = None
648 662 __buffer_dc = None
649 663
650 664 __dataReady = False
651 665
652 666 __timeInterval = None
653 667
654 668 n = None
655 669
656 670
657 671
658 672 def __init__(self):
659 673
660 674 Operation.__init__(self)
661 675 # self.isConfig = False
662 676
663 677 def setup(self, n=None, timeInterval=None, overlapping=False):
664 678 """
665 679 Set the parameters of the integration class.
666 680
667 681 Inputs:
668 682
669 683 n : Number of coherent integrations
670 684 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
671 685 overlapping :
672 686
673 687 """
674 688
675 689 self.__initime = None
676 690 self.__lastdatatime = 0
677 691 self.__buffer_spc = None
678 692 self.__buffer_cspc = None
679 693 self.__buffer_dc = None
680 694 self.__dataReady = False
681 695
682 696
683 697 if n == None and timeInterval == None:
684 698 raise ValueError, "n or timeInterval should be specified ..."
685 699
686 700 if n != None:
687 701 self.n = n
688 702 self.__byTime = False
689 703 else:
690 704 self.__integrationtime = timeInterval #if (type(timeInterval)!=integer) -> change this line
691 705 self.n = 9999
692 706 self.__byTime = True
693 707
694 708 if overlapping:
695 709 self.__withOverapping = True
696 710 else:
697 711 self.__withOverapping = False
698 712 self.__buffer_spc = 0
699 713 self.__buffer_cspc = 0
700 714 self.__buffer_dc = 0
701 715
702 716 self.__profIndex = 0
703 717
704 718 def putData(self, data_spc, data_cspc, data_dc):
705 719
706 720 """
707 721 Add a profile to the __buffer_spc and increase in one the __profileIndex
708 722
709 723 """
710 724
711 725 if not self.__withOverapping:
712 726 self.__buffer_spc += data_spc
713 727
714 728 if data_cspc == None:
715 729 self.__buffer_cspc = None
716 730 else:
717 731 self.__buffer_cspc += data_cspc
718 732
719 733 if data_dc == None:
720 734 self.__buffer_dc = None
721 735 else:
722 736 self.__buffer_dc += data_dc
723 737
724 738 self.__profIndex += 1
725 739 return
726 740
727 741 #Overlapping data
728 742 nChannels, nFFTPoints, nHeis = data_spc.shape
729 743 data_spc = numpy.reshape(data_spc, (1, nChannels, nFFTPoints, nHeis))
730 744 if data_cspc != None:
731 745 data_cspc = numpy.reshape(data_cspc, (1, -1, nFFTPoints, nHeis))
732 746 if data_dc != None:
733 747 data_dc = numpy.reshape(data_dc, (1, -1, nHeis))
734 748
735 749 #If the buffer is empty then it takes the data value
736 750 if self.__buffer_spc == None:
737 751 self.__buffer_spc = data_spc
738 752
739 753 if data_cspc == None:
740 754 self.__buffer_cspc = None
741 755 else:
742 756 self.__buffer_cspc += data_cspc
743 757
744 758 if data_dc == None:
745 759 self.__buffer_dc = None
746 760 else:
747 761 self.__buffer_dc += data_dc
748 762
749 763 self.__profIndex += 1
750 764 return
751 765
752 766 #If the buffer length is lower than n then stakcing the data value
753 767 if self.__profIndex < self.n:
754 768 self.__buffer_spc = numpy.vstack((self.__buffer_spc, data_spc))
755 769
756 770 if data_cspc != None:
757 771 self.__buffer_cspc = numpy.vstack((self.__buffer_cspc, data_cspc))
758 772
759 773 if data_dc != None:
760 774 self.__buffer_dc = numpy.vstack((self.__buffer_dc, data_dc))
761 775
762 776 self.__profIndex += 1
763 777 return
764 778
765 779 #If the buffer length is equal to n then replacing the last buffer value with the data value
766 780 self.__buffer_spc = numpy.roll(self.__buffer_spc, -1, axis=0)
767 781 self.__buffer_spc[self.n-1] = data_spc
768 782
769 783 if data_cspc != None:
770 784 self.__buffer_cspc = numpy.roll(self.__buffer_cspc, -1, axis=0)
771 785 self.__buffer_cspc[self.n-1] = data_cspc
772 786
773 787 if data_dc != None:
774 788 self.__buffer_dc = numpy.roll(self.__buffer_dc, -1, axis=0)
775 789 self.__buffer_dc[self.n-1] = data_dc
776 790
777 791 self.__profIndex = self.n
778 792 return
779 793
780 794
781 795 def pushData(self):
782 796 """
783 797 Return the sum of the last profiles and the profiles used in the sum.
784 798
785 799 Affected:
786 800
787 801 self.__profileIndex
788 802
789 803 """
790 804 data_spc = None
791 805 data_cspc = None
792 806 data_dc = None
793 807
794 808 if not self.__withOverapping:
795 809 data_spc = self.__buffer_spc
796 810 data_cspc = self.__buffer_cspc
797 811 data_dc = self.__buffer_dc
798 812
799 813 n = self.__profIndex
800 814
801 815 self.__buffer_spc = 0
802 816 self.__buffer_cspc = 0
803 817 self.__buffer_dc = 0
804 818 self.__profIndex = 0
805 819
806 820 return data_spc, data_cspc, data_dc, n
807 821
808 822 #Integration with Overlapping
809 823 data_spc = numpy.sum(self.__buffer_spc, axis=0)
810 824
811 825 if self.__buffer_cspc != None:
812 826 data_cspc = numpy.sum(self.__buffer_cspc, axis=0)
813 827
814 828 if self.__buffer_dc != None:
815 829 data_dc = numpy.sum(self.__buffer_dc, axis=0)
816 830
817 831 n = self.__profIndex
818 832
819 833 return data_spc, data_cspc, data_dc, n
820 834
821 835 def byProfiles(self, *args):
822 836
823 837 self.__dataReady = False
824 838 avgdata_spc = None
825 839 avgdata_cspc = None
826 840 avgdata_dc = None
827 841 # n = None
828 842
829 843 self.putData(*args)
830 844
831 845 if self.__profIndex == self.n:
832 846
833 847 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
834 848 self.__dataReady = True
835 849
836 850 return avgdata_spc, avgdata_cspc, avgdata_dc
837 851
838 852 def byTime(self, datatime, *args):
839 853
840 854 self.__dataReady = False
841 855 avgdata_spc = None
842 856 avgdata_cspc = None
843 857 avgdata_dc = None
844 858 n = None
845 859
846 860 self.putData(*args)
847 861
848 862 if (datatime - self.__initime) >= self.__integrationtime:
849 863 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
850 864 self.n = n
851 865 self.__dataReady = True
852 866
853 867 return avgdata_spc, avgdata_cspc, avgdata_dc
854 868
855 869 def integrate(self, datatime, *args):
856 870
857 871 if self.__initime == None:
858 872 self.__initime = datatime
859 873
860 874 if self.__byTime:
861 875 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(datatime, *args)
862 876 else:
863 877 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
864 878
865 879 self.__lastdatatime = datatime
866 880
867 881 if avgdata_spc == None:
868 882 return None, None, None, None
869 883
870 884 avgdatatime = self.__initime
871 885 try:
872 886 self.__timeInterval = (self.__lastdatatime - self.__initime)/(self.n - 1)
873 887 except:
874 888 self.__timeInterval = self.__lastdatatime - self.__initime
875 889
876 890 deltatime = datatime -self.__lastdatatime
877 891
878 892 if not self.__withOverapping:
879 893 self.__initime = datatime
880 894 else:
881 895 self.__initime += deltatime
882 896
883 897 return avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc
884 898
885 899 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
886 900
887 901 if n==1:
888 902 dataOut.flagNoData = False
889 903 return
890 904
891 905 if not self.isConfig:
892 906 self.setup(n, timeInterval, overlapping)
893 907 self.isConfig = True
894 908
895 909 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
896 910 dataOut.data_spc,
897 911 dataOut.data_cspc,
898 912 dataOut.data_dc)
899 913
900 914 # dataOut.timeInterval *= n
901 915 dataOut.flagNoData = True
902 916
903 917 if self.__dataReady:
904 918
905 919 dataOut.data_spc = avgdata_spc
906 920 dataOut.data_cspc = avgdata_cspc
907 921 dataOut.data_dc = avgdata_dc
908 922
909 923 dataOut.nIncohInt *= self.n
910 924 dataOut.utctime = avgdatatime
911 925 #dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt * dataOut.nIncohInt * dataOut.nFFTPoints
912 926 dataOut.timeInterval = self.__timeInterval*self.n
913 927 dataOut.flagNoData = False
914
915 class ProfileConcat(Operation):
916
917 isConfig = False
918 buffer = None
919
920 def __init__(self):
921
922 Operation.__init__(self)
923 self.profileIndex = 0
924
925 def reset(self):
926 self.buffer = numpy.zeros_like(self.buffer)
927 self.start_index = 0
928 self.times = 1
929
930 def setup(self, data, m, n=1):
931 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
932 self.profiles = data.shape[1]
933 self.start_index = 0
934 self.times = 1
935
936 def concat(self, data):
937
938 self.buffer[:,self.start_index:self.profiles*self.times] = data.copy()
939 self.start_index = self.start_index + self.profiles
940
941 def run(self, dataOut, m):
942
943 dataOut.flagNoData = True
944
945 if not self.isConfig:
946 self.setup(dataOut.data, m, 1)
947 self.isConfig = True
948
949 self.concat(dataOut.data)
950 self.times += 1
951 if self.times > m:
952 dataOut.data = self.buffer
953 self.reset()
954 dataOut.flagNoData = False
955 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
956 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
957 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * 5
958 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
959
960 class ProfileSelector(Operation):
961
962 profileIndex = None
963 # Tamanho total de los perfiles
964 nProfiles = None
965
966 def __init__(self):
967
968 Operation.__init__(self)
969 self.profileIndex = 0
970
971 def incIndex(self):
972 self.profileIndex += 1
973
974 if self.profileIndex >= self.nProfiles:
975 self.profileIndex = 0
976
977 def isProfileInRange(self, minIndex, maxIndex):
978
979 if self.profileIndex < minIndex:
980 return False
981
982 if self.profileIndex > maxIndex:
983 return False
984
985 return True
986
987 def isProfileInList(self, profileList):
988
989 if self.profileIndex not in profileList:
990 return False
991
992 return True
993
994 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None):
995
996 dataOut.flagNoData = True
997 self.nProfiles = dataOut.nProfiles
998
999 if profileList != None:
1000 if self.isProfileInList(profileList):
1001 dataOut.flagNoData = False
1002
1003 self.incIndex()
1004 return 1
1005
1006
1007 elif profileRangeList != None:
1008 minIndex = profileRangeList[0]
1009 maxIndex = profileRangeList[1]
1010 if self.isProfileInRange(minIndex, maxIndex):
1011 dataOut.flagNoData = False
1012
1013 self.incIndex()
1014 return 1
1015 elif beam != None:
1016 if self.isProfileInList(dataOut.beamRangeDict[beam]):
1017 dataOut.flagNoData = False
1018
1019 self.incIndex()
1020 return 1
1021
1022 else:
1023 raise ValueError, "ProfileSelector needs profileList or profileRangeList"
1024
1025 return 0
@@ -1,524 +1,751
1 1 import numpy
2 2
3 3 from jroproc_base import ProcessingUnit, Operation
4 4 from model.data.jrodata import Voltage
5 5
6 6 class VoltageProc(ProcessingUnit):
7 7
8 8
9 9 def __init__(self):
10 10
11 11 ProcessingUnit.__init__(self)
12 12
13 13 # self.objectDict = {}
14 14 self.dataOut = Voltage()
15 15 self.flip = 1
16 16
17 17 def run(self):
18 18 if self.dataIn.type == 'AMISR':
19 19 self.__updateObjFromAmisrInput()
20 20
21 21 if self.dataIn.type == 'Voltage':
22 22 self.dataOut.copy(self.dataIn)
23 23
24 24 # self.dataOut.copy(self.dataIn)
25 25
26 26 def __updateObjFromAmisrInput(self):
27 27
28 28 self.dataOut.timeZone = self.dataIn.timeZone
29 29 self.dataOut.dstFlag = self.dataIn.dstFlag
30 30 self.dataOut.errorCount = self.dataIn.errorCount
31 31 self.dataOut.useLocalTime = self.dataIn.useLocalTime
32 32
33 33 self.dataOut.flagNoData = self.dataIn.flagNoData
34 34 self.dataOut.data = self.dataIn.data
35 35 self.dataOut.utctime = self.dataIn.utctime
36 36 self.dataOut.channelList = self.dataIn.channelList
37 37 self.dataOut.timeInterval = self.dataIn.timeInterval
38 38 self.dataOut.heightList = self.dataIn.heightList
39 39 self.dataOut.nProfiles = self.dataIn.nProfiles
40 40
41 41 self.dataOut.nCohInt = self.dataIn.nCohInt
42 42 self.dataOut.ippSeconds = self.dataIn.ippSeconds
43 43 self.dataOut.frequency = self.dataIn.frequency
44 44 #
45 45 # pass#
46 46 #
47 47 # def init(self):
48 48 #
49 49 #
50 50 # if self.dataIn.type == 'AMISR':
51 51 # self.__updateObjFromAmisrInput()
52 52 #
53 53 # if self.dataIn.type == 'Voltage':
54 54 # self.dataOut.copy(self.dataIn)
55 55 # # No necesita copiar en cada init() los atributos de dataIn
56 56 # # la copia deberia hacerse por cada nuevo bloque de datos
57 57
58 58 def selectChannels(self, channelList):
59 59
60 60 channelIndexList = []
61 61
62 62 for channel in channelList:
63 63 index = self.dataOut.channelList.index(channel)
64 64 channelIndexList.append(index)
65 65
66 66 self.selectChannelsByIndex(channelIndexList)
67 67
68 68 def selectChannelsByIndex(self, channelIndexList):
69 69 """
70 70 Selecciona un bloque de datos en base a canales segun el channelIndexList
71 71
72 72 Input:
73 73 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
74 74
75 75 Affected:
76 76 self.dataOut.data
77 77 self.dataOut.channelIndexList
78 78 self.dataOut.nChannels
79 79 self.dataOut.m_ProcessingHeader.totalSpectra
80 80 self.dataOut.systemHeaderObj.numChannels
81 81 self.dataOut.m_ProcessingHeader.blockSize
82 82
83 83 Return:
84 84 None
85 85 """
86 86
87 87 for channelIndex in channelIndexList:
88 88 if channelIndex not in self.dataOut.channelIndexList:
89 89 print channelIndexList
90 90 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
91 91
92 92 # nChannels = len(channelIndexList)
93 93
94 94 data = self.dataOut.data[channelIndexList,:]
95 95
96 96 self.dataOut.data = data
97 97 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
98 98 # self.dataOut.nChannels = nChannels
99 99
100 100 return 1
101 101
102 102 def selectHeights(self, minHei=None, maxHei=None):
103 103 """
104 104 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
105 105 minHei <= height <= maxHei
106 106
107 107 Input:
108 108 minHei : valor minimo de altura a considerar
109 109 maxHei : valor maximo de altura a considerar
110 110
111 111 Affected:
112 112 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
113 113
114 114 Return:
115 115 1 si el metodo se ejecuto con exito caso contrario devuelve 0
116 116 """
117 117
118 118 if minHei == None:
119 119 minHei = self.dataOut.heightList[0]
120 120
121 121 if maxHei == None:
122 122 maxHei = self.dataOut.heightList[-1]
123 123
124 124 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
125 125 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
126 126
127 127
128 128 if (maxHei > self.dataOut.heightList[-1]):
129 129 maxHei = self.dataOut.heightList[-1]
130 130 # raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
131 131
132 132 minIndex = 0
133 133 maxIndex = 0
134 134 heights = self.dataOut.heightList
135 135
136 136 inda = numpy.where(heights >= minHei)
137 137 indb = numpy.where(heights <= maxHei)
138 138
139 139 try:
140 140 minIndex = inda[0][0]
141 141 except:
142 142 minIndex = 0
143 143
144 144 try:
145 145 maxIndex = indb[0][-1]
146 146 except:
147 147 maxIndex = len(heights)
148 148
149 149 self.selectHeightsByIndex(minIndex, maxIndex)
150 150
151 151 return 1
152 152
153 153
154 154 def selectHeightsByIndex(self, minIndex, maxIndex):
155 155 """
156 156 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
157 157 minIndex <= index <= maxIndex
158 158
159 159 Input:
160 160 minIndex : valor de indice minimo de altura a considerar
161 161 maxIndex : valor de indice maximo de altura a considerar
162 162
163 163 Affected:
164 164 self.dataOut.data
165 165 self.dataOut.heightList
166 166
167 167 Return:
168 168 1 si el metodo se ejecuto con exito caso contrario devuelve 0
169 169 """
170 170
171 171 if (minIndex < 0) or (minIndex > maxIndex):
172 172 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
173 173
174 174 if (maxIndex >= self.dataOut.nHeights):
175 175 maxIndex = self.dataOut.nHeights-1
176 176 # raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
177 177
178 178 # nHeights = maxIndex - minIndex + 1
179 179
180 180 #voltage
181 181 data = self.dataOut.data[:,minIndex:maxIndex+1]
182 182
183 183 # firstHeight = self.dataOut.heightList[minIndex]
184 184
185 185 self.dataOut.data = data
186 186 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
187 187
188 188 return 1
189 189
190 190
191 def filterByHeights(self, window):
191 def filterByHeights(self, window, axis=1):
192 192 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
193 193
194 194 if window == None:
195 195 window = (self.dataOut.radarControllerHeaderObj.txA/self.dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
196 196
197 197 newdelta = deltaHeight * window
198 r = self.dataOut.data.shape[1] % window
199 buffer = self.dataOut.data[:,0:self.dataOut.data.shape[1]-r]
200 buffer = buffer.reshape(self.dataOut.data.shape[0],self.dataOut.data.shape[1]/window,window)
201 buffer = numpy.sum(buffer,2)
202 self.dataOut.data = buffer
198 r = self.dataOut.data.shape[axis] % window
199 if axis == 1:
200 buffer = self.dataOut.data[:,0:self.dataOut.data.shape[axis]-r]
201 buffer = buffer.reshape(self.dataOut.data.shape[0],self.dataOut.data.shape[axis]/window,window)
202 buffer = numpy.sum(buffer,axis+1)
203
204 elif axis == 2:
205 buffer = self.dataOut.data[:, :, 0:self.dataOut.data.shape[axis]-r]
206 buffer = buffer.reshape(self.dataOut.data.shape[0],self.dataOut.data.shape[1],self.dataOut.data.shape[axis]/window,window)
207 buffer = numpy.sum(buffer,axis+1)
208
209 else:
210 raise ValueError, "axis value should be 1 or 2, the input value %d is not valid" % (axis)
211
212 self.dataOut.data = buffer.copy()
203 213 self.dataOut.heightList = numpy.arange(self.dataOut.heightList[0],newdelta*(self.dataOut.nHeights-r)/window,newdelta)
204 214 self.dataOut.windowOfFilter = window
205
215
216 return 1
217
206 218 def deFlip(self):
207 219 self.dataOut.data *= self.flip
208 220 self.flip *= -1.
209 221
210 222 def setRadarFrequency(self, frequency=None):
211 223 if frequency != None:
212 224 self.dataOut.frequency = frequency
213 225
214 226 return 1
215 227
216 228 class CohInt(Operation):
217 229
218 230 isConfig = False
219 231
220 232 __profIndex = 0
221 233 __withOverapping = False
222 234
223 235 __byTime = False
224 236 __initime = None
225 237 __lastdatatime = None
226 238 __integrationtime = None
227 239
228 240 __buffer = None
229 241
230 242 __dataReady = False
231 243
232 244 n = None
233 245
234 246
235 247 def __init__(self):
236 248
237 249 Operation.__init__(self)
238 250
239 251 # self.isConfig = False
240 252
241 def setup(self, n=None, timeInterval=None, overlapping=False):
253 def setup(self, n=None, timeInterval=None, overlapping=False, byblock=False):
242 254 """
243 255 Set the parameters of the integration class.
244 256
245 257 Inputs:
246 258
247 259 n : Number of coherent integrations
248 260 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
249 261 overlapping :
250 262
251 263 """
252 264
253 265 self.__initime = None
254 266 self.__lastdatatime = 0
255 267 self.__buffer = None
256 268 self.__dataReady = False
257
269 self.byblock = byblock
258 270
259 271 if n == None and timeInterval == None:
260 272 raise ValueError, "n or timeInterval should be specified ..."
261 273
262 274 if n != None:
263 275 self.n = n
264 276 self.__byTime = False
265 277 else:
266 278 self.__integrationtime = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line
267 279 self.n = 9999
268 280 self.__byTime = True
269 281
270 282 if overlapping:
271 283 self.__withOverapping = True
272 284 self.__buffer = None
273 285 else:
274 286 self.__withOverapping = False
275 287 self.__buffer = 0
276 288
277 289 self.__profIndex = 0
278 290
279 291 def putData(self, data):
280 292
281 293 """
282 294 Add a profile to the __buffer and increase in one the __profileIndex
283 295
284 296 """
285 297
286 298 if not self.__withOverapping:
287 299 self.__buffer += data.copy()
288 300 self.__profIndex += 1
289 301 return
290 302
291 303 #Overlapping data
292 304 nChannels, nHeis = data.shape
293 305 data = numpy.reshape(data, (1, nChannels, nHeis))
294 306
295 307 #If the buffer is empty then it takes the data value
296 308 if self.__buffer == None:
297 309 self.__buffer = data
298 310 self.__profIndex += 1
299 311 return
300 312
301 313 #If the buffer length is lower than n then stakcing the data value
302 314 if self.__profIndex < self.n:
303 315 self.__buffer = numpy.vstack((self.__buffer, data))
304 316 self.__profIndex += 1
305 317 return
306 318
307 319 #If the buffer length is equal to n then replacing the last buffer value with the data value
308 320 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
309 321 self.__buffer[self.n-1] = data
310 322 self.__profIndex = self.n
311 323 return
312 324
313 325
314 326 def pushData(self):
315 327 """
316 328 Return the sum of the last profiles and the profiles used in the sum.
317 329
318 330 Affected:
319 331
320 332 self.__profileIndex
321 333
322 334 """
323 335
324 336 if not self.__withOverapping:
325 337 data = self.__buffer
326 338 n = self.__profIndex
327 339
328 340 self.__buffer = 0
329 341 self.__profIndex = 0
330 342
331 343 return data, n
332 344
333 345 #Integration with Overlapping
334 346 data = numpy.sum(self.__buffer, axis=0)
335 347 n = self.__profIndex
336 348
337 349 return data, n
338 350
339 351 def byProfiles(self, data):
340 352
341 353 self.__dataReady = False
342 354 avgdata = None
343 355 # n = None
344 356
345 357 self.putData(data)
346 358
347 359 if self.__profIndex == self.n:
348 360
349 361 avgdata, n = self.pushData()
350 362 self.__dataReady = True
351 363
352 364 return avgdata
353 365
354 366 def byTime(self, data, datatime):
355 367
356 368 self.__dataReady = False
357 369 avgdata = None
358 370 n = None
359 371
360 372 self.putData(data)
361 373
362 374 if (datatime - self.__initime) >= self.__integrationtime:
363 375 avgdata, n = self.pushData()
364 376 self.n = n
365 377 self.__dataReady = True
366 378
367 379 return avgdata
368 380
369 381 def integrate(self, data, datatime=None):
370 382
371 383 if self.__initime == None:
372 384 self.__initime = datatime
373 385
374 386 if self.__byTime:
375 387 avgdata = self.byTime(data, datatime)
376 388 else:
377 389 avgdata = self.byProfiles(data)
378 390
379 391
380 392 self.__lastdatatime = datatime
381 393
382 394 if avgdata == None:
383 395 return None, None
384 396
385 397 avgdatatime = self.__initime
386 398
387 399 deltatime = datatime -self.__lastdatatime
388 400
389 401 if not self.__withOverapping:
390 402 self.__initime = datatime
391 403 else:
392 404 self.__initime += deltatime
393 405
394 406 return avgdata, avgdatatime
395
407
408 def integrateByBlock(self, dataOut):
409 times = int(dataOut.data.shape[1]/self.n)
410 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex)
411
412 id_min = 0
413 id_max = self.n
414
415 for i in range(times):
416 junk = dataOut.data[:,id_min:id_max,:]
417 avgdata[:,i,:] = junk.sum(axis=1)
418 id_min += self.n
419 id_max += self.n
420
421 timeInterval = dataOut.ippSeconds*self.n
422 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
423 self.__dataReady = True
424 return avgdata, avgdatatime
425
396 426 def run(self, dataOut, **kwargs):
397 427
398 428 if not self.isConfig:
399 429 self.setup(**kwargs)
400 430 self.isConfig = True
401
402 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
431
432 if self.byblock:
433 avgdata, avgdatatime = self.integrateByBlock(dataOut)
434 else:
435 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
403 436
404 437 # dataOut.timeInterval *= n
405 438 dataOut.flagNoData = True
406 439
407 440 if self.__dataReady:
408 441 dataOut.data = avgdata
409 442 dataOut.nCohInt *= self.n
410 443 dataOut.utctime = avgdatatime
411 444 dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
412 445 dataOut.flagNoData = False
413 446
414 447 class Decoder(Operation):
415 448
416 449 isConfig = False
417 450 __profIndex = 0
418 451
419 452 code = None
420 453
421 454 nCode = None
422 455 nBaud = None
423 456
457
424 458 def __init__(self):
425 459
426 460 Operation.__init__(self)
461
462 self.times = None
463 self.osamp = None
464 self.__setValues = False
427 465 # self.isConfig = False
428 466
429 def setup(self, code, shape):
467 def setup(self, code, shape, times, osamp):
430 468
431 469 self.__profIndex = 0
432 470
433 471 self.code = code
434 472
435 473 self.nCode = len(code)
436 474 self.nBaud = len(code[0])
437 475
438 self.__nChannels, self.__nHeis = shape
476 if times != None:
477 self.times = times
439 478
440 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
479 if ((osamp != None) and (osamp >1)):
480 self.osamp = osamp
481 self.code = numpy.repeat(code, repeats=self.osamp,axis=1)
482 self.nBaud = self.nBaud*self.osamp
441 483
442 __codeBuffer[:,0:self.nBaud] = self.code
443
444 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
445
446 self.ndatadec = self.__nHeis - self.nBaud + 1
484 if len(shape) == 2:
485 self.__nChannels, self.__nHeis = shape
486
487 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
488
489 __codeBuffer[:,0:self.nBaud] = self.code
490
491 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
492
493 self.ndatadec = self.__nHeis - self.nBaud + 1
494
495 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
496 else:
497 self.__nChannels, self.__nProfiles, self.__nHeis = shape
498
499 self.ndatadec = self.__nHeis - self.nBaud + 1
500
501 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex)
447 502
448 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
503
449 504
450 505 def convolutionInFreq(self, data):
451 506
452 507 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
453 508
454 509 fft_data = numpy.fft.fft(data, axis=1)
455 510
456 511 conv = fft_data*fft_code
457 512
458 513 data = numpy.fft.ifft(conv,axis=1)
459 514
460 515 datadec = data[:,:-self.nBaud+1]
461 516
462 517 return datadec
463 518
464 519 def convolutionInFreqOpt(self, data):
465 520
466 521 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
467 522
468 523 data = cfunctions.decoder(fft_code, data)
469 524
470 525 datadec = data[:,:-self.nBaud+1]
471 526
472 527 return datadec
473 528
474 529 def convolutionInTime(self, data):
475 530
476 531 code = self.code[self.__profIndex]
477 532
478 533 for i in range(self.__nChannels):
479 534 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='valid')
480 535
481 536 return self.datadecTime
482 537
483 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0):
538 def convolutionByBlockInTime(self, data):
539 junk = numpy.lib.stride_tricks.as_strided(self.code, (self.times, self.code.size), (0, self.code.itemsize))
540 junk = junk.flatten()
541 code_block = numpy.reshape(junk, (self.nCode*self.times,self.nBaud))
542
543 for i in range(self.__nChannels):
544 for j in range(self.__nProfiles):
545 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='valid')
546
547 return self.datadecTime
548
549 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, times=None, osamp=None):
484 550
485 551 if code == None:
486 552 code = dataOut.code
487 553 else:
488 554 code = numpy.array(code).reshape(nCode,nBaud)
555
556
557
558 if not self.isConfig:
559
560 self.setup(code, dataOut.data.shape, times, osamp)
561
489 562 dataOut.code = code
490 563 dataOut.nCode = nCode
491 564 dataOut.nBaud = nBaud
492 565 dataOut.radarControllerHeaderObj.code = code
493 566 dataOut.radarControllerHeaderObj.nCode = nCode
494 567 dataOut.radarControllerHeaderObj.nBaud = nBaud
495 568
496
497 if not self.isConfig:
498
499 self.setup(code, dataOut.data.shape)
500 569 self.isConfig = True
501 570
502 571 if mode == 0:
503 572 datadec = self.convolutionInTime(dataOut.data)
504 573
505 574 if mode == 1:
506 575 datadec = self.convolutionInFreq(dataOut.data)
507 576
508 577 if mode == 2:
509 578 datadec = self.convolutionInFreqOpt(dataOut.data)
579
580 if mode == 3:
581 datadec = self.convolutionByBlockInTime(dataOut.data)
582
583 if not(self.__setValues):
584 dataOut.code = self.code
585 dataOut.nCode = self.nCode
586 dataOut.nBaud = self.nBaud
587 dataOut.radarControllerHeaderObj.code = self.code
588 dataOut.radarControllerHeaderObj.nCode = self.nCode
589 dataOut.radarControllerHeaderObj.nBaud = self.nBaud
590 self.__setValues = True
510 591
511 592 dataOut.data = datadec
512 593
513 594 dataOut.heightList = dataOut.heightList[0:self.ndatadec]
514 595
515 596 dataOut.flagDecodeData = True #asumo q la data no esta decodificada
516 597
517 598 if self.__profIndex == self.nCode-1:
518 599 self.__profIndex = 0
519 600 return 1
520 601
521 602 self.__profIndex += 1
522 603
523 604 return 1
524 605 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
606
607
608 class ProfileConcat(Operation):
609
610 isConfig = False
611 buffer = None
612
613 def __init__(self):
614
615 Operation.__init__(self)
616 self.profileIndex = 0
617
618 def reset(self):
619 self.buffer = numpy.zeros_like(self.buffer)
620 self.start_index = 0
621 self.times = 1
622
623 def setup(self, data, m, n=1):
624 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
625 self.profiles = data.shape[1]
626 self.start_index = 0
627 self.times = 1
628
629 def concat(self, data):
630
631 self.buffer[:,self.start_index:self.profiles*self.times] = data.copy()
632 self.start_index = self.start_index + self.profiles
633
634 def run(self, dataOut, m):
635
636 dataOut.flagNoData = True
637
638 if not self.isConfig:
639 self.setup(dataOut.data, m, 1)
640 self.isConfig = True
641
642 self.concat(dataOut.data)
643 self.times += 1
644 if self.times > m:
645 dataOut.data = self.buffer
646 self.reset()
647 dataOut.flagNoData = False
648 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
649 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
650 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * 5
651 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
652
653 class ProfileSelector(Operation):
654
655 profileIndex = None
656 # Tamanho total de los perfiles
657 nProfiles = None
658
659 def __init__(self):
660
661 Operation.__init__(self)
662 self.profileIndex = 0
663
664 def incIndex(self):
665 self.profileIndex += 1
666
667 if self.profileIndex >= self.nProfiles:
668 self.profileIndex = 0
669
670 def isProfileInRange(self, minIndex, maxIndex):
671
672 if self.profileIndex < minIndex:
673 return False
674
675 if self.profileIndex > maxIndex:
676 return False
677
678 return True
679
680 def isProfileInList(self, profileList):
681
682 if self.profileIndex not in profileList:
683 return False
684
685 return True
686
687 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False):
688
689 dataOut.flagNoData = True
690 self.nProfiles = dataOut.nProfiles
691
692 if byblock:
693
694 if profileList != None:
695 dataOut.data = dataOut.data[:,profileList,:]
696 pass
697 else:
698 pmin = profileRangeList[0]
699 pmax = profileRangeList[1]
700 dataOut.data = dataOut.data[:,pmin:pmax+1,:]
701 dataOut.flagNoData = False
702 self.profileIndex = 0
703 return 1
704
705 if profileList != None:
706 if self.isProfileInList(profileList):
707 dataOut.flagNoData = False
708
709 self.incIndex()
710 return 1
711
712
713 elif profileRangeList != None:
714 minIndex = profileRangeList[0]
715 maxIndex = profileRangeList[1]
716 if self.isProfileInRange(minIndex, maxIndex):
717 dataOut.flagNoData = False
718
719 self.incIndex()
720 return 1
721 elif beam != None: #beam is only for AMISR data
722 if self.isProfileInList(dataOut.beamRangeDict[beam]):
723 dataOut.flagNoData = False
724
725 self.incIndex()
726 return 1
727
728 else:
729 raise ValueError, "ProfileSelector needs profileList or profileRangeList"
730
731 return 0
732
733
734
735 class Reshaper(Operation):
736 def __init__(self):
737 Operation.__init__(self)
738 self.updateNewHeights = False
739
740 def run(self, dataOut, shape):
741 shape_tuple = tuple(shape)
742 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
743 dataOut.flagNoData = False
744
745 if not(self.updateNewHeights):
746 old_nheights = dataOut.nHeights
747 new_nheights = dataOut.data.shape[2]
748 factor = new_nheights / old_nheights
749 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
750 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * factor
751 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight) No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now