##// END OF EJS Templates
update Agosto
avaldez -
r1324:10adac0db3a5
parent child
Show More
@@ -235,7 +235,6 class JROData(GenericData):
235 return delta
235 return delta
236
236
237 def getltctime(self):
237 def getltctime(self):
238
239 if self.useLocalTime:
238 if self.useLocalTime:
240 return self.utctime - self.timeZone * 60
239 return self.utctime - self.timeZone * 60
241
240
@@ -1032,7 +1031,7 class Correlation(JROData):
1032 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1031 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1033
1032
1034
1033
1035 class Parameters(Spectra):
1034 class Parameters(JROData):
1036
1035
1037 experimentInfo = None # Information about the experiment
1036 experimentInfo = None # Information about the experiment
1038 # Information from previous data
1037 # Information from previous data
@@ -1087,7 +1086,6 class Parameters(Spectra):
1087 return datatime
1086 return datatime
1088
1087
1089 def getTimeInterval(self):
1088 def getTimeInterval(self):
1090
1091 if hasattr(self, 'timeInterval1'):
1089 if hasattr(self, 'timeInterval1'):
1092 return self.timeInterval1
1090 return self.timeInterval1
1093 else:
1091 else:
@@ -1210,7 +1208,7 class PlotterData(object):
1210 '''
1208 '''
1211 Update data object with new dataOut
1209 Update data object with new dataOut
1212 '''
1210 '''
1213
1211 print("UPDATE ESTOYU AQUI")
1214 self.profileIndex = dataOut.profileIndex
1212 self.profileIndex = dataOut.profileIndex
1215 self.tm = tm
1213 self.tm = tm
1216 self.type = dataOut.type
1214 self.type = dataOut.type
@@ -1278,6 +1276,14 class PlotterData(object):
1278 buffer = dataOut.dataPP_WIDTH
1276 buffer = dataOut.dataPP_WIDTH
1279 self.flagDataAsBlock = dataOut.flagDataAsBlock
1277 self.flagDataAsBlock = dataOut.flagDataAsBlock
1280 self.nProfiles = dataOut.nProfiles
1278 self.nProfiles = dataOut.nProfiles
1279 if plot == 'pp_rti_power':
1280 buffer = 10*numpy.log10(dataOut.dataPP_POWER)
1281 if plot == 'pp_rti_signal':
1282 buffer = 10*numpy.log10(dataOut.dataPP_POW)
1283 if plot == 'weather':
1284 print("ESTOY AQUI")
1285 print("jrodata",dataOut.data_360.shape)
1286 buffer = 10*numpy.log10(dataOut.data_360/(625**2))
1281
1287
1282 if plot == 'spc':
1288 if plot == 'spc':
1283 self.data['spc'][tm] = buffer
1289 self.data['spc'][tm] = buffer
@@ -9,6 +9,7 from queue import Queue
9 from functools import wraps
9 from functools import wraps
10 from threading import Thread
10 from threading import Thread
11 import matplotlib
11 import matplotlib
12 import wradlib as wrl
12
13
13 if 'BACKEND' in os.environ:
14 if 'BACKEND' in os.environ:
14 matplotlib.use(os.environ['BACKEND'])
15 matplotlib.use(os.environ['BACKEND'])
@@ -233,7 +234,7 class Plot(Operation):
233 self.__throttle_plot = apply_throttle(self.throttle)
234 self.__throttle_plot = apply_throttle(self.throttle)
234 self.data = PlotterData(
235 self.data = PlotterData(
235 self.CODE, self.throttle, self.exp_code, self.buffering, snr=self.showSNR)
236 self.CODE, self.throttle, self.exp_code, self.buffering, snr=self.showSNR)
236
237
237 if self.plot_server:
238 if self.plot_server:
238 if not self.plot_server.startswith('tcp://'):
239 if not self.plot_server.startswith('tcp://'):
239 self.plot_server = 'tcp://{}'.format(self.plot_server)
240 self.plot_server = 'tcp://{}'.format(self.plot_server)
@@ -250,8 +251,7 class Plot(Operation):
250 '''
251 '''
251
252
252 self.setup()
253 self.setup()
253
254 self.time_label = 'LT' if self.localtime else 'UTC'
254 self.time_label = 'LT' if self.localtime else 'UTC'
255
255
256 if self.width is None:
256 if self.width is None:
257 self.width = 8
257 self.width = 8
@@ -273,6 +273,7 class Plot(Operation):
273 facecolor='w')
273 facecolor='w')
274 self.figures.append(fig)
274 self.figures.append(fig)
275 for n in range(self.nplots):
275 for n in range(self.nplots):
276 #cgax,ax,paax = wrl.vis.create_cg(data_w,r=r,az=azi, proj='cg')
276 ax = fig.add_subplot(self.nrows, self.ncols,
277 ax = fig.add_subplot(self.nrows, self.ncols,
277 n + 1, polar=self.polar)
278 n + 1, polar=self.polar)
278 ax.tick_params(labelsize=8)
279 ax.tick_params(labelsize=8)
@@ -381,10 +382,10 class Plot(Operation):
381 xmax += time.timezone
382 xmax += time.timezone
382 else:
383 else:
383 xmax = self.xmax
384 xmax = self.xmax
384
385
385 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
386 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
386 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
387 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
387
388
388 for n, ax in enumerate(self.axes):
389 for n, ax in enumerate(self.axes):
389 if ax.firsttime:
390 if ax.firsttime:
390
391
@@ -398,14 +399,14 class Plot(Operation):
398 ystep = ystep/5
399 ystep = ystep/5
399 ystep = ystep/(10**digD)
400 ystep = ystep/(10**digD)
400
401
401 else:
402 else:
402 ystep = ((ymax + (10**(dig)))//10**(dig))*(10**(dig))
403 ystep = ((ymax + (10**(dig)))//10**(dig))*(10**(dig))
403 ystep = ystep/5
404 ystep = ystep/5
404
405
405 if self.xaxis is not 'time':
406 if self.xaxis is not 'time':
406
407
407 dig = int(numpy.log10(xmax))
408 dig = int(numpy.log10(xmax))
408
409
409 if dig <= 0:
410 if dig <= 0:
410 digD = len(str(xmax)) - 2
411 digD = len(str(xmax)) - 2
411 xdec = xmax*(10**digD)
412 xdec = xmax*(10**digD)
@@ -414,8 +415,8 class Plot(Operation):
414 xstep = ((xdec + (10**(dig)))//10**(dig))*(10**(dig))
415 xstep = ((xdec + (10**(dig)))//10**(dig))*(10**(dig))
415 xstep = xstep*0.5
416 xstep = xstep*0.5
416 xstep = xstep/(10**digD)
417 xstep = xstep/(10**digD)
417
418
418 else:
419 else:
419 xstep = ((xmax + (10**(dig)))//10**(dig))*(10**(dig))
420 xstep = ((xmax + (10**(dig)))//10**(dig))*(10**(dig))
420 xstep = xstep/5
421 xstep = xstep/5
421
422
@@ -495,14 +496,14 class Plot(Operation):
495
496
496 self.plot()
497 self.plot()
497 self.format()
498 self.format()
498
499
499 for n, fig in enumerate(self.figures):
500 for n, fig in enumerate(self.figures):
500 if self.nrows == 0 or self.nplots == 0:
501 if self.nrows == 0 or self.nplots == 0:
501 log.warning('No data', self.name)
502 log.warning('No data', self.name)
502 fig.text(0.5, 0.5, 'No Data', fontsize='large', ha='center')
503 fig.text(0.5, 0.5, 'No Data', fontsize='large', ha='center')
503 fig.canvas.manager.set_window_title(self.CODE)
504 fig.canvas.manager.set_window_title(self.CODE)
504 continue
505 continue
505
506
506 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
507 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
507 self.getDateTime(self.data.max_time).strftime('%Y/%m/%d')))
508 self.getDateTime(self.data.max_time).strftime('%Y/%m/%d')))
508 fig.canvas.draw()
509 fig.canvas.draw()
@@ -512,7 +513,7 class Plot(Operation):
512
513
513 if self.save:
514 if self.save:
514 self.save_figure(n)
515 self.save_figure(n)
515
516
516 if self.plot_server:
517 if self.plot_server:
517 self.send_to_server()
518 self.send_to_server()
518
519
@@ -539,7 +540,7 class Plot(Operation):
539 figname = os.path.join(
540 figname = os.path.join(
540 self.save,
541 self.save,
541 labels[n],
542 labels[n],
542 '{}_{}.png'.format(
543 '{}_{}.png'.format(
543 labels[n],
544 labels[n],
544 self.getDateTime(self.data.max_time).strftime(
545 self.getDateTime(self.data.max_time).strftime(
545 '%Y%m%d_%H%M%S'
546 '%Y%m%d_%H%M%S'
@@ -572,7 +573,7 class Plot(Operation):
572 return
573 return
573
574
574 self.sender_time = self.data.tm
575 self.sender_time = self.data.tm
575
576
576 attrs = ['titles', 'zmin', 'zmax', 'tag', 'ymin', 'ymax']
577 attrs = ['titles', 'zmin', 'zmax', 'tag', 'ymin', 'ymax']
577 for attr in attrs:
578 for attr in attrs:
578 value = getattr(self, attr)
579 value = getattr(self, attr)
@@ -589,7 +590,7 class Plot(Operation):
589 self.data.meta['interval'] = int(interval)
590 self.data.meta['interval'] = int(interval)
590 # msg = self.data.jsonify(self.data.tm, self.plot_name, self.plot_type)
591 # msg = self.data.jsonify(self.data.tm, self.plot_name, self.plot_type)
591 self.sender_queue.put(self.data.tm)
592 self.sender_queue.put(self.data.tm)
592
593
593 while True:
594 while True:
594 if self.sender_queue.empty():
595 if self.sender_queue.empty():
595 break
596 break
@@ -628,7 +629,7 class Plot(Operation):
628 self.ncols: number of cols
629 self.ncols: number of cols
629 self.nplots: number of plots (channels or pairs)
630 self.nplots: number of plots (channels or pairs)
630 self.ylabel: label for Y axes
631 self.ylabel: label for Y axes
631 self.titles: list of axes title
632 self.titles: list of axes title
632
633
633 '''
634 '''
634 raise NotImplementedError
635 raise NotImplementedError
@@ -638,7 +639,7 class Plot(Operation):
638 Must be defined in the child class
639 Must be defined in the child class
639 '''
640 '''
640 raise NotImplementedError
641 raise NotImplementedError
641
642
642 def run(self, dataOut, **kwargs):
643 def run(self, dataOut, **kwargs):
643 '''
644 '''
644 Main plotting routine
645 Main plotting routine
@@ -646,7 +647,7 class Plot(Operation):
646
647
647 if self.isConfig is False:
648 if self.isConfig is False:
648 self.__setup(**kwargs)
649 self.__setup(**kwargs)
649
650
650 t = getattr(dataOut, self.attr_time)
651 t = getattr(dataOut, self.attr_time)
651
652
652 if dataOut.useLocalTime:
653 if dataOut.useLocalTime:
@@ -657,7 +658,7 class Plot(Operation):
657 self.getDateTime = datetime.datetime.utcfromtimestamp
658 self.getDateTime = datetime.datetime.utcfromtimestamp
658 if self.localtime:
659 if self.localtime:
659 t -= time.timezone
660 t -= time.timezone
660
661
661 if self.xmin is None:
662 if self.xmin is None:
662 self.tmin = t
663 self.tmin = t
663 if 'buffer' in self.plot_type:
664 if 'buffer' in self.plot_type:
@@ -665,8 +666,8 class Plot(Operation):
665 else:
666 else:
666 self.tmin = (
667 self.tmin = (
667 self.getDateTime(t).replace(
668 self.getDateTime(t).replace(
668 hour=int(self.xmin),
669 hour=int(self.xmin),
669 minute=0,
670 minute=0,
670 second=0) - self.getDateTime(0)).total_seconds()
671 second=0) - self.getDateTime(0)).total_seconds()
671
672
672 self.data.setup()
673 self.data.setup()
@@ -684,8 +685,8 class Plot(Operation):
684 tm -= time.timezone
685 tm -= time.timezone
685 if dataOut.useLocalTime and not self.localtime:
686 if dataOut.useLocalTime and not self.localtime:
686 tm += time.timezone
687 tm += time.timezone
687
688
688 if self.data and (tm - self.tmin) >= self.xrange*60*60:
689 if self.data and (tm - self.tmin) >= self.xrange*60*60:
689 self.save_counter = self.save_period
690 self.save_counter = self.save_period
690 self.__plot()
691 self.__plot()
691 if 'time' in self.xaxis:
692 if 'time' in self.xaxis:
@@ -697,7 +698,7 class Plot(Operation):
697 self.clear_figures()
698 self.clear_figures()
698
699
699 self.data.update(dataOut, tm)
700 self.data.update(dataOut, tm)
700
701 print("plotbase--",self.data['weather'].shape)
701 if self.isPlotConfig is False:
702 if self.isPlotConfig is False:
702 self.__setup_plot()
703 self.__setup_plot()
703 self.isPlotConfig = True
704 self.isPlotConfig = True
@@ -714,4 +715,3 class Plot(Operation):
714 self.__plot()
715 self.__plot()
715 if self.data and not self.data.flagNoData and self.pause:
716 if self.data and not self.data.flagNoData and self.pause:
716 figpause(10)
717 figpause(10)
717
@@ -6,6 +6,10 from schainpy.model.graphics.jroplot_base import Plot, plt
6 from schainpy.model.graphics.jroplot_spectra import SpectraPlot, RTIPlot, CoherencePlot
6 from schainpy.model.graphics.jroplot_spectra import SpectraPlot, RTIPlot, CoherencePlot
7 from schainpy.utils import log
7 from schainpy.utils import log
8
8
9 '''-------'''
10 import wradlib as wrl
11 '''-------'''
12
9 EARTH_RADIUS = 6.3710e3
13 EARTH_RADIUS = 6.3710e3
10
14
11
15
@@ -69,6 +73,24 class PowerPlot(RTIPlot):
69 colormap = 'jet'
73 colormap = 'jet'
70 plot_name = 'TotalPower'
74 plot_name = 'TotalPower'
71
75
76 class PPPowerPlot(RTIPlot):
77 '''
78 Plot for Pulse Pair Power Data P =S +N
79 '''
80
81 CODE = 'pp_rti_power'
82 colormap = 'jet'
83 plot_name = 'TotalPP_Power'
84
85 class PPSignalPlot(RTIPlot):
86 '''
87 Plot for Pulse Pair Power Data S = P- N (0 moment)
88 '''
89
90 CODE = 'pp_rti_signal'
91 colormap = 'jet'
92 plot_name = 'TotalPP_Signal'
93
72
94
73 class SpectralWidthPlot(RTIPlot):
95 class SpectralWidthPlot(RTIPlot):
74 '''
96 '''
@@ -339,3 +361,53 class PolarMapPlot(Plot):
339 self.titles = ['{} {}'.format(
361 self.titles = ['{} {}'.format(
340 self.data.parameters[x], title) for x in self.channels]
362 self.data.parameters[x], title) for x in self.channels]
341
363
364
365 class WeatherPlot(Plot):
366 CODE = 'weather'
367 plot_name = 'Weather'
368 plot_type = 'ppistyle'
369
370 def setup(self):
371 #self.xaxis = 'Range (Km)'
372 self.ncols = 1
373 self.nrows = 1
374 self.nplots = 1
375 self.ylabel = 'Range (Km)'
376 self.titles = ['Weather']
377 self.colorbar = False
378 self.width = 8
379 self.height = 8
380 self.ini = 50
381
382 def plot(self):
383 stoprange = float(33*1.5)
384 rangestep = float(0.15)
385 r = numpy.arange(0, stoprange, rangestep)
386 '''
387 self.x= r
388 self.y= r
389 ini = self.ini
390 self.ini = self.ini+100
391 azi = numpy.linspace(0,359,360)
392 azi = azi + ini
393 azi = azi % 36
394 '''
395 azi = self.data['weather'][1]
396 data = self.data['weather'][0]
397 data_w= data[:,-1,:]
398 try:
399 zeros=numpy.zeros([(360-data_w.shape[0]),data_w.shape[1]])
400 print("zeros",zeros.shape)
401 data_w= numpy.vstack([data_w,zeros])
402 except:
403 pass
404
405 for i,ax in enumerate(self.axes):
406 if ax.firsttime:
407 plt.clf()
408 cgax, pm = wrl.vis.plot_ppi(data_w,r=r,az=azi,fig=self.figures[0], proj='cg')
409 else:
410 plt.clf()
411 cgax, pm = wrl.vis.plot_ppi(data_w,r=r,az=azi,fig=self.figures[0], proj='cg')
412
413 print("cgax",cgax)
@@ -121,7 +121,7 class CrossSpectraPlot(Plot):
121 else:
121 else:
122 x = self.data.xrange[2]
122 x = self.data.xrange[2]
123 self.xlabel = "Velocity (m/s)"
123 self.xlabel = "Velocity (m/s)"
124
124
125 self.titles = []
125 self.titles = []
126
126
127 y = self.data.heights
127 y = self.data.heights
@@ -134,17 +134,17 class CrossSpectraPlot(Plot):
134 noise = self.data['noise'][:,-1]
134 noise = self.data['noise'][:,-1]
135 pair = self.data.pairs[n]
135 pair = self.data.pairs[n]
136 ax = self.axes[4 * n]
136 ax = self.axes[4 * n]
137 if ax.firsttime:
137 if ax.firsttime:
138 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
138 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
139 self.xmin = self.xmin if self.xmin else -self.xmax
139 self.xmin = self.xmin if self.xmin else -self.xmax
140 self.zmin = self.zmin if self.zmin else numpy.nanmin(nspc)
140 self.zmin = self.zmin if self.zmin else numpy.nanmin(nspc)
141 self.zmax = self.zmax if self.zmax else numpy.nanmax(nspc)
141 self.zmax = self.zmax if self.zmax else numpy.nanmax(nspc)
142 ax.plt = ax.pcolormesh(x , y , nspc[pair[0]].T,
142 ax.plt = ax.pcolormesh(x , y , nspc[pair[0]].T,
143 vmin=self.zmin,
143 vmin=self.zmin,
144 vmax=self.zmax,
144 vmax=self.zmax,
145 cmap=plt.get_cmap(self.colormap)
145 cmap=plt.get_cmap(self.colormap)
146 )
146 )
147 else:
147 else:
148 ax.plt.set_array(nspc[pair[0]].T.ravel())
148 ax.plt.set_array(nspc[pair[0]].T.ravel())
149 self.titles.append('CH {}: {:3.2f}dB'.format(pair[0], noise[pair[0]]))
149 self.titles.append('CH {}: {:3.2f}dB'.format(pair[0], noise[pair[0]]))
150
150
@@ -155,10 +155,10 class CrossSpectraPlot(Plot):
155 vmax=self.zmax,
155 vmax=self.zmax,
156 cmap=plt.get_cmap(self.colormap)
156 cmap=plt.get_cmap(self.colormap)
157 )
157 )
158 else:
158 else:
159 ax.plt.set_array(nspc[pair[1]].T.ravel())
159 ax.plt.set_array(nspc[pair[1]].T.ravel())
160 self.titles.append('CH {}: {:3.2f}dB'.format(pair[1], noise[pair[1]]))
160 self.titles.append('CH {}: {:3.2f}dB'.format(pair[1], noise[pair[1]]))
161
161
162 out = cspc[n] / numpy.sqrt(spc[pair[0]] * spc[pair[1]])
162 out = cspc[n] / numpy.sqrt(spc[pair[0]] * spc[pair[1]])
163 coh = numpy.abs(out)
163 coh = numpy.abs(out)
164 phase = numpy.arctan2(out.imag, out.real) * 180 / numpy.pi
164 phase = numpy.arctan2(out.imag, out.real) * 180 / numpy.pi
@@ -174,13 +174,13 class CrossSpectraPlot(Plot):
174 ax.plt.set_array(coh.T.ravel())
174 ax.plt.set_array(coh.T.ravel())
175 self.titles.append(
175 self.titles.append(
176 'Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
176 'Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
177
177
178 ax = self.axes[4 * n + 3]
178 ax = self.axes[4 * n + 3]
179 if ax.firsttime:
179 if ax.firsttime:
180 ax.plt = ax.pcolormesh(x, y, phase.T,
180 ax.plt = ax.pcolormesh(x, y, phase.T,
181 vmin=-180,
181 vmin=-180,
182 vmax=180,
182 vmax=180,
183 cmap=plt.get_cmap(self.colormap_phase)
183 cmap=plt.get_cmap(self.colormap_phase)
184 )
184 )
185 else:
185 else:
186 ax.plt.set_array(phase.T.ravel())
186 ax.plt.set_array(phase.T.ravel())
@@ -285,7 +285,7 class PhasePlot(CoherencePlot):
285
285
286 class NoisePlot(Plot):
286 class NoisePlot(Plot):
287 '''
287 '''
288 Plot for noise
288 Plot for noise
289 '''
289 '''
290
290
291 CODE = 'noise'
291 CODE = 'noise'
@@ -349,10 +349,10 class PowerProfilePlot(Plot):
349 self.y = y
349 self.y = y
350
350
351 x = self.data['spcprofile']
351 x = self.data['spcprofile']
352
352
353 if self.xmin is None: self.xmin = numpy.nanmin(x)*0.9
353 if self.xmin is None: self.xmin = numpy.nanmin(x)*0.9
354 if self.xmax is None: self.xmax = numpy.nanmax(x)*1.1
354 if self.xmax is None: self.xmax = numpy.nanmax(x)*1.1
355
355
356 if self.axes[0].firsttime:
356 if self.axes[0].firsttime:
357 for ch in self.data.channels:
357 for ch in self.data.channels:
358 self.axes[0].plot(x[ch], y, lw=1, label='Ch{}'.format(ch))
358 self.axes[0].plot(x[ch], y, lw=1, label='Ch{}'.format(ch))
@@ -506,7 +506,7 class BeaconPhase(Plot):
506 server=None, folder=None, username=None, password=None,
506 server=None, folder=None, username=None, password=None,
507 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
507 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
508
508
509 if dataOut.flagNoData:
509 if dataOut.flagNoData:
510 return dataOut
510 return dataOut
511
511
512 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
512 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
@@ -648,4 +648,4 class BeaconPhase(Plot):
648 thisDatetime=thisDatetime,
648 thisDatetime=thisDatetime,
649 update_figfile=update_figfile)
649 update_figfile=update_figfile)
650
650
651 return dataOut No newline at end of file
651 return dataOut
@@ -11,6 +11,8 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecora
11 from schainpy.model.io.jroIO_base import *
11 from schainpy.model.io.jroIO_base import *
12 from schainpy.utils import log
12 from schainpy.utils import log
13
13
14 import wradlib as wrl
15
14
16
15 class ParamReader(JRODataReader,ProcessingUnit):
17 class ParamReader(JRODataReader,ProcessingUnit):
16 '''
18 '''
@@ -183,17 +185,18 class ParamReader(JRODataReader,ProcessingUnit):
183 except IOError:
185 except IOError:
184 traceback.print_exc()
186 traceback.print_exc()
185 raise IOError("The file %s can't be opened" %(filename))
187 raise IOError("The file %s can't be opened" %(filename))
186
188
187 #In case has utctime attribute
189 #In case has utctime attribute
188 grp2 = grp1['utctime']
190 grp2 = grp1['utctime']
189 # thisUtcTime = grp2.value[0] - 5*3600 #To convert to local time
191 # thisUtcTime = grp2.value[0] - 5*3600 #To convert to local time
190 thisUtcTime = grp2.value[0]
192 thisUtcTime = grp2.value[0]
191
193 #thisUtcTime = grp2
192 fp.close()
194 fp.close()
193
195
194 if self.timezone == 'lt':
196 if self.timezone == 'lt':
195 thisUtcTime -= 5*3600
197 thisUtcTime -= 5*3600
196
198
199
197 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
200 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
198 thisDate = thisDatetime.date()
201 thisDate = thisDatetime.date()
199 thisTime = thisDatetime.time()
202 thisTime = thisDatetime.time()
@@ -266,8 +269,9 class ParamReader(JRODataReader,ProcessingUnit):
266 endTime = self.endTime
269 endTime = self.endTime
267
270
268 grp = fp['Data']
271 grp = fp['Data']
272 #grp2 = grp['utctime'][()] # nuevo
273 #thisUtcTime = grp2 # nuevo
269 thisUtcTime = grp['utctime'].value.astype(numpy.float)[0]
274 thisUtcTime = grp['utctime'].value.astype(numpy.float)[0]
270
271 #ERROOOOR
275 #ERROOOOR
272 if self.timezone == 'lt':
276 if self.timezone == 'lt':
273 thisUtcTime -= 5*3600
277 thisUtcTime -= 5*3600
@@ -304,14 +308,14 class ParamReader(JRODataReader,ProcessingUnit):
304
308
305 listMetaname = []
309 listMetaname = []
306 listMetadata = []
310 listMetadata = []
311 listShapes = {}
307 for item in list(gp.items()):
312 for item in list(gp.items()):
308 name = item[0]
313 name = item[0]
309
310 if name=='array dimensions':
314 if name=='array dimensions':
311 table = gp[name][:]
315 table = gp[name][:]
312 listShapes = {}
316 listShapes = {}
313 for shapes in table:
317 for shapes in table:
314 listShapes[shapes[0]] = numpy.array([shapes[1],shapes[2],shapes[3],shapes[4],shapes[5]])
318 listShapes[shapes[0].decode()] = numpy.array([shapes[1],shapes[2],shapes[3],shapes[4],shapes[5]])
315 else:
319 else:
316 data = gp[name].value
320 data = gp[name].value
317 listMetaname.append(name)
321 listMetaname.append(name)
@@ -328,11 +332,9 class ParamReader(JRODataReader,ProcessingUnit):
328 grp = self.fp['Data']
332 grp = self.fp['Data']
329 listdataname = []
333 listdataname = []
330 listdata = []
334 listdata = []
331
332 for item in list(grp.items()):
335 for item in list(grp.items()):
333 name = item[0]
336 name = item[0]
334 listdataname.append(name)
337 listdataname.append(name)
335
336 array = self.__setDataArray(grp[name],self.listShapes[name])
338 array = self.__setDataArray(grp[name],self.listShapes[name])
337 listdata.append(array)
339 listdata.append(array)
338
340
@@ -341,7 +343,6 class ParamReader(JRODataReader,ProcessingUnit):
341 return
343 return
342
344
343 def __setDataArray(self, dataset, shapes):
345 def __setDataArray(self, dataset, shapes):
344
345 nDims = shapes[0]
346 nDims = shapes[0]
346 nDim2 = shapes[1] #Dimension 0
347 nDim2 = shapes[1] #Dimension 0
347 nDim1 = shapes[2] #Dimension 1, number of Points or Parameters
348 nDim1 = shapes[2] #Dimension 1, number of Points or Parameters
@@ -407,7 +408,6 class ParamReader(JRODataReader,ProcessingUnit):
407 listShapes = self.listShapes
408 listShapes = self.listShapes
408
409
409 blockIndex = self.blockIndex
410 blockIndex = self.blockIndex
410 # blockList = self.blockList
411
411
412 for i in range(len(listMeta)):
412 for i in range(len(listMeta)):
413 setattr(self.dataOut,listMetaname[i],listMeta[i])
413 setattr(self.dataOut,listMetaname[i],listMeta[i])
@@ -497,7 +497,7 class ParamWriter(Operation):
497 setType = None
497 setType = None
498
498
499 def __init__(self):
499 def __init__(self):
500
500
501 Operation.__init__(self)
501 Operation.__init__(self)
502 return
502 return
503
503
@@ -530,9 +530,9 class ParamWriter(Operation):
530 dsDict['variable'] = self.dataList[i]
530 dsDict['variable'] = self.dataList[i]
531 #--------------------- Conditionals ------------------------
531 #--------------------- Conditionals ------------------------
532 #There is no data
532 #There is no data
533
533
534 if dataAux is None:
534 if dataAux is None:
535
535
536 return 0
536 return 0
537
537
538 if isinstance(dataAux, (int, float, numpy.integer, numpy.float)):
538 if isinstance(dataAux, (int, float, numpy.integer, numpy.float)):
@@ -704,7 +704,7 class ParamWriter(Operation):
704 return False
704 return False
705
705
706 def setNextFile(self):
706 def setNextFile(self):
707
707
708 ext = self.ext
708 ext = self.ext
709 path = self.path
709 path = self.path
710 setFile = self.setFile
710 setFile = self.setFile
@@ -785,7 +785,7 class ParamWriter(Operation):
785 for j in range(dsInfo['dsNumber']):
785 for j in range(dsInfo['dsNumber']):
786 dsInfo = dsList[i]
786 dsInfo = dsList[i]
787 tableName = dsInfo['dsName']
787 tableName = dsInfo['dsName']
788
788
789
789
790 if dsInfo['nDim'] == 3:
790 if dsInfo['nDim'] == 3:
791 shape = dsInfo['shape'].astype(int)
791 shape = dsInfo['shape'].astype(int)
@@ -954,7 +954,7 class ParamWriter(Operation):
954
954
955 self.dataOut = dataOut
955 self.dataOut = dataOut
956 if not(self.isConfig):
956 if not(self.isConfig):
957 self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
957 self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
958 metadataList=metadataList, dataList=dataList, mode=mode,
958 metadataList=metadataList, dataList=dataList, mode=mode,
959 setType=setType)
959 setType=setType)
960
960
@@ -963,7 +963,7 class ParamWriter(Operation):
963
963
964 self.putData()
964 self.putData()
965 return
965 return
966
966
967
967
968
968
969 class ParameterReader(Reader, ProcessingUnit):
969 class ParameterReader(Reader, ProcessingUnit):
@@ -992,55 +992,61 class ParameterReader(Reader, ProcessingUnit):
992
992
993 self.set_kwargs(**kwargs)
993 self.set_kwargs(**kwargs)
994 if not self.ext.startswith('.'):
994 if not self.ext.startswith('.'):
995 self.ext = '.{}'.format(self.ext)
995 self.ext = '.{}'.format(self.ext)
996
996
997 if self.online:
997 if self.online:
998 log.log("Searching files in online mode...", self.name)
998 log.log("Searching files in online mode...", self.name)
999
999
1000 for nTries in range(self.nTries):
1000 for nTries in range(self.nTries):
1001 fullpath = self.searchFilesOnLine(self.path, self.startDate,
1001 fullpath = self.searchFilesOnLine(self.path, self.startDate,
1002 self.endDate, self.expLabel, self.ext, self.walk,
1002 self.endDate, self.expLabel, self.ext, self.walk,
1003 self.filefmt, self.folderfmt)
1003 self.filefmt, self.folderfmt)
1004
1004
1005 try:
1005 try:
1006 fullpath = next(fullpath)
1006 fullpath = next(fullpath)
1007 except:
1007 except:
1008 fullpath = None
1008 fullpath = None
1009
1009
1010 if fullpath:
1010 if fullpath:
1011 break
1011 break
1012
1012
1013 log.warning(
1013 log.warning(
1014 'Waiting {} sec for a valid file in {}: try {} ...'.format(
1014 'Waiting {} sec for a valid file in {}: try {} ...'.format(
1015 self.delay, self.path, nTries + 1),
1015 self.delay, self.path, nTries + 1),
1016 self.name)
1016 self.name)
1017 time.sleep(self.delay)
1017 time.sleep(self.delay)
1018
1018
1019 if not(fullpath):
1019 if not(fullpath):
1020 raise schainpy.admin.SchainError(
1020 raise schainpy.admin.SchainError(
1021 'There isn\'t any valid file in {}'.format(self.path))
1021 'There isn\'t any valid file in {}'.format(self.path))
1022
1022
1023 pathname, filename = os.path.split(fullpath)
1023 pathname, filename = os.path.split(fullpath)
1024 self.year = int(filename[1:5])
1024 self.year = int(filename[1:5])
1025 self.doy = int(filename[5:8])
1025 self.doy = int(filename[5:8])
1026 self.set = int(filename[8:11]) - 1
1026 self.set = int(filename[8:11]) - 1
1027 else:
1027 else:
1028 log.log("Searching files in {}".format(self.path), self.name)
1028 log.log("Searching files in {}".format(self.path), self.name)
1029 self.filenameList = self.searchFilesOffLine(self.path, self.startDate,
1029 self.filenameList = self.searchFilesOffLine(self.path, self.startDate,
1030 self.endDate, self.expLabel, self.ext, self.walk, self.filefmt, self.folderfmt)
1030 self.endDate, self.expLabel, self.ext, self.walk, self.filefmt, self.folderfmt)
1031
1032 self.setNextFile()
1033
1031
1032 self.setNextFile()
1033 '''
1034 # try to implement wradlib
1035 pathname,filename = os.path.split(self.filename)
1036 f = wrl.util.get_wradlib_data_file(self.filename)
1037 fcontent = wrl.io.read_generic_hdf5(f)
1038 print(pathname,filename)
1039 '''
1034 return
1040 return
1035
1041
1036 def readFirstHeader(self):
1042 def readFirstHeader(self):
1037 '''Read metadata and data'''
1043 '''Read metadata and data'''
1038
1044
1039 self.__readMetadata()
1045 self.__readMetadata()
1040 self.__readData()
1046 self.__readData()
1041 self.__setBlockList()
1047 self.__setBlockList()
1042 self.blockIndex = 0
1048 self.blockIndex = 0
1043
1049
1044 return
1050 return
1045
1051
1046 def __setBlockList(self):
1052 def __setBlockList(self):
@@ -1057,19 +1063,27 class ParameterReader(Reader, ProcessingUnit):
1057
1063
1058 startTime = self.startTime
1064 startTime = self.startTime
1059 endTime = self.endTime
1065 endTime = self.endTime
1060
1061 index = self.listDataname.index('utctime')
1066 index = self.listDataname.index('utctime')
1062 thisUtcTime = self.listData[index]
1067 thisUtcTime = self.listData[index]
1063 self.interval = numpy.min(thisUtcTime[1:] - thisUtcTime[:-1])
1068 self.interval = numpy.min(thisUtcTime[1:] - thisUtcTime[:-1])
1064
1069 try:
1070 index = self.listMetaname.index('timeZone')
1071 tz = self.listMeta[index]
1072 if tz == 0:
1073 print("[Metadata] Attribute timeZone = %d, dataOut in utc"%(tz))
1074 else:
1075 print("[Metadata] Attribute timeZone = %d, dataOut in LT"%(tz))
1076 thisUtcTime += tz*60
1077 except:
1078 print("[Metadata] There is no attribute timeZone , by default assume dataOut was recorded in LT")
1079 tz=300
1080 thisUtcTime += tz*60
1065 if self.timezone == 'lt':
1081 if self.timezone == 'lt':
1066 thisUtcTime -= 5*3600
1082 thisUtcTime -= 5*3600
1067
1083
1068 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
1084 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0])
1069
1070 thisDate = thisDatetime.date()
1085 thisDate = thisDatetime.date()
1071 thisTime = thisDatetime.time()
1086 thisTime = thisDatetime.time()
1072
1073 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
1087 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
1074 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
1088 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
1075
1089
@@ -1099,7 +1113,7 class ParameterReader(Reader, ProcessingUnit):
1099 else:
1113 else:
1100 data = gp[name].value
1114 data = gp[name].value
1101 listMetaname.append(name)
1115 listMetaname.append(name)
1102 listMetadata.append(data)
1116 listMetadata.append(data)
1103 elif self.metadata:
1117 elif self.metadata:
1104 metadata = json.loads(self.metadata)
1118 metadata = json.loads(self.metadata)
1105 listShapes = {}
1119 listShapes = {}
@@ -1115,7 +1129,7 class ParameterReader(Reader, ProcessingUnit):
1115
1129
1116 self.listShapes = listShapes
1130 self.listShapes = listShapes
1117 self.listMetaname = listMetaname
1131 self.listMetaname = listMetaname
1118 self.listMeta = listMetadata
1132 self.listMeta = listMetadata
1119
1133
1120 return
1134 return
1121
1135
@@ -1123,7 +1137,7 class ParameterReader(Reader, ProcessingUnit):
1123
1137
1124 listdataname = []
1138 listdataname = []
1125 listdata = []
1139 listdata = []
1126
1140
1127 if 'Data' in self.fp:
1141 if 'Data' in self.fp:
1128 grp = self.fp['Data']
1142 grp = self.fp['Data']
1129 for item in list(grp.items()):
1143 for item in list(grp.items()):
@@ -1137,7 +1151,7 class ParameterReader(Reader, ProcessingUnit):
1137 for i in range(dim):
1151 for i in range(dim):
1138 array.append(grp[name]['table{:02d}'.format(i)].value)
1152 array.append(grp[name]['table{:02d}'.format(i)].value)
1139 array = numpy.array(array)
1153 array = numpy.array(array)
1140
1154
1141 listdata.append(array)
1155 listdata.append(array)
1142 elif self.metadata:
1156 elif self.metadata:
1143 metadata = json.loads(self.metadata)
1157 metadata = json.loads(self.metadata)
@@ -1160,9 +1174,8 class ParameterReader(Reader, ProcessingUnit):
1160 self.listDataname = listdataname
1174 self.listDataname = listdataname
1161 self.listData = listdata
1175 self.listData = listdata
1162 return
1176 return
1163
1164 def getData(self):
1165
1177
1178 def getData(self):
1166 for i in range(len(self.listMeta)):
1179 for i in range(len(self.listMeta)):
1167 setattr(self.dataOut, self.listMetaname[i], self.listMeta[i])
1180 setattr(self.dataOut, self.listMetaname[i], self.listMeta[i])
1168
1181
@@ -1174,9 +1187,16 class ParameterReader(Reader, ProcessingUnit):
1174 setattr(self.dataOut, self.listDataname[j], self.listData[j][:,self.blockIndex])
1187 setattr(self.dataOut, self.listDataname[j], self.listData[j][:,self.blockIndex])
1175
1188
1176 self.dataOut.paramInterval = self.interval
1189 self.dataOut.paramInterval = self.interval
1190
1191 try:
1192 thisDatetime = datetime.datetime.fromtimestamp(self.dataOut.utctime)
1193 '''REMEMBER THIS'''
1194 #print("[Reading] Block No. %d -> %s" % (self.blockIndex,thisDatetime.ctime()))
1195 except:
1196 pass
1197
1177 self.dataOut.flagNoData = False
1198 self.dataOut.flagNoData = False
1178 self.blockIndex += 1
1199 self.blockIndex += 1
1179
1180 return
1200 return
1181
1201
1182 def run(self, **kwargs):
1202 def run(self, **kwargs):
@@ -1230,7 +1250,7 class ParameterWriter(Operation):
1230 lastTime = None
1250 lastTime = None
1231
1251
1232 def __init__(self):
1252 def __init__(self):
1233
1253
1234 Operation.__init__(self)
1254 Operation.__init__(self)
1235 return
1255 return
1236
1256
@@ -1257,7 +1277,7 class ParameterWriter(Operation):
1257 dsDict['nDim'] = len(dataAux.shape)
1277 dsDict['nDim'] = len(dataAux.shape)
1258 dsDict['shape'] = dataAux.shape
1278 dsDict['shape'] = dataAux.shape
1259 dsDict['dsNumber'] = dataAux.shape[0]
1279 dsDict['dsNumber'] = dataAux.shape[0]
1260
1280
1261 dsList.append(dsDict)
1281 dsList.append(dsDict)
1262 tableList.append((self.dataList[i], dsDict['nDim']))
1282 tableList.append((self.dataList[i], dsDict['nDim']))
1263
1283
@@ -1274,7 +1294,7 class ParameterWriter(Operation):
1274 self.lastTime = currentTime
1294 self.lastTime = currentTime
1275 self.currentDay = dataDay
1295 self.currentDay = dataDay
1276 return False
1296 return False
1277
1297
1278 timeDiff = currentTime - self.lastTime
1298 timeDiff = currentTime - self.lastTime
1279
1299
1280 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
1300 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
@@ -1292,7 +1312,7 class ParameterWriter(Operation):
1292
1312
1293 self.dataOut = dataOut
1313 self.dataOut = dataOut
1294 if not(self.isConfig):
1314 if not(self.isConfig):
1295 self.setup(path=path, blocksPerFile=blocksPerFile,
1315 self.setup(path=path, blocksPerFile=blocksPerFile,
1296 metadataList=metadataList, dataList=dataList,
1316 metadataList=metadataList, dataList=dataList,
1297 setType=setType)
1317 setType=setType)
1298
1318
@@ -1301,9 +1321,9 class ParameterWriter(Operation):
1301
1321
1302 self.putData()
1322 self.putData()
1303 return
1323 return
1304
1324
1305 def setNextFile(self):
1325 def setNextFile(self):
1306
1326
1307 ext = self.ext
1327 ext = self.ext
1308 path = self.path
1328 path = self.path
1309 setFile = self.setFile
1329 setFile = self.setFile
@@ -1369,17 +1389,17 class ParameterWriter(Operation):
1369 return
1389 return
1370
1390
1371 def writeData(self, fp):
1391 def writeData(self, fp):
1372
1392
1373 grp = fp.create_group("Data")
1393 grp = fp.create_group("Data")
1374 dtsets = []
1394 dtsets = []
1375 data = []
1395 data = []
1376
1396
1377 for dsInfo in self.dsList:
1397 for dsInfo in self.dsList:
1378 if dsInfo['nDim'] == 0:
1398 if dsInfo['nDim'] == 0:
1379 ds = grp.create_dataset(
1399 ds = grp.create_dataset(
1380 dsInfo['variable'],
1400 dsInfo['variable'],
1381 (self.blocksPerFile, ),
1401 (self.blocksPerFile, ),
1382 chunks=True,
1402 chunks=True,
1383 dtype=numpy.float64)
1403 dtype=numpy.float64)
1384 dtsets.append(ds)
1404 dtsets.append(ds)
1385 data.append((dsInfo['variable'], -1))
1405 data.append((dsInfo['variable'], -1))
@@ -1387,7 +1407,7 class ParameterWriter(Operation):
1387 sgrp = grp.create_group(dsInfo['variable'])
1407 sgrp = grp.create_group(dsInfo['variable'])
1388 for i in range(dsInfo['dsNumber']):
1408 for i in range(dsInfo['dsNumber']):
1389 ds = sgrp.create_dataset(
1409 ds = sgrp.create_dataset(
1390 'table{:02d}'.format(i),
1410 'table{:02d}'.format(i),
1391 (self.blocksPerFile, ) + dsInfo['shape'][1:],
1411 (self.blocksPerFile, ) + dsInfo['shape'][1:],
1392 chunks=True)
1412 chunks=True)
1393 dtsets.append(ds)
1413 dtsets.append(ds)
@@ -1395,7 +1415,7 class ParameterWriter(Operation):
1395 fp.flush()
1415 fp.flush()
1396
1416
1397 log.log('Creating file: {}'.format(fp.filename), self.name)
1417 log.log('Creating file: {}'.format(fp.filename), self.name)
1398
1418
1399 self.ds = dtsets
1419 self.ds = dtsets
1400 self.data = data
1420 self.data = data
1401 self.firsttime = True
1421 self.firsttime = True
@@ -109,6 +109,13 class ParametersProc(ProcessingUnit):
109 self.dataOut.flagNoData = False
109 self.dataOut.flagNoData = False
110 self.dataOut.utctimeInit = self.dataIn.utctime
110 self.dataOut.utctimeInit = self.dataIn.utctime
111 self.dataOut.paramInterval = self.dataIn.nProfiles*self.dataIn.nCohInt*self.dataIn.ippSeconds
111 self.dataOut.paramInterval = self.dataIn.nProfiles*self.dataIn.nCohInt*self.dataIn.ippSeconds
112
113 if hasattr(self.dataIn, 'flagDataAsBlock'):
114 self.dataOut.flagDataAsBlock = self.dataIn.flagDataAsBlock
115
116 if hasattr(self.dataIn, 'profileIndex'):
117 self.dataOut.profileIndex = self.dataIn.profileIndex
118
112 if hasattr(self.dataIn, 'dataPP_POW'):
119 if hasattr(self.dataIn, 'dataPP_POW'):
113 self.dataOut.dataPP_POW = self.dataIn.dataPP_POW
120 self.dataOut.dataPP_POW = self.dataIn.dataPP_POW
114
121
@@ -183,7 +190,6 class ParametersProc(ProcessingUnit):
183 if self.dataIn.type == "Parameters":
190 if self.dataIn.type == "Parameters":
184 self.dataOut.copy(self.dataIn)
191 self.dataOut.copy(self.dataIn)
185 self.dataOut.flagNoData = False
192 self.dataOut.flagNoData = False
186
187 return True
193 return True
188
194
189 self.__updateObjFromInput()
195 self.__updateObjFromInput()
@@ -592,7 +598,86 class GaussianFit(Operation):
592 def misfit2(self,state,y_data,x,num_intg):
598 def misfit2(self,state,y_data,x,num_intg):
593 return num_intg*sum((numpy.log(y_data)-numpy.log(self.y_model2(x,state)))**2)#/(64-9.)
599 return num_intg*sum((numpy.log(y_data)-numpy.log(self.y_model2(x,state)))**2)#/(64-9.)
594
600
601 class WeatherRadar(Operation):
602 '''
603 Function tat implements Weather Radar operations-
604 Input:
605 Output:
606 Parameters affected:
607 '''
608 isConfig = False
609
610 def __init__(self):
611 Operation.__init__(self)
595
612
613 def setup(self,dataOut,Pt=0,Gt=0,Gr=0,lambda_=0, aL=0,
614 tauW= 0,thetaT=0,thetaR=0,Km =0):
615 self.nCh = dataOut.nChannels
616 self.nHeis = dataOut.nHeights
617 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
618 self.Range = numpy.arange(dataOut.nHeights)*deltaHeight + dataOut.heightList[0]
619 self.Range = self.Range.reshape(1,self.nHeis)
620 self.Range = numpy.tile(self.Range,[self.nCh,1])
621 '''-----------1 Constante del Radar----------'''
622 self.Pt = Pt
623 self.Gt = Gt
624 self.Gr = Gr
625 self.lambda_ = lambda_
626 self.aL = aL
627 self.tauW = tauW
628 self.thetaT = thetaT
629 self.thetaR = thetaR
630 self.Km = Km
631 Numerator = ((4*numpy.pi)**3 * aL**2 * 16 *numpy.log(2))
632 Denominator = (Pt * Gt * Gr * lambda_**2 * SPEED_OF_LIGHT * tauW * numpy.pi*thetaT*thetaR)
633 self.RadarConstant = Numerator/Denominator
634 '''-----------2 Reflectividad del Radar y Factor de Reflectividad------'''
635 self.n_radar = numpy.zeros((self.nCh,self.nHeis))
636 self.Z_radar = numpy.zeros((self.nCh,self.nHeis))
637
638 def setMoments(self,dataOut,i):
639
640 type = dataOut.inputUnit
641 nCh = dataOut.nChannels
642 nHeis= dataOut.nHeights
643 data_param = numpy.zeros((nCh,4,nHeis))
644 if type == "Voltage":
645 data_param[:,0,:] = dataOut.dataPP_POW/(dataOut.nCohInt**2)
646 data_param[:,1,:] = dataOut.dataPP_DOP
647 data_param[:,2,:] = dataOut.dataPP_WIDTH
648 data_param[:,3,:] = dataOut.dataPP_SNR
649 if type == "Spectra":
650 data_param[:,0,:] = dataOut.data_POW
651 data_param[:,1,:] = dataOut.data_DOP
652 data_param[:,2,:] = dataOut.data_WIDTH
653 data_param[:,3,:] = dataOut.data_SNR
654
655 return data_param[:,i,:]
656
657
658 def run(self,dataOut,Pt=25,Gt=200.0,Gr=50.0,lambda_=0.32, aL=2.5118,
659 tauW= 4.0e-6,thetaT=0.165,thetaR=0.367,Km =0.93):
660
661 if not self.isConfig:
662 self.setup(dataOut= dataOut,Pt=25,Gt=200.0,Gr=50.0,lambda_=0.32, aL=2.5118,
663 tauW= 4.0e-6,thetaT=0.165,thetaR=0.367,Km =0.93)
664 self.isConfig = True
665 '''-----------------------------Potencia de Radar -Signal S-----------------------------'''
666 Pr = self.setMoments(dataOut,0)
667
668 for R in range(self.nHeis):
669 self.n_radar[:,R] = self.RadarConstant*Pr[:,R]* (self.Range[:,R])**2
670
671 self.Z_radar[:,R] = self.n_radar[:,R]* self.lambda_**4/( numpy.pi**5 * self.Km**2)
672
673 '''----------- Factor de Reflectividad Equivalente lamda_ < 10 cm , lamda_= 3.2cm-------'''
674 Zeh = self.Z_radar
675 dBZeh = 10*numpy.log10(Zeh)
676 dataOut.factor_Zeh= dBZeh
677 self.n_radar = numpy.zeros((self.nCh,self.nHeis))
678 self.Z_radar = numpy.zeros((self.nCh,self.nHeis))
679
680 return dataOut
596
681
597 class PrecipitationProc(Operation):
682 class PrecipitationProc(Operation):
598
683
@@ -3998,3 +4083,249 class SMOperations():
3998 # error[indInvalid1] = 13
4083 # error[indInvalid1] = 13
3999 #
4084 #
4000 # return heights, error
4085 # return heights, error
4086
4087 class PulsePairVoltage(Operation):
4088 '''
4089 Function PulsePair(Signal Power, Velocity)
4090 The real component of Lag[0] provides Intensity Information
4091 The imag component of Lag[1] Phase provides Velocity Information
4092
4093 Configuration Parameters:
4094 nPRF = Number of Several PRF
4095 theta = Degree Azimuth angel Boundaries
4096
4097 Input:
4098 self.dataOut
4099 lag[N]
4100 Affected:
4101 self.dataOut.spc
4102 '''
4103 isConfig = False
4104 __profIndex = 0
4105 __initime = None
4106 __lastdatatime = None
4107 __buffer = None
4108 noise = None
4109 __dataReady = False
4110 n = None
4111 __nch = 0
4112 __nHeis = 0
4113 removeDC = False
4114 ipp = None
4115 lambda_ = 0
4116
4117 def __init__(self,**kwargs):
4118 Operation.__init__(self,**kwargs)
4119
4120 def setup(self, dataOut, n = None, removeDC=False):
4121 '''
4122 n= Numero de PRF's de entrada
4123 '''
4124 self.__initime = None
4125 self.__lastdatatime = 0
4126 self.__dataReady = False
4127 self.__buffer = 0
4128 self.__profIndex = 0
4129 self.noise = None
4130 self.__nch = dataOut.nChannels
4131 self.__nHeis = dataOut.nHeights
4132 self.removeDC = removeDC
4133 self.lambda_ = 3.0e8/(9345.0e6)
4134 self.ippSec = dataOut.ippSeconds
4135 self.nCohInt = dataOut.nCohInt
4136 print("IPPseconds",dataOut.ippSeconds)
4137
4138 print("ELVALOR DE n es:", n)
4139 if n == None:
4140 raise ValueError("n should be specified.")
4141
4142 if n != None:
4143 if n<2:
4144 raise ValueError("n should be greater than 2")
4145
4146 self.n = n
4147 self.__nProf = n
4148
4149 self.__buffer = numpy.zeros((dataOut.nChannels,
4150 n,
4151 dataOut.nHeights),
4152 dtype='complex')
4153
4154 def putData(self,data):
4155 '''
4156 Add a profile to he __buffer and increase in one the __profiel Index
4157 '''
4158 self.__buffer[:,self.__profIndex,:]= data
4159 self.__profIndex += 1
4160 return
4161
4162 def pushData(self,dataOut):
4163 '''
4164 Return the PULSEPAIR and the profiles used in the operation
4165 Affected : self.__profileIndex
4166 '''
4167 #················· Remove DC···································
4168 if self.removeDC==True:
4169 mean = numpy.mean(self.__buffer,1)
4170 tmp = mean.reshape(self.__nch,1,self.__nHeis)
4171 dc= numpy.tile(tmp,[1,self.__nProf,1])
4172 self.__buffer = self.__buffer - dc
4173 #··················Calculo de Potencia ························
4174 pair0 = self.__buffer*numpy.conj(self.__buffer)
4175 pair0 = pair0.real
4176 lag_0 = numpy.sum(pair0,1)
4177 #··················Calculo de Ruido x canal····················
4178 self.noise = numpy.zeros(self.__nch)
4179 for i in range(self.__nch):
4180 daux = numpy.sort(pair0[i,:,:],axis= None)
4181 self.noise[i]=hildebrand_sekhon( daux ,self.nCohInt)
4182
4183 self.noise = self.noise.reshape(self.__nch,1)
4184 self.noise = numpy.tile(self.noise,[1,self.__nHeis])
4185 noise_buffer = self.noise.reshape(self.__nch,1,self.__nHeis)
4186 noise_buffer = numpy.tile(noise_buffer,[1,self.__nProf,1])
4187 #·················· Potencia recibida= P , Potencia senal = S , Ruido= N··
4188 #·················· P= S+N ,P=lag_0/N ·································
4189 #···················· Power ··················································
4190 data_power = lag_0/(self.n*self.nCohInt)
4191 #------------------ Senal ···················································
4192 data_intensity = pair0 - noise_buffer
4193 data_intensity = numpy.sum(data_intensity,axis=1)*(self.n*self.nCohInt)#*self.nCohInt)
4194 #data_intensity = (lag_0-self.noise*self.n)*(self.n*self.nCohInt)
4195 for i in range(self.__nch):
4196 for j in range(self.__nHeis):
4197 if data_intensity[i][j] < 0:
4198 data_intensity[i][j] = numpy.min(numpy.absolute(data_intensity[i][j]))
4199
4200 #················· Calculo de Frecuencia y Velocidad doppler········
4201 pair1 = self.__buffer[:,:-1,:]*numpy.conjugate(self.__buffer[:,1:,:])
4202 lag_1 = numpy.sum(pair1,1)
4203 data_freq = (-1/(2.0*math.pi*self.ippSec*self.nCohInt))*numpy.angle(lag_1)
4204 data_velocity = (self.lambda_/2.0)*data_freq
4205
4206 #················ Potencia promedio estimada de la Senal···········
4207 lag_0 = lag_0/self.n
4208 S = lag_0-self.noise
4209
4210 #················ Frecuencia Doppler promedio ·····················
4211 lag_1 = lag_1/(self.n-1)
4212 R1 = numpy.abs(lag_1)
4213
4214 #················ Calculo del SNR··································
4215 data_snrPP = S/self.noise
4216 for i in range(self.__nch):
4217 for j in range(self.__nHeis):
4218 if data_snrPP[i][j] < 1.e-20:
4219 data_snrPP[i][j] = 1.e-20
4220
4221 #················· Calculo del ancho espectral ······················
4222 L = S/R1
4223 L = numpy.where(L<0,1,L)
4224 L = numpy.log(L)
4225 tmp = numpy.sqrt(numpy.absolute(L))
4226 data_specwidth = (self.lambda_/(2*math.sqrt(2)*math.pi*self.ippSec*self.nCohInt))*tmp*numpy.sign(L)
4227 n = self.__profIndex
4228 class Block360(Operation):
4229 '''
4230 '''
4231 isConfig = False
4232 __profIndex = 0
4233 __initime = None
4234 __lastdatatime = None
4235 __buffer = None
4236 __dataReady = False
4237 n = None
4238 __nch = 0
4239 __nHeis = 0
4240
4241 def __init__(self,**kwargs):
4242 Operation.__init__(self,**kwargs)
4243
4244 def setup(self, dataOut, n = None):
4245 '''
4246 n= Numero de PRF's de entrada
4247 '''
4248 self.__initime = None
4249 self.__lastdatatime = 0
4250 self.__dataReady = False
4251 self.__buffer = 0
4252 self.__profIndex = 0
4253
4254
4255 print("ELVALOR DE n es:", n)
4256 if n == None:
4257 raise ValueError("n should be specified.")
4258
4259 if n != None:
4260 if n<2:
4261 raise ValueError("n should be greater than 2")
4262
4263 self.n = n
4264
4265 self.__buffer = numpy.zeros(( n, dataOut.nHeights))
4266
4267 def putData(self,data):
4268 '''
4269 Add a profile to he __buffer and increase in one the __profiel Index
4270 '''
4271 self.__buffer[self.__profIndex,:]= data
4272 self.__profIndex += 1
4273 return #················· Remove DC···································
4274
4275 def pushData(self,dataOut):
4276 '''
4277 Return the PULSEPAIR and the profiles used in the operation
4278 Affected : self.__profileIndex
4279 '''
4280
4281
4282 data_360 = self.__buffer
4283 n = self.__profIndex
4284
4285 self.__buffer = numpy.zeros(( self.n,330))
4286 self.__profIndex = 0
4287 return data_360,n
4288
4289
4290 def byProfiles(self,dataOut):
4291
4292 self.__dataReady = False
4293 data_360 = None
4294 self.putData(data=dataOut.data_POW[0])
4295 if self.__profIndex == self.n:
4296 data_360, n = self.pushData(dataOut=dataOut)
4297 self.__dataReady = True
4298
4299 return data_360
4300
4301
4302 def blockOp(self, dataOut, datatime= None):
4303
4304 if self.__initime == None:
4305 self.__initime = datatime
4306 data_360 = self.byProfiles(dataOut)
4307 self.__lastdatatime = datatime
4308
4309 if data_360 is None:
4310 return None, None
4311
4312 avgdatatime = self.__initime
4313 deltatime = datatime - self.__lastdatatime
4314 self.__initime = datatime
4315
4316 return data_360, avgdatatime
4317
4318 def run(self, dataOut,n = None,**kwargs):
4319
4320 if not self.isConfig:
4321 self.setup(dataOut = dataOut, n = n , **kwargs)
4322 self.isConfig = True
4323 data_360, avgdatatime = self.blockOp(dataOut, dataOut.utctime)
4324 dataOut.flagNoData = True
4325
4326 if self.__dataReady:
4327 dataOut.data_360 = data_360 # S
4328 print("data_360",data_360.shape,avgdatatime)
4329 dataOut.utctime = avgdatatime
4330 dataOut.flagNoData = False
4331 return dataOut
@@ -1484,6 +1484,7 class PulsePairVoltage(Operation):
1484 dataOut.dataPP_SNR = data_snrPP
1484 dataOut.dataPP_SNR = data_snrPP
1485 dataOut.dataPP_WIDTH = data_specwidth
1485 dataOut.dataPP_WIDTH = data_specwidth
1486 dataOut.PRFbyAngle = self.n #numero de PRF*cada angulo rotado que equivale a un tiempo.
1486 dataOut.PRFbyAngle = self.n #numero de PRF*cada angulo rotado que equivale a un tiempo.
1487 dataOut.nProfiles = int(dataOut.nProfiles/n)
1487 dataOut.utctime = avgdatatime
1488 dataOut.utctime = avgdatatime
1488 dataOut.flagNoData = False
1489 dataOut.flagNoData = False
1489 return dataOut
1490 return dataOut
@@ -47,7 +47,7 while(True):
47 elev.append(ang_elev)
47 elev.append(ang_elev)
48 time0.append(seconds)
48 time0.append(seconds)
49 count +=1
49 count +=1
50 if count == 100:
50 if count == 360:
51 timetuple=time.localtime()
51 timetuple=time.localtime()
52 epoc = time.mktime(timetuple)
52 epoc = time.mktime(timetuple)
53 #print(epoc)
53 #print(epoc)
@@ -76,7 +76,7 opObj10 = procUnitConfObjC.addOperation(name='ParameterWriter')
76 opObj10.addParameter(name='path',value=figpath)
76 opObj10.addParameter(name='path',value=figpath)
77 #opObj10.addParameter(name='mode',value=0)
77 #opObj10.addParameter(name='mode',value=0)
78 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
78 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
79 opObj10.addParameter(name='metadataList',value='utctimeInit,timeInterval',format='list')
79 opObj10.addParameter(name='metadataList',value='utctimeInit,paramInterval,heightList',format='list')
80 opObj10.addParameter(name='dataList',value='data_POW,data_DOP,data_WIDTH,data_SNR')#,format='list'
80 opObj10.addParameter(name='dataList',value='data_POW,data_DOP,utctime')#,format='list'
81
81
82 controllerObj.start()
82 controllerObj.start()
@@ -2,7 +2,7 import os,sys
2 import datetime
2 import datetime
3 import time
3 import time
4 from schainpy.controller import Project
4 from schainpy.controller import Project
5 path = '/home/alex/Downloads/NEW_WR2/spc16removeDC'
5 path = '/home/alex/Downloads/hdf5_testPP2'
6 figpath = path
6 figpath = path
7 desc = "Simulator Test"
7 desc = "Simulator Test"
8
8
@@ -51,7 +51,7 opObj11 = procUnitConfObjA.addOperation(name='PulsePairVoltage', optype='other')
51 opObj11.addParameter(name='n', value='625', format='int')#10
51 opObj11.addParameter(name='n', value='625', format='int')#10
52 opObj11.addParameter(name='removeDC', value=1, format='int')
52 opObj11.addParameter(name='removeDC', value=1, format='int')
53
53
54 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairPowerPlot', optype='other')
54 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairPowerPlot', optype='other')#,dataPP_SNR,dataPP_WIDTH
55 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairSignalPlot', optype='other')
55 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairSignalPlot', optype='other')
56
56
57
57
@@ -61,13 +61,11 opObj11.addParameter(name='removeDC', value=1, format='int')
61 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairSpecwidthPlot', optype='other')
61 #opObj11 = procUnitConfObjA.addOperation(name='PulsepairSpecwidthPlot', optype='other')
62
62
63 procUnitConfObjB= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjA.getId())
63 procUnitConfObjB= controllerObj.addProcUnit(datatype='ParametersProc',inputId=procUnitConfObjA.getId())
64
65
66 opObj10 = procUnitConfObjB.addOperation(name='ParameterWriter')
64 opObj10 = procUnitConfObjB.addOperation(name='ParameterWriter')
67 opObj10.addParameter(name='path',value=figpath)
65 opObj10.addParameter(name='path',value=figpath)
68 #opObj10.addParameter(name='mode',value=0)
66 #opObj10.addParameter(name='mode',value=2)
69 opObj10.addParameter(name='blocksPerFile',value='100',format='int')
67 opObj10.addParameter(name='blocksPerFile',value='50',format='int')
70 opObj10.addParameter(name='metadataList',value='utctimeInit,timeInterval',format='list')
68 opObj10.addParameter(name='metadataList',value='utctimeInit,paramInterval,heightList,profileIndex,flagDataAsBlock',format='list')
71 opObj10.addParameter(name='dataList',value='dataPP_POW,dataPP_DOP,dataPP_SNR,dataPP_WIDTH')#,format='list'
69 opObj10.addParameter(name='dataList',value='dataPP_POW,dataPP_DOP,utctime',format='list')#,format='list'
72
70
73 controllerObj.start()
71 controllerObj.start()
@@ -82,9 +82,9 num_perfiles = int(var_tiempo/IPP)
82 dir_pedestal = "/home/alex/Downloads/pedestal"
82 dir_pedestal = "/home/alex/Downloads/pedestal"
83 #·········· DATA ADQ······························
83 #·········· DATA ADQ······························
84 if mode=="T":
84 if mode=="T":
85 dir_adq = "/home/alex/Downloads/hdf5_testPP/d2020194" # Time domain
85 dir_adq = "/home/alex/Downloads/hdf5_testPP/d2020204" # Time domain
86 else:
86 else:
87 dir_adq = "/home/alex/Downloads/hdf5_test/d2020194" # Frequency domain
87 dir_adq = "/home/alex/Downloads/hdf5_test/d2020204" # Frequency domain
88
88
89 print( "Velocidad angular :", w)
89 print( "Velocidad angular :", w)
90 print( "Resolucion minima en grados :", alfa)
90 print( "Resolucion minima en grados :", alfa)
@@ -103,7 +103,7 print("utc_pedestal :",utc_pedestal)
103 print("utc_adq :",utc_adq)
103 print("utc_adq :",utc_adq)
104 #·············Relacion: utc_adq (+/-) var_tiempo*nro_file= utc_pedestal
104 #·············Relacion: utc_adq (+/-) var_tiempo*nro_file= utc_pedestal
105 time_Interval_p = 0.01
105 time_Interval_p = 0.01
106 n_perfiles_p = 100
106 n_perfiles_p = 360
107 if utc_adq>utc_pedestal:
107 if utc_adq>utc_pedestal:
108 nro_file = int((int(utc_adq) - int(utc_pedestal))/(time_Interval_p*n_perfiles_p))
108 nro_file = int((int(utc_adq) - int(utc_pedestal))/(time_Interval_p*n_perfiles_p))
109 ff_pedestal = list_pedestal[nro_file]
109 ff_pedestal = list_pedestal[nro_file]
@@ -129,7 +129,7 list_adq = getfirstFilefromPath(path=dir_adq ,meta="D",ext=".hdf5")
129
129
130 nro_file = nro_file #10
130 nro_file = nro_file #10
131 nro_key_perfil = nro_key_p
131 nro_key_perfil = nro_key_p
132 blocksPerFile = 100
132 blocksPerFile = 360
133 wr_path = "/home/alex/Downloads/hdf5_wr/"
133 wr_path = "/home/alex/Downloads/hdf5_wr/"
134 # Lectura de archivos de adquisicion para adicion de azimuth
134 # Lectura de archivos de adquisicion para adicion de azimuth
135 for thisFile in range(len(list_adq)):
135 for thisFile in range(len(list_adq)):
General Comments 0
You need to be logged in to leave comments. Login now