##// END OF EJS Templates
Merge branch 'schain_mp' of http://10.10.110.76/rhodecode/schain into schain_mp
jespinoza -
r893:c193b27159d8
parent child
Show More
@@ -0,0 +1,11
1 ## ROADMAP
2 ## SCHAIN BRANCHES
3
4 ### BRANCH - SCHAIN_MP
5
6 * Revisar si funciona con varios publishers.
7 * Revisar xRange y reinicializaciΓ³n de grΓ‘fico.
8 * Grabar cada spectra independientemente.
9 * Agregar kwargs al init
10 * Agregar grΓ‘ficos restantes
11 * PresentaciΓ³n
@@ -1,377 +1,377
1
1
2 import os
2 import os
3 import zmq
3 import zmq
4 import time
4 import time
5 import numpy
5 import numpy
6 import datetime
6 import datetime
7 import numpy as np
7 import numpy as np
8 import matplotlib.pyplot as plt
8 import matplotlib.pyplot as plt
9 from mpl_toolkits.axes_grid1 import make_axes_locatable
9 from mpl_toolkits.axes_grid1 import make_axes_locatable
10 from matplotlib.ticker import FuncFormatter, LinearLocator
10 from matplotlib.ticker import FuncFormatter, LinearLocator
11 from multiprocessing import Process
11 from multiprocessing import Process
12
12
13 from schainpy.model.proc.jroproc_base import Operation
13 from schainpy.model.proc.jroproc_base import Operation
14
14
15 #plt.ion()
15 #plt.ion()
16
16
17 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime('%H:%M'))
17 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime('%H:%M'))
18
18
19 d1970 = datetime.datetime(1970,1,1)
19 d1970 = datetime.datetime(1970,1,1)
20
20
21 class PlotData(Operation, Process):
21 class PlotData(Operation, Process):
22
22
23 CODE = 'Figure'
23 CODE = 'Figure'
24 colormap = 'jet'
24 colormap = 'jet'
25 __MAXNUMX = 80
25 __MAXNUMX = 80
26 __MAXNUMY = 80
26 __MAXNUMY = 80
27 __missing = 1E30
27 __missing = 1E30
28
28
29 def __init__(self, **kwargs):
29 def __init__(self, **kwargs):
30
30
31 Operation.__init__(self)
31 Operation.__init__(self)
32 Process.__init__(self)
32 Process.__init__(self)
33 self.mp = False
33 self.mp = False
34 self.dataOut = None
34 self.dataOut = None
35 self.isConfig = False
35 self.isConfig = False
36 self.figure = None
36 self.figure = None
37 self.axes = []
37 self.axes = []
38 self.localtime = kwargs.pop('localtime', True)
38 self.localtime = kwargs.pop('localtime', True)
39 self.show = kwargs.get('show', True)
39 self.show = kwargs.get('show', True)
40 self.save = kwargs.get('save', False)
40 self.save = kwargs.get('save', False)
41 self.colormap = kwargs.get('colormap', self.colormap)
41 self.colormap = kwargs.get('colormap', self.colormap)
42 self.showprofile = kwargs.get('showprofile', False)
42 self.showprofile = kwargs.get('showprofile', False)
43 self.title = kwargs.get('wintitle', '')
43 self.title = kwargs.get('wintitle', '')
44 self.xaxis = kwargs.get('xaxis', 'time')
44 self.xaxis = kwargs.get('xaxis', 'time')
45 self.zmin = kwargs.get('zmin', None)
45 self.zmin = kwargs.get('zmin', None)
46 self.zmax = kwargs.get('zmax', None)
46 self.zmax = kwargs.get('zmax', None)
47 self.xmin = kwargs.get('xmin', None)
47 self.xmin = kwargs.get('xmin', None)
48 self.xmax = kwargs.get('xmax', None)
48 self.xmax = kwargs.get('xmax', None)
49 self.xrange = kwargs.get('xrange', 24)
49 self.xrange = kwargs.get('xrange', 24)
50 self.ymin = kwargs.get('ymin', None)
50 self.ymin = kwargs.get('ymin', None)
51 self.ymax = kwargs.get('ymax', None)
51 self.ymax = kwargs.get('ymax', None)
52
52
53 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
53 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
54
54
55 if x_buffer.shape[0] < 2:
55 if x_buffer.shape[0] < 2:
56 return x_buffer, y_buffer, z_buffer
56 return x_buffer, y_buffer, z_buffer
57
57
58 deltas = x_buffer[1:] - x_buffer[0:-1]
58 deltas = x_buffer[1:] - x_buffer[0:-1]
59 x_median = np.median(deltas)
59 x_median = np.median(deltas)
60
60
61 index = np.where(deltas > 5*x_median)
61 index = np.where(deltas > 5*x_median)
62
62
63 if len(index[0]) != 0:
63 if len(index[0]) != 0:
64 z_buffer[::,index[0],::] = self.__missing
64 z_buffer[::,index[0],::] = self.__missing
65 z_buffer = np.ma.masked_inside(z_buffer,
65 z_buffer = np.ma.masked_inside(z_buffer,
66 0.99*self.__missing,
66 0.99*self.__missing,
67 1.01*self.__missing)
67 1.01*self.__missing)
68
68
69 return x_buffer, y_buffer, z_buffer
69 return x_buffer, y_buffer, z_buffer
70
70
71 def decimate(self):
71 def decimate(self):
72
72
73 dx = int(len(self.x)/self.__MAXNUMX) + 1
73 dx = int(len(self.x)/self.__MAXNUMX) + 1
74 dy = int(len(self.y)/self.__MAXNUMY) + 1
74 dy = int(len(self.y)/self.__MAXNUMY) + 1
75
75
76 x = self.x[::dx]
76 x = self.x[::dx]
77 y = self.y[::dy]
77 y = self.y[::dy]
78 z = self.z[::, ::dx, ::dy]
78 z = self.z[::, ::dx, ::dy]
79
79
80 return x, y, z
80 return x, y, z
81
81
82 def __plot(self):
82 def __plot(self):
83
83
84 print 'plotting...{}'.format(self.CODE)
84 print 'plotting...{}'.format(self.CODE)
85
85
86 self.plot()
86 self.plot()
87 self.figure.suptitle('{} {} - Date:{}'.format(self.title, self.CODE.upper(),
87 self.figure.suptitle('{} {} - Date:{}'.format(self.title, self.CODE.upper(),
88 datetime.datetime.utcfromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')))
88 datetime.datetime.utcfromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')))
89
89
90 if self.save:
90 if self.save:
91 figname = os.path.join(self.save, '{}_{}.png'.format(self.CODE,
91 figname = os.path.join(self.save, '{}_{}.png'.format(self.CODE,
92 datetime.datetime.utcfromtimestamp(self.times[-1]).strftime('%y%m%d_%H%M%S')))
92 datetime.datetime.utcfromtimestamp(self.times[-1]).strftime('%y%m%d_%H%M%S')))
93 print 'Saving figure: {}'.format(figname)
93 print 'Saving figure: {}'.format(figname)
94 self.figure.savefig(figname)
94 self.figure.savefig(figname)
95
95
96 self.figure.canvas.draw()
96 self.figure.canvas.draw()
97
97
98 def plot(self):
98 def plot(self):
99
99
100 print 'plotting...{}'.format(self.CODE.upper())
100 print 'plotting...{}'.format(self.CODE.upper())
101 return
101 return
102
102
103 def run(self):
103 def run(self):
104
104
105 print '[Starting] {}'.format(self.name)
105 print '[Starting] {}'.format(self.name)
106 context = zmq.Context()
106 context = zmq.Context()
107 receiver = context.socket(zmq.SUB)
107 receiver = context.socket(zmq.SUB)
108 receiver.setsockopt(zmq.SUBSCRIBE, '')
108 receiver.setsockopt(zmq.SUBSCRIBE, '')
109 receiver.setsockopt(zmq.CONFLATE, True)
109 receiver.setsockopt(zmq.CONFLATE, True)
110 receiver.connect("ipc:///tmp/zmq.plots")
110 receiver.connect("ipc:///tmp/zmq.plots")
111
111
112 while True:
112 while True:
113 try:
113 try:
114 #if True:
114 #if True:
115 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
115 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
116 self.dataOut = self.data['dataOut']
116 self.dataOut = self.data['dataOut']
117 self.times = self.data['times']
117 self.times = self.data['times']
118 self.times.sort()
118 self.times.sort()
119 self.min_time = self.times[0]
119 self.min_time = self.times[0]
120 self.max_time = self.times[-1]
120 self.max_time = self.times[-1]
121
121
122 if self.isConfig is False:
122 if self.isConfig is False:
123 self.setup()
123 self.setup()
124 self.isConfig = True
124 self.isConfig = True
125
125
126 self.__plot()
126 self.__plot()
127
127
128 if 'ENDED' in self.data:
128 if 'ENDED' in self.data:
129 #self.setup()
129 # self.setup()
130 #self.__plot()
130 # self.__plot()
131 pass
131 pass
132
132
133 except zmq.Again as e:
133 except zmq.Again as e:
134 print 'Waiting for data...'
134 print 'Waiting for data...'
135 plt.pause(5)
135 plt.pause(5)
136 #time.sleep(3)
136 #time.sleep(3)
137
137
138 def close(self):
138 def close(self):
139 if self.dataOut:
139 if self.dataOut:
140 self._plot()
140 self._plot()
141
141
142
142
143 class PlotSpectraData(PlotData):
143 class PlotSpectraData(PlotData):
144
144
145 CODE = 'spc'
145 CODE = 'spc'
146 colormap = 'jro'
146 colormap = 'jro'
147
147
148 def setup(self):
148 def setup(self):
149
149
150 ncolspan = 1
150 ncolspan = 1
151 colspan = 1
151 colspan = 1
152 self.ncols = int(numpy.sqrt(self.dataOut.nChannels)+0.9)
152 self.ncols = int(numpy.sqrt(self.dataOut.nChannels)+0.9)
153 self.nrows = int(self.dataOut.nChannels*1./self.ncols + 0.9)
153 self.nrows = int(self.dataOut.nChannels*1./self.ncols + 0.9)
154 self.width = 3.6*self.ncols
154 self.width = 3.6*self.ncols
155 self.height = 3.2*self.nrows
155 self.height = 3.2*self.nrows
156 if self.showprofile:
156 if self.showprofile:
157 ncolspan = 3
157 ncolspan = 3
158 colspan = 2
158 colspan = 2
159 self.width += 1.2*self.ncols
159 self.width += 1.2*self.ncols
160
160
161 self.ylabel = 'Range [Km]'
161 self.ylabel = 'Range [Km]'
162 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
162 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
163
163
164 if self.figure is None:
164 if self.figure is None:
165 self.figure = plt.figure(figsize=(self.width, self.height),
165 self.figure = plt.figure(figsize=(self.width, self.height),
166 edgecolor='k',
166 edgecolor='k',
167 facecolor='w')
167 facecolor='w')
168 else:
168 else:
169 self.figure.clf()
169 self.figure.clf()
170
170
171 n = 0
171 n = 0
172 for y in range(self.nrows):
172 for y in range(self.nrows):
173 for x in range(self.ncols):
173 for x in range(self.ncols):
174 if n>=self.dataOut.nChannels:
174 if n>=self.dataOut.nChannels:
175 break
175 break
176 ax = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan), 1, colspan)
176 ax = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan), 1, colspan)
177 if self.showprofile:
177 if self.showprofile:
178 ax.ax_profile = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan+colspan), 1, 1)
178 ax.ax_profile = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan+colspan), 1, 1)
179
179
180 ax.firsttime = True
180 ax.firsttime = True
181 self.axes.append(ax)
181 self.axes.append(ax)
182 n += 1
182 n += 1
183
183
184 self.figure.subplots_adjust(wspace=0.9, hspace=0.5)
184 self.figure.subplots_adjust(wspace=0.9, hspace=0.5)
185 self.figure.show()
185 self.figure.show()
186
186
187 def plot(self):
187 def plot(self):
188
188
189 if self.xaxis == "frequency":
189 if self.xaxis == "frequency":
190 x = self.dataOut.getFreqRange(1)/1000.
190 x = self.dataOut.getFreqRange(1)/1000.
191 xlabel = "Frequency (kHz)"
191 xlabel = "Frequency (kHz)"
192 elif self.xaxis == "time":
192 elif self.xaxis == "time":
193 x = self.dataOut.getAcfRange(1)
193 x = self.dataOut.getAcfRange(1)
194 xlabel = "Time (ms)"
194 xlabel = "Time (ms)"
195 else:
195 else:
196 x = self.dataOut.getVelRange(1)
196 x = self.dataOut.getVelRange(1)
197 xlabel = "Velocity (m/s)"
197 xlabel = "Velocity (m/s)"
198
198
199 y = self.dataOut.getHeiRange()
199 y = self.dataOut.getHeiRange()
200 z = self.data[self.CODE]
200 z = self.data[self.CODE]
201
201
202 for n, ax in enumerate(self.axes):
202 for n, ax in enumerate(self.axes):
203
203
204 if ax.firsttime:
204 if ax.firsttime:
205 self.xmax = self.xmax if self.xmax else np.nanmax(x)
205 self.xmax = self.xmax if self.xmax else np.nanmax(x)
206 self.xmin = self.xmin if self.xmin else -self.xmax
206 self.xmin = self.xmin if self.xmin else -self.xmax
207 self.ymin = self.ymin if self.ymin else np.nanmin(y)
207 self.ymin = self.ymin if self.ymin else np.nanmin(y)
208 self.ymax = self.ymax if self.ymax else np.nanmax(y)
208 self.ymax = self.ymax if self.ymax else np.nanmax(y)
209 self.zmin = self.zmin if self.zmin else np.nanmin(z)
209 self.zmin = self.zmin if self.zmin else np.nanmin(z)
210 self.zmax = self.zmax if self.zmax else np.nanmax(z)
210 self.zmax = self.zmax if self.zmax else np.nanmax(z)
211 ax.plot = ax.pcolormesh(x, y, z[n].T,
211 ax.plot = ax.pcolormesh(x, y, z[n].T,
212 vmin=self.zmin,
212 vmin=self.zmin,
213 vmax=self.zmax,
213 vmax=self.zmax,
214 cmap=plt.get_cmap(self.colormap)
214 cmap=plt.get_cmap(self.colormap)
215 )
215 )
216 divider = make_axes_locatable(ax)
216 divider = make_axes_locatable(ax)
217 cax = divider.new_horizontal(size='3%', pad=0.05)
217 cax = divider.new_horizontal(size='3%', pad=0.05)
218 self.figure.add_axes(cax)
218 self.figure.add_axes(cax)
219 plt.colorbar(ax.plot, cax)
219 plt.colorbar(ax.plot, cax)
220
220
221 ax.set_xlim(self.xmin, self.xmax)
221 ax.set_xlim(self.xmin, self.xmax)
222 ax.set_ylim(self.ymin, self.ymax)
222 ax.set_ylim(self.ymin, self.ymax)
223
223
224 ax.xaxis.set_major_locator(LinearLocator(5))
224 ax.xaxis.set_major_locator(LinearLocator(5))
225 #ax.yaxis.set_major_locator(LinearLocator(4))
225 #ax.yaxis.set_major_locator(LinearLocator(4))
226
226
227 ax.set_ylabel(self.ylabel)
227 ax.set_ylabel(self.ylabel)
228 ax.set_xlabel(xlabel)
228 ax.set_xlabel(xlabel)
229
229
230 ax.firsttime = False
230 ax.firsttime = False
231
231
232 if self.showprofile:
232 if self.showprofile:
233 ax.plot_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
233 ax.plot_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
234 ax.ax_profile.set_xlim(self.zmin, self.zmax)
234 ax.ax_profile.set_xlim(self.zmin, self.zmax)
235 ax.ax_profile.set_ylim(self.ymin, self.ymax)
235 ax.ax_profile.set_ylim(self.ymin, self.ymax)
236 ax.ax_profile.set_xlabel('dB')
236 ax.ax_profile.set_xlabel('dB')
237 ax.ax_profile.grid(b=True, axis='x')
237 ax.ax_profile.grid(b=True, axis='x')
238 ax.plot_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
238 ax.plot_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
239 color="k", linestyle="dashed", lw=2)[0]
239 color="k", linestyle="dashed", lw=2)[0]
240 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
240 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
241 else:
241 else:
242 ax.plot.set_array(z[n].T.ravel())
242 ax.plot.set_array(z[n].T.ravel())
243 if self.showprofile:
243 if self.showprofile:
244 ax.plot_profile.set_data(self.data['rti'][self.max_time][n], y)
244 ax.plot_profile.set_data(self.data['rti'][self.max_time][n], y)
245 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
245 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
246
246
247 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
247 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
248 size=8)
248 size=8)
249
249
250 class PlotRTIData(PlotData):
250 class PlotRTIData(PlotData):
251
251
252 CODE = 'rti'
252 CODE = 'rti'
253 colormap = 'jro'
253 colormap = 'jro'
254
254
255 def setup(self):
255 def setup(self):
256
256
257 self.ncols = 1
257 self.ncols = 1
258 self.nrows = self.dataOut.nChannels
258 self.nrows = self.dataOut.nChannels
259 self.width = 10
259 self.width = 10
260 self.height = 2.2*self.nrows
260 self.height = 2.2*self.nrows
261 self.ylabel = 'Range [Km]'
261 self.ylabel = 'Range [Km]'
262 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
262 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
263
263
264 if self.figure is None:
264 if self.figure is None:
265 self.figure = plt.figure(figsize=(self.width, self.height),
265 self.figure = plt.figure(figsize=(self.width, self.height),
266 edgecolor='k',
266 edgecolor='k',
267 facecolor='w')
267 facecolor='w')
268 else:
268 else:
269 self.figure.clf()
269 self.figure.clf()
270
270
271 for n in range(self.nrows):
271 for n in range(self.nrows):
272 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
272 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
273 ax.firsttime = True
273 ax.firsttime = True
274 self.axes.append(ax)
274 self.axes.append(ax)
275
275
276 self.figure.subplots_adjust(hspace=0.5)
276 self.figure.subplots_adjust(hspace=0.5)
277 self.figure.show()
277 self.figure.show()
278
278
279 def plot(self):
279 def plot(self):
280
280
281 self.x = np.array(self.times)
281 self.x = np.array(self.times)
282 self.y = self.dataOut.getHeiRange()
282 self.y = self.dataOut.getHeiRange()
283 self.z = []
283 self.z = []
284
284
285 for ch in range(self.nrows):
285 for ch in range(self.nrows):
286 self.z.append([self.data[self.CODE][t][ch] for t in self.times])
286 self.z.append([self.data[self.CODE][t][ch] for t in self.times])
287
287
288 self.z = np.array(self.z)
288 self.z = np.array(self.z)
289
289
290 for n, ax in enumerate(self.axes):
290 for n, ax in enumerate(self.axes):
291
291
292 x, y, z = self.fill_gaps(*self.decimate())
292 x, y, z = self.fill_gaps(*self.decimate())
293
293
294 if ax.firsttime:
294 if ax.firsttime:
295 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
295 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
296 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
296 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
297 self.zmin = self.zmin if self.zmin else np.nanmin(self.z)
297 self.zmin = self.zmin if self.zmin else np.nanmin(self.z)
298 zmax = self.zmax if self.zmax else np.nanmax(self.z)
298 zmax = self.zmax if self.zmax else np.nanmax(self.z)
299 plot = ax.pcolormesh(x, y, z[n].T,
299 plot = ax.pcolormesh(x, y, z[n].T,
300 vmin=self.zmin,
300 vmin=self.zmin,
301 vmax=self.zmax,
301 vmax=self.zmax,
302 cmap=plt.get_cmap(self.colormap)
302 cmap=plt.get_cmap(self.colormap)
303 )
303 )
304 divider = make_axes_locatable(ax)
304 divider = make_axes_locatable(ax)
305 cax = divider.new_horizontal(size='2%', pad=0.05)
305 cax = divider.new_horizontal(size='2%', pad=0.05)
306 self.figure.add_axes(cax)
306 self.figure.add_axes(cax)
307 plt.colorbar(plot, cax)
307 plt.colorbar(plot, cax)
308 ax.set_ylim(self.ymin, self.ymax)
308 ax.set_ylim(self.ymin, self.ymax)
309 if self.xaxis=='time':
309 if self.xaxis=='time':
310 ax.xaxis.set_major_formatter(FuncFormatter(func))
310 ax.xaxis.set_major_formatter(FuncFormatter(func))
311 ax.xaxis.set_major_locator(LinearLocator(6))
311 ax.xaxis.set_major_locator(LinearLocator(6))
312
312
313 ax.yaxis.set_major_locator(LinearLocator(4))
313 ax.yaxis.set_major_locator(LinearLocator(4))
314
314
315 ax.set_ylabel(self.ylabel)
315 ax.set_ylabel(self.ylabel)
316
316
317 if self.xmin is None:
317 if self.xmin is None:
318 print 'is none'
318 print 'is none'
319 xmin = self.min_time
319 xmin = self.min_time
320 else:
320 else:
321
321
322 xmin = (datetime.datetime.combine(self.dataOut.datatime.date(),
322 xmin = (datetime.datetime.combine(self.dataOut.datatime.date(),
323 datetime.time(self.xmin, 0, 0))-d1970).total_seconds()
323 datetime.time(self.xmin, 0, 0))-d1970).total_seconds()
324
324
325 xmax = xmin+self.xrange*60*60
325 xmax = xmin+self.xrange*60*60
326
326
327 ax.set_xlim(xmin, xmax)
327 ax.set_xlim(xmin, xmax)
328 ax.firsttime = False
328 ax.firsttime = False
329 else:
329 else:
330 ax.collections.remove(ax.collections[0])
330 ax.collections.remove(ax.collections[0])
331 plot = ax.pcolormesh(x, y, z[n].T,
331 plot = ax.pcolormesh(x, y, z[n].T,
332 vmin=self.zmin,
332 vmin=self.zmin,
333 vmax=self.zmax,
333 vmax=self.zmax,
334 cmap=plt.get_cmap(self.colormap)
334 cmap=plt.get_cmap(self.colormap)
335 )
335 )
336 ax.set_title('{} {}'.format(self.titles[n],
336 ax.set_title('{} {}'.format(self.titles[n],
337 datetime.datetime.utcfromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
337 datetime.datetime.utcfromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
338 size=8)
338 size=8)
339
339
340
340
341 class PlotCOHData(PlotRTIData):
341 class PlotCOHData(PlotRTIData):
342
342
343 CODE = 'coh'
343 CODE = 'coh'
344
344
345 def setup(self):
345 def setup(self):
346
346
347 self.ncols = 1
347 self.ncols = 1
348 self.nrows = self.dataOut.nPairs
348 self.nrows = self.dataOut.nPairs
349 self.width = 10
349 self.width = 10
350 self.height = 2.2*self.nrows
350 self.height = 2.2*self.nrows
351 self.ylabel = 'Range [Km]'
351 self.ylabel = 'Range [Km]'
352 self.titles = ['Channels {}'.format(x) for x in self.dataOut.pairsList]
352 self.titles = ['Channels {}'.format(x) for x in self.dataOut.pairsList]
353
353
354 if self.figure is None:
354 if self.figure is None:
355 self.figure = plt.figure(figsize=(self.width, self.height),
355 self.figure = plt.figure(figsize=(self.width, self.height),
356 edgecolor='k',
356 edgecolor='k',
357 facecolor='w')
357 facecolor='w')
358 else:
358 else:
359 self.figure.clf()
359 self.figure.clf()
360
360
361 for n in range(self.nrows):
361 for n in range(self.nrows):
362 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
362 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
363 ax.firsttime = True
363 ax.firsttime = True
364 self.axes.append(ax)
364 self.axes.append(ax)
365
365
366 self.figure.subplots_adjust(hspace=0.5)
366 self.figure.subplots_adjust(hspace=0.5)
367 self.figure.show()
367 self.figure.show()
368
368
369 class PlotSNRData(PlotRTIData):
369 class PlotSNRData(PlotRTIData):
370
370
371 CODE = 'coh'
371 CODE = 'coh'
372
372
373
373
374 class PlotPHASEData(PlotCOHData):
374 class PlotPHASEData(PlotCOHData):
375
375
376 CODE = 'phase'
376 CODE = 'phase'
377 colormap = 'seismic'
377 colormap = 'seismic'
@@ -1,299 +1,301
1 '''
1 '''
2
2
3 $Author: murco $
3 $Author: murco $
4 $Id: jroproc_base.py 1 2012-11-12 18:56:07Z murco $
4 $Id: jroproc_base.py 1 2012-11-12 18:56:07Z murco $
5 '''
5 '''
6
6
7 class ProcessingUnit(object):
7 class ProcessingUnit(object):
8
8
9 """
9 """
10 Esta es la clase base para el procesamiento de datos.
10 Esta es la clase base para el procesamiento de datos.
11
11
12 Contiene el metodo "call" para llamar operaciones. Las operaciones pueden ser:
12 Contiene el metodo "call" para llamar operaciones. Las operaciones pueden ser:
13 - Metodos internos (callMethod)
13 - Metodos internos (callMethod)
14 - Objetos del tipo Operation (callObject). Antes de ser llamados, estos objetos
14 - Objetos del tipo Operation (callObject). Antes de ser llamados, estos objetos
15 tienen que ser agreagados con el metodo "add".
15 tienen que ser agreagados con el metodo "add".
16
16
17 """
17 """
18 # objeto de datos de entrada (Voltage, Spectra o Correlation)
18 # objeto de datos de entrada (Voltage, Spectra o Correlation)
19 dataIn = None
19 dataIn = None
20 dataInList = []
20 dataInList = []
21
21
22 # objeto de datos de entrada (Voltage, Spectra o Correlation)
22 # objeto de datos de entrada (Voltage, Spectra o Correlation)
23 dataOut = None
23 dataOut = None
24
24
25 operations2RunDict = None
25 operations2RunDict = None
26
26
27 isConfig = False
27 isConfig = False
28
28
29
29
30 def __init__(self, *args, **kwargs):
30 def __init__(self, *args, **kwargs):
31
31
32 self.dataIn = None
32 self.dataIn = None
33 self.dataInList = []
33 self.dataInList = []
34
34
35 self.dataOut = None
35 self.dataOut = None
36
36
37 self.operations2RunDict = {}
37 self.operations2RunDict = {}
38
38
39 self.isConfig = False
39 self.isConfig = False
40
40
41 self.args = args
41 self.args = args
42 # if (kwargs):
43 # self.kwargs = kwargs
42 self.kwargs = kwargs
44 self.kwargs = kwargs
43
45
44 def addOperation(self, opObj, objId):
46 def addOperation(self, opObj, objId):
45
47
46 """
48 """
47 Agrega un objeto del tipo "Operation" (opObj) a la lista de objetos "self.objectList" y retorna el
49 Agrega un objeto del tipo "Operation" (opObj) a la lista de objetos "self.objectList" y retorna el
48 identificador asociado a este objeto.
50 identificador asociado a este objeto.
49
51
50 Input:
52 Input:
51
53
52 object : objeto de la clase "Operation"
54 object : objeto de la clase "Operation"
53
55
54 Return:
56 Return:
55
57
56 objId : identificador del objeto, necesario para ejecutar la operacion
58 objId : identificador del objeto, necesario para ejecutar la operacion
57 """
59 """
58
60
59 self.operations2RunDict[objId] = opObj
61 self.operations2RunDict[objId] = opObj
60
62
61 return objId
63 return objId
62
64
63 def getOperationObj(self, objId):
65 def getOperationObj(self, objId):
64
66
65 if objId not in self.operations2RunDict.keys():
67 if objId not in self.operations2RunDict.keys():
66 return None
68 return None
67
69
68 return self.operations2RunDict[objId]
70 return self.operations2RunDict[objId]
69
71
70 def operation(self, **kwargs):
72 def operation(self, **kwargs):
71
73
72 """
74 """
73 Operacion directa sobre la data (dataOut.data). Es necesario actualizar los valores de los
75 Operacion directa sobre la data (dataOut.data). Es necesario actualizar los valores de los
74 atributos del objeto dataOut
76 atributos del objeto dataOut
75
77
76 Input:
78 Input:
77
79
78 **kwargs : Diccionario de argumentos de la funcion a ejecutar
80 **kwargs : Diccionario de argumentos de la funcion a ejecutar
79 """
81 """
80
82
81 raise NotImplementedError
83 raise NotImplementedError
82
84
83 def callMethod(self, name, **kwargs):
85 def callMethod(self, name, **kwargs):
84
86
85 """
87 """
86 Ejecuta el metodo con el nombre "name" y con argumentos **kwargs de la propia clase.
88 Ejecuta el metodo con el nombre "name" y con argumentos **kwargs de la propia clase.
87
89
88 Input:
90 Input:
89 name : nombre del metodo a ejecutar
91 name : nombre del metodo a ejecutar
90
92
91 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
93 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
92
94
93 """
95 """
94
96
95 #Checking the inputs
97 #Checking the inputs
96 if name == 'run':
98 if name == 'run':
97
99
98 if not self.checkInputs():
100 if not self.checkInputs():
99 self.dataOut.flagNoData = True
101 self.dataOut.flagNoData = True
100 return False
102 return False
101 else:
103 else:
102 #Si no es un metodo RUN la entrada es la misma dataOut (interna)
104 #Si no es un metodo RUN la entrada es la misma dataOut (interna)
103 if self.dataOut.isEmpty():
105 if self.dataOut.isEmpty():
104 return False
106 return False
105
107
106 #Getting the pointer to method
108 #Getting the pointer to method
107 methodToCall = getattr(self, name)
109 methodToCall = getattr(self, name)
108
110
109 #Executing the self method
111 #Executing the self method
110
112
111 if hasattr(self, 'mp'):
113 if hasattr(self, 'mp'):
112 if self.mp is False:
114 if self.mp is False:
113 self.mp = True
115 self.mp = True
114 self.start()
116 self.start()
115 else:
117 else:
116 methodToCall(**kwargs)
118 methodToCall(**kwargs)
117
119
118 if self.dataOut is None:
120 if self.dataOut is None:
119 return False
121 return False
120
122
121 if self.dataOut.isEmpty():
123 if self.dataOut.isEmpty():
122 return False
124 return False
123
125
124 return True
126 return True
125
127
126 def callObject(self, objId):
128 def callObject(self, objId):
127
129
128 """
130 """
129 Ejecuta la operacion asociada al identificador del objeto "objId"
131 Ejecuta la operacion asociada al identificador del objeto "objId"
130
132
131 Input:
133 Input:
132
134
133 objId : identificador del objeto a ejecutar
135 objId : identificador del objeto a ejecutar
134
136
135 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
137 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
136
138
137 Return:
139 Return:
138
140
139 None
141 None
140 """
142 """
141
143
142 if self.dataOut is not None and self.dataOut.isEmpty():
144 if self.dataOut is not None and self.dataOut.isEmpty():
143 return False
145 return False
144
146
145 externalProcObj = self.operations2RunDict[objId]
147 externalProcObj = self.operations2RunDict[objId]
146
148
147 if hasattr(externalProcObj, 'mp'):
149 if hasattr(externalProcObj, 'mp'):
148 if externalProcObj.mp is False:
150 if externalProcObj.mp is False:
149 externalProcObj.mp = True
151 externalProcObj.mp = True
150 externalProcObj.start()
152 externalProcObj.start()
151 else:
153 else:
152 externalProcObj.run(self.dataOut, **externalProcObj.kwargs)
154 externalProcObj.run(self.dataOut, **externalProcObj.kwargs)
153
155
154 return True
156 return True
155
157
156 def call(self, opType, opName=None, opId=None):
158 def call(self, opType, opName=None, opId=None):
157
159
158 """
160 """
159 Return True si ejecuta la operacion interna nombrada "opName" o la operacion externa
161 Return True si ejecuta la operacion interna nombrada "opName" o la operacion externa
160 identificada con el id "opId"; con los argumentos "**kwargs".
162 identificada con el id "opId"; con los argumentos "**kwargs".
161
163
162 False si la operacion no se ha ejecutado.
164 False si la operacion no se ha ejecutado.
163
165
164 Input:
166 Input:
165
167
166 opType : Puede ser "self" o "external"
168 opType : Puede ser "self" o "external"
167
169
168 Depende del tipo de operacion para llamar a:callMethod or callObject:
170 Depende del tipo de operacion para llamar a:callMethod or callObject:
169
171
170 1. If opType = "self": Llama a un metodo propio de esta clase:
172 1. If opType = "self": Llama a un metodo propio de esta clase:
171
173
172 name_method = getattr(self, name)
174 name_method = getattr(self, name)
173 name_method(**kwargs)
175 name_method(**kwargs)
174
176
175
177
176 2. If opType = "other" o"external": Llama al metodo "run()" de una instancia de la
178 2. If opType = "other" o"external": Llama al metodo "run()" de una instancia de la
177 clase "Operation" o de un derivado de ella:
179 clase "Operation" o de un derivado de ella:
178
180
179 instanceName = self.operationList[opId]
181 instanceName = self.operationList[opId]
180 instanceName.run(**kwargs)
182 instanceName.run(**kwargs)
181
183
182 opName : Si la operacion es interna (opType = 'self'), entonces el "opName" sera
184 opName : Si la operacion es interna (opType = 'self'), entonces el "opName" sera
183 usada para llamar a un metodo interno de la clase Processing
185 usada para llamar a un metodo interno de la clase Processing
184
186
185 opId : Si la operacion es externa (opType = 'other' o 'external), entonces el
187 opId : Si la operacion es externa (opType = 'other' o 'external), entonces el
186 "opId" sera usada para llamar al metodo "run" de la clase Operation
188 "opId" sera usada para llamar al metodo "run" de la clase Operation
187 registrada anteriormente con ese Id
189 registrada anteriormente con ese Id
188
190
189 Exception:
191 Exception:
190 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
192 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
191 "addOperation" e identificado con el valor "opId" = el id de la operacion.
193 "addOperation" e identificado con el valor "opId" = el id de la operacion.
192 De lo contrario retornara un error del tipo ValueError
194 De lo contrario retornara un error del tipo ValueError
193
195
194 """
196 """
195
197
196 if opType == 'self':
198 if opType == 'self':
197
199
198 if not opName:
200 if not opName:
199 raise ValueError, "opName parameter should be defined"
201 raise ValueError, "opName parameter should be defined"
200
202
201 sts = self.callMethod(opName, **self.kwargs)
203 sts = self.callMethod(opName, **self.kwargs)
202
204
203 elif opType == 'other' or opType == 'external' or opType == 'plotter':
205 elif opType == 'other' or opType == 'external' or opType == 'plotter':
204
206
205 if not opId:
207 if not opId:
206 raise ValueError, "opId parameter should be defined"
208 raise ValueError, "opId parameter should be defined"
207
209
208 if opId not in self.operations2RunDict.keys():
210 if opId not in self.operations2RunDict.keys():
209 raise ValueError, "Any operation with id=%s has been added" %str(opId)
211 raise ValueError, "Any operation with id=%s has been added" %str(opId)
210
212
211 sts = self.callObject(opId)
213 sts = self.callObject(opId)
212
214
213 else:
215 else:
214 raise ValueError, "opType should be 'self', 'external' or 'plotter'; and not '%s'" %opType
216 raise ValueError, "opType should be 'self', 'external' or 'plotter'; and not '%s'" %opType
215
217
216 return sts
218 return sts
217
219
218 def setInput(self, dataIn):
220 def setInput(self, dataIn):
219
221
220 self.dataIn = dataIn
222 self.dataIn = dataIn
221 self.dataInList.append(dataIn)
223 self.dataInList.append(dataIn)
222
224
223 def getOutputObj(self):
225 def getOutputObj(self):
224
226
225 return self.dataOut
227 return self.dataOut
226
228
227 def checkInputs(self):
229 def checkInputs(self):
228
230
229 for thisDataIn in self.dataInList:
231 for thisDataIn in self.dataInList:
230
232
231 if thisDataIn.isEmpty():
233 if thisDataIn.isEmpty():
232 return False
234 return False
233
235
234 return True
236 return True
235
237
236 def setup(self):
238 def setup(self):
237
239
238 raise NotImplementedError
240 raise NotImplementedError
239
241
240 def run(self):
242 def run(self):
241
243
242 raise NotImplementedError
244 raise NotImplementedError
243
245
244 def close(self):
246 def close(self):
245 #Close every thread, queue or any other object here is it is neccesary.
247 #Close every thread, queue or any other object here is it is neccesary.
246 return
248 return
247
249
248 class Operation(object):
250 class Operation(object):
249
251
250 """
252 """
251 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
253 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
252 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
254 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
253 acumulacion dentro de esta clase
255 acumulacion dentro de esta clase
254
256
255 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
257 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
256
258
257 """
259 """
258
260
259 __buffer = None
261 __buffer = None
260 isConfig = False
262 isConfig = False
261
263
262 def __init__(self, **kwargs):
264 def __init__(self, **kwargs):
263
265
264 self.__buffer = None
266 self.__buffer = None
265 self.isConfig = False
267 self.isConfig = False
266 self.kwargs = kwargs
268 self.kwargs = kwargs
267
269
268 def setup(self):
270 def setup(self):
269
271
270 self.isConfig = True
272 self.isConfig = True
271
273
272 raise NotImplementedError
274 raise NotImplementedError
273
275
274 def run(self, dataIn, **kwargs):
276 def run(self, dataIn, **kwargs):
275
277
276 """
278 """
277 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los
279 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los
278 atributos del objeto dataIn.
280 atributos del objeto dataIn.
279
281
280 Input:
282 Input:
281
283
282 dataIn : objeto del tipo JROData
284 dataIn : objeto del tipo JROData
283
285
284 Return:
286 Return:
285
287
286 None
288 None
287
289
288 Affected:
290 Affected:
289 __buffer : buffer de recepcion de datos.
291 __buffer : buffer de recepcion de datos.
290
292
291 """
293 """
292 if not self.isConfig:
294 if not self.isConfig:
293 self.setup(**kwargs)
295 self.setup(**kwargs)
294
296
295 raise NotImplementedError
297 raise NotImplementedError
296
298
297 def close(self):
299 def close(self):
298
300
299 pass
301 pass
@@ -1,378 +1,378
1 '''
1 '''
2 @author: Juan C. Espinoza
2 @author: Juan C. Espinoza
3 '''
3 '''
4
4
5 import time
5 import time
6 import json
6 import json
7 import numpy
7 import numpy
8 import paho.mqtt.client as mqtt
8 import paho.mqtt.client as mqtt
9 import zmq
9 import zmq
10 import cPickle as pickle
10 import cPickle as pickle
11 import datetime
11 import datetime
12 from zmq.utils.monitor import recv_monitor_message
12 from zmq.utils.monitor import recv_monitor_message
13 from functools import wraps
13 from functools import wraps
14 from threading import Thread
14 from threading import Thread
15 from multiprocessing import Process
15 from multiprocessing import Process
16
16
17 from schainpy.model.proc.jroproc_base import Operation, ProcessingUnit
17 from schainpy.model.proc.jroproc_base import Operation, ProcessingUnit
18
18
19 MAXNUMX = 100
19 MAXNUMX = 100
20 MAXNUMY = 100
20 MAXNUMY = 100
21 throttle_value = 5
21 throttle_value = 5
22
22
23 class PrettyFloat(float):
23 class PrettyFloat(float):
24 def __repr__(self):
24 def __repr__(self):
25 return '%.2f' % self
25 return '%.2f' % self
26
26
27 def roundFloats(obj):
27 def roundFloats(obj):
28 if isinstance(obj, list):
28 if isinstance(obj, list):
29 return map(roundFloats, obj)
29 return map(roundFloats, obj)
30 elif isinstance(obj, float):
30 elif isinstance(obj, float):
31 return round(obj, 2)
31 return round(obj, 2)
32
32
33
33
34 class throttle(object):
34 class throttle(object):
35 """Decorator that prevents a function from being called more than once every
35 """Decorator that prevents a function from being called more than once every
36 time period.
36 time period.
37 To create a function that cannot be called more than once a minute, but
37 To create a function that cannot be called more than once a minute, but
38 will sleep until it can be called:
38 will sleep until it can be called:
39 @throttle(minutes=1)
39 @throttle(minutes=1)
40 def foo():
40 def foo():
41 pass
41 pass
42
42
43 for i in range(10):
43 for i in range(10):
44 foo()
44 foo()
45 print "This function has run %s times." % i
45 print "This function has run %s times." % i
46 """
46 """
47
47
48 def __init__(self, seconds=0, minutes=0, hours=0):
48 def __init__(self, seconds=0, minutes=0, hours=0):
49 self.throttle_period = datetime.timedelta(
49 self.throttle_period = datetime.timedelta(
50 seconds=seconds, minutes=minutes, hours=hours
50 seconds=seconds, minutes=minutes, hours=hours
51 )
51 )
52 self.time_of_last_call = datetime.datetime.min
52 self.time_of_last_call = datetime.datetime.min
53
53
54 def __call__(self, fn):
54 def __call__(self, fn):
55 @wraps(fn)
55 @wraps(fn)
56 def wrapper(*args, **kwargs):
56 def wrapper(*args, **kwargs):
57 now = datetime.datetime.now()
57 now = datetime.datetime.now()
58 time_since_last_call = now - self.time_of_last_call
58 time_since_last_call = now - self.time_of_last_call
59 time_left = self.throttle_period - time_since_last_call
59 time_left = self.throttle_period - time_since_last_call
60
60
61 if time_left > datetime.timedelta(seconds=0):
61 if time_left > datetime.timedelta(seconds=0):
62 return
62 return
63
63
64 self.time_of_last_call = datetime.datetime.now()
64 self.time_of_last_call = datetime.datetime.now()
65 return fn(*args, **kwargs)
65 return fn(*args, **kwargs)
66
66
67 return wrapper
67 return wrapper
68
68
69
69
70 class PublishData(Operation):
70 class PublishData(Operation):
71 """Clase publish."""
71 """Clase publish."""
72
72
73 def __init__(self, **kwargs):
73 def __init__(self, **kwargs):
74 """Inicio."""
74 """Inicio."""
75 Operation.__init__(self, **kwargs)
75 Operation.__init__(self, **kwargs)
76 self.isConfig = False
76 self.isConfig = False
77 self.client = None
77 self.client = None
78 self.zeromq = None
78 self.zeromq = None
79 self.mqtt = None
79 self.mqtt = None
80
80
81 def on_disconnect(self, client, userdata, rc):
81 def on_disconnect(self, client, userdata, rc):
82 if rc != 0:
82 if rc != 0:
83 print("Unexpected disconnection.")
83 print("Unexpected disconnection.")
84 self.connect()
84 self.connect()
85
85
86 def connect(self):
86 def connect(self):
87 print 'trying to connect'
87 print 'trying to connect'
88 try:
88 try:
89 self.client.connect(
89 self.client.connect(
90 host=self.host,
90 host=self.host,
91 port=self.port,
91 port=self.port,
92 keepalive=60*10,
92 keepalive=60*10,
93 bind_address='')
93 bind_address='')
94 print "connected"
94 print "connected"
95 self.client.loop_start()
95 self.client.loop_start()
96 # self.client.publish(
96 # self.client.publish(
97 # self.topic + 'SETUP',
97 # self.topic + 'SETUP',
98 # json.dumps(setup),
98 # json.dumps(setup),
99 # retain=True
99 # retain=True
100 # )
100 # )
101 except:
101 except:
102 print "MQTT Conection error."
102 print "MQTT Conection error."
103 self.client = False
103 self.client = False
104
104
105 def setup(self, port=1883, username=None, password=None, clientId="user", zeromq=1, **kwargs):
105 def setup(self, port=1883, username=None, password=None, clientId="user", zeromq=1, **kwargs):
106 self.counter = 0
106 self.counter = 0
107 self.topic = kwargs.get('topic', 'schain')
107 self.topic = kwargs.get('topic', 'schain')
108 self.delay = kwargs.get('delay', 0)
108 self.delay = kwargs.get('delay', 0)
109 self.plottype = kwargs.get('plottype', 'spectra')
109 self.plottype = kwargs.get('plottype', 'spectra')
110 self.host = kwargs.get('host', "10.10.10.82")
110 self.host = kwargs.get('host', "10.10.10.82")
111 self.port = kwargs.get('port', 3000)
111 self.port = kwargs.get('port', 3000)
112 self.clientId = clientId
112 self.clientId = clientId
113 self.cnt = 0
113 self.cnt = 0
114 self.zeromq = zeromq
114 self.zeromq = zeromq
115 self.mqtt = kwargs.get('plottype', 0)
115 self.mqtt = kwargs.get('plottype', 0)
116 self.client = None
116 self.client = None
117 setup = []
117 setup = []
118 if mqtt is 1:
118 if mqtt is 1:
119 print 'mqqt es 1'
119 print 'mqqt es 1'
120 self.client = mqtt.Client(
120 self.client = mqtt.Client(
121 client_id=self.clientId + self.topic + 'SCHAIN',
121 client_id=self.clientId + self.topic + 'SCHAIN',
122 clean_session=True)
122 clean_session=True)
123 self.client.on_disconnect = self.on_disconnect
123 self.client.on_disconnect = self.on_disconnect
124 self.connect()
124 self.connect()
125 for plot in self.plottype:
125 for plot in self.plottype:
126 setup.append({
126 setup.append({
127 'plot': plot,
127 'plot': plot,
128 'topic': self.topic + plot,
128 'topic': self.topic + plot,
129 'title': getattr(self, plot + '_' + 'title', False),
129 'title': getattr(self, plot + '_' + 'title', False),
130 'xlabel': getattr(self, plot + '_' + 'xlabel', False),
130 'xlabel': getattr(self, plot + '_' + 'xlabel', False),
131 'ylabel': getattr(self, plot + '_' + 'ylabel', False),
131 'ylabel': getattr(self, plot + '_' + 'ylabel', False),
132 'xrange': getattr(self, plot + '_' + 'xrange', False),
132 'xrange': getattr(self, plot + '_' + 'xrange', False),
133 'yrange': getattr(self, plot + '_' + 'yrange', False),
133 'yrange': getattr(self, plot + '_' + 'yrange', False),
134 'zrange': getattr(self, plot + '_' + 'zrange', False),
134 'zrange': getattr(self, plot + '_' + 'zrange', False),
135 })
135 })
136 if zeromq is 1:
136 if zeromq is 1:
137 context = zmq.Context()
137 context = zmq.Context()
138 self.zmq_socket = context.socket(zmq.PUSH)
138 self.zmq_socket = context.socket(zmq.PUSH)
139 server = kwargs.get('server', 'zmq.pipe')
139 server = kwargs.get('server', 'zmq.pipe')
140
140
141 if 'tcp://' in server:
141 if 'tcp://' in server:
142 address = server
142 address = server
143 else:
143 else:
144 address = 'ipc:///tmp/%s' % server
144 address = 'ipc:///tmp/%s' % server
145
145
146 self.zmq_socket.connect(address)
146 self.zmq_socket.connect(address)
147 time.sleep(1)
147 time.sleep(1)
148 print 'zeromq configured'
148 print 'zeromq configured'
149
149
150
150
151 def publish_data(self):
151 def publish_data(self):
152 self.dataOut.finished = False
152 self.dataOut.finished = False
153 if self.mqtt is 1:
153 if self.mqtt is 1:
154 yData = self.dataOut.heightList[:2].tolist()
154 yData = self.dataOut.heightList[:2].tolist()
155 if self.plottype == 'spectra':
155 if self.plottype == 'spectra':
156 data = getattr(self.dataOut, 'data_spc')
156 data = getattr(self.dataOut, 'data_spc')
157 z = data/self.dataOut.normFactor
157 z = data/self.dataOut.normFactor
158 zdB = 10*numpy.log10(z)
158 zdB = 10*numpy.log10(z)
159 xlen, ylen = zdB[0].shape
159 xlen, ylen = zdB[0].shape
160 dx = int(xlen/MAXNUMX) + 1
160 dx = int(xlen/MAXNUMX) + 1
161 dy = int(ylen/MAXNUMY) + 1
161 dy = int(ylen/MAXNUMY) + 1
162 Z = [0 for i in self.dataOut.channelList]
162 Z = [0 for i in self.dataOut.channelList]
163 for i in self.dataOut.channelList:
163 for i in self.dataOut.channelList:
164 Z[i] = zdB[i][::dx, ::dy].tolist()
164 Z[i] = zdB[i][::dx, ::dy].tolist()
165 payload = {
165 payload = {
166 'timestamp': self.dataOut.utctime,
166 'timestamp': self.dataOut.utctime,
167 'data': roundFloats(Z),
167 'data': roundFloats(Z),
168 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
168 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
169 'interval': self.dataOut.getTimeInterval(),
169 'interval': self.dataOut.getTimeInterval(),
170 'type': self.plottype,
170 'type': self.plottype,
171 'yData': yData
171 'yData': yData
172 }
172 }
173 # print payload
173 # print payload
174
174
175 elif self.plottype in ('rti', 'power'):
175 elif self.plottype in ('rti', 'power'):
176 data = getattr(self.dataOut, 'data_spc')
176 data = getattr(self.dataOut, 'data_spc')
177 z = data/self.dataOut.normFactor
177 z = data/self.dataOut.normFactor
178 avg = numpy.average(z, axis=1)
178 avg = numpy.average(z, axis=1)
179 avgdB = 10*numpy.log10(avg)
179 avgdB = 10*numpy.log10(avg)
180 xlen, ylen = z[0].shape
180 xlen, ylen = z[0].shape
181 dy = numpy.floor(ylen/self.__MAXNUMY) + 1
181 dy = numpy.floor(ylen/self.__MAXNUMY) + 1
182 AVG = [0 for i in self.dataOut.channelList]
182 AVG = [0 for i in self.dataOut.channelList]
183 for i in self.dataOut.channelList:
183 for i in self.dataOut.channelList:
184 AVG[i] = avgdB[i][::dy].tolist()
184 AVG[i] = avgdB[i][::dy].tolist()
185 payload = {
185 payload = {
186 'timestamp': self.dataOut.utctime,
186 'timestamp': self.dataOut.utctime,
187 'data': roundFloats(AVG),
187 'data': roundFloats(AVG),
188 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
188 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
189 'interval': self.dataOut.getTimeInterval(),
189 'interval': self.dataOut.getTimeInterval(),
190 'type': self.plottype,
190 'type': self.plottype,
191 'yData': yData
191 'yData': yData
192 }
192 }
193 elif self.plottype == 'noise':
193 elif self.plottype == 'noise':
194 noise = self.dataOut.getNoise()/self.dataOut.normFactor
194 noise = self.dataOut.getNoise()/self.dataOut.normFactor
195 noisedB = 10*numpy.log10(noise)
195 noisedB = 10*numpy.log10(noise)
196 payload = {
196 payload = {
197 'timestamp': self.dataOut.utctime,
197 'timestamp': self.dataOut.utctime,
198 'data': roundFloats(noisedB.reshape(-1, 1).tolist()),
198 'data': roundFloats(noisedB.reshape(-1, 1).tolist()),
199 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
199 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
200 'interval': self.dataOut.getTimeInterval(),
200 'interval': self.dataOut.getTimeInterval(),
201 'type': self.plottype,
201 'type': self.plottype,
202 'yData': yData
202 'yData': yData
203 }
203 }
204 elif self.plottype == 'snr':
204 elif self.plottype == 'snr':
205 data = getattr(self.dataOut, 'data_SNR')
205 data = getattr(self.dataOut, 'data_SNR')
206 avgdB = 10*numpy.log10(data)
206 avgdB = 10*numpy.log10(data)
207
207
208 ylen = data[0].size
208 ylen = data[0].size
209 dy = numpy.floor(ylen/self.__MAXNUMY) + 1
209 dy = numpy.floor(ylen/self.__MAXNUMY) + 1
210 AVG = [0 for i in self.dataOut.channelList]
210 AVG = [0 for i in self.dataOut.channelList]
211 for i in self.dataOut.channelList:
211 for i in self.dataOut.channelList:
212 AVG[i] = avgdB[i][::dy].tolist()
212 AVG[i] = avgdB[i][::dy].tolist()
213 payload = {
213 payload = {
214 'timestamp': self.dataOut.utctime,
214 'timestamp': self.dataOut.utctime,
215 'data': roundFloats(AVG),
215 'data': roundFloats(AVG),
216 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
216 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
217 'type': self.plottype,
217 'type': self.plottype,
218 'yData': yData
218 'yData': yData
219 }
219 }
220 else:
220 else:
221 print "Tipo de grafico invalido"
221 print "Tipo de grafico invalido"
222 payload = {
222 payload = {
223 'data': 'None',
223 'data': 'None',
224 'timestamp': 'None',
224 'timestamp': 'None',
225 'type': None
225 'type': None
226 }
226 }
227 # print 'Publishing data to {}'.format(self.host)
227 # print 'Publishing data to {}'.format(self.host)
228 self.client.publish(self.topic + self.plottype, json.dumps(payload), qos=0)
228 self.client.publish(self.topic + self.plottype, json.dumps(payload), qos=0)
229
229
230 if self.zeromq is 1:
230 if self.zeromq is 1:
231 print '[Sending] {} - {}'.format(self.dataOut.type, self.dataOut.datatime)
231 print '[Sending] {} - {}'.format(self.dataOut.type, self.dataOut.datatime)
232 self.zmq_socket.send_pyobj(self.dataOut)
232 self.zmq_socket.send_pyobj(self.dataOut)
233
233
234 def run(self, dataOut, **kwargs):
234 def run(self, dataOut, **kwargs):
235 self.dataOut = dataOut
235 self.dataOut = dataOut
236 if not self.isConfig:
236 if not self.isConfig:
237 self.setup(**kwargs)
237 self.setup(**kwargs)
238 self.isConfig = True
238 self.isConfig = True
239
239
240 self.publish_data()
240 self.publish_data()
241 time.sleep(self.delay)
241 time.sleep(self.delay)
242
242
243 def close(self):
243 def close(self):
244 if self.zeromq is 1:
244 if self.zeromq is 1:
245 self.dataOut.finished = True
245 self.dataOut.finished = True
246 self.zmq_socket.send_pyobj(self.dataOut)
246 self.zmq_socket.send_pyobj(self.dataOut)
247
247
248 if self.client:
248 if self.client:
249 self.client.loop_stop()
249 self.client.loop_stop()
250 self.client.disconnect()
250 self.client.disconnect()
251
251
252
252
253 class ReceiverData(ProcessingUnit, Process):
253 class ReceiverData(ProcessingUnit, Process):
254
254
255 def __init__(self, **kwargs):
255 def __init__(self, **kwargs):
256
256
257 ProcessingUnit.__init__(self, **kwargs)
257 ProcessingUnit.__init__(self, **kwargs)
258 Process.__init__(self)
258 Process.__init__(self)
259 self.mp = False
259 self.mp = False
260 self.isConfig = False
260 self.isConfig = False
261 self.plottypes =[]
261 self.plottypes =[]
262 self.connections = 0
262 self.connections = 0
263 server = kwargs.get('server', 'zmq.pipe')
263 server = kwargs.get('server', 'zmq.pipe')
264 if 'tcp://' in server:
264 if 'tcp://' in server:
265 address = server
265 address = server
266 else:
266 else:
267 address = 'ipc:///tmp/%s' % server
267 address = 'ipc:///tmp/%s' % server
268
268
269 self.address = address
269 self.address = address
270 self.plottypes = [s.strip() for s in kwargs.get('plottypes', 'rti').split(',')]
270 self.plottypes = [s.strip() for s in kwargs.get('plottypes', 'rti').split(',')]
271 self.realtime = kwargs.get('realtime', False)
271 self.realtime = kwargs.get('realtime', False)
272 global throttle_value
272 global throttle_value
273 throttle_value = kwargs.get('throttle', 10)
273 throttle_value = kwargs.get('throttle', 10)
274 self.setup()
274 self.setup()
275
275
276 def setup(self):
276 def setup(self):
277
277
278 self.data = {}
278 self.data = {}
279 self.data['times'] = []
279 self.data['times'] = []
280 for plottype in self.plottypes:
280 for plottype in self.plottypes:
281 self.data[plottype] = {}
281 self.data[plottype] = {}
282 self.data['noise'] = {}
282 self.data['noise'] = {}
283 self.isConfig = True
283 self.isConfig = True
284
284
285 def event_monitor(self, monitor):
285 def event_monitor(self, monitor):
286
286
287 events = {}
287 events = {}
288
288
289 for name in dir(zmq):
289 for name in dir(zmq):
290 if name.startswith('EVENT_'):
290 if name.startswith('EVENT_'):
291 value = getattr(zmq, name)
291 value = getattr(zmq, name)
292 events[value] = name
292 events[value] = name
293
293
294 while monitor.poll():
294 while monitor.poll():
295 evt = recv_monitor_message(monitor)
295 evt = recv_monitor_message(monitor)
296 if evt['event'] == 32:
296 if evt['event'] == 32:
297 self.connections += 1
297 self.connections += 1
298 if evt['event'] == 512:
298 if evt['event'] == 512:
299 pass
299 pass
300 if self.connections == 0 and self.started is True:
300 if self.connections == 0 and self.started is True:
301 self.ended = True
301 self.ended = True
302 # send('ENDED')
302 # send('ENDED')
303 evt.update({'description': events[evt['event']]})
303 evt.update({'description': events[evt['event']]})
304
304
305 if evt['event'] == zmq.EVENT_MONITOR_STOPPED:
305 if evt['event'] == zmq.EVENT_MONITOR_STOPPED:
306 break
306 break
307 monitor.close()
307 monitor.close()
308 print("event monitor thread done!")
308 print("event monitor thread done!")
309
309
310 @throttle(seconds=throttle_value)
310 @throttle(seconds=throttle_value)
311 def sendData(self, data):
311 def sendData(self, data):
312 self.send(data)
312 self.send(data)
313
313
314 def send(self, data):
314 def send(self, data):
315 print '[sending] data=%s size=%s' % (data.keys(), len(data['times']))
315 print '[sending] data=%s size=%s' % (data.keys(), len(data['times']))
316 self.sender.send_pyobj(data)
316 self.sender.send_pyobj(data)
317
317
318 def update(self):
318 def update(self):
319
319
320 t = self.dataOut.ltctime
320 t = self.dataOut.ltctime
321 self.data['times'].append(t)
321 self.data['times'].append(t)
322 self.data['dataOut'] = self.dataOut
322 self.data['dataOut'] = self.dataOut
323
323
324 for plottype in self.plottypes:
324 for plottype in self.plottypes:
325
325
326 if plottype == 'spc':
326 if plottype == 'spc':
327 z = self.dataOut.data_spc/self.dataOut.normFactor
327 z = self.dataOut.data_spc/self.dataOut.normFactor
328 self.data[plottype] = 10*numpy.log10(z)
328 self.data[plottype] = 10*numpy.log10(z)
329 self.data['noise'][t] = 10*numpy.log10(self.dataOut.getNoise()/self.dataOut.normFactor)
329 self.data['noise'][t] = 10*numpy.log10(self.dataOut.getNoise()/self.dataOut.normFactor)
330 if plottype == 'rti':
330 if plottype == 'rti':
331 self.data[plottype][t] = self.dataOut.getPower()
331 self.data[plottype][t] = self.dataOut.getPower()
332 if plottype == 'snr':
332 if plottype == 'snr':
333 self.data[plottype][t] = 10*numpy.log10(self.dataOut.data_SNR)
333 self.data[plottype][t] = 10*numpy.log10(self.dataOut.data_SNR)
334 if plottype == 'dop':
334 if plottype == 'dop':
335 self.data[plottype][t] = 10*numpy.log10(self.dataOut.data_DOP)
335 self.data[plottype][t] = 10*numpy.log10(self.dataOut.data_DOP)
336 if plottype == 'coh':
336 if plottype == 'coh':
337 self.data[plottype][t] = self.dataOut.getCoherence()
337 self.data[plottype][t] = self.dataOut.getCoherence()
338 if plottype == 'phase':
338 if plottype == 'phase':
339 self.data[plottype][t] = self.dataOut.getCoherence(phase=True)
339 self.data[plottype][t] = self.dataOut.getCoherence(phase=True)
340
340
341 def run(self):
341 def run(self):
342
342
343 print '[Starting] {} from {}'.format(self.name, self.address)
343 print '[Starting] {} from {}'.format(self.name, self.address)
344
344
345 self.context = zmq.Context()
345 self.context = zmq.Context()
346 self.receiver = self.context.socket(zmq.PULL)
346 self.receiver = self.context.socket(zmq.PULL)
347 self.receiver.bind(self.address)
347 self.receiver.bind(self.address)
348 monitor = self.receiver.get_monitor_socket()
348 monitor = self.receiver.get_monitor_socket()
349 self.sender = self.context.socket(zmq.PUB)
349 self.sender = self.context.socket(zmq.PUB)
350
350
351 self.sender.bind("ipc:///tmp/zmq.plots")
351 self.sender.bind("ipc:///tmp/zmq.plots")
352
352
353 t = Thread(target=self.event_monitor, args=(monitor,))
353 t = Thread(target=self.event_monitor, args=(monitor,))
354 t.start()
354 t.start()
355
355
356 while True:
356 while True:
357 self.dataOut = self.receiver.recv_pyobj()
357 self.dataOut = self.receiver.recv_pyobj()
358 print '[Receiving] {} - {}'.format(self.dataOut.type,
358 print '[Receiving] {} - {}'.format(self.dataOut.type,
359 self.dataOut.datatime.ctime())
359 self.dataOut.datatime.ctime())
360
360
361 self.update()
361 self.update()
362
362
363 if self.dataOut.finished is True:
363 if self.dataOut.finished is True:
364 self.send(self.data)
364 self.send(self.data)
365 self.connections -= 1
365 self.connections -= 1
366 if self.connections==0 and self.started:
366 if self.connections == 0 and self.started:
367 self.ended = True
367 self.ended = True
368 self.data['ENDED'] = True
368 self.data['ENDED'] = True
369 self.send(self.data)
369 self.send(self.data)
370 self.setup()
370 self.setup()
371 else:
371 else:
372 if self.realtime:
372 if self.realtime:
373 self.send(self.data)
373 self.send(self.data)
374 else:
374 else:
375 self.sendData(self.data)
375 self.sendData(self.data)
376 self.started = True
376 self.started = True
377
377
378 return
378 return
@@ -1,77 +1,75
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 '''
2 '''
3 Created on Jul 7, 2014
3 Created on Jul 7, 2014
4
4
5 @author: roj-idl71
5 @author: roj-idl71
6 '''
6 '''
7 import os, sys
7 import os, sys
8 from datetime import datetime, timedelta
8 from datetime import datetime, timedelta
9 import multiprocessing
9 import multiprocessing
10 from schainpy.controller import Project
10 from schainpy.controller import Project
11
11
12 def main(date):
12 def main(date):
13
13
14 controllerObj = Project()
14 controllerObj = Project()
15
15
16 controllerObj.setup(id = '191', name='test01', description='')
16 controllerObj.setup(id='191', name='test01', description='')
17
17
18 readUnitConfObj = controllerObj.addReadUnit(datatype='Spectra',
18 readUnitConfObj = controllerObj.addReadUnit(datatype='Spectra',
19 path='/data/workspace/data/zeus/',
19 path='/home/nanosat/data/zeus',
20 startDate=date,
20 startDate=date,
21 endDate=date,
21 endDate=date,
22 startTime='00:00:00',
22 startTime='00:00:00',
23 endTime='23:59:59',
23 endTime='23:59:59',
24 online=0,
24 online=0,
25 walk=1,
25 walk=1,
26 expLabel='')
26 expLabel='')
27
27
28 procUnitConfObj1 = controllerObj.addProcUnit(datatype='Spectra', inputId=readUnitConfObj.getId())
28 procUnitConfObj1 = controllerObj.addProcUnit(datatype='Spectra', inputId=readUnitConfObj.getId())
29 #opObj11 = procUnitConfObj1.addOperation(name='removeDC')
29 #opObj11 = procUnitConfObj1.addOperation(name='removeDC')
30 #opObj11.addParameter(name='mode', value='1', format='int')
30 #opObj11.addParameter(name='mode', value='1', format='int')
31
31
32 #opObj11 = procUnitConfObj1.addOperation(name='removeInterference')
32 #opObj11 = procUnitConfObj1.addOperation(name='removeInterference')
33
33
34
34
35 # opObj11 = procUnitConfObj1.addOperation(name='RTIPlot', optype='other')
35 # opObj11 = procUnitConfObj1.addOperation(name='RTIPlot', optype='other')
36 # opObj11.addParameter(name='id', value='10', format='int')
36 # opObj11.addParameter(name='id', value='10', format='int')
37 # opObj11.addParameter(name='wintitle', value='150Km', format='str')
37 # opObj11.addParameter(name='wintitle', value='150Km', format='str')
38 # opObj11.addParameter(name='colormap', value='jro', format='str')
38 # opObj11.addParameter(name='colormap', value='jro', format='str')
39 # opObj11.addParameter(name='xaxis', value='time', format='str')
39 # opObj11.addParameter(name='xaxis', value='time', format='str')
40 # opObj11.addParameter(name='xmin', value='0', format='int')
40 # opObj11.addParameter(name='xmin', value='0', format='int')
41 # opObj11.addParameter(name='xmax', value='23', format='int')
41 # opObj11.addParameter(name='xmax', value='23', format='int')
42 # #opObj11.addParameter(name='ymin', value='100', format='int')
42 # #opObj11.addParameter(name='ymin', value='100', format='int')
43 # #opObj11.addParameter(name='ymax', value='150', format='int')
43 # #opObj11.addParameter(name='ymax', value='150', format='int')
44 # opObj11.addParameter(name='zmin', value='10', format='int')
44 # opObj11.addParameter(name='zmin', value='10', format='int')
45 # opObj11.addParameter(name='zmax', value='35', format='int')
45 # opObj11.addParameter(name='zmax', value='35', format='int')
46
46
47
47
48
48
49
49
50 opObj11 = procUnitConfObj1.addOperation(name='PlotRTIData', optype='other')
50 opObj11 = procUnitConfObj1.addOperation(name='PlotRTIData', optype='other')
51 opObj11.addParameter(name='id', value='12', format='int')
51 opObj11.addParameter(name='id', value='12', format='int')
52 opObj11.addParameter(name='wintitle', value='150Km', format='str')
52 opObj11.addParameter(name='wintitle', value='150Km', format='str')
53 opObj11.addParameter(name='colormap', value='jro', format='str')
53 opObj11.addParameter(name='colormap', value='jro', format='str')
54 opObj11.addParameter(name='xaxis', value='time', format='str')
54 opObj11.addParameter(name='xaxis', value='time', format='str')
55 opObj11.addParameter(name='xmin', value='0', format='int')
55 opObj11.addParameter(name='xmin', value='0', format='int')
56 opObj11.addParameter(name='xmax', value='23', format='int')
56 opObj11.addParameter(name='xmax', value='23', format='int')
57 #opObj11.addParameter(name='ymin', value='100', format='int')
57 #opObj11.addParameter(name='ymin', value='100', format='int')
58 #opObj11.addParameter(name='ymax', value='150', format='int')
58 #opObj11.addParameter(name='ymax', value='150', format='int')
59 opObj11.addParameter(name='zmin', value='10', format='int')
59 opObj11.addParameter(name='zmin', value='10', format='int')
60 opObj11.addParameter(name='zmax', value='35', format='int')
60 opObj11.addParameter(name='zmax', value='35', format='int')
61 #opObj11.addParameter(name='pause', value='1', format='bool')
61 #opObj11.addParameter(name='pause', value='1', format='bool')
62 opObj11.addParameter(name='show', value='0', format='bool')
62 opObj11.addParameter(name='show', value='0', format='bool')
63 opObj11.addParameter(name='save', value='/tmp', format='str')
63 opObj11.addParameter(name='save', value='/tmp', format='str')
64
64
65
65
66 controllerObj.start()
66 controllerObj.start()
67
67
68 if __name__=='__main__':
68 if __name__=='__main__':
69
69
70 dt = datetime(2017, 1, 12)
70 dt = datetime(2017, 1, 12)
71
71
72 dates = [(dt+timedelta(x)).strftime('%Y/%m/%d') for x in range(20)]
72 dates = [(dt+timedelta(x)).strftime('%Y/%m/%d') for x in range(20)]
73
73
74 p = multiprocessing.Pool(4)
74 p = multiprocessing.Pool(4)
75 p.map(main, dates)
75 p.map(main, dates)
76
77 No newline at end of file
@@ -1,42 +1,42
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 '''
2 '''
3 Created on Jul 7, 2014
3 Created on Jul 7, 2014
4
4
5 @author: roj-idl71
5 @author: roj-idl71
6 '''
6 '''
7 import os, sys
7 import os, sys
8
8
9 from schainpy.controller import Project
9 from schainpy.controller import Project
10
10
11 if __name__ == '__main__':
11 if __name__ == '__main__':
12 desc = "Segundo Test"
12 desc = "Segundo Test"
13
13
14 controllerObj = Project()
14 controllerObj = Project()
15 controllerObj.setup(id = '191', name='test01', description=desc)
15 controllerObj.setup(id='191', name='test01', description=desc)
16
16
17 proc1 = controllerObj.addProcUnit(name='ReceiverData')
17 proc1 = controllerObj.addProcUnit(name='ReceiverData')
18 # proc1.addParameter(name='server', value='tcp://10.10.10.87:3000', format='str')
18 # proc1.addParameter(name='server', value='tcp://10.10.10.87:3000', format='str')
19 proc1.addParameter(name='realtime', value='1', format='bool')
19 proc1.addParameter(name='realtime', value='1', format='bool')
20 proc1.addParameter(name='plottypes', value='rti,spc', format='str')
20 proc1.addParameter(name='plottypes', value='rti,spc', format='str')
21
21
22 op1 = proc1.addOperation(name='PlotRTIData', optype='other')
22 op1 = proc1.addOperation(name='PlotRTIData', optype='other')
23 op1.addParameter(name='wintitle', value='Julia 150Km', format='str')
23 op1.addParameter(name='wintitle', value='Julia 150Km', format='str')
24
24
25 op2 = proc1.addOperation(name='PlotSpectraData', optype='other')
25 op2 = proc1.addOperation(name='PlotSpectraData', optype='other')
26 op2.addParameter(name='wintitle', value='Julia 150Km', format='str')
26 op2.addParameter(name='wintitle', value='Julia 150Km', format='str')
27 op2.addParameter(name='xaxis', value='velocity', format='str')
27 op2.addParameter(name='xaxis', value='velocity', format='str')
28 op2.addParameter(name='showprofile', value='1', format='bool')
28 op2.addParameter(name='showprofile', value='1', format='bool')
29 #op2.addParameter(name='xmin', value='-0.1', format='float')
29 #op2.addParameter(name='xmin', value='-0.1', format='float')
30 #op2.addParameter(name='xmax', value='0.1', format='float')
30 #op2.addParameter(name='xmax', value='0.1', format='float')
31
31
32 # op1 = proc1.addOperation(name='PlotPHASEData', optype='other')
32 # op1 = proc1.addOperation(name='PlotPHASEData', optype='other')
33 # op1.addParameter(name='wintitle', value='Julia 150Km', format='str')
33 # op1.addParameter(name='wintitle', value='Julia 150Km', format='str')
34
34
35
35
36 # proc1 = controllerObj.addProcUnit(name='ReceiverData')
36 # proc1 = controllerObj.addProcUnit(name='ReceiverData')
37 # proc1.addParameter(name='server', value='pipe2', format='str')
37 # proc1.addParameter(name='server', value='pipe2', format='str')
38 # proc1.addParameter(name='mode', value='buffer', format='str')
38 # proc1.addParameter(name='mode', value='buffer', format='str')
39 # proc1.addParameter(name='plottypes', value='snr', format='str')
39 # proc1.addParameter(name='plottypes', value='snr', format='str')
40
40
41
41
42 controllerObj.start()
42 controllerObj.start()
General Comments 0
You need to be logged in to leave comments. Login now